Compare commits
105
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7714881c8c | ||
|
|
2f75202db5 | ||
|
|
3b418076f1 | ||
|
|
662e167c6f | ||
|
|
ff4e68def4 | ||
|
|
731b2231bc | ||
|
|
29acc8ce25 | ||
|
|
9759fdc2c6 | ||
|
|
f7b069e5d6 | ||
|
|
5843ef58f8 | ||
|
|
4942be40f4 | ||
|
|
0a4e832b1d | ||
|
|
1239342094 | ||
|
|
7220e5b418 | ||
|
|
11d26a23b6 | ||
|
|
456b7cddaa | ||
|
|
1b370f2739 | ||
|
|
2907f1c460 | ||
|
|
3c271e8ff3 | ||
|
|
3c5ed514df | ||
|
|
be1b270e5c | ||
|
|
5032434a7d | ||
|
|
f99f4a4dc3 | ||
|
|
aa4d4934d5 | ||
|
|
8335ede8f7 | ||
|
|
a361eae158 | ||
|
|
5910c1fca3 | ||
|
|
dc9c08ce2b | ||
|
|
51561a9a11 | ||
|
|
0536405a72 | ||
|
|
737a355baf | ||
|
|
32ec1f8331 | ||
|
|
4338e9e843 | ||
|
|
03e050a14a | ||
|
|
ee419a2b97 | ||
|
|
c583f087a2 | ||
|
|
28d80cb986 | ||
|
|
e8a73d5e80 | ||
|
|
a1c43d5bb2 | ||
|
|
e84e19fd5c | ||
|
|
2a63487c08 | ||
|
|
70a70c327c | ||
|
|
ed44961367 | ||
|
|
281c7027d4 | ||
|
|
844fd4fe9b | ||
|
|
631a371e58 | ||
|
|
34657f90ff | ||
|
|
02f842016f | ||
|
|
4aaa1b3a11 | ||
|
|
879ae7e244 | ||
|
|
16a9d0c031 | ||
|
|
7fa244c3a0 | ||
|
|
8abbe79ab6 | ||
|
|
88922adf7b | ||
|
|
ed26d5ba7a | ||
|
|
d6ea0091f8 | ||
|
|
5f6ddfaf55 | ||
|
|
17821cff4e | ||
|
|
8b17ba9d74 | ||
|
|
7f3807c8fd | ||
|
|
6c468e6b38 | ||
|
|
f0a6e318f1 | ||
|
|
668a717445 | ||
|
|
2499ceb1c7 | ||
|
|
e1a81682ac | ||
|
|
14bb0d3eb3 | ||
|
|
922b3a3107 | ||
|
|
7ce57c3faa | ||
|
|
4d9d809f85 | ||
|
|
dd225e0a0e | ||
|
|
8732f50ded | ||
|
|
e0b3929d7a | ||
|
|
b6960476a8 | ||
|
|
c96a7783dd | ||
|
|
89fa58ddff | ||
|
|
02a09d0e31 | ||
|
|
1a2c41cc08 | ||
|
|
710cafff3a | ||
|
|
d856786161 | ||
|
|
9e0d9581c6 | ||
|
|
7b8de39fab | ||
|
|
c2712a7d99 | ||
|
|
56f81d9c2e | ||
|
|
3b1f89623e | ||
|
|
fe1fef5a52 | ||
|
|
c63ab674bd | ||
|
|
26bc06e1dd | ||
|
|
b3eff2c3d7 | ||
|
|
7a29ada08e | ||
|
|
2f66a593d8 | ||
|
|
bf96276080 | ||
|
|
ff79d32a89 | ||
|
|
89fe7c17ea | ||
|
|
e1c3121080 | ||
|
|
fa5b8e1cef | ||
|
|
ba05c442f0 | ||
|
|
d567dff38a | ||
|
|
c103ea0548 | ||
|
|
c4a313fe69 | ||
|
|
c65a252d1b | ||
|
|
aeaa175358 | ||
|
|
a94ad7560a | ||
|
|
87a98e2998 | ||
|
|
a1fdd07308 | ||
|
|
0d9399eb07 |
No files matched your search
@@ -7,6 +7,95 @@ All notable changes to this project are documented here. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
> **Early beta.** 1.5 rebuilds the home screen around views and blocks, and
|
||||
> this first beta still has known bugs and rough edges that will change before
|
||||
> the stable release. Please report what you run into on #59. (Remove this
|
||||
> note when going stable.)
|
||||
|
||||
### Added
|
||||
- Views. Home is now the first of any number of views, switched from the
|
||||
view's name in the top bar. That menu also opens *Lists & filters…*, every
|
||||
list, saved filter and tag in one place, and *Manage views*, where views
|
||||
are added, renamed, given an icon, reordered and deleted (#59).
|
||||
- A list or saved filter can be pinned as a view from its ⋮ menu: the new
|
||||
view shows its tasks, completed ones below, and is named after it (#59).
|
||||
- A view can be narrowed to a scope. Everything in it then counts only the
|
||||
tasks in that scope: the tiles, previews and lists, a list opened from it
|
||||
(with a chip to show all of its tasks again), and a search started there
|
||||
(with a chip to search everything). A list a scope names shows even when
|
||||
it is kept out of the smart lists. When a list or filter a view uses is
|
||||
deleted, the view says so instead of quietly showing more (#59).
|
||||
- A start screen setting under Settings: open on Home (the default), the
|
||||
last used view, another view, a list or a saved filter. A list or filter
|
||||
opens over Home, so back leads there (#141).
|
||||
- Every view is also a launcher shortcut (#59).
|
||||
- The filter editor matches *all rules* or *any rule*, and each of lists,
|
||||
tags and due date can be turned round with *is / is not*, so "list Next or
|
||||
tag nextAction" is one filter now. Due dates gain *This week*, *This month*
|
||||
and *Next N days*. An *Advanced editor* builds nested groups of *all of* /
|
||||
*any of*, each of which can be negated; a filter the simple editor can't
|
||||
show opens there (#172).
|
||||
- A new filter can start from a template: *Next actions (GTD)*, *This week*,
|
||||
*This month*, *High priority*, *Waiting for* or *No date*. It fills in the
|
||||
rules and, if the filter has none yet, its name; *Next actions* asks which
|
||||
list holds them. A tag no task carries yet can be typed in (#154, #172).
|
||||
- A view's scope is edited in the same editor, from *Edit view*. Any block
|
||||
that shows tasks can show *Custom rules* instead of a list or filter, which
|
||||
can be saved as a filter (#59, #172).
|
||||
- A compact density under Settings → Appearance: shorter rows in the lists,
|
||||
the task lists and settings, so more fits on the screen.
|
||||
- A "Reduce motion" switch under Settings → Appearance takes the movement out
|
||||
of the app, as the system's "Remove animations" does: screens and sections
|
||||
fade instead of sliding, buttons don't spin or bounce, and looping animations
|
||||
such as the wave on the Today progress ring and the pull-to-sync indicator
|
||||
stay still. The system setting does the same whatever the switch says (#157).
|
||||
- Edit layout, from a view's ⋮ menu, from Edit view, or by long-pressing a
|
||||
block: drag blocks into a new order, make tiles half or full width, remove a
|
||||
block (with undo) and add new ones; ✓ keeps the changes, ✕ undoes them all. Tapping a block opens its settings: its
|
||||
title, what it shows, its own options, and whether it ignores the view's
|
||||
scope, which a small mark on the block then shows (#59).
|
||||
- New blocks: count tiles of any list, tag, filter or smart list with their
|
||||
own title, colour and icon; progress of any of those, also half width;
|
||||
previews of 3, 5 or 10 tasks that can be checked off in place; recently completed, unchecked to
|
||||
undo; a week strip with a dot per task due, opening a day's tasks; and
|
||||
section headings. Tiles follow the compact density too (#59).
|
||||
- A quick-add bar at the bottom of every view, on by default and switched off
|
||||
per view in Edit view, which says where its tasks go. A task added there
|
||||
goes to the list the view's scope keeps to, otherwise to the default list,
|
||||
and takes the tags, priority and due date that keep it in the view; one
|
||||
that still falls outside says so, with a button to open its list, and one
|
||||
no block of the view shows says where it went. The
|
||||
bar's expand button opens the full editor with what was typed (#59, #186).
|
||||
- Quick-add understands `@date` and `+list` while typing, marks them and
|
||||
shows what they stand for: `@today`, `@tomorrow`, `@nextweek`, `@fri`,
|
||||
`@3d`, `@2w`, `@1m`, `@2026-11-20` or the short date of your language,
|
||||
each with an optional time (`@fri@14:30`, `@tomorrow@9am`), or a time alone
|
||||
(`@14:30`: today, or tomorrow once it has passed); `+Errands`, a unique
|
||||
start of a list's name (`+err`), or `+"Shared household"`. The last of each
|
||||
counts. The words are translated, and the English ones always work (#186).
|
||||
- A new task from a list or filter opened within a view's scope takes that
|
||||
scope's list, tags and due date too (#59).
|
||||
|
||||
### Changed
|
||||
- All shows completed tasks too. Today, All, lists and a view's task list
|
||||
close with the same Completed section, with Today's tight spacing and the
|
||||
lists' Clear, which asks before deleting what it shows (#140).
|
||||
- Menus only fade in and out under Reduce motion (#157).
|
||||
- The home screen's search, settings and new-list buttons are plain icons now,
|
||||
for everyone. The expressive shapes they sat on are still there, and now
|
||||
reach every top-bar and header button (lists, filters, a list's search and
|
||||
view options, a task's edit, delete and menu): pick "Expressive shapes" under
|
||||
Settings → Appearance → Buttons (#118).
|
||||
|
||||
## [1.4.1] - 2026-11-30
|
||||
|
||||
### Added
|
||||
- Spanish translation, offered in the language picker, with a Spanish store
|
||||
listing.
|
||||
|
||||
### Changed
|
||||
- Galician translation is now nearly complete.
|
||||
|
||||
## [1.4.0] - 2026-11-25
|
||||
|
||||
### Added
|
||||
|
||||
@@ -33,8 +33,8 @@ android {
|
||||
// (1.0.x: 1.0.0 -> 10000; from 1.1.0: 1.1.0-beta.1 -> 1010001,
|
||||
// 1.1.0 -> 1010099), and CI fails if the committed one doesn't match.
|
||||
// See docs/RELEASING.md.
|
||||
versionCode = 1040099
|
||||
versionName = "1.4.0"
|
||||
versionCode = 1050001
|
||||
versionName = "1.5.0-beta.1"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
@@ -259,6 +259,7 @@ dependencies {
|
||||
implementation(libs.floret.core.reminders)
|
||||
implementation(libs.floret.core.locale)
|
||||
implementation(libs.floret.core.crash)
|
||||
implementation(libs.floret.core.prefs)
|
||||
implementation(libs.floret.identity)
|
||||
implementation(libs.floret.components)
|
||||
implementation(libs.floret.glance)
|
||||
|
||||
@@ -3,48 +3,56 @@ package de.jeanlucmakiola.agendula
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.text.format.DateFormat
|
||||
import android.view.View
|
||||
import android.view.ViewTreeObserver
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.core.net.toUri
|
||||
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.agendula.ui.common.LocalFirstDayOfWeek
|
||||
import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import de.jeanlucmakiola.agendula.data.di.LaunchHook
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.smartListNamed
|
||||
import de.jeanlucmakiola.agendula.ui.imports.importIntentUri
|
||||
import de.jeanlucmakiola.agendula.ui.navigation.AppShortcuts
|
||||
import de.jeanlucmakiola.agendula.ui.RootScreen
|
||||
import de.jeanlucmakiola.agendula.ui.crash.CrashReportActivity
|
||||
import de.jeanlucmakiola.agendula.ui.navigation.NavRequest
|
||||
import de.jeanlucmakiola.agendula.ui.settings.SettingsViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.theme.AgendulaTheme
|
||||
import de.jeanlucmakiola.agendula.ui.theme.SystemTheme
|
||||
import de.jeanlucmakiola.agendula.ui.views.ViewSession
|
||||
import de.jeanlucmakiola.floret.crash.CrashReportDialog
|
||||
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||
import de.jeanlucmakiola.floret.crash.submitCrashReport
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Single activity. The theme follows [SettingsViewModel]; [RootScreen] is the
|
||||
* Single activity. The theme follows the stored [Settings]; [RootScreen] is the
|
||||
* (replaceable) functional scaffold over the real data layer. Notification taps
|
||||
* arrive as a [NavRequest] (see [navRequestOf]).
|
||||
*/
|
||||
@@ -55,6 +63,8 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
@Inject lateinit var settingsPrefs: SettingsPrefs
|
||||
|
||||
@Inject lateinit var viewSession: ViewSession
|
||||
|
||||
// A captured crash report awaiting the user's decision, surfaced as a dialog
|
||||
// over the app on the next launch (the single-crash path). A startup
|
||||
// crash-loop is handled out of band, before setContent — see below.
|
||||
@@ -63,6 +73,12 @@ class MainActivity : ComponentActivity() {
|
||||
// A notification tap's destination, handed to the nav host and cleared once taken.
|
||||
private var navRequest by mutableStateOf<NavRequest?>(null)
|
||||
|
||||
// A request arrived after launch, so the start destination mustn't land on top of it.
|
||||
private var navigatedSinceLaunch = false
|
||||
|
||||
// Set once the stored settings reach the composition; see [holdFirstFrameForAppearance].
|
||||
private var appearanceReady = false
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
@@ -76,7 +92,16 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
enableEdgeToEdge()
|
||||
AppShortcuts.publish(this)
|
||||
// Every view is a launcher shortcut, kept up with the views as they change.
|
||||
lifecycleScope.launch {
|
||||
combine(settingsPrefs.views, settingsPrefs.storedViewIds) { views, stored -> views to stored }
|
||||
.distinctUntilChanged { a, b ->
|
||||
a.second == b.second && a.first.map { Triple(it.id, it.name, it.icon) } == b.first.map { Triple(it.id, it.name, it.icon) }
|
||||
}
|
||||
.collect { (views, stored) ->
|
||||
withContext(Dispatchers.Default) { AppShortcuts.publish(this@MainActivity, views, stored) }
|
||||
}
|
||||
}
|
||||
|
||||
// The stored setting, never the view model's placeholder: a night mode
|
||||
// that flips back and forth would recreate the activity each time.
|
||||
@@ -88,7 +113,26 @@ class MainActivity : ComponentActivity() {
|
||||
// Only on a fresh launch: after a rotation or process restore the intent
|
||||
// is the same old one and the back stack already holds its destination.
|
||||
val fromHistory = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0
|
||||
if (savedInstanceState == null && !fromHistory) navRequest = navRequestOf(intent)
|
||||
if (savedInstanceState == null && !fromHistory) {
|
||||
navRequest = navRequestOf(intent)?.also(::switchViewFor)
|
||||
// A plain launch opens the start destination (#141); anything else opens what it asked for.
|
||||
if (navRequest == null) {
|
||||
viewSession.beginStart()
|
||||
}
|
||||
}
|
||||
// Collected on every creation: a start destination worked out across a rotation still opens.
|
||||
lifecycleScope.launch {
|
||||
viewSession.startPush.collect { filter ->
|
||||
val push = when (filter) {
|
||||
is TaskFilter.OfList -> NavRequest.OpenList(filter.listId, overHomeOnly = true)
|
||||
is TaskFilter.Saved -> NavRequest.OpenFilter(filter.id, overHomeOnly = true)
|
||||
else -> return@collect
|
||||
}
|
||||
viewSession.takeStartPush()
|
||||
// Not over something another intent opened meanwhile; the nav host checks the user's own steps.
|
||||
if (!navigatedSinceLaunch) navRequest = push
|
||||
}
|
||||
}
|
||||
|
||||
// Surface a single captured crash as a dialog on the next launch.
|
||||
if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this)
|
||||
@@ -97,18 +141,17 @@ class MainActivity : ComponentActivity() {
|
||||
if (savedInstanceState == null) {
|
||||
launchHooks.forEach { hook -> lifecycleScope.launch { runCatching { hook.onLaunch(intent) } } }
|
||||
}
|
||||
holdFirstFrameForAppearance()
|
||||
setContent {
|
||||
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
||||
val ui by settingsViewModel.state.collectAsStateWithLifecycle()
|
||||
val darkTheme = ui.settings.themeMode.isDark(isSystemInDarkTheme())
|
||||
// The stored settings, not a placeholder: until they're read the first
|
||||
// frame is held, so a compact or shaped layout never opens on the defaults.
|
||||
val stored by remember { settingsPrefs.settings }.collectAsStateWithLifecycle(initialValue = null)
|
||||
if (stored != null) SideEffect { appearanceReady = true }
|
||||
val settings = stored ?: Settings()
|
||||
val context = LocalContext.current
|
||||
val use24Hour = ui.settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context))
|
||||
val firstDayOfWeek = ui.settings.effectiveWeekStart
|
||||
AgendulaTheme(
|
||||
darkTheme = darkTheme,
|
||||
dynamicColor = ui.settings.dynamicColor,
|
||||
pureBlack = ui.settings.themeMode.isPureBlack,
|
||||
) {
|
||||
val use24Hour = settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context))
|
||||
val firstDayOfWeek = settings.effectiveWeekStart
|
||||
AgendulaTheme(settings) {
|
||||
CompositionLocalProvider(
|
||||
LocalUse24HourFormat provides use24Hour,
|
||||
LocalFirstDayOfWeek provides firstDayOfWeek,
|
||||
@@ -138,10 +181,39 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the launch window up until the stored appearance is in the first
|
||||
* composition, at most [APPEARANCE_WAIT_MS], so a slow read can't hold the launch.
|
||||
*/
|
||||
private fun holdFirstFrameForAppearance() {
|
||||
val content = findViewById<View>(android.R.id.content)
|
||||
val since = SystemClock.uptimeMillis()
|
||||
content.viewTreeObserver.addOnPreDrawListener(
|
||||
object : ViewTreeObserver.OnPreDrawListener {
|
||||
override fun onPreDraw(): Boolean {
|
||||
val draw = appearanceReady || SystemClock.uptimeMillis() - since > APPEARANCE_WAIT_MS
|
||||
if (draw) content.viewTreeObserver.removeOnPreDrawListener(this)
|
||||
return draw
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
navRequestOf(intent)?.let { navRequest = it }
|
||||
navRequestOf(intent)?.let {
|
||||
navigatedSinceLaunch = true
|
||||
switchViewFor(it)
|
||||
navRequest = it
|
||||
}
|
||||
}
|
||||
|
||||
/** A view's shortcut switches to it at once, so home never shows the one before. */
|
||||
private fun switchViewFor(request: NavRequest) {
|
||||
if (request !is NavRequest.OpenView) return
|
||||
viewSession.switchTo(request.viewId)
|
||||
AppShortcuts.reportUsed(this, request.viewId)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
@@ -164,6 +236,8 @@ class MainActivity : ComponentActivity() {
|
||||
private const val ACTION_OPEN_SMART = "de.jeanlucmakiola.agendula.action.OPEN_SMART"
|
||||
private const val ACTION_OPEN_LIST = "de.jeanlucmakiola.agendula.action.OPEN_LIST"
|
||||
private const val ACTION_OPEN_FILTER = "de.jeanlucmakiola.agendula.action.OPEN_FILTER"
|
||||
private const val ACTION_OPEN_VIEW = "de.jeanlucmakiola.agendula.action.OPEN_VIEW"
|
||||
private const val EXTRA_VIEW_ID = "de.jeanlucmakiola.agendula.extra.VIEW_ID"
|
||||
private const val EXTRA_FILTER_ID = "de.jeanlucmakiola.agendula.extra.FILTER_ID"
|
||||
private const val EXTRA_SMART_LIST = "de.jeanlucmakiola.agendula.extra.SMART_LIST"
|
||||
private const val EXTRA_LIST_ID = "de.jeanlucmakiola.agendula.extra.LIST_ID"
|
||||
@@ -247,6 +321,12 @@ class MainActivity : ComponentActivity() {
|
||||
.putExtra(EXTRA_FILTER_ID, filterId)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/** Opens one view — its launcher shortcut. */
|
||||
fun viewIntent(context: Context, viewId: Long): Intent =
|
||||
Intent(ACTION_OPEN_VIEW, "agendula://view/$viewId".toUri(), context, MainActivity::class.java)
|
||||
.putExtra(EXTRA_VIEW_ID, viewId)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
internal fun navRequestOf(intent: Intent?): NavRequest? {
|
||||
if (intent == null) return null
|
||||
if (BuildConfig.SYNC_ENABLED) {
|
||||
@@ -271,6 +351,8 @@ class MainActivity : ComponentActivity() {
|
||||
?.let { return NavRequest.OpenList(it) }
|
||||
ACTION_OPEN_FILTER -> intent.getLongExtra(EXTRA_FILTER_ID, -1L).takeIf { it > 0L }
|
||||
?.let { return NavRequest.OpenFilter(it) }
|
||||
ACTION_OPEN_VIEW -> intent.getLongExtra(EXTRA_VIEW_ID, -1L).takeIf { it > 0L }
|
||||
?.let { return NavRequest.OpenView(it) }
|
||||
}
|
||||
importIntentUri(intent)?.let { return NavRequest.Import(it) }
|
||||
if (intent.action == Intent.ACTION_SEND && intent.type?.startsWith("text/plain") == true) {
|
||||
@@ -285,3 +367,6 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The longest the first frame waits for the stored appearance. */
|
||||
private const val APPEARANCE_WAIT_MS = 600L
|
||||
@@ -15,6 +15,23 @@ import de.jeanlucmakiola.agendula.domain.DefaultDueDate
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
|
||||
import de.jeanlucmakiola.agendula.domain.NewTaskDates
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.NewTaskOrigin
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.dueWindows
|
||||
import de.jeanlucmakiola.agendula.domain.newTaskPreset
|
||||
import de.jeanlucmakiola.agendula.domain.presetDue
|
||||
import de.jeanlucmakiola.agendula.domain.showsIn
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddParse
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.datesForDue
|
||||
import de.jeanlucmakiola.agendula.domain.datesForTimedDue
|
||||
import de.jeanlucmakiola.agendula.domain.defaultTaskList
|
||||
import de.jeanlucmakiola.agendula.domain.dueVerdict
|
||||
import de.jeanlucmakiola.agendula.domain.listUniverse
|
||||
import de.jeanlucmakiola.agendula.domain.openTaskDated
|
||||
import de.jeanlucmakiola.agendula.domain.scopePreset
|
||||
import de.jeanlucmakiola.agendula.domain.localeWeekStart
|
||||
import de.jeanlucmakiola.agendula.domain.newTaskDates
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
@@ -32,9 +49,17 @@ import de.jeanlucmakiola.agendula.domain.asReminderLead
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSortOrder
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.UpcomingRange
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDestination
|
||||
import de.jeanlucmakiola.agendula.domain.StartDestination
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.withHomeFirst
|
||||
import de.jeanlucmakiola.agendula.domain.withinUpcoming
|
||||
import de.jeanlucmakiola.floret.prefs.ActionStyle
|
||||
import de.jeanlucmakiola.floret.prefs.AppearancePrefs
|
||||
import de.jeanlucmakiola.floret.prefs.LayoutDensity
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.get
|
||||
import de.jeanlucmakiola.floret.prefs.set
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderLead
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverrideCodec
|
||||
@@ -58,19 +83,6 @@ import javax.inject.Singleton
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** [BLACK] is dark with pure-black surfaces, for AMOLED screens. */
|
||||
enum class ThemeMode {
|
||||
SYSTEM, LIGHT, DARK, BLACK;
|
||||
|
||||
fun isDark(systemDark: Boolean): Boolean = when (this) {
|
||||
SYSTEM -> systemDark
|
||||
LIGHT -> false
|
||||
DARK, BLACK -> true
|
||||
}
|
||||
|
||||
val isPureBlack: Boolean get() = this == BLACK
|
||||
}
|
||||
|
||||
/** Clock convention: AUTO follows the device's 24-hour switch. */
|
||||
enum class TimeFormatPref { AUTO, TWELVE_HOUR, TWENTY_FOUR_HOUR }
|
||||
|
||||
@@ -108,6 +120,12 @@ const val DEFAULT_ALL_DAY_REMINDER_MINUTE = 9 * 60
|
||||
data class Settings(
|
||||
val themeMode: ThemeMode = ThemeMode.SYSTEM,
|
||||
val dynamicColor: Boolean = true,
|
||||
/** How tightly rows and tiles pack. */
|
||||
val density: LayoutDensity = LayoutDensity.COMFORTABLE,
|
||||
/** Plain icons or expressive shapes for header and top-bar actions (#118). */
|
||||
val actionStyle: ActionStyle = ActionStyle.ICONS,
|
||||
/** Stops looping animations; the system "Remove animations" does so regardless (#157). */
|
||||
val reduceMotion: Boolean = false,
|
||||
/** The list a new task defaults to; `null` = first available. */
|
||||
val defaultListId: Long? = null,
|
||||
/** Default reminders (0 before due = at due time); empty = none. */
|
||||
@@ -195,8 +213,9 @@ data class Settings(
|
||||
now: Instant = Clock.System.now(),
|
||||
zone: ZoneId = ZoneId.systemDefault(),
|
||||
): SmartView {
|
||||
if (filter !is TaskFilter.Smart) return SmartView(tasks, hiddenByRange = false)
|
||||
val end = if (filter.list == SmartList.UPCOMING) upcomingRange.end(now, zone) else null
|
||||
// A day of the week strip leaves out the same lists as the smart lists, as its dots do.
|
||||
if (filter !is TaskFilter.Smart && filter !is TaskFilter.DueOn) return SmartView(tasks, hiddenByRange = false)
|
||||
val end = if ((filter as? TaskFilter.Smart)?.list == SmartList.UPCOMING) upcomingRange.end(now, zone) else null
|
||||
if (hiddenFromSmartLists.isEmpty() && end == null) return SmartView(tasks, hiddenByRange = false)
|
||||
var hiddenByRange = false
|
||||
val kept = tasks.filter { task ->
|
||||
@@ -256,6 +275,60 @@ data class Settings(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A task from the quick-add bar added from [origin], within [scope] (`null`
|
||||
* for none) read against [clock]; `null` when there is no list to put it in.
|
||||
* It goes where the editor would put one added there: the list [parse] names,
|
||||
* else [origin]'s list, else the one the scope keeps tasks to, else the
|
||||
* default list (one of the filter's or the scope's lists, where it can). It
|
||||
* takes the tags, priority and, without a date of its own, the due date that
|
||||
* keep it in both (see [scopePreset], [newTaskPreset]). [writable] are the lists that take tasks.
|
||||
*/
|
||||
fun quickAddTask(
|
||||
parse: QuickAddParse,
|
||||
scope: Rule?,
|
||||
writable: List<TaskList>,
|
||||
clock: RuleClock,
|
||||
now: Instant = Clock.System.now(),
|
||||
origin: NewTaskOrigin = NewTaskOrigin(),
|
||||
): TaskForm? {
|
||||
fun usable(id: Long?) = id?.takeIf { writable.any { it.id == id } }
|
||||
val preset = scope.scopePreset(clock)
|
||||
val filterPreset = origin.filter?.newTaskPreset(clock.today)
|
||||
val listId = usable(parse.list?.id)
|
||||
?: usable(origin.listId)
|
||||
?: usable(preset.listId)
|
||||
?: defaultTaskList(
|
||||
writable,
|
||||
defaultListId,
|
||||
within = filterPreset?.listIds?.takeIf { it.isNotEmpty() } ?: scope?.listUniverse().orEmpty(),
|
||||
)
|
||||
?: return null
|
||||
val due = parse.due
|
||||
val dates = when {
|
||||
due == null -> {
|
||||
val presetDue = filterPreset?.dueDate ?: preset.dueDate ?: origin.smartList?.dueWindows?.presetDue(clock.today)
|
||||
defaultNewTaskDates(clock.today, now, presetDue) { dates ->
|
||||
val probe = openTaskDated(dates.start, dates.due, dates.isAllDay)
|
||||
dates.showsIn(origin.smartList, origin.filter, clock.todayStart, clock.todayEnd, upcomingRange.end(now, clock.zone), clock) &&
|
||||
(scope == null || scope.dueVerdict(probe, clock) != false)
|
||||
}
|
||||
}
|
||||
due.time == null -> datesForDue(due.date, defaultStartDate, clock.today, now)
|
||||
else -> datesForTimedDue(due.date, due.time, defaultStartDate, clock.today, now, clock.zone)
|
||||
}
|
||||
return TaskForm(
|
||||
title = parse.title,
|
||||
listId = listId,
|
||||
start = dates.start,
|
||||
due = dates.due,
|
||||
isAllDay = dates.isAllDay,
|
||||
startsNow = dates.start == now,
|
||||
priority = maxOf(preset.priority, filterPreset?.priority ?: Priority.NONE),
|
||||
tags = (listOfNotNull(origin.tag) + filterPreset?.tags.orEmpty() + preset.tags).distinct(),
|
||||
)
|
||||
}
|
||||
|
||||
fun persistenceFor(listId: Long): ListPersistence = perListPersistentReminders[listId] ?: ListPersistence.INHERIT
|
||||
|
||||
/** Whether a reminder for a task in [listId] is persistent: its list's override, else the app setting. */
|
||||
@@ -288,9 +361,11 @@ class SettingsPrefs @Inject constructor(
|
||||
val settings: Flow<Settings> = dataStore.data.map { p ->
|
||||
val scope = scopeOf(p)
|
||||
Settings(
|
||||
themeMode = p[THEME_MODE]?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() }
|
||||
?: ThemeMode.SYSTEM,
|
||||
dynamicColor = p[DYNAMIC_COLOR] ?: true,
|
||||
themeMode = p[AppearancePrefs.themeMode],
|
||||
dynamicColor = p[AppearancePrefs.dynamicColor],
|
||||
density = p[AppearancePrefs.density],
|
||||
actionStyle = p[AppearancePrefs.actionStyle],
|
||||
reduceMotion = p[AppearancePrefs.reduceMotion],
|
||||
defaultListId = p[DEFAULT_LIST_ID]?.takeIf { it > 0 },
|
||||
// The single lead of earlier versions carries over until a list is saved.
|
||||
defaultReminders = p[DEFAULT_REMINDERS]?.let(::parseLeads)
|
||||
@@ -465,8 +540,11 @@ class SettingsPrefs @Inject constructor(
|
||||
if (day == null) it.remove(WEEK_START) else it[WEEK_START] = day.name
|
||||
}
|
||||
|
||||
suspend fun setThemeMode(mode: ThemeMode) = dataStore.edit { it[THEME_MODE] = mode.name }
|
||||
suspend fun setDynamicColor(enabled: Boolean) = dataStore.edit { it[DYNAMIC_COLOR] = enabled }
|
||||
suspend fun setThemeMode(mode: ThemeMode) = dataStore.edit { it[AppearancePrefs.themeMode] = mode }
|
||||
suspend fun setDynamicColor(enabled: Boolean) = dataStore.edit { it[AppearancePrefs.dynamicColor] = enabled }
|
||||
suspend fun setDensity(density: LayoutDensity) = dataStore.edit { it[AppearancePrefs.density] = density }
|
||||
suspend fun setActionStyle(style: ActionStyle) = dataStore.edit { it[AppearancePrefs.actionStyle] = style }
|
||||
suspend fun setReduceMotion(enabled: Boolean) = dataStore.edit { it[AppearancePrefs.reduceMotion] = enabled }
|
||||
suspend fun setDefaultListId(id: Long?) = dataStore.edit {
|
||||
if (id == null) it.remove(DEFAULT_LIST_ID) else it[DEFAULT_LIST_ID] = id
|
||||
}
|
||||
@@ -634,13 +712,104 @@ class SettingsPrefs @Inject constructor(
|
||||
.distinctUntilChanged()
|
||||
.flowOn(Dispatchers.Default)
|
||||
|
||||
/**
|
||||
* Stores [view] in place of the one with its id, or after the others; an id of
|
||||
* 0 makes a new one. Returns the view's id, or `null` when the views are stored
|
||||
* by another version and can't be written. Ids are never handed out twice, so
|
||||
* a launcher shortcut to a deleted view can't open a newer one.
|
||||
*/
|
||||
suspend fun saveView(view: View): Long? {
|
||||
var id: Long? = view.id
|
||||
dataStore.edit { p ->
|
||||
if (!ViewCodec.writable(p[VIEWS])) {
|
||||
id = null
|
||||
return@edit
|
||||
}
|
||||
if (view.id <= 0) {
|
||||
val taken = maxOf(ViewCodec.maxId(p[VIEWS]) ?: 0L, View.HOME_ID)
|
||||
val next = maxOf(p[VIEW_NEXT_ID] ?: 0L, taken + 1)
|
||||
p[VIEW_NEXT_ID] = next + 1
|
||||
id = next
|
||||
}
|
||||
p[VIEWS] = ViewCodec.upsert(p[VIEWS], view.copy(id = id!!), modeOf(p).name)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes view [id], never Home; the last used view and the start destination
|
||||
* fall back to Home. Returns false when the views are another version's and
|
||||
* can't be written.
|
||||
*/
|
||||
suspend fun deleteView(id: Long): Boolean {
|
||||
if (id == View.HOME_ID) return false
|
||||
var written = false
|
||||
dataStore.edit { p ->
|
||||
if (!ViewCodec.writable(p[VIEWS])) return@edit
|
||||
written = true
|
||||
p[VIEWS] = ViewCodec.remove(p[VIEWS], id)
|
||||
if (p[ACTIVE_VIEW] == id) p.remove(ACTIVE_VIEW)
|
||||
if (decodeStart(p[START_DESTINATION], modeOf(p).name) == StartDestination.View(id)) p.remove(START_DESTINATION)
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
/** Puts the views in the order of [ids]; Home stays first, as [views] reads it. False when they can't be written. */
|
||||
suspend fun reorderViews(ids: List<Long>): Boolean {
|
||||
var written = false
|
||||
dataStore.edit { p ->
|
||||
if (!ViewCodec.writable(p[VIEWS])) return@edit
|
||||
written = true
|
||||
p[VIEWS] = ViewCodec.reorder(p[VIEWS], ids)
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the stored view [id] by [transform], read and written in one edit.
|
||||
* False when there is no such view or the views can't be written.
|
||||
*/
|
||||
suspend fun updateView(id: Long, transform: (View) -> View): Boolean {
|
||||
var written = false
|
||||
dataStore.edit { p ->
|
||||
if (!ViewCodec.writable(p[VIEWS])) return@edit
|
||||
val mode = modeOf(p).name
|
||||
val view = ViewCodec.decode(p[VIEWS], mode).firstOrNull { it.id == id } ?: return@edit
|
||||
p[VIEWS] = ViewCodec.upsert(p[VIEWS], transform(view), mode)
|
||||
written = true
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
/** Whether the views are stored in a form this version can write. */
|
||||
suspend fun writableViews(): Boolean = ViewCodec.writable(dataStore.data.first()[VIEWS])
|
||||
|
||||
/**
|
||||
* The ids of every stored view, also of one whose line doesn't read; `null`
|
||||
* while the views are another version's, when nothing can be said to be gone.
|
||||
*/
|
||||
val storedViewIds: Flow<Set<Long>?> = dataStore.data.map { p ->
|
||||
if (ViewCodec.writable(p[VIEWS])) ViewCodec.ids(p[VIEWS]) + View.HOME_ID else null
|
||||
}.distinctUntilChanged()
|
||||
|
||||
/** The view last shown; Home until another is. */
|
||||
val activeViewId: Flow<Long> = dataStore.data.map { it[ACTIVE_VIEW] ?: View.HOME_ID }.distinctUntilChanged()
|
||||
|
||||
suspend fun setActiveView(id: Long) = dataStore.edit { it[ACTIVE_VIEW] = id }
|
||||
|
||||
/** Where the app opens (#141); Home until chosen. A list of another store reads as the default. */
|
||||
val startDestination: Flow<StartDestination> =
|
||||
dataStore.data.map { p -> decodeStart(p[START_DESTINATION], modeOf(p).name) }.distinctUntilChanged()
|
||||
|
||||
suspend fun setStartDestination(destination: StartDestination) = dataStore.edit { p ->
|
||||
p[START_DESTINATION] = encodeStart(destination, modeOf(p).name)
|
||||
}
|
||||
|
||||
suspend fun setDefaultEditFields(fields: Set<TaskFormField>) = dataStore.edit {
|
||||
it[DEFAULT_EDIT_FIELDS] = fields.mapTo(mutableSetOf()) { field -> field.name }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val THEME_MODE = stringPreferencesKey("theme_mode")
|
||||
val DYNAMIC_COLOR = booleanPreferencesKey("dynamic_color")
|
||||
val DEFAULT_LIST_ID = longPreferencesKey("default_list_id")
|
||||
val REMINDER_LEAD = intPreferencesKey("reminder_lead_minutes")
|
||||
val DEFAULT_REMINDERS = stringPreferencesKey("default_reminder_minutes")
|
||||
@@ -678,6 +847,9 @@ class SettingsPrefs @Inject constructor(
|
||||
val SAVED_FILTERS = SavedFilterMigration.KEY
|
||||
val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id")
|
||||
val VIEWS = ViewsMigration.KEY
|
||||
val VIEW_NEXT_ID = longPreferencesKey("view_next_id")
|
||||
val ACTIVE_VIEW = longPreferencesKey("active_view")
|
||||
val START_DESTINATION = stringPreferencesKey("start_destination")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -688,6 +860,30 @@ class SettingsPrefs @Inject constructor(
|
||||
*/
|
||||
private val reminderCodec = ReminderOverrideCodec.DEFAULT
|
||||
|
||||
/**
|
||||
* A start destination as stored: `last`, `view:3`, `filter:4`, or `list:OWN:5`
|
||||
* with the list qualified by its store, as the views' are.
|
||||
*/
|
||||
internal fun encodeStart(destination: StartDestination, mode: String): String = when (destination) {
|
||||
StartDestination.LastUsed -> "last"
|
||||
is StartDestination.View -> "view:${destination.id}"
|
||||
is StartDestination.List -> "list:$mode:${destination.id}"
|
||||
is StartDestination.Filter -> "filter:${destination.id}"
|
||||
}
|
||||
|
||||
/** The start destination [stored] names; nothing, or a list of another store than [mode]'s, reads as the default. */
|
||||
internal fun decodeStart(stored: String?, mode: String): StartDestination {
|
||||
val value = stored?.substringAfter(':')
|
||||
return when (stored?.substringBefore(':')) {
|
||||
"last" -> StartDestination.LastUsed
|
||||
"view" -> value?.toLongOrNull()?.let { StartDestination.View(it) }
|
||||
"filter" -> value?.toLongOrNull()?.let { StartDestination.Filter(it) }
|
||||
"list" -> value?.takeIf { it.startsWith("$mode:") }?.substringAfter(':')?.toLongOrNull()
|
||||
?.let { StartDestination.List(it) }
|
||||
else -> null
|
||||
} ?: DefaultStartDestination
|
||||
}
|
||||
|
||||
private fun listPersistencePrefix(mode: String, listId: Long) = "$mode:$listId="
|
||||
|
||||
/** `MODE:listId=ALWAYS|NEVER` entries, [mode]'s only. */
|
||||
|
||||
@@ -83,6 +83,75 @@ internal object ViewCodec {
|
||||
}
|
||||
}.joinToString("\n")
|
||||
|
||||
/**
|
||||
* [raw] with [view] written in place of the stored view with its id, or added
|
||||
* at the end. Lines that don't read stay, those of [view] after its blocks. A
|
||||
* layout of another version is returned as it is: writing over it would lose it.
|
||||
*/
|
||||
fun upsert(raw: String?, view: View, mode: String): String {
|
||||
val layout = Layout.of(raw) ?: return raw.orEmpty()
|
||||
val chunk = layout.chunks.firstOrNull { it.id == view.id }
|
||||
val encoded = encode(listOf(view), mode).lines().drop(1)
|
||||
val written = if (chunk == null) {
|
||||
layout.chunks + Chunk(encoded)
|
||||
} else {
|
||||
val unread = chunk.lines.drop(1).filter { runCatching { decodeBlock(it.split('|'), mode) }.getOrNull() == null }
|
||||
layout.chunks.map { if (it === chunk) Chunk(encoded + unread) else it }
|
||||
}
|
||||
return layout.copy(chunks = written).text()
|
||||
}
|
||||
|
||||
/** Whether a layout stored as [raw] can be written: nothing stored, or this version's. */
|
||||
fun writable(raw: String?): Boolean = Layout.of(raw) != null
|
||||
|
||||
/** The view ids in [raw], read from every view line, also one that doesn't read otherwise. */
|
||||
fun ids(raw: String?): Set<Long> = Layout.of(raw)?.chunks?.mapNotNullTo(HashSet()) { it.id }.orEmpty()
|
||||
|
||||
/** The highest of [ids]. */
|
||||
fun maxId(raw: String?): Long? = ids(raw).maxOrNull()
|
||||
|
||||
/** [raw] without the view [id]; another version's layout is returned as it is. */
|
||||
fun remove(raw: String?, id: Long): String {
|
||||
val layout = Layout.of(raw) ?: return raw.orEmpty()
|
||||
return layout.copy(chunks = layout.chunks.filterNot { it.id == id }).text()
|
||||
}
|
||||
|
||||
/**
|
||||
* [raw] with its views in the order of [ids]. A view [ids] leaves out, and one
|
||||
* that doesn't read, keeps its slot.
|
||||
*/
|
||||
fun reorder(raw: String?, ids: List<Long>): String {
|
||||
val layout = Layout.of(raw) ?: return raw.orEmpty()
|
||||
val named = layout.chunks.filter { it.id in ids }
|
||||
val ordered = named.sortedBy { ids.indexOf(it.id) }.iterator()
|
||||
return layout.copy(chunks = layout.chunks.map { if (it.id in ids) ordered.next() else it }).text()
|
||||
}
|
||||
|
||||
/** One view's lines: its `view` line and the block lines under it. */
|
||||
private class Chunk(val lines: List<String>) {
|
||||
val id: Long? = lines.first().split('|').getOrNull(1)?.toLongOrNull()
|
||||
}
|
||||
|
||||
/** A stored layout of this version: lines before the first view, then each view's. */
|
||||
private data class Layout(val head: List<String>, val chunks: List<Chunk>) {
|
||||
fun text(): String = (listOf(VERSION) + head + chunks.flatMap { it.lines }).joinToString("\n")
|
||||
|
||||
companion object {
|
||||
/** [raw] in chunks; nothing stored reads as an empty layout, another version as `null`. */
|
||||
fun of(raw: String?): Layout? {
|
||||
val lines = raw.orEmpty().split('\n').filter { it.isNotBlank() }
|
||||
if (lines.isEmpty()) return Layout(emptyList(), emptyList())
|
||||
if (lines.first() != VERSION) return null
|
||||
val head = lines.drop(1).takeWhile { !it.startsWith("view|") }
|
||||
val chunks = mutableListOf<MutableList<String>>()
|
||||
lines.drop(1 + head.size).forEach { line ->
|
||||
if (line.startsWith("view|")) chunks += mutableListOf(line) else chunks.last() += line
|
||||
}
|
||||
return Layout(head, chunks.map { Chunk(it) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeView(f: List<String>, mode: String): View? {
|
||||
if (f.size != 6) return null
|
||||
return View(
|
||||
@@ -155,6 +224,7 @@ internal object ViewCodec {
|
||||
"count" to options.count.toString(),
|
||||
"showAll" to flag(options.showAll),
|
||||
"inlineDone" to flag(options.inlineDone),
|
||||
"title" to options.title?.let(::encode),
|
||||
)
|
||||
is BlockOptions.TaskList -> listOf(
|
||||
"sort" to options.sort?.name,
|
||||
@@ -166,8 +236,9 @@ internal object ViewCodec {
|
||||
"counts" to flag(options.counts),
|
||||
)
|
||||
is BlockOptions.SectionHeading -> listOf("text" to encode(options.text))
|
||||
is BlockOptions.RecentlyCompleted -> listOf("count" to options.count.toString())
|
||||
BlockOptions.Tags, BlockOptions.Filters, BlockOptions.WeekStrip -> emptyList()
|
||||
is BlockOptions.RecentlyCompleted -> listOf("count" to options.count.toString(), "title" to options.title?.let(::encode))
|
||||
is BlockOptions.WeekStrip -> listOf("title" to options.title?.let(::encode))
|
||||
BlockOptions.Tags, BlockOptions.Filters -> emptyList()
|
||||
}.mapNotNull { (key, value) -> value?.let { "$key=$it" } }.joinToString(";")
|
||||
|
||||
/** [type]'s options from [p]; a key missing or not reading keeps its default. */
|
||||
@@ -185,6 +256,7 @@ internal object ViewCodec {
|
||||
count = previewCount(p["count"]),
|
||||
showAll = p["showAll"] != "0",
|
||||
inlineDone = p["inlineDone"] == "1",
|
||||
title = text(p["title"]),
|
||||
)
|
||||
BlockType.TASK_LIST -> BlockOptions.TaskList(
|
||||
sort = p["sort"]?.let { enumOrNull<TaskSortOrder>(it) },
|
||||
@@ -198,8 +270,8 @@ internal object ViewCodec {
|
||||
BlockType.TAGS -> BlockOptions.Tags
|
||||
BlockType.FILTERS -> BlockOptions.Filters
|
||||
BlockType.SECTION_HEADING -> BlockOptions.SectionHeading(p["text"]?.let(::decode).orEmpty())
|
||||
BlockType.WEEK_STRIP -> BlockOptions.WeekStrip
|
||||
BlockType.RECENTLY_COMPLETED -> BlockOptions.RecentlyCompleted(previewCount(p["count"]))
|
||||
BlockType.WEEK_STRIP -> BlockOptions.WeekStrip(text(p["title"]))
|
||||
BlockType.RECENTLY_COMPLETED -> BlockOptions.RecentlyCompleted(previewCount(p["count"]), text(p["title"]))
|
||||
}
|
||||
|
||||
/** A stored title; empty reads as none, so the source's own name shows. */
|
||||
|
||||
@@ -99,6 +99,9 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Read as a saved filter's rule is, with the week start only when the rule has weeks in it.
|
||||
is TaskFilter.Matching -> (if (filter.rule.readsWeekStart) settingsPrefs.firstDayOfWeek else flowOf(DayOfWeek.MONDAY))
|
||||
.flatMapLatest { weekStart -> observing { FilteredTasks(loadTasks(filter, weekStart = weekStart)) } }
|
||||
else -> observing { FilteredTasks(loadTasks(filter)) }
|
||||
}
|
||||
|
||||
@@ -134,10 +137,12 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
is TaskFilter.OfLists -> TaskQuery(includeCompleted = true)
|
||||
is TaskFilter.Tagged -> TaskQuery(includeCompleted = true)
|
||||
is TaskFilter.Saved -> TaskQuery(includeCompleted = true)
|
||||
is TaskFilter.DueOn -> TaskQuery(includeCompleted = true)
|
||||
is TaskFilter.Matching -> TaskQuery(includeCompleted = true)
|
||||
}
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), zone)
|
||||
val clock = saved?.let { RuleClock(todayStart, todayEnd, zone, weekStart) }
|
||||
val clock = if (saved != null || filter is TaskFilter.Matching) RuleClock(todayStart, todayEnd, zone, weekStart) else null
|
||||
val all = SeriesCollapse.visible(dataSource.tasks(query))
|
||||
// (done, total) of direct children per parent, over the unfiltered set.
|
||||
val progress: Map<Long, Pair<Int, Int>> = all
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** The due date a new task starts with, counted from the day it is created. */
|
||||
@@ -49,6 +52,30 @@ fun datesForDue(dueDate: LocalDate?, start: DefaultStartDate, today: LocalDate,
|
||||
return NewTaskDates(start = startDate?.let(::allDayInstantOf), due = allDayInstantOf(dueDate), isAllDay = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* The dates a new task due at [time] on [dueDate] opens with: the default [start]
|
||||
* goes along at that time, a start of today being [now]. The start is never
|
||||
* before now nor after the due; a due already past wins, and the start is the due.
|
||||
*/
|
||||
fun datesForTimedDue(
|
||||
dueDate: LocalDate,
|
||||
time: LocalTime,
|
||||
start: DefaultStartDate,
|
||||
today: LocalDate,
|
||||
now: Instant,
|
||||
zone: ZoneId = ZoneId.systemDefault(),
|
||||
): NewTaskDates {
|
||||
fun at(date: LocalDate) = Instant.fromEpochSeconds(LocalDateTime.of(date, time).atZone(zone).toEpochSecond())
|
||||
val due = at(dueDate)
|
||||
val startAt = when (start) {
|
||||
DefaultStartDate.NONE -> null
|
||||
DefaultStartDate.TODAY -> now
|
||||
else -> start.dateFor(dueDate, today)?.let(::at)
|
||||
}
|
||||
// A start counted back to today at the due's time may be past already; it starts now then.
|
||||
return NewTaskDates(start = startAt?.let { minOf(maxOf(it, now), due) }, due = due, isAllDay = false)
|
||||
}
|
||||
|
||||
/**
|
||||
* A new task's dates from the [due] and [start] defaults, or from [presetDue]
|
||||
* when there is no default due, or when the view the task is added from would
|
||||
@@ -88,3 +115,29 @@ fun NewTaskDates.showsIn(
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The list a new task goes to when nothing names one: the default list when it
|
||||
* takes tasks and is one of [within], else the first of [within], else the first
|
||||
* synced list, else any. [within] counts only when one of its lists takes tasks.
|
||||
* [writable] are the lists that take tasks.
|
||||
*/
|
||||
fun defaultTaskList(writable: List<TaskList>, defaultListId: Long?, within: Set<Long> = emptySet()): Long? {
|
||||
val inside = writable.filter { it.id in within }
|
||||
val candidates = inside.ifEmpty { writable }
|
||||
return defaultListId?.takeIf { id -> candidates.any { it.id == id } }
|
||||
?: inside.firstOrNull()?.id
|
||||
?: writable.firstOrNull { !it.isLocal }?.id
|
||||
?: writable.firstOrNull()?.id
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a new task is added from, past a view's scope: the list, tag, saved
|
||||
* filter or smart list a screen or a view's task list shows, which preset it.
|
||||
*/
|
||||
data class NewTaskOrigin(
|
||||
val listId: Long? = null,
|
||||
val tag: String? = null,
|
||||
val filter: SavedFilter? = null,
|
||||
val smartList: SmartList? = null,
|
||||
)
|
||||
@@ -0,0 +1,357 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import java.time.DateTimeException
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.chrono.IsoChronology
|
||||
import java.time.format.DateTimeFormatterBuilder
|
||||
import java.time.format.FormatStyle
|
||||
import java.time.temporal.TemporalAdjusters
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The words the `@date` syntax understands, each lowercase. A word may be in
|
||||
* several languages at once (see [plus]), but must not stand for two things.
|
||||
*/
|
||||
data class QuickAddKeywords(
|
||||
val today: Set<String>,
|
||||
val tomorrow: Set<String>,
|
||||
val nextWeek: Set<String>,
|
||||
val weekdays: Map<DayOfWeek, Set<String>>,
|
||||
val days: Set<String>,
|
||||
val weeks: Set<String>,
|
||||
val months: Set<String>,
|
||||
) {
|
||||
/** These words and [other]'s together. */
|
||||
operator fun plus(other: QuickAddKeywords) = QuickAddKeywords(
|
||||
today = today + other.today,
|
||||
tomorrow = tomorrow + other.tomorrow,
|
||||
nextWeek = nextWeek + other.nextWeek,
|
||||
weekdays = DayOfWeek.entries.associateWith { weekdays[it].orEmpty() + other.weekdays[it].orEmpty() },
|
||||
days = days + other.days,
|
||||
weeks = weeks + other.weeks,
|
||||
months = months + other.months,
|
||||
)
|
||||
|
||||
/** The date words by what they mean, for telling whether one means two things. */
|
||||
val dateWords: Map<String, Set<String>>
|
||||
get() = buildMap {
|
||||
put("today", today)
|
||||
put("tomorrow", tomorrow)
|
||||
put("nextweek", nextWeek)
|
||||
DayOfWeek.entries.forEach { put(it.name, weekdays[it].orEmpty()) }
|
||||
}
|
||||
|
||||
/** The unit letters of a relative date by unit. */
|
||||
val unitWords: Map<String, Set<String>> get() = mapOf("days" to days, "weeks" to weeks, "months" to months)
|
||||
|
||||
/** Words standing for more than one thing, among the date words and among the units. */
|
||||
fun collisions(): Set<String> = listOf(dateWords, unitWords).flatMapTo(HashSet()) { groups ->
|
||||
groups.values.flatMap { it }.groupingBy { it }.eachCount().filterValues { it > 1 }.keys
|
||||
}
|
||||
|
||||
companion object {
|
||||
val English = QuickAddKeywords(
|
||||
today = setOf("today"),
|
||||
tomorrow = setOf("tomorrow"),
|
||||
nextWeek = setOf("nextweek"),
|
||||
weekdays = mapOf(
|
||||
DayOfWeek.MONDAY to setOf("monday", "mon"),
|
||||
DayOfWeek.TUESDAY to setOf("tuesday", "tue"),
|
||||
DayOfWeek.WEDNESDAY to setOf("wednesday", "wed"),
|
||||
DayOfWeek.THURSDAY to setOf("thursday", "thu"),
|
||||
DayOfWeek.FRIDAY to setOf("friday", "fri"),
|
||||
DayOfWeek.SATURDAY to setOf("saturday", "sat"),
|
||||
DayOfWeek.SUNDAY to setOf("sunday", "sun"),
|
||||
),
|
||||
days = setOf("d"),
|
||||
weeks = setOf("w"),
|
||||
months = setOf("m"),
|
||||
)
|
||||
|
||||
/** The words of a comma-separated list, as a translation gives them; one with a space can't be typed in a token. */
|
||||
fun words(list: String): Set<String> =
|
||||
list.split(',').map { it.trim().lowercase(Locale.ROOT) }.filterTo(LinkedHashSet()) { it.isNotEmpty() && it.none(Char::isWhitespace) }
|
||||
|
||||
const val TODAY = "quick_add_keyword_today"
|
||||
const val TOMORROW = "quick_add_keyword_tomorrow"
|
||||
const val NEXT_WEEK = "quick_add_keyword_next_week"
|
||||
const val DAYS = "quick_add_keyword_days"
|
||||
const val WEEKS = "quick_add_keyword_weeks"
|
||||
const val MONTHS = "quick_add_keyword_months"
|
||||
|
||||
/** The string resource translating [day]'s words. */
|
||||
fun weekdayName(day: DayOfWeek) = "quick_add_keyword_${day.name.lowercase(Locale.ROOT)}"
|
||||
|
||||
/** The string resources translating the words, by name; each holds a comma-separated list. */
|
||||
val RESOURCE_NAMES: List<String> = listOf(TODAY, TOMORROW, NEXT_WEEK) + DayOfWeek.entries.map(::weekdayName) + listOf(DAYS, WEEKS, MONTHS)
|
||||
|
||||
/** The words the string resources hold, [get] reading one by name; one it lacks has none. */
|
||||
fun fromTranslations(get: (String) -> String?): QuickAddKeywords {
|
||||
fun of(name: String) = get(name)?.let(::words).orEmpty()
|
||||
return QuickAddKeywords(
|
||||
today = of(TODAY),
|
||||
tomorrow = of(TOMORROW),
|
||||
nextWeek = of(NEXT_WEEK),
|
||||
weekdays = DayOfWeek.entries.associateWith { of(weekdayName(it)) },
|
||||
days = of(DAYS),
|
||||
weeks = of(WEEKS),
|
||||
months = of(MONTHS),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How a locale writes a day and month: `20.11.`, `11/20`, with the year after
|
||||
* them or, where [yearFirst], before them (`26-12-01`).
|
||||
*/
|
||||
data class ShortDateFormat(val dayFirst: Boolean, val separator: Char, val yearFirst: Boolean = false) {
|
||||
companion object {
|
||||
private const val SEPARATORS = "./-"
|
||||
|
||||
/** The short form [locale]'s own short date pattern uses. */
|
||||
fun of(locale: Locale): ShortDateFormat {
|
||||
val pattern = runCatching {
|
||||
DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, null, IsoChronology.INSTANCE, locale)
|
||||
}.getOrDefault("M/d/yy")
|
||||
val day = pattern.indexOf('d')
|
||||
val month = pattern.indexOf('M')
|
||||
if (day < 0 || month < 0) return ShortDateFormat(dayFirst = false, separator = '/')
|
||||
val first = minOf(day, month)
|
||||
val separator = pattern.drop(first).firstOrNull { it in SEPARATORS } ?: '/'
|
||||
val year = pattern.indexOf('y')
|
||||
return ShortDateFormat(dayFirst = day < month, separator = separator, yearFirst = year in 0 until first)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What quick-add reads its input against: [today] and [now], where weeks start, the words and the short date form. */
|
||||
data class QuickAddContext(
|
||||
val today: LocalDate,
|
||||
val weekStart: DayOfWeek,
|
||||
val keywords: QuickAddKeywords = QuickAddKeywords.English,
|
||||
val shortDate: ShortDateFormat = ShortDateFormat(dayFirst = false, separator = '/'),
|
||||
/** The lists a `+list` can name: the ones a task can be added to. */
|
||||
val lists: List<TaskList> = emptyList(),
|
||||
/** The time now, which tells whether a lone `@time` is today's or tomorrow's. */
|
||||
val now: LocalTime = LocalTime.MIDNIGHT,
|
||||
)
|
||||
|
||||
/** A due day, at [time] or all day when it has none. */
|
||||
data class QuickDue(val date: LocalDate, val time: LocalTime? = null)
|
||||
|
||||
/** A recognised token, from [start] up to [end] (exclusive) of the input. */
|
||||
data class QuickToken(val start: Int, val end: Int, val kind: Kind) {
|
||||
enum class Kind { DATE, LIST }
|
||||
}
|
||||
|
||||
/** What quick-add made of an input: the [title] without its tokens, and what they set. */
|
||||
data class QuickAddParse(
|
||||
val title: String,
|
||||
val due: QuickDue? = null,
|
||||
val list: TaskList? = null,
|
||||
val tokens: List<QuickToken> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* The `@date` and `+list` syntax of the quick-add bar.
|
||||
*
|
||||
* A token starts a word: at the start of the input or after whitespace, so
|
||||
* `bob@example.com` and `C++` stay text. It runs to the next whitespace. The
|
||||
* last date and the last list are taken; an earlier one, or one that names
|
||||
* nothing, stays in the title as typed.
|
||||
*
|
||||
* `@date[@time]`, or `@time` alone for today at that time (tomorrow once it has
|
||||
* passed). A token is read as a date first, and as a lone time only when it is
|
||||
* none: `@20.11.` is a day, `@20` is 20:00, `@3d` three days. The date is one of:
|
||||
* - `today`, `tomorrow`, `nextweek` (the first day of next week);
|
||||
* - a weekday, `fri` or `friday`: the next one, a week ahead on that day itself;
|
||||
* - `3d`, `2w`, `1m`: that many days, weeks or months ahead (up to 999);
|
||||
* - `2026-11-20`, or the locale's short form, `20.11.`, `20.11`, `20.11.26`,
|
||||
* `20.11.2026` (`11/20`, `11/20/26`, `26-11-20`…): without a year, a day already past is next year's.
|
||||
*
|
||||
* Words come from [QuickAddKeywords], in any case. The time is `9`, `14:30`, `14h30`, `9am`,
|
||||
* `2:30pm`; with one that doesn't read the whole token stays text.
|
||||
*
|
||||
* `+list` names a list the task can be added to, ignoring case:
|
||||
* - `+"Shared household"`: exactly that name, spaces and all;
|
||||
* - `+Errands`: the list of that name, also with its spaces left out
|
||||
* (`+sharedhousehold`), or else the one list whose name, spaces left out, starts with
|
||||
* it (`+shared`), given at least two letters.
|
||||
*
|
||||
* Two lists of that name, or several starting with it, name none.
|
||||
*/
|
||||
object QuickAddSyntax {
|
||||
|
||||
fun parse(input: String, context: QuickAddContext): QuickAddParse {
|
||||
var due: Pair<QuickDue, QuickToken>? = null
|
||||
var list: Pair<TaskList, QuickToken>? = null
|
||||
var i = 0
|
||||
while (i < input.length) {
|
||||
if (input[i].isWhitespace()) {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
val start = i
|
||||
var end = wordEnd(input, start)
|
||||
if (input[start] == '+') {
|
||||
val quoted = quotedList(input, start, context.lists)
|
||||
if (quoted != null) {
|
||||
end = quoted.second
|
||||
list = quoted.first to QuickToken(start, end, QuickToken.Kind.LIST)
|
||||
} else {
|
||||
listNamed(input.substring(start + 1, end), context.lists)?.let {
|
||||
list = it to QuickToken(start, end, QuickToken.Kind.LIST)
|
||||
}
|
||||
}
|
||||
} else if (input[start] == '@') {
|
||||
parseDue(input.substring(start + 1, end), context)?.let {
|
||||
due = it to QuickToken(start, end, QuickToken.Kind.DATE)
|
||||
}
|
||||
}
|
||||
i = end
|
||||
}
|
||||
val tokens = listOfNotNull(due?.second, list?.second).sortedBy { it.start }
|
||||
return QuickAddParse(title = stripped(input, tokens), due = due?.first, list = list?.first, tokens = tokens)
|
||||
}
|
||||
|
||||
private fun wordEnd(input: String, from: Int): Int {
|
||||
var end = from
|
||||
while (end < input.length && !input[end].isWhitespace()) end++
|
||||
return end
|
||||
}
|
||||
|
||||
/** `+"name"` at [start]: the list and where the token ends, when the quotes close a name that is a list's. */
|
||||
private fun quotedList(input: String, start: Int, lists: List<TaskList>): Pair<TaskList, Int>? {
|
||||
if (input.getOrNull(start + 1) != '"') return null
|
||||
val close = input.indexOf('"', start + 2)
|
||||
if (close < 0) return null
|
||||
val end = close + 1
|
||||
if (end < input.length && !input[end].isWhitespace()) return null
|
||||
val name = input.substring(start + 2, close).trim().lowercase(Locale.ROOT)
|
||||
if (name.isEmpty()) return null
|
||||
val found = lists.filter { it.name.trim().lowercase(Locale.ROOT) == name }
|
||||
return found.singleOrNull()?.let { it to end }
|
||||
}
|
||||
|
||||
/** The list [word] names, by the rules of `+list`; `null` for none, or for more than one. */
|
||||
fun listNamed(word: String, lists: List<TaskList>): TaskList? {
|
||||
val key = word.lowercase(Locale.ROOT)
|
||||
if (key.isEmpty()) return null
|
||||
val exact = lists.filter { it.name.trim().lowercase(Locale.ROOT) == key || compact(it.name) == key }
|
||||
if (exact.isNotEmpty()) return exact.singleOrNull()
|
||||
if (key.length < MIN_PREFIX) return null
|
||||
return lists.filter { compact(it.name).startsWith(key) }.singleOrNull()
|
||||
}
|
||||
|
||||
/** The fewest letters that name a list by the start of its name. */
|
||||
private const val MIN_PREFIX = 2
|
||||
|
||||
private fun compact(name: String) = name.filterNot(Char::isWhitespace).lowercase(Locale.ROOT)
|
||||
|
||||
/** The due [token] (what follows the `@`) stands for, or `null` when it reads as none. */
|
||||
fun parseDue(token: String, context: QuickAddContext): QuickDue? {
|
||||
val at = token.indexOf('@')
|
||||
if (at < 0) {
|
||||
parseDate(token.lowercase(Locale.ROOT), context)?.let { return QuickDue(it) }
|
||||
val time = parseTime(token) ?: return null
|
||||
val day = if (time.isAfter(context.now)) context.today else context.today.plusDays(1)
|
||||
return QuickDue(day, time)
|
||||
}
|
||||
val time = parseTime(token.substring(at + 1)) ?: return null
|
||||
val date = parseDate(token.substring(0, at).lowercase(Locale.ROOT), context) ?: return null
|
||||
return QuickDue(date, time)
|
||||
}
|
||||
|
||||
private val RELATIVE = Regex("""(\d{1,3})(\p{L}+)""")
|
||||
private val ISO = Regex("""(\d{4})-(\d{2})-(\d{2})""")
|
||||
|
||||
private fun parseDate(word: String, context: QuickAddContext): LocalDate? {
|
||||
if (word.isEmpty()) return null
|
||||
val k = context.keywords
|
||||
val today = context.today
|
||||
when (word) {
|
||||
in k.today -> return today
|
||||
in k.tomorrow -> return today.plusDays(1)
|
||||
in k.nextWeek -> return today.with(TemporalAdjusters.previousOrSame(context.weekStart)).plusWeeks(1)
|
||||
}
|
||||
k.weekdays.entries.firstOrNull { word in it.value }?.let { return today.with(TemporalAdjusters.next(it.key)) }
|
||||
RELATIVE.matchEntire(word)?.let { m ->
|
||||
val n = m.groupValues[1].toLong()
|
||||
val unit = m.groupValues[2]
|
||||
return when (unit) {
|
||||
in k.days -> today.plusDays(n)
|
||||
in k.weeks -> today.plusWeeks(n)
|
||||
in k.months -> today.plusMonths(n)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
ISO.matchEntire(word)?.let { m ->
|
||||
return dateOf(m.groupValues[1].toInt(), m.groupValues[2].toInt(), m.groupValues[3].toInt())
|
||||
}
|
||||
return shortDate(word, context)
|
||||
}
|
||||
|
||||
private fun shortDate(word: String, context: QuickAddContext): LocalDate? {
|
||||
val format = context.shortDate
|
||||
val sep = Regex.escape(format.separator.toString())
|
||||
val pattern = if (format.yearFirst) {
|
||||
"""(?:(\d{2}|\d{4})$sep)?(\d{1,2})$sep(\d{1,2})$sep?"""
|
||||
} else {
|
||||
"""(\d{1,2})$sep(\d{1,2})(?:$sep(?:(\d{2}|\d{4}))?)?"""
|
||||
}
|
||||
val groups = Regex(pattern).matchEntire(word)?.groupValues ?: return null
|
||||
val (first, second, yearText) = if (format.yearFirst) listOf(groups[2], groups[3], groups[1]) else groups.drop(1)
|
||||
val day = (if (format.dayFirst) first else second).toInt()
|
||||
val month = (if (format.dayFirst) second else first).toInt()
|
||||
if (yearText.isNotEmpty()) {
|
||||
val year = yearText.toInt().let { if (yearText.length == 2) 2000 + it else it }
|
||||
return dateOf(year, month, day)
|
||||
}
|
||||
val today = context.today
|
||||
val thisYear = dateOf(today.year, month, day)
|
||||
if (thisYear != null && !thisYear.isBefore(today)) return thisYear
|
||||
return dateOf(today.year + 1, month, day)
|
||||
}
|
||||
|
||||
private fun dateOf(year: Int, month: Int, day: Int): LocalDate? =
|
||||
try {
|
||||
LocalDate.of(year, month, day)
|
||||
} catch (_: DateTimeException) {
|
||||
null
|
||||
}
|
||||
|
||||
private val TIME = Regex("""(\d{1,2})(?:[:h](\d{2}))?(am|pm)?""")
|
||||
|
||||
/** `9`, `14:30`, `14h30`, `9am`, `2:30pm`; `null` for anything else. */
|
||||
fun parseTime(text: String): LocalTime? {
|
||||
val match = TIME.matchEntire(text.lowercase(Locale.ROOT)) ?: return null
|
||||
val (hourText, minuteText, half) = match.destructured
|
||||
var hour = hourText.toInt()
|
||||
val minute = minuteText.ifEmpty { "0" }.toInt()
|
||||
if (minute > 59) return null
|
||||
when (half) {
|
||||
"" -> if (hour > 23) return null
|
||||
else -> {
|
||||
if (hour !in 1..12) return null
|
||||
hour = hour % 12 + if (half == "pm") 12 else 0
|
||||
}
|
||||
}
|
||||
return LocalTime.of(hour, minute)
|
||||
}
|
||||
|
||||
/** [input] without [tokens], the gaps they leave closed up. */
|
||||
private fun stripped(input: String, tokens: List<QuickToken>): String {
|
||||
if (tokens.isEmpty()) return input.trim()
|
||||
val parts = ArrayList<String>(tokens.size + 1)
|
||||
var last = 0
|
||||
tokens.sortedBy { it.start }.forEach { token ->
|
||||
parts += input.substring(last, token.start)
|
||||
last = token.end
|
||||
}
|
||||
parts += input.substring(last)
|
||||
return parts.map(String::trim).filter(String::isNotEmpty).joinToString(" ")
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
@@ -23,6 +24,15 @@ sealed interface TaskFilter {
|
||||
data class Tagged(val tag: String) : TaskFilter
|
||||
/** A [SavedFilter] by id; the repository resolves it to its definition. */
|
||||
data class Saved(val id: Long) : TaskFilter
|
||||
|
||||
/** Every task due on [date], open and completed: a day of the week strip. */
|
||||
data class DueOn(val date: LocalDate) : TaskFilter
|
||||
|
||||
/**
|
||||
* Every task [rule] admits, open and completed: a block's custom rules,
|
||||
* read as a [Saved] filter's rule is. [title] names its screen.
|
||||
*/
|
||||
data class Matching(val rule: Rule, val title: String? = null) : TaskFilter
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,6 +63,8 @@ object TaskFiltering {
|
||||
is TaskFilter.Tagged -> filter.tag in task.tags
|
||||
is TaskFilter.Saved -> ruleClock != null &&
|
||||
saved?.takeIf { it.id == filter.id }?.matches(task, ruleClock) == true
|
||||
is TaskFilter.DueOn -> task.dateOf(TaskEnd.DUE, ruleClock?.zone ?: ZoneId.systemDefault()) == filter.date
|
||||
is TaskFilter.Matching -> ruleClock != null && filter.rule.matches(task, ruleClock)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -102,6 +102,9 @@ object TaskGroups {
|
||||
if (due.isNotEmpty() && DueWindow.UPCOMING !in due) add(TaskGrouping.DAY)
|
||||
}
|
||||
is TaskFilter.Tagged -> emptySet()
|
||||
// A single day has no later days to split.
|
||||
is TaskFilter.DueOn -> setOf(TaskGrouping.DAY)
|
||||
is TaskFilter.Matching -> emptySet()
|
||||
}
|
||||
return TaskGrouping.entries - dropped
|
||||
}
|
||||
@@ -137,4 +140,8 @@ fun TaskFilter.groupingKey(): String? = when (this) {
|
||||
is TaskFilter.Tagged -> "tag:$tag"
|
||||
is TaskFilter.Saved -> "saved:$id"
|
||||
is TaskFilter.OfLists -> null
|
||||
// One grouping for every day the week strip opens.
|
||||
is TaskFilter.DueOn -> "dueOn"
|
||||
// One grouping for every block's custom rules.
|
||||
is TaskFilter.Matching -> "rules"
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import de.jeanlucmakiola.floret.components.GridSpan
|
||||
import de.jeanlucmakiola.floret.components.gridRows
|
||||
|
||||
/**
|
||||
* A stored home layout: [blocks] in order, over the tasks [scope] admits (every
|
||||
* task when `null`). Home is the first view.
|
||||
@@ -111,10 +114,12 @@ sealed interface BlockOptions {
|
||||
override val type get() = BlockType.COUNT_TILE
|
||||
}
|
||||
|
||||
/** [title] replaces the source's name when set. */
|
||||
data class Preview(
|
||||
val count: Int = PREVIEW_COUNTS.first(),
|
||||
val showAll: Boolean = true,
|
||||
val inlineDone: Boolean = false,
|
||||
val title: String? = null,
|
||||
) : BlockOptions {
|
||||
init {
|
||||
require(count in PREVIEW_COUNTS) { "Preview count $count" }
|
||||
@@ -153,11 +158,13 @@ sealed interface BlockOptions {
|
||||
override val type get() = BlockType.SECTION_HEADING
|
||||
}
|
||||
|
||||
data object WeekStrip : BlockOptions {
|
||||
/** [title] heads the strip when set. */
|
||||
data class WeekStrip(val title: String? = null) : BlockOptions {
|
||||
override val type get() = BlockType.WEEK_STRIP
|
||||
}
|
||||
|
||||
data class RecentlyCompleted(val count: Int = PREVIEW_COUNTS.first()) : BlockOptions {
|
||||
/** [title] replaces "Recently completed" when set. */
|
||||
data class RecentlyCompleted(val count: Int = PREVIEW_COUNTS.first(), val title: String? = null) : BlockOptions {
|
||||
init {
|
||||
require(count in PREVIEW_COUNTS) { "Preview count $count" }
|
||||
}
|
||||
@@ -178,7 +185,7 @@ sealed interface BlockOptions {
|
||||
BlockType.TAGS -> Tags
|
||||
BlockType.FILTERS -> Filters
|
||||
BlockType.SECTION_HEADING -> SectionHeading()
|
||||
BlockType.WEEK_STRIP -> WeekStrip
|
||||
BlockType.WEEK_STRIP -> WeekStrip()
|
||||
BlockType.RECENTLY_COMPLETED -> RecentlyCompleted()
|
||||
}
|
||||
}
|
||||
@@ -187,8 +194,13 @@ sealed interface BlockOptions {
|
||||
/** The tonal colour roles a count tile can take. */
|
||||
enum class TileColor { PRIMARY, SECONDARY, TERTIARY, ERROR }
|
||||
|
||||
/** The curated icons a view (or a tile) can carry. Stored by name. */
|
||||
enum class ViewIcon { HOME, WORK, PERSON, STAR, CALENDAR, LIST, FLAG, BOLT, HEART, SCHOOL, SHOPPING, FITNESS }
|
||||
/** The curated icons a view (or a tile) can carry, in the picker's order. Stored by name. */
|
||||
enum class ViewIcon {
|
||||
HOME, DASHBOARD, WORK, HEART, BOLT, CALENDAR, TODAY, INBOX, LIST, DONE, FLAG,
|
||||
PERSON, GROUP, STAR, FILTER, TAG, FOLDER, ARCHIVE, ALARM, NOTIFICATIONS, LIGHTBULB,
|
||||
SCHOOL, BOOK, SHOPPING, MONEY, FITNESS, PETS, RESTAURANT, FLIGHT, PLACE, GLOBE,
|
||||
PALETTE, DEVICES, CODE, BUG, BUILD, NOTE, HISTORY, GRID, TREE,
|
||||
}
|
||||
|
||||
/** Where the app opens. */
|
||||
sealed interface StartDestination {
|
||||
@@ -242,27 +254,8 @@ fun List<Block>.normalized(): List<Block> {
|
||||
|
||||
/**
|
||||
* The blocks laid out in rows: a full block alone, half blocks two by two. A half
|
||||
* block followed by a full one, or by nothing, sits alone in its row.
|
||||
* block followed by a full one, or by nothing, sits alone in its row. Packed by
|
||||
* floret-kit's [gridRows], as the edit grid packs them.
|
||||
*/
|
||||
fun List<Block>.rows(): List<List<Block>> {
|
||||
val rows = mutableListOf<List<Block>>()
|
||||
var pending: Block? = null
|
||||
for (block in this) {
|
||||
val half = pending
|
||||
when {
|
||||
block.width == BlockWidth.FULL -> {
|
||||
if (half != null) rows += listOf(half)
|
||||
rows += listOf(block)
|
||||
pending = null
|
||||
}
|
||||
half == null -> pending = block
|
||||
else -> {
|
||||
rows += listOf(half, block)
|
||||
pending = null
|
||||
}
|
||||
}
|
||||
}
|
||||
pending?.let { rows += listOf(it) }
|
||||
return rows
|
||||
}
|
||||
|
||||
fun List<Block>.rows(): List<List<Block>> =
|
||||
gridRows(map { if (it.width == BlockWidth.HALF) GridSpan.Half else GridSpan.Full }).map { row -> row.map(::get) }
|
||||
@@ -0,0 +1,81 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.temporal.TemporalAdjusters
|
||||
|
||||
/*
|
||||
* Editing a view's layout. Each edit returns blocks that keep the layout rules
|
||||
* (see [layoutProblems]): ids stay unique, widths stay the ones a type allows and
|
||||
* a task list stays the only one and the last.
|
||||
*/
|
||||
|
||||
/** Whether a block of [type] can be added to these blocks: a second task list can't. */
|
||||
fun List<Block>.canAdd(type: BlockType): Boolean = type != BlockType.TASK_LIST || none { it.type == BlockType.TASK_LIST }
|
||||
|
||||
/** An id no block here has, nor any of [reserved] (a removed block its undo may bring back). */
|
||||
fun List<Block>.nextBlockId(reserved: Set<Long> = emptySet()): Long =
|
||||
(maxOf(maxOfOrNull { it.id } ?: 0L, reserved.maxOrNull() ?: 0L)) + 1
|
||||
|
||||
/**
|
||||
* These blocks with a new [type] block reading [source], at the end but before
|
||||
* a task list; unchanged when [canAdd] says no or [source] doesn't suit the type.
|
||||
* Its id is none of [reserved] either.
|
||||
*/
|
||||
fun List<Block>.withBlock(type: BlockType, source: BlockSource? = null, reserved: Set<Long> = emptySet()): List<Block> {
|
||||
if (!canAdd(type) || (source != null) != type.takesSource) return this
|
||||
val block = Block(nextBlockId(reserved), type, source)
|
||||
val taskList = indexOfFirst { it.type == BlockType.TASK_LIST }
|
||||
return if (taskList < 0) this + block else toMutableList().apply { add(taskList, block) }
|
||||
}
|
||||
|
||||
/** These blocks without block [id]. */
|
||||
fun List<Block>.without(id: Long): List<Block> = filterNot { it.id == id }
|
||||
|
||||
/**
|
||||
* [block] put back at [index], e.g. undoing its removal; a task list still goes
|
||||
* last. Unchanged when it is here already, or is a task list and one is; given a
|
||||
* new id when another block took its own meanwhile.
|
||||
*/
|
||||
fun List<Block>.restored(block: Block, index: Int): List<Block> {
|
||||
if (any { it == block } || !canAdd(block.type)) return this
|
||||
val back = if (any { it.id == block.id }) block.copy(id = nextBlockId()) else block
|
||||
return toMutableList().apply { add(index.coerceIn(0, size), back) }.normalized()
|
||||
}
|
||||
|
||||
/** These blocks in the order of [ids]; blocks [ids] leaves out keep their place after them. A task list stays last. */
|
||||
fun List<Block>.reordered(ids: List<Long>): List<Block> {
|
||||
val rank = ids.withIndex().associate { (i, id) -> id to i }
|
||||
return withIndex().sortedBy { (i, block) -> rank[block.id] ?: (ids.size + i) }.map { it.value }.normalized()
|
||||
}
|
||||
|
||||
/** Block [id] made [width] wide, when its type allows that width. */
|
||||
fun List<Block>.resized(id: Long, width: BlockWidth): List<Block> =
|
||||
map { if (it.id == id && width in it.type.widths) it.copy(width = width) else it }
|
||||
|
||||
/** [block] in place of the block with its id. */
|
||||
fun List<Block>.replaced(block: Block): List<Block> = map { if (it.id == block.id) block else it }.normalized()
|
||||
|
||||
/** The seven days of the week holding [today], starting on [weekStart]. */
|
||||
fun weekDays(today: LocalDate, weekStart: DayOfWeek): List<LocalDate> {
|
||||
val first = today.with(TemporalAdjusters.previousOrSame(weekStart))
|
||||
return (0L until 7L).map { first.plusDays(it) }
|
||||
}
|
||||
|
||||
/** How many open, top-level tasks of [tasks] are due on each of [days]; days with none are left out. */
|
||||
fun dueCounts(tasks: List<Task>, days: List<LocalDate>, zone: ZoneId): Map<LocalDate, Int> {
|
||||
val wanted = days.toSet()
|
||||
return tasks.asSequence()
|
||||
.filter { !it.isClosed && !it.isSubtask }
|
||||
.mapNotNull { task -> task.dateOf(TaskEnd.DUE, zone)?.takeIf { it in wanted } }
|
||||
.groupingBy { it }
|
||||
.eachCount()
|
||||
}
|
||||
|
||||
/** The [count] completed, top-level tasks completed last, latest first; those without a completion time go last. */
|
||||
fun recentlyCompleted(tasks: List<Task>, count: Int): List<Task> = tasks.asSequence()
|
||||
.filter { it.isCompleted && !it.isSubtask }
|
||||
.sortedWith(compareByDescending<Task, kotlin.time.Instant?>(nullsFirst()) { it.completedAt })
|
||||
.take(count)
|
||||
.toList()
|
||||
@@ -0,0 +1,282 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import java.time.LocalDate
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** The lists this rule names anywhere in it, as a condition or under a [Rule.Not]. */
|
||||
fun Rule.namedListIds(): Set<Long> =
|
||||
flatten().filterIsInstance<Rule.InList>().flatMapTo(HashSet()) { it.listIds.asIterable() }
|
||||
|
||||
/** The lists this rule names outside any [Rule.Not]: the ones that narrow it. */
|
||||
fun Rule.limitingListIds(): Set<Long> = when (this) {
|
||||
is Rule.InList -> listIds
|
||||
is Rule.AllOf -> children.flatMapTo(HashSet()) { it.limitingListIds() }
|
||||
is Rule.AnyOf -> children.flatMapTo(HashSet()) { it.limitingListIds() }
|
||||
is Rule.Not, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> emptySet()
|
||||
}
|
||||
|
||||
/**
|
||||
* What a new task gets so that a scope admits it, read from the conditions every
|
||||
* task in it meets: the [listId] when they leave one list, their [tags], the
|
||||
* least [priority] and a [dueDate] (see [scopePreset]).
|
||||
*/
|
||||
data class ScopePreset(
|
||||
val listId: Long? = null,
|
||||
val tags: List<String> = emptyList(),
|
||||
val priority: Priority = Priority.NONE,
|
||||
val dueDate: LocalDate? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* The [ScopePreset] of this scope. The list is the one every task in it is in
|
||||
* (see [listUniverse]); otherwise only the conditions at its top, alone or joined
|
||||
* by all-of, count, and one under any-of or not says nothing a task can be given. The due date is the first of none, today and tomorrow that the top's
|
||||
* due conditions all admit; none of them, or no due condition, leaves it empty.
|
||||
*/
|
||||
fun Rule?.scopePreset(clock: RuleClock): ScopePreset {
|
||||
val required = this?.requiredConditions().orEmpty()
|
||||
val listId = this?.listUniverse()?.singleOrNull()
|
||||
if (required.isEmpty()) return ScopePreset(listId = listId)
|
||||
val dues = required.filterIsInstance<Rule.Due>()
|
||||
val dueDate = if (dues.isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
listOf(clock.today, clock.today.plusDays(1))
|
||||
.takeUnless { dues.all { it.spec.matches(openTaskDated(null, null, false), clock) } }
|
||||
?.firstOrNull { day -> dues.all { it.spec.matches(openTaskDated(null, allDayInstantOf(day), true), clock) } }
|
||||
}
|
||||
return ScopePreset(
|
||||
listId = listId,
|
||||
tags = required.filterIsInstance<Rule.HasTag>().map { it.tag }.distinct(),
|
||||
priority = required.filterIsInstance<Rule.MinPriority>().maxOfOrNull { it.priority } ?: Priority.NONE,
|
||||
dueDate = dueDate,
|
||||
)
|
||||
}
|
||||
|
||||
private fun Rule.requiredConditions(): List<Rule> = when (this) {
|
||||
is Rule.AllOf -> children.flatMap { it.requiredConditions() }
|
||||
is Rule.AnyOf, is Rule.Not -> emptyList()
|
||||
is Rule.InList, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> listOf(this)
|
||||
}
|
||||
|
||||
/** An open task with this form's list, tags, priority and dates, to ask a scope whether it shows it. */
|
||||
fun TaskForm.asOpenTask(): Task = openTaskDated(start, due, isAllDay).copy(listId = listId, tags = tags, priority = priority)
|
||||
|
||||
/**
|
||||
* The lists a task has to be in to pass this rule, or `null` when a task of any
|
||||
* list can. Read from list conditions joined by [Rule.AllOf] and [Rule.AnyOf]; a
|
||||
* [Rule.Not] says nothing about where a task is.
|
||||
*/
|
||||
fun Rule.listUniverse(): Set<Long>? = when (this) {
|
||||
is Rule.InList -> listIds
|
||||
is Rule.AllOf -> children.mapNotNull { it.listUniverse() }.reduceOrNull { a, b -> a intersect b }
|
||||
is Rule.AnyOf -> children.map { it.listUniverse() }.let { universes ->
|
||||
if (null in universes) null else universes.flatMapTo(HashSet()) { it.orEmpty() }
|
||||
}
|
||||
is Rule.Not, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* A view's scope as it applies now. [rule] is the stored scope without the lists
|
||||
* since deleted ([goneLists]), so a list condition left with none matches nothing
|
||||
* rather than every list; `null` admits every task. [namedLists] are the lists the
|
||||
* scope still names, which show even when kept out of the smart lists.
|
||||
*/
|
||||
data class AppliedScope(
|
||||
val rule: Rule?,
|
||||
val goneLists: Set<Long> = emptySet(),
|
||||
val namedLists: Set<Long> = emptySet(),
|
||||
/**
|
||||
* Whether a gone list narrowed the scope, so that part now matches nothing.
|
||||
* One under a [Rule.Not] widens it instead, which needs no notice.
|
||||
*/
|
||||
val narrowedByGone: Boolean = false,
|
||||
) {
|
||||
fun admits(task: Task, clock: RuleClock): Boolean = rule == null || rule.matches(task, clock)
|
||||
|
||||
/** [hidden], the lists kept out of the smart lists, less the ones this scope names. */
|
||||
fun hiddenFromSmart(hidden: Set<Long>): Set<Long> = if (namedLists.isEmpty()) hidden else hidden - namedLists
|
||||
|
||||
/** The lists a task in this scope can be in; `null` when any. */
|
||||
val lists: Set<Long>? get() = rule?.listUniverse()
|
||||
|
||||
companion object {
|
||||
val None = AppliedScope(null)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This view's scope against the lists that [exist]. A read that found no list at
|
||||
* all proves nothing, so then no list counts as gone.
|
||||
*/
|
||||
fun View.appliedScope(exist: Set<Long>): AppliedScope {
|
||||
val scope = scope ?: return AppliedScope.None
|
||||
val named = scope.namedListIds()
|
||||
val gone = if (exist.isEmpty()) emptySet() else named - exist
|
||||
val rule = if (gone.isEmpty()) scope else scope.withoutListIds { it in gone }
|
||||
return AppliedScope(rule, gone, named - gone, narrowedByGone = gone.any { it in scope.limitingListIds() })
|
||||
}
|
||||
|
||||
/** The scope [block] reads its tasks through: none when it ignores the view's. */
|
||||
fun AppliedScope.forBlock(block: Block): AppliedScope = if (block.ignoreScope) AppliedScope.None else this
|
||||
|
||||
/**
|
||||
* Whether this source no longer exists: a list or saved filter since deleted. A
|
||||
* read that found no list at all proves nothing about a list.
|
||||
*/
|
||||
fun BlockSource.isGone(lists: Set<Long>, filters: Set<Long>): Boolean = when (this) {
|
||||
is BlockSource.List -> lists.isNotEmpty() && listId !in lists
|
||||
is BlockSource.Filter -> filterId !in filters
|
||||
is BlockSource.Smart, is BlockSource.ListElsewhere, is BlockSource.Tag, is BlockSource.Rules -> false
|
||||
}
|
||||
|
||||
/**
|
||||
* What a block's source is read against: [clock]'s day, Upcoming ending at
|
||||
* [upcomingEnd] (`null` for no end), and the saved [filters] by id.
|
||||
*/
|
||||
class SourceContext(
|
||||
val clock: RuleClock,
|
||||
val upcomingEnd: Instant?,
|
||||
val filters: Map<Long, SavedFilter>,
|
||||
)
|
||||
|
||||
/**
|
||||
* Whether [task] is in this source. A smart list goes by its own rules, statuses
|
||||
* included, and leaves out the lists in [hidden]; any other source by what the
|
||||
* task is, whatever its status. A list of another store holds nothing here.
|
||||
*/
|
||||
fun BlockSource.contains(task: Task, context: SourceContext, hidden: Set<Long> = emptySet()): Boolean {
|
||||
val clock = context.clock
|
||||
return when (this) {
|
||||
is BlockSource.Smart -> task.listId !in hidden && TaskFiltering.matches(
|
||||
task,
|
||||
TaskFilter.Smart(smart),
|
||||
clock.todayStart,
|
||||
clock.todayEnd,
|
||||
upcomingEnd = context.upcomingEnd,
|
||||
)
|
||||
is BlockSource.List -> task.listId == listId
|
||||
is BlockSource.ListElsewhere -> false
|
||||
is BlockSource.Tag -> tag in task.tags
|
||||
is BlockSource.Filter -> context.filters[filterId]?.rule?.matches(task, clock) == true
|
||||
is BlockSource.Rules -> rule.matches(task, clock)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a count or preview of this source shows [task]: an open task in it, or
|
||||
* a completed one for the Completed list.
|
||||
*/
|
||||
fun BlockSource.counts(task: Task, context: SourceContext, hidden: Set<Long> = emptySet()): Boolean {
|
||||
val completedList = this == BlockSource.Smart(SmartList.COMPLETED)
|
||||
return (if (completedList) task.isCompleted else !task.isClosed) && contains(task, context, hidden)
|
||||
}
|
||||
|
||||
/** The task screen this source opens; `null` for one that has none. */
|
||||
val BlockSource.taskFilter: TaskFilter?
|
||||
get() = when (this) {
|
||||
is BlockSource.Smart -> TaskFilter.Smart(smart)
|
||||
is BlockSource.List -> TaskFilter.OfList(listId)
|
||||
is BlockSource.Tag -> TaskFilter.Tagged(tag)
|
||||
is BlockSource.Filter -> TaskFilter.Saved(filterId)
|
||||
is BlockSource.Rules -> TaskFilter.Matching(rule)
|
||||
is BlockSource.ListElsewhere -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* A new view showing [scope]'s tasks, named [name]: one task list over everything
|
||||
* in it, completed ones included, with the quick-add bar.
|
||||
*/
|
||||
fun pinnedView(id: Long, name: String, icon: ViewIcon, scope: Rule): View = View(
|
||||
id = id,
|
||||
name = name,
|
||||
icon = icon,
|
||||
scope = scope,
|
||||
blocks = listOf(Block(1, BlockType.TASK_LIST, BlockSource.Smart(SmartList.ALL))),
|
||||
quickAdd = true,
|
||||
)
|
||||
|
||||
/**
|
||||
* The view pinning [list], or else [filter], makes: named after it, with its
|
||||
* scope, and an id of 0 for the store to give it one. `null` with neither.
|
||||
*/
|
||||
fun pinnedViewOf(list: TaskList?, filter: SavedFilter?): View? = when {
|
||||
list != null -> pinnedView(0, list.name, ViewIcon.LIST, Rule.InList(setOf(list.id)))
|
||||
filter != null -> pinnedView(0, filter.name, ViewIcon.FILTER, filter.rule)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** A new view with no scope and Home's default blocks. */
|
||||
fun newView(id: Long, name: String): View = View.home().copy(id = id, name = name, icon = ViewIcon.DASHBOARD)
|
||||
|
||||
/**
|
||||
* These views in the order of [ids], Home first whatever [ids] says. Views [ids]
|
||||
* leaves out keep their place after the ones it names.
|
||||
*/
|
||||
fun List<View>.reordered(ids: List<Long>): List<View> {
|
||||
val rank = ids.withIndex().associate { (i, id) -> id to i }
|
||||
val (home, rest) = partition { it.id == View.HOME_ID }
|
||||
return home + rest.withIndex().sortedBy { (i, view) -> rank[view.id] ?: (ids.size + i) }.map { it.value }
|
||||
}
|
||||
|
||||
/** Whether a view can be deleted: any but Home. */
|
||||
val View.deletable: Boolean get() = id != View.HOME_ID
|
||||
|
||||
/**
|
||||
* Where the app opens: the view [viewId] shows, with [push] (a list or filter)
|
||||
* on top of it when the start destination is one.
|
||||
*/
|
||||
data class StartPlan(val viewId: Long, val push: TaskFilter? = null)
|
||||
|
||||
/**
|
||||
* How this start destination opens, given the [views] there are and the one
|
||||
* [lastUsed]. A list or filter opens over Home, so back leads there; one since
|
||||
* deleted opens Home alone, as does a view since deleted. [lists] are the lists
|
||||
* there are, `null` when they couldn't be read, and then a list is opened anyway.
|
||||
*/
|
||||
fun StartDestination.plan(views: Set<Long>, lastUsed: Long, lists: Set<Long>?, filters: Set<Long>): StartPlan {
|
||||
fun known(id: Long) = id.takeIf { it in views } ?: View.HOME_ID
|
||||
return when (this) {
|
||||
StartDestination.LastUsed -> StartPlan(known(lastUsed))
|
||||
is StartDestination.View -> StartPlan(known(id))
|
||||
is StartDestination.List ->
|
||||
StartPlan(View.HOME_ID, TaskFilter.OfList(id).takeIf { lists == null || id in lists })
|
||||
is StartDestination.Filter -> StartPlan(View.HOME_ID, TaskFilter.Saved(id).takeIf { id in filters })
|
||||
}
|
||||
}
|
||||
|
||||
/** The start destination before one is chosen. */
|
||||
val DefaultStartDestination: StartDestination = StartDestination.View(View.HOME_ID)
|
||||
|
||||
/**
|
||||
* How much of this source is done today, as `done to total` over [tasks] that
|
||||
* [admits] lets through. Today counts its own rows, completed ones included. Any
|
||||
* other source counts its open tasks and those completed today that it would hold
|
||||
* were they open, so the ring fills as the day's work gets done rather than with
|
||||
* everything ever completed. Completed, all done by definition, counts what was
|
||||
* completed today against itself.
|
||||
*/
|
||||
fun BlockSource.progress(
|
||||
tasks: List<Task>,
|
||||
context: SourceContext,
|
||||
hidden: Set<Long>,
|
||||
admits: (Task) -> Boolean,
|
||||
): Pair<Int, Int> {
|
||||
val clock = context.clock
|
||||
val shown = tasks.filter(admits)
|
||||
fun doneToday(task: Task): Boolean {
|
||||
val at = task.completedAt
|
||||
return task.isCompleted && at != null && at >= clock.todayStart && at < clock.todayEnd
|
||||
}
|
||||
if (this == BlockSource.Smart(SmartList.COMPLETED)) {
|
||||
val done = shown.count { doneToday(it) && contains(it, context, hidden) }
|
||||
return done to done
|
||||
}
|
||||
if (this == BlockSource.Smart(SmartList.TODAY)) {
|
||||
val inToday = shown.filter { contains(it, context, hidden) }
|
||||
return inToday.count { it.isClosed } to inToday.size
|
||||
}
|
||||
val open = shown.count { !it.isClosed && contains(it, context, hidden) }
|
||||
val done = shown.count { doneToday(it) && contains(it.copy(status = TaskStatus.NEEDS_ACTION), context, hidden) }
|
||||
return done to open + done
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.MaterialShapes
|
||||
import androidx.graphics.shapes.RoundedPolygon
|
||||
|
||||
/**
|
||||
* Named shapes for the app's top-bar actions, so each action is recognisably
|
||||
* "its own" when the expressive button style is on, and new actions just pick
|
||||
* the next unused shape. Expose the expressive [MaterialShapes] through a
|
||||
* single opt-in site.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
object ActionShapes {
|
||||
/** Settings — a 4-sided cookie (rounded, scalloped square). */
|
||||
val Settings: RoundedPolygon get() = MaterialShapes.Cookie4Sided
|
||||
|
||||
/** Search — a 6-sided cookie, the same family as [Settings] but distinct. */
|
||||
val Search: RoundedPolygon get() = MaterialShapes.Cookie6Sided
|
||||
|
||||
/** New list — a sunny burst beside the Lists header. */
|
||||
val AddList: RoundedPolygon get() = MaterialShapes.Sunny
|
||||
|
||||
/** New view — the same burst as [AddList], beside the views it adds to. */
|
||||
val AddView: RoundedPolygon get() = MaterialShapes.Sunny
|
||||
|
||||
/** What [AddList], [AddFilter] and [AddView] morph into on press. */
|
||||
val AddListPressed: RoundedPolygon get() = MaterialShapes.Circle
|
||||
|
||||
/** New filter — the same burst as [AddList], so both "add" actions read alike. */
|
||||
val AddFilter: RoundedPolygon get() = MaterialShapes.Sunny
|
||||
|
||||
/** Reorder the lists — a four-leaf clover. */
|
||||
val Reorder: RoundedPolygon get() = MaterialShapes.Clover4Leaf
|
||||
|
||||
/** A list's view options (sort, group, filter) — a 9-sided cookie. */
|
||||
val ViewOptions: RoundedPolygon get() = MaterialShapes.Cookie9Sided
|
||||
|
||||
/** Edit a task, list or filter — a flower. */
|
||||
val Edit: RoundedPolygon get() = MaterialShapes.Flower
|
||||
|
||||
/** Delete — a pentagon, set apart from the softer shapes. */
|
||||
val Delete: RoundedPolygon get() = MaterialShapes.Pentagon
|
||||
|
||||
/** The overflow menu — a puffy cloud. */
|
||||
val More: RoundedPolygon get() = MaterialShapes.Puffy
|
||||
|
||||
/** Add a block to a view's layout — the same burst as the other "add" actions. */
|
||||
val AddBlock: RoundedPolygon get() = MaterialShapes.Sunny
|
||||
|
||||
/** Switch a block between half and full width — a pill, wide like what it makes. */
|
||||
val ResizeBlock: RoundedPolygon get() = MaterialShapes.Pill
|
||||
|
||||
/** Throw away a layout's edits — a clover, apart from the softer ✓ beside it. */
|
||||
val DiscardLayout: RoundedPolygon get() = MaterialShapes.Clover8Leaf
|
||||
|
||||
/** Open what the quick-add bar holds in the full editor — a gem, apart from the round ✓ beside it. */
|
||||
val ExpandQuickAdd: RoundedPolygon get() = MaterialShapes.Gem
|
||||
|
||||
/** Take a block out of a layout — a soft burst, apart from [Delete], since it can be undone. */
|
||||
val RemoveBlock: RoundedPolygon get() = MaterialShapes.SoftBurst
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialShapes
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.toPath
|
||||
import androidx.compose.material3.toShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Matrix
|
||||
import androidx.compose.ui.graphics.Outline
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.graphics.shapes.Morph
|
||||
import androidx.graphics.shapes.RoundedPolygon
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* A top-bar action whose icon sits in a tonal container clipped to one of the
|
||||
* M3 Expressive [MaterialShapes] (cookie, clover, sunny, …) — Agendula's playful
|
||||
* take on a plain [androidx.compose.material3.IconButton]. Each action passes
|
||||
* its own [shape] and [containerColor], so a row of them reads as a set of
|
||||
* distinct little tokens rather than identical grey glyphs.
|
||||
*
|
||||
* Pressing springs the whole shape down and gives it a turn — the scalloped
|
||||
* container is what dips and spins, while the glyph inside stays upright (a
|
||||
* spinning magnifier or list icon would just read as wrong). [spinIcon] opts a
|
||||
* glyph into turning too, for icons that read well mid-spin like the gear.
|
||||
*
|
||||
* With [morphTo] set the press is a different gesture altogether: no turn and no
|
||||
* dip — the container morphs into [morphTo] and pops slightly larger on a bouncy
|
||||
* spring, for an action that should not feel like its neighbours. A tap holds
|
||||
* the popped state for a beat before [onClick] fires, so the gesture is seen.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
fun ShapedActionButton(
|
||||
shape: RoundedPolygon,
|
||||
icon: ImageVector,
|
||||
contentDescription: String?,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
containerColor: Color = MaterialTheme.colorScheme.tertiaryContainer,
|
||||
contentColor: Color = MaterialTheme.colorScheme.onTertiaryContainer,
|
||||
size: Dp = 40.dp,
|
||||
iconSize: Dp = 22.dp,
|
||||
spinIcon: Boolean = false,
|
||||
morphTo: RoundedPolygon? = null,
|
||||
) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
if (morphTo != null) {
|
||||
MorphPopButton(shape, morphTo, icon, contentDescription, onClick, modifier, containerColor, contentColor, size, iconSize, interaction, pressed)
|
||||
return
|
||||
}
|
||||
// The shape (the scalloped cookie) turns and dips on press.
|
||||
val shapeRotation by animateFloatAsState(if (pressed) 40f else 0f, label = "shapeRotation")
|
||||
val scale by animateFloatAsState(if (pressed) 0.82f else 1f, label = "shapeScale")
|
||||
// The glyph's *net* turn: 0 keeps it upright, spinIcon gives it a quarter turn.
|
||||
val iconRotation by animateFloatAsState(
|
||||
if (pressed && spinIcon) 90f else 0f,
|
||||
label = "iconRotation",
|
||||
)
|
||||
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
modifier = modifier
|
||||
.size(size)
|
||||
.scale(scale)
|
||||
.rotate(shapeRotation),
|
||||
shape = shape.toShape(),
|
||||
color = containerColor,
|
||||
contentColor = contentColor,
|
||||
interactionSource = interaction,
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = contentDescription,
|
||||
// Counter the container's turn so the glyph's net rotation is just
|
||||
// [iconRotation] — upright by default, a quarter turn for the gear.
|
||||
modifier = Modifier
|
||||
.size(iconSize)
|
||||
.rotate(iconRotation - shapeRotation),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MorphPopButton(
|
||||
shape: RoundedPolygon,
|
||||
morphTo: RoundedPolygon,
|
||||
icon: ImageVector,
|
||||
contentDescription: String?,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier,
|
||||
containerColor: Color,
|
||||
contentColor: Color,
|
||||
size: Dp,
|
||||
iconSize: Dp,
|
||||
interaction: MutableInteractionSource,
|
||||
pressed: Boolean,
|
||||
) {
|
||||
val morph = remember(shape, morphTo) { Morph(shape, morphTo) }
|
||||
val scope = rememberCoroutineScope()
|
||||
var firing by remember { mutableStateOf(false) }
|
||||
val popped = pressed || firing
|
||||
val bouncy = spring<Float>(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessMedium)
|
||||
val progress by animateFloatAsState(if (popped) 1f else 0f, bouncy, label = "morphProgress")
|
||||
val scale by animateFloatAsState(if (popped) 1.12f else 1f, bouncy, label = "popScale")
|
||||
val iconScale by animateFloatAsState(if (popped) 1.2f else 1f, bouncy, label = "iconScale")
|
||||
|
||||
Surface(
|
||||
onClick = {
|
||||
if (!firing) {
|
||||
firing = true
|
||||
scope.launch {
|
||||
delay(MorphClickDelayMs)
|
||||
onClick()
|
||||
firing = false
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = modifier.size(size).scale(scale),
|
||||
shape = remember(morph, progress) { MorphShape(morph, progress) },
|
||||
color = containerColor,
|
||||
contentColor = contentColor,
|
||||
interactionSource = interaction,
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = contentDescription,
|
||||
modifier = Modifier.size(iconSize).scale(iconScale),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val MorphClickDelayMs = 160L
|
||||
|
||||
/** [morph] at [progress], scaled from the shapes' unit square to the component. */
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
private class MorphShape(private val morph: Morph, private val progress: Float) : Shape {
|
||||
override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline {
|
||||
val path = morph.toPath(progress.coerceIn(0f, 1f), Path())
|
||||
path.transform(Matrix().apply { scale(size.width, size.height) })
|
||||
return Outline.Generic(path)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Named shapes for the app's top-bar actions, so each action is recognisably
|
||||
* "its own" and new actions just pick the next unused shape. Expose the
|
||||
* expressive [MaterialShapes] through a single opt-in site.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
object ActionShapes {
|
||||
/** Settings — a 4-sided cookie (rounded, scalloped square). */
|
||||
val Settings: RoundedPolygon get() = MaterialShapes.Cookie4Sided
|
||||
|
||||
/** Search — a 6-sided cookie, the same family as [Settings] but distinct. */
|
||||
val Search: RoundedPolygon get() = MaterialShapes.Cookie6Sided
|
||||
|
||||
/** New list — a sunny burst beside the Lists header. */
|
||||
val AddList: RoundedPolygon get() = MaterialShapes.Sunny
|
||||
|
||||
/** What [AddList] morphs into on press. */
|
||||
val AddListPressed: RoundedPolygon get() = MaterialShapes.Circle
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package de.jeanlucmakiola.agendula.ui.common
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxScope
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
@@ -13,11 +14,14 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.floret.components.BusyIndicator
|
||||
import de.jeanlucmakiola.floret.identity.rememberLoopingMotion
|
||||
|
||||
/**
|
||||
* Pull down to sync every account (#73). Without an account there is nothing
|
||||
* to sync, so the gesture is off. [topPadding] keeps the indicator below a top
|
||||
* bar the content scrolls under.
|
||||
* bar the content scrolls under. Under reduced motion the indicator is a still
|
||||
* ring rather than the morphing loading shape (#157).
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
@@ -34,17 +38,31 @@ fun SyncPullBox(
|
||||
return
|
||||
}
|
||||
val state = rememberPullToRefreshState()
|
||||
val looping = rememberLoopingMotion()
|
||||
PullToRefreshBox(
|
||||
isRefreshing = syncing,
|
||||
onRefresh = onSync,
|
||||
modifier = modifier,
|
||||
state = state,
|
||||
indicator = {
|
||||
PullToRefreshDefaults.LoadingIndicator(
|
||||
state = state,
|
||||
isRefreshing = syncing,
|
||||
modifier = Modifier.align(Alignment.TopCenter).padding(top = topPadding),
|
||||
)
|
||||
val placement = Modifier.align(Alignment.TopCenter).padding(top = topPadding)
|
||||
if (looping) {
|
||||
PullToRefreshDefaults.LoadingIndicator(state = state, isRefreshing = syncing, modifier = placement)
|
||||
} else {
|
||||
// Reduced motion: a still ring that fills with the pull and stays full while syncing.
|
||||
PullToRefreshDefaults.IndicatorBox(
|
||||
state = state,
|
||||
isRefreshing = syncing,
|
||||
modifier = placement,
|
||||
containerColor = PullToRefreshDefaults.loadingIndicatorContainerColor,
|
||||
) {
|
||||
BusyIndicator(
|
||||
progress = { if (syncing) 1f else state.distanceFraction.coerceIn(0f, 1f) },
|
||||
modifier = Modifier.size(24.dp),
|
||||
strokeWidth = 2.5.dp,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
content = content,
|
||||
)
|
||||
|
||||
@@ -51,8 +51,8 @@ import androidx.compose.material.icons.rounded.Notifications
|
||||
import androidx.compose.material.icons.rounded.Repeat
|
||||
import androidx.compose.material.icons.rounded.MoreVert
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import de.jeanlucmakiola.floret.components.FloretMenu
|
||||
import de.jeanlucmakiola.floret.components.FloretMenuItem
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -80,10 +80,10 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
@@ -111,6 +111,10 @@ import de.jeanlucmakiola.floret.time.formatTime
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.priorityLabel
|
||||
import androidx.compose.animation.core.spring
|
||||
import de.jeanlucmakiola.agendula.ui.common.ActionShapes
|
||||
import de.jeanlucmakiola.floret.components.ActionButton
|
||||
import de.jeanlucmakiola.floret.identity.reducibleSpec
|
||||
|
||||
/**
|
||||
* One task's detail. Each fact is its own tonal card with a leading icon (the
|
||||
@@ -148,44 +152,49 @@ fun TaskDetailScreen(
|
||||
val content = state as? TaskDetailUiState.Content
|
||||
// A read-only share: an edit would never reach the server.
|
||||
val writable = content != null && !content.detail.task.isReadOnly
|
||||
IconButton(onClick = { content?.let { onEdit(it.detail.task) } }, enabled = writable) {
|
||||
Icon(Icons.Rounded.Edit, contentDescription = stringResource(R.string.edit))
|
||||
}
|
||||
IconButton(
|
||||
ActionButton(
|
||||
shape = ActionShapes.Edit,
|
||||
icon = Icons.Rounded.Edit,
|
||||
contentDescription = stringResource(R.string.edit),
|
||||
onClick = { content?.let { onEdit(it.detail.task) } },
|
||||
enabled = writable,
|
||||
)
|
||||
ActionButton(
|
||||
shape = ActionShapes.Delete,
|
||||
icon = Icons.Rounded.Delete,
|
||||
contentDescription = stringResource(R.string.delete),
|
||||
onClick = { confirmDelete = true },
|
||||
enabled = writable,
|
||||
) {
|
||||
Icon(Icons.Rounded.Delete, contentDescription = stringResource(R.string.delete))
|
||||
}
|
||||
)
|
||||
// On an occurrence of a series, cancelling reaches only that occurrence.
|
||||
val task = content?.detail?.task
|
||||
if (task != null) {
|
||||
var menuOpen by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
IconButton(onClick = { menuOpen = true }) {
|
||||
Icon(Icons.Rounded.MoreVert, contentDescription = stringResource(R.string.more_options))
|
||||
}
|
||||
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
|
||||
val cancelled = task.status == TaskStatus.CANCELLED
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Text(stringResource(if (cancelled) R.string.detail_restore else R.string.detail_cancel_task))
|
||||
},
|
||||
onClick = {
|
||||
menuOpen = false
|
||||
viewModel.setCancelled(task, !cancelled)
|
||||
},
|
||||
)
|
||||
if (writable) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.detail_duplicate)) },
|
||||
onClick = {
|
||||
menuOpen = false
|
||||
viewModel.duplicate(task, onDuplicated)
|
||||
ActionButton(
|
||||
shape = ActionShapes.More,
|
||||
icon = Icons.Rounded.MoreVert,
|
||||
contentDescription = stringResource(R.string.more_options),
|
||||
onClick = { menuOpen = true },
|
||||
)
|
||||
val cancelled = task.status == TaskStatus.CANCELLED
|
||||
FloretMenu(
|
||||
expanded = menuOpen,
|
||||
onDismissRequest = { menuOpen = false },
|
||||
groups = listOf(
|
||||
listOfNotNull(
|
||||
FloretMenuItem(
|
||||
stringResource(if (cancelled) R.string.detail_restore else R.string.detail_cancel_task),
|
||||
onClick = { viewModel.setCancelled(task, !cancelled) },
|
||||
),
|
||||
if (writable) {
|
||||
FloretMenuItem(stringResource(R.string.detail_duplicate), onClick = { viewModel.duplicate(task, onDuplicated) })
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -546,7 +555,7 @@ private fun SubtasksGroup(
|
||||
val done = subtasks.count { it.isCompleted }
|
||||
// Completed subtasks sink to the bottom; stable, so order is otherwise kept.
|
||||
val ordered = remember(subtasks) { subtasks.sortedBy { it.isCompleted } }
|
||||
val rotation by animateFloatAsState(if (expanded) 180f else 0f, label = "subtasksChevron")
|
||||
val rotation by animateFloatAsState(if (expanded) 180f else 0f, reducibleSpec(spring()), label = "subtasksChevron")
|
||||
// Segments when expanded: header + the always-present add row + each subtask.
|
||||
val addRow = if (readOnly) 0 else 1
|
||||
val count = if (expanded) subtasks.size + 1 + addRow else 1
|
||||
|
||||
@@ -141,6 +141,7 @@ import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
|
||||
|
||||
/**
|
||||
* Create / edit form, in the family's tonal-card language (mirrors Calendula's
|
||||
@@ -173,6 +174,7 @@ fun TaskEditScreen(
|
||||
val scroll = rememberScrollState()
|
||||
var titleBottom by remember { mutableIntStateOf(Int.MAX_VALUE) }
|
||||
val titleInBar by remember { derivedStateOf { scroll.value > titleBottom } }
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier,
|
||||
@@ -181,8 +183,8 @@ fun TaskEditScreen(
|
||||
title = {
|
||||
AnimatedVisibility(
|
||||
visible = titleInBar && state.title.isNotBlank(),
|
||||
enter = fadeIn() + slideInVertically { it / 2 },
|
||||
exit = fadeOut() + slideOutVertically { it / 2 },
|
||||
enter = if (reduceMotion) fadeIn() else fadeIn() + slideInVertically { it / 2 },
|
||||
exit = if (reduceMotion) fadeOut() else fadeOut() + slideOutVertically { it / 2 },
|
||||
) {
|
||||
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import de.jeanlucmakiola.agendula.data.prefs.Settings
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TaskConflictException
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
@@ -37,6 +39,13 @@ import de.jeanlucmakiola.agendula.domain.dueWindows
|
||||
import de.jeanlucmakiola.agendula.domain.showsIn
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import de.jeanlucmakiola.agendula.domain.presetDue
|
||||
import de.jeanlucmakiola.agendula.domain.appliedScope
|
||||
import de.jeanlucmakiola.agendula.domain.datesForTimedDue
|
||||
import de.jeanlucmakiola.agendula.domain.defaultTaskList
|
||||
import de.jeanlucmakiola.agendula.domain.dueVerdict
|
||||
import de.jeanlucmakiola.agendula.domain.listUniverse
|
||||
import de.jeanlucmakiola.agendula.domain.openTaskDated
|
||||
import de.jeanlucmakiola.agendula.domain.scopePreset
|
||||
import de.jeanlucmakiola.agendula.domain.newTaskPreset
|
||||
import de.jeanlucmakiola.agendula.domain.normalizeTags
|
||||
import de.jeanlucmakiola.agendula.domain.tagsInUse
|
||||
@@ -219,15 +228,21 @@ class TaskEditViewModel @Inject constructor(
|
||||
/**
|
||||
* Start a fresh task, optionally pre-selecting a list / parent. Added from a
|
||||
* saved filter or [presetSmartList], it takes the default due date where that
|
||||
* view still shows it, else a due date that keeps it there.
|
||||
* view still shows it, else a due date that keeps it there. Added within the
|
||||
* scope of view [scopeViewId], it also takes what keeps it in that scope (see
|
||||
* [scopePreset]). [presetDueTime] puts a time on [presetDueDate].
|
||||
*/
|
||||
fun bindNew(
|
||||
presetListId: Long? = null,
|
||||
parentId: Long? = null,
|
||||
initialTitle: String? = null,
|
||||
presetTag: String? = null,
|
||||
presetTags: List<String> = emptyList(),
|
||||
presetFilterId: Long? = null,
|
||||
presetSmartList: SmartList? = null,
|
||||
presetDueDate: LocalDate? = null,
|
||||
presetRule: Rule? = null,
|
||||
scopeViewId: Long? = null,
|
||||
presetDueTime: LocalTime? = null,
|
||||
) {
|
||||
if (bound) return
|
||||
bound = true
|
||||
@@ -239,7 +254,9 @@ class TaskEditViewModel @Inject constructor(
|
||||
this@TaskEditViewModel.settings = settings
|
||||
defaultFields = settings.defaultEditFields
|
||||
val lists = runCatching { repository.taskLists().first() }.getOrElse { emptyList() }
|
||||
// A block's custom rules preset a new task as a saved filter with that rule does.
|
||||
val filter = presetFilterId?.let { settingsPrefs.savedFilter(it).first() }
|
||||
?: presetRule?.let { SavedFilter(0, "", it) }
|
||||
val now = Clock.System.now()
|
||||
val today = now.calendarDate(allDay = false)
|
||||
val preset = filter?.newTaskPreset(today)
|
||||
@@ -247,20 +264,30 @@ class TaskEditViewModel @Inject constructor(
|
||||
val (todayStart, todayEnd) = DayWindow.today(now, zone)
|
||||
val upcomingEnd = settings.upcomingRange.end(now, zone)
|
||||
val ruleClock = RuleClock(todayStart, todayEnd, zone, settingsPrefs.firstDayOfWeek.first())
|
||||
val presetDue = preset?.dueDate ?: presetSmartList?.dueWindows?.presetDue(today)
|
||||
val dates = settings.defaultNewTaskDates(today, now, presetDue, subtask = parentId != null) {
|
||||
it.showsIn(presetSmartList, filter, todayStart, todayEnd, upcomingEnd, ruleClock)
|
||||
val scope = scopeViewId?.let { id -> settingsPrefs.views.first().firstOrNull { it.id == id } }
|
||||
?.appliedScope(lists.mapTo(HashSet()) { it.id })?.rule
|
||||
val scopePreset = scope.scopePreset(ruleClock)
|
||||
val presetDue = presetDueDate ?: preset?.dueDate ?: scopePreset.dueDate ?: presetSmartList?.dueWindows?.presetDue(today)
|
||||
val dates = if (presetDueDate != null && presetDueTime != null) {
|
||||
datesForTimedDue(presetDueDate, presetDueTime, settings.defaultStartDate, today, now, zone)
|
||||
} else {
|
||||
settings.defaultNewTaskDates(today, now, presetDue, subtask = parentId != null) { dates ->
|
||||
// A day's list wants the task on that day, whatever the default due date.
|
||||
if (presetDueDate != null) {
|
||||
dates.due?.calendarDate(dates.isAllDay, zone) == presetDueDate
|
||||
} else {
|
||||
dates.showsIn(presetSmartList, filter, todayStart, todayEnd, upcomingEnd, ruleClock) &&
|
||||
(scope == null || scope.dueVerdict(openTaskDated(dates.start, dates.due, dates.isAllDay), ruleClock) != false)
|
||||
}
|
||||
}
|
||||
}
|
||||
// A read-only or vanished default — or a widget's preset list, if it was
|
||||
// since deleted or turned read-only — would give the task a list it
|
||||
// cannot be saved to.
|
||||
val writable = lists.filter { it.acceptsWrites }
|
||||
val filterLists = preset?.listIds.orEmpty()
|
||||
val defaultList = presetListId?.takeIf { id -> writable.any { it.id == id } }
|
||||
?: settings.defaultListId?.takeIf { id -> writable.any { it.id == id } && (filterLists.isEmpty() || id in filterLists) }
|
||||
?: writable.firstOrNull { it.id in filterLists }?.id
|
||||
?: writable.firstOrNull { !it.isLocal }?.id
|
||||
?: writable.firstOrNull()?.id
|
||||
?: scopePreset.listId?.takeIf { id -> writable.any { it.id == id } }
|
||||
?: defaultTaskList(writable, settings.defaultListId, within = preset?.listIds?.takeIf { it.isNotEmpty() } ?: scope?.listUniverse().orEmpty())
|
||||
defaultStart = dates.start?.let { start ->
|
||||
DefaultStart(
|
||||
at = start,
|
||||
@@ -280,13 +307,13 @@ class TaskEditViewModel @Inject constructor(
|
||||
due = dates.due,
|
||||
isAllDay = dates.isAllDay,
|
||||
untimedEnds = repository.supportsUntimedEnds(),
|
||||
priority = preset?.priority ?: Priority.NONE,
|
||||
priority = maxOf(preset?.priority ?: Priority.NONE, scopePreset.priority),
|
||||
parentId = parentId,
|
||||
lists = lists,
|
||||
repeatFromAvailable = repository.supportsRepeatFromCompletion(),
|
||||
parentCandidates = loadParents(defaultList, selfId = null),
|
||||
title = initialTitle.orEmpty(),
|
||||
tags = (listOfNotNull(presetTag) + preset?.tags.orEmpty()).distinct(),
|
||||
tags = (presetTags + preset?.tags.orEmpty() + scopePreset.tags).distinct(),
|
||||
).withDefaultReminders(),
|
||||
).also { baseline = it.toForm().copy(title = "") }
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.ButtonGroup
|
||||
import androidx.compose.material3.ButtonGroupScope
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -57,6 +56,7 @@ import de.jeanlucmakiola.floret.components.SelectedCheck
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.components.BusyIndicator
|
||||
|
||||
private const val ZIP_MIME = "application/zip"
|
||||
private const val ZIP_NAME = "agendula-tasks.zip"
|
||||
@@ -238,7 +238,7 @@ private fun ExportStatus(state: ExportUiState) {
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
CircularProgressIndicator(Modifier.size(18.dp))
|
||||
BusyIndicator(Modifier.size(18.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.export_running),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Add
|
||||
import androidx.compose.material.icons.rounded.ArrowDropDown
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.DoNotDisturbOn
|
||||
import androidx.compose.material.icons.rounded.MoreVert
|
||||
import de.jeanlucmakiola.floret.components.FloretMenu
|
||||
import de.jeanlucmakiola.floret.components.FloretMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSurface
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.identity.FloretDensity
|
||||
|
||||
/** A picker the advanced editor has open, for the node at [path]. */
|
||||
private sealed interface Picking {
|
||||
val path: RulePath
|
||||
|
||||
/** [adding] puts a new condition into the group at [path] rather than changing the one there. */
|
||||
data class Field(override val path: RulePath, val adding: Boolean) : Picking
|
||||
data class Value(override val path: RulePath, val field: RuleField, val adding: Boolean) : Picking
|
||||
}
|
||||
|
||||
/**
|
||||
* The advanced editor: the rule as nested groups, each *all of* or *any of*,
|
||||
* maybe negated, holding conditions and further groups. [rule] is a group at the
|
||||
* root (see [forAdvanced]); [onChange] gets each change to it.
|
||||
*/
|
||||
@Composable
|
||||
internal fun AdvancedEditor(
|
||||
rule: Rule,
|
||||
lists: List<TaskList>,
|
||||
tagsInUse: List<String>,
|
||||
onChange: ((Rule) -> Rule) -> Unit,
|
||||
) {
|
||||
var picking by remember { mutableStateOf<Picking?>(null) }
|
||||
val listNames = remember(lists) { lists.associate { it.id to it.name } }
|
||||
|
||||
GroupCard(
|
||||
group = rule,
|
||||
path = emptyList(),
|
||||
listNames = listNames,
|
||||
onChange = onChange,
|
||||
onPick = { picking = it },
|
||||
modifier = Modifier.padding(horizontal = GroupedListInset),
|
||||
)
|
||||
GroupedHint(stringResource(R.string.filter_advanced_note), style = MaterialTheme.typography.bodySmall, verticalPadding = 8.dp)
|
||||
|
||||
when (val open = picking) {
|
||||
null -> Unit
|
||||
is Picking.Field -> FieldPicker(
|
||||
selected = if (open.adding) null else rule.at(open.path)?.field,
|
||||
onSelect = { field -> picking = Picking.Value(open.path, field, open.adding) },
|
||||
onDismiss = { if (picking == open) picking = null },
|
||||
)
|
||||
is Picking.Value -> {
|
||||
val current = if (open.adding) null else rule.at(open.path)?.positive?.takeIf { it.field == open.field }
|
||||
val done = { condition: Rule ->
|
||||
onChange { root ->
|
||||
if (open.adding) {
|
||||
root.addTo(open.path, condition)
|
||||
} else {
|
||||
root.updateAt(open.path) { old -> if (old.negated) Rule.Not(condition) else condition }
|
||||
}
|
||||
}
|
||||
}
|
||||
val dismiss = { picking = null }
|
||||
when (open.field) {
|
||||
RuleField.LIST -> {
|
||||
val list = current as? Rule.InList
|
||||
ListsPicker(
|
||||
lists = lists,
|
||||
selected = list?.listIds.orEmpty(),
|
||||
onDone = { ids -> done(Rule.InList(ids, list?.elsewhere.orEmpty())) },
|
||||
onDismiss = dismiss,
|
||||
)
|
||||
}
|
||||
RuleField.TAG -> TagPicker(
|
||||
tags = tagsInUse,
|
||||
selected = (current as? Rule.HasTag)?.tag,
|
||||
onSelect = { done(Rule.HasTag(it)) },
|
||||
onDismiss = dismiss,
|
||||
)
|
||||
RuleField.PRIORITY -> PriorityPicker(
|
||||
selected = (current as? Rule.MinPriority)?.priority,
|
||||
onSelect = { done(Rule.MinPriority(it)) },
|
||||
onDismiss = dismiss,
|
||||
)
|
||||
RuleField.DUE -> DuePicker(
|
||||
selected = (current as? Rule.Due)?.spec,
|
||||
onSelect = { done(Rule.Due(it)) },
|
||||
onDismiss = dismiss,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One group: its kind and negation, its children, and the buttons that add to it. */
|
||||
@Composable
|
||||
private fun GroupCard(
|
||||
group: Rule,
|
||||
path: RulePath,
|
||||
listNames: Map<Long, String>,
|
||||
onChange: ((Rule) -> Rule) -> Unit,
|
||||
onPick: (Picking) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val match = group.groupMatch ?: Match.ALL
|
||||
val children = group.groupChildren
|
||||
val nested = path.isNotEmpty()
|
||||
GroupedSurface(
|
||||
position = Position.Alone,
|
||||
color = if (path.size % 2 == 0) MaterialTheme.colorScheme.surfaceContainerLow else MaterialTheme.colorScheme.surfaceContainer,
|
||||
modifier = modifier,
|
||||
) {
|
||||
Column(Modifier.padding(vertical = 8.dp)) {
|
||||
GroupHeader(
|
||||
match = match,
|
||||
negated = group.negated,
|
||||
deletable = nested,
|
||||
onToggleMatch = {
|
||||
val other = if (match == Match.ALL) Match.ANY else Match.ALL
|
||||
onChange { it.updateAt(path) { g -> g.withGroupMatch(other) } }
|
||||
},
|
||||
onToggleNot = { onChange { it.updateAt(path, Rule::toggleNot) } },
|
||||
onDelete = { onChange { it.removeAt(path) } },
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
if (children.isEmpty()) {
|
||||
GroupedHint(
|
||||
stringResource(if (match == Match.ALL) R.string.filter_group_empty_all else R.string.filter_group_empty_any),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(horizontal = 4.dp),
|
||||
)
|
||||
}
|
||||
children.forEachIndexed { index, child ->
|
||||
val childPath = path + index
|
||||
if (child.isGroup) {
|
||||
GroupCard(
|
||||
group = child,
|
||||
path = childPath,
|
||||
listNames = listNames,
|
||||
onChange = onChange,
|
||||
onPick = onPick,
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
)
|
||||
} else {
|
||||
ConditionRow(
|
||||
condition = child,
|
||||
position = conditionPosition(children, index),
|
||||
listNames = listNames,
|
||||
onField = { onPick(Picking.Field(childPath, adding = false)) },
|
||||
onValue = { child.field?.let { onPick(Picking.Value(childPath, it, adding = false)) } },
|
||||
onToggleNot = { onChange { it.updateAt(childPath, Rule::toggleNot) } },
|
||||
onRemove = { onChange { it.removeAt(childPath) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 8.dp)) {
|
||||
TextButton(onClick = { onPick(Picking.Field(path, adding = true)) }) {
|
||||
Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.filter_add_rule))
|
||||
}
|
||||
TextButton(onClick = { onChange { it.addTo(path, newGroupUnder(group)) } }) {
|
||||
Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.filter_add_group))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A group's kind, which a tap switches, its negation, and its ⋮ menu. */
|
||||
@Composable
|
||||
private fun GroupHeader(
|
||||
match: Match,
|
||||
negated: Boolean,
|
||||
deletable: Boolean,
|
||||
onToggleMatch: () -> Unit,
|
||||
onToggleNot: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (negated) {
|
||||
InlineChip(text = stringResource(R.string.filter_group_not), onClick = onToggleNot, toggles = false)
|
||||
}
|
||||
InlineChip(
|
||||
text = stringResource(if (match == Match.ALL) R.string.filter_group_all else R.string.filter_group_any),
|
||||
onClick = onToggleMatch,
|
||||
)
|
||||
Text(
|
||||
stringResource(
|
||||
when {
|
||||
negated && match == Match.ALL -> R.string.filter_group_not_all_hint
|
||||
negated -> R.string.filter_group_not_any_hint
|
||||
match == Match.ALL -> R.string.filter_group_all_hint
|
||||
else -> R.string.filter_group_any_hint
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
var menuOpen by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
IconButton(onClick = { menuOpen = true }) {
|
||||
Icon(Icons.Rounded.MoreVert, contentDescription = stringResource(R.string.filter_group_menu))
|
||||
}
|
||||
FloretMenu(
|
||||
expanded = menuOpen,
|
||||
onDismissRequest = { menuOpen = false },
|
||||
groups = listOf(
|
||||
listOfNotNull(
|
||||
FloretMenuItem(
|
||||
stringResource(if (negated) R.string.filter_group_negate_off else R.string.filter_group_negate),
|
||||
Icons.Rounded.DoNotDisturbOn,
|
||||
onClick = onToggleNot,
|
||||
),
|
||||
if (deletable) FloretMenuItem(stringResource(R.string.filter_group_delete), Icons.Rounded.Delete, onClick = onDelete) else null,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One condition: what it checks, which a tap changes, its operator, which a tap
|
||||
* turns round, and its value, which a tap on the row changes; ✕ removes it.
|
||||
*/
|
||||
@Composable
|
||||
private fun ConditionRow(
|
||||
condition: Rule,
|
||||
position: Position,
|
||||
listNames: Map<Long, String>,
|
||||
onField: () -> Unit,
|
||||
onValue: () -> Unit,
|
||||
onToggleNot: () -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
) {
|
||||
val field = condition.field ?: return
|
||||
GroupedRow(
|
||||
title = conditionValue(condition.positive, listNames),
|
||||
position = position,
|
||||
minHeight = FloretDensity.nestedRowHeight,
|
||||
leading = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
InlineChip(text = fieldLabel(field), onClick = onField, quiet = true)
|
||||
InlineChip(text = operatorLabel(field, condition.negated), onClick = onToggleNot, toggles = false)
|
||||
}
|
||||
},
|
||||
trailing = {
|
||||
IconButton(onClick = onRemove) {
|
||||
Icon(Icons.Rounded.Close, contentDescription = stringResource(R.string.filter_rule_remove))
|
||||
}
|
||||
},
|
||||
onClick = onValue,
|
||||
)
|
||||
}
|
||||
|
||||
/** Where the condition at [index] sits in its run of conditions, which read as one connected list. */
|
||||
private fun conditionPosition(children: List<Rule>, index: Int): Position {
|
||||
var first = index
|
||||
while (first > 0 && !children[first - 1].isGroup) first--
|
||||
var last = index
|
||||
while (last < children.lastIndex && !children[last + 1].isGroup) last++
|
||||
return positionOf(index - first, last - first + 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* A small pill inside a row, tapped in place: a group's kind, a condition's field
|
||||
* or operator. [toggles] marks one that switches between two values, which reads
|
||||
* as a switch to accessibility; [quiet] draws it without a container.
|
||||
*/
|
||||
@Composable
|
||||
private fun InlineChip(text: String, onClick: () -> Unit, toggles: Boolean = true, quiet: Boolean = false) {
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
shape = CircleShape,
|
||||
color = if (quiet) MaterialTheme.colorScheme.surfaceContainerHighest else MaterialTheme.colorScheme.secondaryContainer,
|
||||
contentColor = if (quiet) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
modifier = Modifier.semantics {
|
||||
role = Role.Button
|
||||
if (toggles) stateDescription = text
|
||||
},
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.heightIn(min = 32.dp).padding(start = 12.dp, end = if (toggles) 4.dp else 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(text, style = MaterialTheme.typography.labelLarge, maxLines = 1)
|
||||
if (toggles) Icon(Icons.Rounded.ArrowDropDown, contentDescription = null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun operatorLabel(field: RuleField, negated: Boolean): String = stringResource(
|
||||
when {
|
||||
field == RuleField.PRIORITY -> if (negated) R.string.filter_op_below else R.string.filter_op_at_least
|
||||
negated -> R.string.filter_op_is_not
|
||||
else -> R.string.filter_op_is
|
||||
},
|
||||
)
|
||||
|
||||
/** What a condition compares against, as in "Work, Home", "focus", "High" or "Next 7 days". */
|
||||
@Composable
|
||||
private fun conditionValue(condition: Rule, listNames: Map<Long, String>): String = when (condition) {
|
||||
is Rule.InList -> {
|
||||
val deleted = stringResource(R.string.view_scope_list_deleted)
|
||||
val elsewhere = stringResource(R.string.view_scope_list_elsewhere)
|
||||
val names = condition.listIds.map { listNames[it] ?: deleted }.sorted() + List(condition.elsewhere.size) { elsewhere }
|
||||
if (names.isEmpty()) stringResource(R.string.filter_value_no_list) else names.joinToString(", ")
|
||||
}
|
||||
is Rule.HasTag -> condition.tag
|
||||
is Rule.MinPriority -> priorityName(condition.priority)
|
||||
is Rule.Due -> dueLabel(condition.spec)
|
||||
else -> ""
|
||||
}
|
||||
@@ -4,19 +4,16 @@ import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.ChevronRight
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -24,27 +21,16 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.FilterCriteria
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.ui.common.ListColorChip
|
||||
import de.jeanlucmakiola.agendula.ui.common.NameField
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.SelectedCheck
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
|
||||
/**
|
||||
* Creates or edits a [SavedFilter]: a name, then due windows, priority, lists and
|
||||
* tags. Each multi-choice section leads with an "any" row that is selected while
|
||||
* nothing in it is, so an untouched section visibly doesn't narrow. A filter
|
||||
* whose rule has no flat form can only be renamed or deleted here.
|
||||
* Creates or edits a [SavedFilter]: a name, then its rules in the simple or the
|
||||
* advanced editor (see [RuleEditorSections]). A new filter starts by picking a
|
||||
* template, or none.
|
||||
*/
|
||||
@Composable
|
||||
fun FilterEditScreen(
|
||||
@@ -58,8 +44,6 @@ fun FilterEditScreen(
|
||||
val lists by viewModel.lists.collectAsStateWithLifecycle()
|
||||
val tagsInUse by viewModel.tags.collectAsStateWithLifecycle()
|
||||
val filter = draft?.filter
|
||||
val criteria = draft?.criteria
|
||||
var choosingPriority by rememberSaveable { mutableStateOf(false) }
|
||||
var confirmDelete by rememberSaveable { mutableStateOf(false) }
|
||||
val save = { viewModel.save(onSaved) }
|
||||
|
||||
@@ -75,23 +59,18 @@ fun FilterEditScreen(
|
||||
) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
) {
|
||||
if (filter == null) return@CollapsingScaffold
|
||||
val current = draft ?: return@CollapsingScaffold
|
||||
val filter = current.filter
|
||||
|
||||
NameField(
|
||||
name = filter.name,
|
||||
placeholder = stringResource(R.string.filter_name_hint),
|
||||
autoFocus = isNew,
|
||||
autoFocus = isNew && !current.choosingTemplate && filter.name.isEmpty(),
|
||||
onNameChange = viewModel::rename,
|
||||
onImeAction = save,
|
||||
)
|
||||
|
||||
// A rule the flat sections can't show is kept as it is: only the name changes here.
|
||||
if (criteria == null) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedRow(title = stringResource(R.string.filter_rules_not_editable), position = Position.Alone)
|
||||
} else {
|
||||
CriteriaSections(criteria, lists, tagsInUse, viewModel, onChoosePriority = { choosingPriority = true })
|
||||
}
|
||||
RuleEditorSections(current.rules, lists, tagsInUse, onChange = viewModel::updateRules)
|
||||
|
||||
if (filter.id > 0) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
@@ -106,14 +85,12 @@ fun FilterEditScreen(
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
|
||||
if (choosingPriority && criteria != null) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.filter_section_priority),
|
||||
options = Priority.entries,
|
||||
selected = criteria.minPriority,
|
||||
label = { minPriorityLabel(it) },
|
||||
onSelect = { priority -> viewModel.updateCriteria { it.copy(minPriority = priority) } },
|
||||
onDismiss = { choosingPriority = false },
|
||||
if (draft?.choosingTemplate == true) {
|
||||
TemplateChooser(
|
||||
lists = lists,
|
||||
title = stringResource(R.string.filter_new_title),
|
||||
onStart = viewModel::startFrom,
|
||||
onDismiss = onBack,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -133,149 +110,3 @@ fun FilterEditScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The flat criteria: due windows, priority, lists and tags. */
|
||||
@Composable
|
||||
private fun CriteriaSections(
|
||||
criteria: FilterCriteria,
|
||||
lists: List<TaskList>,
|
||||
tagsInUse: List<String>,
|
||||
viewModel: FilterEditViewModel,
|
||||
onChoosePriority: () -> Unit,
|
||||
) {
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_due))
|
||||
val windows = DueWindow.entries
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_due),
|
||||
position = positionOf(0, windows.size + 1),
|
||||
selected = criteria.due.isEmpty(),
|
||||
onClick = { viewModel.updateCriteria { it.copy(due = emptySet()) } },
|
||||
)
|
||||
windows.forEachIndexed { index, window ->
|
||||
ChoiceRow(
|
||||
title = dueWindowLabel(window),
|
||||
position = positionOf(index + 1, windows.size + 1),
|
||||
selected = window in criteria.due,
|
||||
onClick = { viewModel.updateCriteria { it.copy(due = it.due.toggle(window)) } },
|
||||
)
|
||||
}
|
||||
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_priority))
|
||||
GroupedRow(
|
||||
title = minPriorityLabel(criteria.minPriority),
|
||||
position = Position.Alone,
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = onChoosePriority,
|
||||
)
|
||||
|
||||
if (lists.isNotEmpty()) {
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_lists))
|
||||
val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_list),
|
||||
position = positionOf(0, lists.size + 1),
|
||||
selected = criteria.anyList,
|
||||
onClick = { viewModel.updateCriteria { it.copy(listIds = emptySet(), listsElsewhere = emptySet()) } },
|
||||
)
|
||||
lists.forEachIndexed { index, list ->
|
||||
ChoiceRow(
|
||||
title = list.name,
|
||||
summary = list.accountName.takeIf { showAccount },
|
||||
position = positionOf(index + 1, lists.size + 1),
|
||||
selected = list.id in criteria.listIds,
|
||||
leading = { ListColorChip(list.color) },
|
||||
onClick = { viewModel.updateCriteria { it.copy(listIds = it.listIds.toggle(list.id)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// A tag no open task carries any more stays listed while the filter uses
|
||||
// it, so it can still be unticked.
|
||||
val tags = remember(tagsInUse, criteria.tags) {
|
||||
(tagsInUse + criteria.tags).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER)
|
||||
}
|
||||
if (tags.isNotEmpty()) {
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_tags))
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_tag),
|
||||
position = positionOf(0, tags.size + 1),
|
||||
selected = criteria.tags.isEmpty(),
|
||||
onClick = { viewModel.updateCriteria { it.copy(tags = emptySet()) } },
|
||||
)
|
||||
tags.forEachIndexed { index, tag ->
|
||||
ChoiceRow(
|
||||
title = tag,
|
||||
position = positionOf(index + 1, tags.size + 1),
|
||||
selected = tag in criteria.tags,
|
||||
onClick = { viewModel.updateCriteria { it.copy(tags = it.tags.toggle(tag)) } },
|
||||
)
|
||||
}
|
||||
if (criteria.tags.size > 1) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.filter_match_all_tags),
|
||||
summary = stringResource(
|
||||
if (criteria.tagMatch == TagMatch.ALL) R.string.filter_match_all_on else R.string.filter_match_all_off,
|
||||
),
|
||||
position = Position.Alone,
|
||||
trailing = {
|
||||
Switch(
|
||||
checked = criteria.tagMatch == TagMatch.ALL,
|
||||
onCheckedChange = { all ->
|
||||
viewModel.updateCriteria { it.copy(tagMatch = if (all) TagMatch.ALL else TagMatch.ANY) }
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.updateCriteria { it.copy(tagMatch = if (it.tagMatch == TagMatch.ALL) TagMatch.ANY else TagMatch.ALL) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChoiceRow(
|
||||
title: String,
|
||||
position: Position,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
summary: String? = null,
|
||||
leading: @Composable (() -> Unit)? = null,
|
||||
) {
|
||||
GroupedRow(
|
||||
title = title,
|
||||
summary = summary,
|
||||
position = position,
|
||||
selected = selected,
|
||||
leading = leading,
|
||||
trailing = if (selected) {
|
||||
{ SelectedCheck() }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = onClick,
|
||||
)
|
||||
}
|
||||
|
||||
private fun <T> Set<T>.toggle(item: T): Set<T> = if (item in this) this - item else this + item
|
||||
|
||||
@Composable
|
||||
private fun dueWindowLabel(window: DueWindow): String = stringResource(
|
||||
when (window) {
|
||||
DueWindow.OVERDUE -> R.string.smart_overdue
|
||||
DueWindow.TODAY -> R.string.smart_today
|
||||
DueWindow.UPCOMING -> R.string.smart_upcoming
|
||||
DueWindow.NO_DATE -> R.string.smart_no_date
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun minPriorityLabel(priority: Priority): String = stringResource(
|
||||
when (priority) {
|
||||
Priority.NONE -> R.string.filter_priority_any
|
||||
Priority.LOW -> R.string.filter_priority_low
|
||||
Priority.MEDIUM -> R.string.filter_priority_medium
|
||||
Priority.HIGH -> R.string.filter_priority_high
|
||||
},
|
||||
)
|
||||
@@ -5,7 +5,7 @@ import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.FilterCriteria
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
@@ -33,12 +33,10 @@ class FilterEditViewModel @Inject constructor(
|
||||
) : ViewModel() {
|
||||
|
||||
/**
|
||||
* The filter being edited and its [criteria], kept apart so a choice the
|
||||
* rule can't hold, like all tags with none picked, survives while editing.
|
||||
* [criteria] is `null` when the rule has no flat form; [filter] then keeps
|
||||
* its rule as loaded.
|
||||
* The filter being edited, by name; its rule is [rules]' and goes into it on
|
||||
* save. A new filter starts [choosingTemplate].
|
||||
*/
|
||||
data class Draft(val filter: SavedFilter, val criteria: FilterCriteria?)
|
||||
data class Draft(val filter: SavedFilter, val rules: RuleDraft, val choosingTemplate: Boolean = false)
|
||||
|
||||
private val _draft = MutableStateFlow<Draft?>(null)
|
||||
|
||||
@@ -62,7 +60,7 @@ class FilterEditViewModel @Inject constructor(
|
||||
if (bound) return
|
||||
bound = true
|
||||
if (filterId == null) {
|
||||
load(SavedFilter(id = 0, name = ""))
|
||||
_draft.value = Draft(SavedFilter(id = 0, name = ""), RuleDraft.of(Rule.Everything), choosingTemplate = true)
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
@@ -77,20 +75,39 @@ class FilterEditViewModel @Inject constructor(
|
||||
_draft.update { it?.copy(filter = it.filter.copy(name = name)) }
|
||||
}
|
||||
|
||||
/** Changes the criteria, and the rule with them; a filter without a flat form is left as it is. */
|
||||
fun updateCriteria(transform: (FilterCriteria) -> FilterCriteria) {
|
||||
_draft.update { draft ->
|
||||
val criteria = draft?.criteria?.let(transform) ?: return@update draft
|
||||
Draft(draft.filter.copy(rule = criteria.toRule()), criteria)
|
||||
/** Changes the rules being edited. */
|
||||
fun updateRules(transform: (RuleDraft) -> RuleDraft) {
|
||||
_draft.update { it?.copy(rules = transform(it.rules)) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the new filter from [template]'s rules, or from none; *Next actions*
|
||||
* with [nextList]. An unnamed filter takes the template's [name].
|
||||
*/
|
||||
fun startFrom(template: FilterTemplate?, nextList: Long? = null, name: String? = null) {
|
||||
// The first pick wins; the picker stays up, and the editor untouched, until its rules are read.
|
||||
if (_draft.value?.choosingTemplate != true || starting) return
|
||||
starting = true
|
||||
viewModelScope.launch {
|
||||
val form = template?.let { repository.templateForm(it, nextList) }
|
||||
_draft.update { draft ->
|
||||
draft?.copy(
|
||||
filter = if (name != null && draft.filter.name.isBlank()) draft.filter.copy(name = name) else draft.filter,
|
||||
rules = form?.let(RuleDraft::of) ?: draft.rules,
|
||||
choosingTemplate = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var starting = false
|
||||
|
||||
private fun load(filter: SavedFilter) {
|
||||
_draft.value = Draft(filter, filter.criteria)
|
||||
_draft.value = Draft(filter, RuleDraft.of(filter.rule))
|
||||
}
|
||||
|
||||
fun save(onSaved: (Long) -> Unit) {
|
||||
val filter = _draft.value?.filter ?: return
|
||||
val filter = _draft.value?.let { it.filter.copy(rule = it.rules.rule) } ?: return
|
||||
if (filter.name.isBlank() || saving) return
|
||||
saving = true
|
||||
viewModelScope.launch {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.tagsInUse
|
||||
import kotlinx.coroutines.flow.first
|
||||
|
||||
/**
|
||||
* A rule being edited: [rule] is what saves, and [simple] the simple editor's
|
||||
* form of it while that editor shows, `null` in the advanced one. The form is
|
||||
* kept apart so a choice the rule can't hold, like *any rule* with nothing
|
||||
* picked, survives while editing.
|
||||
*/
|
||||
data class RuleDraft(val rule: Rule, val simple: SimpleRule?, private val left: SimpleRule? = null) {
|
||||
|
||||
val advanced: Boolean get() = simple == null
|
||||
|
||||
/** Whether the simple editor can show the rule as it is now. */
|
||||
val canSimplify: Boolean get() = simple != null || SimpleRule.of(rule) != null
|
||||
|
||||
/** Changes the simple form, and the rule with them; nothing in the advanced editor. */
|
||||
fun editSimple(transform: (SimpleRule) -> SimpleRule): RuleDraft {
|
||||
val form = simple?.let(transform)?.tidy() ?: return this
|
||||
return RuleDraft(form.toRule(), form)
|
||||
}
|
||||
|
||||
/** Changes the rule in the advanced editor; nothing in the simple one. */
|
||||
fun editAdvanced(transform: (Rule) -> Rule): RuleDraft = if (simple != null) this else copy(rule = transform(rule))
|
||||
|
||||
/** Over to the advanced editor, which can show any rule; the simple form is kept for the way back. */
|
||||
fun toAdvanced(): RuleDraft = RuleDraft(rule.forAdvanced(), null, simple)
|
||||
|
||||
/**
|
||||
* Over to the simple editor, when it can show the rule; the rule stays as it
|
||||
* is. Unchanged since leaving it, the form comes back as it was left.
|
||||
*/
|
||||
fun toSimple(): RuleDraft = when {
|
||||
simple != null -> this
|
||||
left != null && left.toRule() == rule -> RuleDraft(rule, left)
|
||||
else -> SimpleRule.of(rule)?.let { RuleDraft(rule, it) } ?: this
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** [rule] in the simple editor when it can show it, else in the advanced one. */
|
||||
fun of(rule: Rule): RuleDraft = SimpleRule.of(rule)?.let { RuleDraft(rule, it) } ?: RuleDraft(rule.forAdvanced(), null)
|
||||
|
||||
fun of(form: SimpleRule): RuleDraft = RuleDraft(form.toRule(), form)
|
||||
}
|
||||
}
|
||||
|
||||
/** [template]'s form against the tags in use as read now (none when they can't be), [nextList] for *Next actions*. */
|
||||
internal suspend fun TasksRepository.templateForm(template: FilterTemplate, nextList: Long?): SimpleRule {
|
||||
val tags = runCatching { tagsInUse(tasks(TaskFilter.Smart(SmartList.ALL)).first()) }.getOrDefault(emptyList())
|
||||
return template.form(nextList, tags)
|
||||
}
|
||||
|
||||
/** The rules a new filter can start from (#154); the user changes them as they like. */
|
||||
enum class FilterTemplate {
|
||||
NEXT_ACTIONS,
|
||||
THIS_WEEK,
|
||||
THIS_MONTH,
|
||||
HIGH_PRIORITY,
|
||||
WAITING_FOR,
|
||||
NO_DATE,
|
||||
;
|
||||
|
||||
/**
|
||||
* The template's rules. *Next actions* is [nextList] or the next-action tag,
|
||||
* the tag alone without a list. Tags are matched by name, ignoring case, to
|
||||
* [tags] (the ones in use); one not in use yet is taken as written.
|
||||
*/
|
||||
fun form(nextList: Long?, tags: List<String>): SimpleRule {
|
||||
fun tag(name: String) = tags.firstOrNull { it.equals(name, ignoreCase = true) } ?: name
|
||||
return when (this) {
|
||||
NEXT_ACTIONS -> SimpleRule(
|
||||
match = Match.ANY,
|
||||
listIds = setOfNotNull(nextList),
|
||||
tags = setOf(tag(NEXT_ACTION_TAG)),
|
||||
)
|
||||
THIS_WEEK -> SimpleRule(due = setOf(DueSpec.Window(DueWindow.OVERDUE), DueSpec.ThisWeek))
|
||||
THIS_MONTH -> SimpleRule(due = setOf(DueSpec.ThisMonth))
|
||||
HIGH_PRIORITY -> SimpleRule(minPriority = Priority.HIGH)
|
||||
WAITING_FOR -> SimpleRule(tags = setOf(tag(WAITING_TAG)))
|
||||
NO_DATE -> SimpleRule(due = setOf(DueSpec.Window(DueWindow.NO_DATE)))
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val NEXT_ACTION_TAG = "nextAction"
|
||||
const val WAITING_TAG = "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import de.jeanlucmakiola.agendula.data.prefs.RuleCodec
|
||||
import de.jeanlucmakiola.agendula.domain.BlockSource
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
|
||||
/** What the bare rule editor is for, which names it and decides whether it offers *Save as filter*. */
|
||||
enum class RulePurpose {
|
||||
/** A view's scope. */
|
||||
SCOPE,
|
||||
|
||||
/** What a block shows: *Custom rules*, which can be saved as a filter. */
|
||||
SOURCE,
|
||||
}
|
||||
|
||||
/**
|
||||
* What the rule editor hands back to the screen that opened it for a result:
|
||||
* the rules, or the filter they were saved as.
|
||||
*/
|
||||
sealed interface RuleEditResult {
|
||||
data class Rules(val rule: Rule) : RuleEditResult
|
||||
data class Filter(val filterId: Long) : RuleEditResult
|
||||
|
||||
/** This result as a block's source. */
|
||||
val source: BlockSource
|
||||
get() = when (this) {
|
||||
is Rules -> BlockSource.Rules(rule)
|
||||
is Filter -> BlockSource.Filter(filterId)
|
||||
}
|
||||
|
||||
fun encode(): String = when (this) {
|
||||
is Rules -> "rules:${RuleText.encode(rule)}"
|
||||
is Filter -> "filter:$filterId"
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** The key the result is put under in the opener's saved state. */
|
||||
const val KEY = "ruleEditResult"
|
||||
|
||||
fun decode(text: String): RuleEditResult? = when {
|
||||
text.startsWith("rules:") -> RuleText.decode(text.removePrefix("rules:"))?.let(::Rules)
|
||||
text.startsWith("filter:") -> text.removePrefix("filter:").toLongOrNull()?.let(::Filter)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A rule as text, to hand between screens. Lists keep their ids, those of other stores their refs. */
|
||||
internal object RuleText {
|
||||
private const val MODE = "here"
|
||||
|
||||
fun encode(rule: Rule): String = RuleCodec.encode(rule, MODE)
|
||||
|
||||
fun decode(text: String): Rule? = runCatching { RuleCodec.decode(text, MODE) }.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.FilterList
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.ui.common.NameField
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.OptionalFormSection
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
|
||||
/**
|
||||
* Edits a bare rule, no filter around it: a view's scope or a block's custom
|
||||
* rules ([purpose]). Custom rules can be saved as a filter too, named here.
|
||||
* [onDone] gets what to hand back to the opener (see [RuleEditViewModel.save]).
|
||||
*/
|
||||
@Composable
|
||||
fun RuleEditScreen(
|
||||
viewModel: RuleEditViewModel,
|
||||
purpose: RulePurpose,
|
||||
onDone: (RuleEditResult?) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
val lists by viewModel.lists.collectAsStateWithLifecycle()
|
||||
val tagsInUse by viewModel.tags.collectAsStateWithLifecycle()
|
||||
val saveFailed by viewModel.saveFailed.collectAsStateWithLifecycle()
|
||||
val blockGone by viewModel.blockGone.collectAsStateWithLifecycle()
|
||||
val save = { viewModel.save(onDone) }
|
||||
val title = stringResource(if (purpose == RulePurpose.SCOPE) R.string.rule_scope_title else R.string.rule_source_title)
|
||||
|
||||
CollapsingScaffold(
|
||||
title = title,
|
||||
onBack = onBack,
|
||||
largeTopBar = false,
|
||||
actions = {
|
||||
Button(
|
||||
onClick = save,
|
||||
enabled = state?.canSave == true,
|
||||
modifier = Modifier.padding(end = 12.dp),
|
||||
) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
) {
|
||||
val current = state ?: return@CollapsingScaffold
|
||||
if (saveFailed || blockGone) {
|
||||
Text(
|
||||
stringResource(if (blockGone) R.string.block_gone_while_editing else R.string.view_save_failed),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = GroupedListInset).padding(bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
RuleEditorSections(current.rules, lists, tagsInUse, onChange = viewModel::updateRules)
|
||||
|
||||
if (purpose == RulePurpose.SOURCE) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.rule_save_as_filter),
|
||||
checked = current.saveAsFilter,
|
||||
onCheckedChange = viewModel::setSaveAsFilter,
|
||||
position = Position.Alone,
|
||||
summary = stringResource(R.string.rule_save_as_filter_hint),
|
||||
leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) },
|
||||
)
|
||||
OptionalFormSection(visible = current.saveAsFilter) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
NameField(
|
||||
name = current.filterName,
|
||||
placeholder = stringResource(R.string.filter_name_hint),
|
||||
autoFocus = current.saveAsFilter,
|
||||
onNameChange = viewModel::renameFilter,
|
||||
onImeAction = save,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
|
||||
if (state?.choosingTemplate == true) {
|
||||
TemplateChooser(
|
||||
lists = lists,
|
||||
title = title,
|
||||
onStart = viewModel::startFrom,
|
||||
onDismiss = onBack,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.BlockSource
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.tagsInUse
|
||||
import de.jeanlucmakiola.agendula.domain.withoutListIds
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Holds a bare rule being edited, a view's scope or a block's custom rules, until
|
||||
* it's saved to its [Target]. Call [bind] first.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class RuleEditViewModel @Inject constructor(
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
/** Where the rule goes on save. */
|
||||
sealed interface Target {
|
||||
/** The source of the stored block [blockId] of view [viewId]. */
|
||||
data class Block(val viewId: Long, val blockId: Long) : Target
|
||||
|
||||
/** Back to the screen that opened the editor, as a [RuleEditResult]. */
|
||||
data class Result(val initial: Rule?) : Target
|
||||
}
|
||||
|
||||
/**
|
||||
* The rule being edited. [saveAsFilter] stores it as a filter named
|
||||
* [filterName] too, and hands back that filter; only for a block's source.
|
||||
*/
|
||||
data class State(
|
||||
val rules: RuleDraft,
|
||||
val choosingTemplate: Boolean = false,
|
||||
val saveAsFilter: Boolean = false,
|
||||
val filterName: String = "",
|
||||
) {
|
||||
val canSave: Boolean get() = !saveAsFilter || filterName.isNotBlank()
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow<State?>(null)
|
||||
|
||||
/** `null` until [bind] has loaded the rule. */
|
||||
val state: StateFlow<State?> = _state.asStateFlow()
|
||||
|
||||
private val _saveFailed = MutableStateFlow(false)
|
||||
|
||||
/** Set when the block couldn't be written: the views are another version's. */
|
||||
val saveFailed: StateFlow<Boolean> = _saveFailed.asStateFlow()
|
||||
|
||||
private val _blockGone = MutableStateFlow(false)
|
||||
|
||||
/** Set when the block was removed while its rules were edited; there is nothing to save them to. */
|
||||
val blockGone: StateFlow<Boolean> = _blockGone.asStateFlow()
|
||||
|
||||
val lists: StateFlow<List<TaskList>> = repository.taskLists()
|
||||
.catch { emit(emptyList()) }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
|
||||
|
||||
/** Every tag on an open task. */
|
||||
val tags: StateFlow<List<String>> = repository.tasks(TaskFilter.Smart(SmartList.ALL))
|
||||
.map { tagsInUse(it) }
|
||||
.catch { emit(emptyList()) }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
|
||||
|
||||
private var target: Target? = null
|
||||
private var saving = false
|
||||
|
||||
/**
|
||||
* Loads the rule [target] holds. New custom rules ([RulePurpose.SOURCE]
|
||||
* without any yet) start from the templates. Lists deleted since drop out,
|
||||
* so a condition left without lists shows as matching nothing, as it does.
|
||||
*/
|
||||
fun bind(target: Target, purpose: RulePurpose) {
|
||||
if (this.target != null) return
|
||||
this.target = target
|
||||
viewModelScope.launch {
|
||||
val stored = when (target) {
|
||||
is Target.Result -> target.initial
|
||||
is Target.Block -> settingsPrefs.views.first().firstOrNull { it.id == target.viewId }
|
||||
?.blocks?.firstOrNull { it.id == target.blockId }
|
||||
?.let { (it.source as? BlockSource.Rules)?.rule }
|
||||
}
|
||||
val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull().orEmpty()
|
||||
val rule = stored?.let { if (existing.isEmpty()) it else it.withoutListIds { id -> id !in existing } }
|
||||
_state.value = State(
|
||||
rules = RuleDraft.of(rule ?: Rule.Everything),
|
||||
choosingTemplate = rule == null && purpose == RulePurpose.SOURCE,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun updateRules(transform: (RuleDraft) -> RuleDraft) {
|
||||
_state.update { it?.copy(rules = transform(it.rules)) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts from [template]'s rules, or from none; *Next actions* with
|
||||
* [nextList]. [name] goes to an unnamed *Save as filter*.
|
||||
*/
|
||||
fun startFrom(template: FilterTemplate?, nextList: Long? = null, name: String? = null) {
|
||||
// The first pick wins; the picker stays up, and the editor untouched, until its rules are read.
|
||||
if (_state.value?.choosingTemplate != true || starting) return
|
||||
starting = true
|
||||
viewModelScope.launch {
|
||||
val form = template?.let { repository.templateForm(it, nextList) }
|
||||
_state.update { state ->
|
||||
state?.copy(
|
||||
rules = form?.let(RuleDraft::of) ?: state.rules,
|
||||
filterName = if (name != null && state.filterName.isBlank()) name else state.filterName,
|
||||
choosingTemplate = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var starting = false
|
||||
|
||||
fun setSaveAsFilter(on: Boolean) = _state.update { it?.copy(saveAsFilter = on) }
|
||||
|
||||
fun renameFilter(name: String) = _state.update { it?.copy(filterName = name) }
|
||||
|
||||
/**
|
||||
* Saves the rule, as a filter too when asked: into the block, or handed to
|
||||
* [onDone] as a result. [onDone] gets `null` for a block, which is written
|
||||
* here; a block that can't be written gets no filter either.
|
||||
*/
|
||||
fun save(onDone: (RuleEditResult?) -> Unit) {
|
||||
val state = _state.value ?: return
|
||||
val target = target ?: return
|
||||
if (saving || !state.canSave) return
|
||||
saving = true
|
||||
viewModelScope.launch {
|
||||
// Lists deleted while this was open don't come back with it.
|
||||
val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull().orEmpty()
|
||||
val rule = state.rules.rule.let { if (existing.isEmpty()) it else it.withoutListIds { id -> id !in existing } }
|
||||
val rules = RuleEditResult.Rules(rule)
|
||||
// A retry after a failed block write updates the filter made by the first try.
|
||||
suspend fun asFilter() = RuleEditResult.Filter(
|
||||
settingsPrefs.saveFilter(SavedFilter(savedFilterId ?: 0, state.filterName.trim(), rule)).also { savedFilterId = it },
|
||||
)
|
||||
when (target) {
|
||||
is Target.Result -> onDone(if (state.saveAsFilter) asFilter() else rules)
|
||||
is Target.Block -> {
|
||||
var written = writeSource(target, rules.source)
|
||||
if (written == WriteOutcome.WRITTEN && state.saveAsFilter) written = writeSource(target, asFilter().source)
|
||||
when (written) {
|
||||
WriteOutcome.WRITTEN -> onDone(null)
|
||||
WriteOutcome.GONE -> {
|
||||
saving = false
|
||||
_blockGone.value = true
|
||||
}
|
||||
WriteOutcome.REFUSED -> {
|
||||
saving = false
|
||||
_saveFailed.value = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var savedFilterId: Long? = null
|
||||
|
||||
private enum class WriteOutcome { WRITTEN, GONE, REFUSED }
|
||||
|
||||
/** Points the block at [source]: written, the block (or its view) is gone, or the views can't be written. */
|
||||
private suspend fun writeSource(target: Target.Block, source: BlockSource): WriteOutcome {
|
||||
var found = false
|
||||
val written = settingsPrefs.updateView(target.viewId) { view ->
|
||||
found = view.blocks.any { it.id == target.blockId }
|
||||
view.copy(blocks = view.blocks.map { if (it.id == target.blockId) it.copy(source = source) else it })
|
||||
}
|
||||
return when {
|
||||
written && found -> WriteOutcome.WRITTEN
|
||||
// updateView refuses a view it can't find as it does a store it can't write.
|
||||
!written && !settingsPrefs.writableViews() -> WriteOutcome.REFUSED
|
||||
else -> WriteOutcome.GONE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
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.automirrored.rounded.ListAlt
|
||||
import androidx.compose.material.icons.rounded.AccountTree
|
||||
import androidx.compose.material.icons.rounded.ChevronRight
|
||||
import androidx.compose.material.icons.rounded.Tune
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.ui.common.ListColorChip
|
||||
import de.jeanlucmakiola.floret.components.ConnectedChoiceRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
|
||||
/**
|
||||
* The rules of a filter, scope or block: the simple editor, or the advanced one
|
||||
* for a rule it can't show, with a row to switch between them. [onChange] gets
|
||||
* each change to apply to the draft.
|
||||
*/
|
||||
@Composable
|
||||
internal fun RuleEditorSections(
|
||||
draft: RuleDraft,
|
||||
lists: List<TaskList>,
|
||||
tagsInUse: List<String>,
|
||||
onChange: ((RuleDraft) -> RuleDraft) -> Unit,
|
||||
) {
|
||||
val simple = draft.simple
|
||||
if (simple != null) {
|
||||
SimpleSections(simple, lists, tagsInUse, onChange = { transform -> onChange { it.editSimple(transform) } })
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.filter_advanced),
|
||||
summary = stringResource(R.string.filter_advanced_hint),
|
||||
position = Position.Alone,
|
||||
leading = { Icon(Icons.Rounded.AccountTree, contentDescription = null) },
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { onChange { it.toAdvanced() } },
|
||||
)
|
||||
} else {
|
||||
AdvancedEditor(draft.rule, lists, tagsInUse, onChange = { transform -> onChange { it.editAdvanced(transform) } })
|
||||
Spacer(Modifier.height(16.dp))
|
||||
val canSimplify = draft.canSimplify
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.filter_simple),
|
||||
summary = stringResource(if (canSimplify) R.string.filter_simple_hint else R.string.filter_simple_unavailable),
|
||||
position = Position.Alone,
|
||||
dimmed = !canSimplify,
|
||||
leading = { Icon(Icons.Rounded.Tune, contentDescription = null) },
|
||||
trailing = if (canSimplify) {
|
||||
{ Icon(Icons.Rounded.ChevronRight, contentDescription = null) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = if (canSimplify) ({ onChange { it.toSimple() } }) else null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The simple editor: *all / any* on top, then lists, tags, due and priority,
|
||||
* each turned round by *is / is not* where that reads. Each multi-choice section
|
||||
* leads with an "any" row that is selected while nothing in it is, so an
|
||||
* untouched section visibly doesn't narrow.
|
||||
*/
|
||||
@Composable
|
||||
private fun SimpleSections(
|
||||
form: SimpleRule,
|
||||
lists: List<TaskList>,
|
||||
tagsInUse: List<String>,
|
||||
onChange: ((SimpleRule) -> SimpleRule) -> Unit,
|
||||
) {
|
||||
var choosingPriority by rememberSaveable { mutableStateOf(false) }
|
||||
var choosingDays by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
GroupedSectionHeader(stringResource(R.string.filter_match_title))
|
||||
ConnectedChoiceRow(
|
||||
options = Match.entries,
|
||||
selected = form.match,
|
||||
label = { stringResource(if (it == Match.ALL) R.string.filter_match_all else R.string.filter_match_any) },
|
||||
onSelect = { match -> onChange { it.copy(match = match) } },
|
||||
)
|
||||
|
||||
if (lists.isNotEmpty()) {
|
||||
NegatableHeader(stringResource(R.string.filter_section_lists), form.listsNegated, shown = !form.anyList) { negated ->
|
||||
onChange { it.copy(listsNegated = negated) }
|
||||
}
|
||||
val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_list),
|
||||
position = positionOf(0, lists.size + 1),
|
||||
selected = form.anyList,
|
||||
leading = { Icon(Icons.AutoMirrored.Rounded.ListAlt, contentDescription = null) },
|
||||
onClick = { onChange { it.copy(listIds = emptySet(), listsElsewhere = emptySet(), listsNegated = false) } },
|
||||
)
|
||||
lists.forEachIndexed { index, list ->
|
||||
ChoiceRow(
|
||||
title = list.name,
|
||||
summary = list.accountName.takeIf { showAccount },
|
||||
position = positionOf(index + 1, lists.size + 1),
|
||||
selected = list.id in form.listIds,
|
||||
leading = { ListColorChip(list.color) },
|
||||
onClick = { onChange { it.copy(listIds = it.listIds.toggle(list.id)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// A tag no open task carries any more stays listed while the form uses it, so it can still be unticked.
|
||||
val tags = remember(tagsInUse, form.tags) {
|
||||
(tagsInUse + form.tags).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER)
|
||||
}
|
||||
run {
|
||||
NegatableHeader(stringResource(R.string.filter_section_tags), form.tagsNegated, shown = form.tags.isNotEmpty()) { negated ->
|
||||
onChange { it.copy(tagsNegated = negated) }
|
||||
}
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_tag),
|
||||
position = positionOf(0, tags.size + 2),
|
||||
selected = form.tags.isEmpty(),
|
||||
onClick = { onChange { it.copy(tags = emptySet(), tagsNegated = false) } },
|
||||
)
|
||||
tags.forEachIndexed { index, tag ->
|
||||
ChoiceRow(
|
||||
title = tag,
|
||||
position = positionOf(index + 1, tags.size + 2),
|
||||
selected = tag in form.tags,
|
||||
onClick = { onChange { it.copy(tags = it.tags.toggle(tag)) } },
|
||||
)
|
||||
}
|
||||
OtherTagRow(position = positionOf(tags.size + 1, tags.size + 2), known = tags, onAdd = { tag -> onChange { it.copy(tags = it.tags + tag) } })
|
||||
if (form.tags.size > 1) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.filter_match_all_tags),
|
||||
summary = stringResource(
|
||||
if (form.tagMatch == TagMatch.ALL) R.string.filter_match_all_on else R.string.filter_match_all_off,
|
||||
),
|
||||
checked = form.tagMatch == TagMatch.ALL,
|
||||
onCheckedChange = { all -> onChange { it.copy(tagMatch = if (all) TagMatch.ALL else TagMatch.ANY) } },
|
||||
position = Position.Alone,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
NegatableHeader(stringResource(R.string.filter_section_due), form.dueNegated, shown = form.due.isNotEmpty()) { negated ->
|
||||
onChange { it.copy(dueNegated = negated) }
|
||||
}
|
||||
val windows = listOf(DueSpec.Window(DueWindow.OVERDUE), DueSpec.Window(DueWindow.TODAY), DueSpec.Window(DueWindow.UPCOMING))
|
||||
val ranges = listOf(DueSpec.ThisWeek, DueSpec.ThisMonth)
|
||||
val rows = 1 + windows.size + ranges.size + 2
|
||||
ChoiceRow(
|
||||
title = stringResource(R.string.filter_any_due),
|
||||
position = positionOf(0, rows),
|
||||
selected = form.due.isEmpty(),
|
||||
onClick = { onChange { it.copy(due = emptySet(), dueNegated = false) } },
|
||||
)
|
||||
(windows + ranges).forEachIndexed { index, spec ->
|
||||
ChoiceRow(
|
||||
title = dueLabel(spec),
|
||||
position = positionOf(index + 1, rows),
|
||||
selected = spec in form.due,
|
||||
onClick = { onChange { it.toggleDue(spec) } },
|
||||
)
|
||||
}
|
||||
val nextDays = form.nextDays
|
||||
GroupedRow(
|
||||
title = nextDays?.let { dueLabel(it) } ?: stringResource(R.string.filter_due_next_days_any),
|
||||
position = positionOf(rows - 2, rows),
|
||||
selected = nextDays != null,
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { choosingDays = true },
|
||||
)
|
||||
val noDate = DueSpec.Window(DueWindow.NO_DATE)
|
||||
ChoiceRow(
|
||||
title = dueLabel(noDate),
|
||||
position = positionOf(rows - 1, rows),
|
||||
selected = noDate in form.due,
|
||||
onClick = { onChange { it.toggleDue(noDate) } },
|
||||
)
|
||||
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_priority))
|
||||
GroupedRow(
|
||||
title = minPriorityLabel(form.minPriority),
|
||||
position = Position.Alone,
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { choosingPriority = true },
|
||||
)
|
||||
|
||||
if (choosingPriority) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.filter_section_priority),
|
||||
options = Priority.entries,
|
||||
selected = form.minPriority,
|
||||
label = { minPriorityLabel(it) },
|
||||
onSelect = { priority -> onChange { it.copy(minPriority = priority) } },
|
||||
onDismiss = { choosingPriority = false },
|
||||
)
|
||||
}
|
||||
if (choosingDays) {
|
||||
NextDaysPicker(
|
||||
selected = nextDays?.days,
|
||||
withNone = true,
|
||||
onSelect = { days -> onChange { it.withNextDays(days?.let(DueSpec::NextDays)) } },
|
||||
onDismiss = { choosingDays = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A section header with an *is / is not* switch at its end, [shown] while the
|
||||
* section picks something; "any" can't be turned round.
|
||||
*/
|
||||
@Composable
|
||||
private fun NegatableHeader(title: String, negated: Boolean, shown: Boolean, onNegate: (Boolean) -> Unit) {
|
||||
if (!shown) {
|
||||
GroupedSectionHeader(title)
|
||||
return
|
||||
}
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
GroupedSectionHeader(title, Modifier.weight(1f))
|
||||
ConnectedChoiceRow(
|
||||
options = listOf(false, true),
|
||||
selected = negated,
|
||||
label = { stringResource(if (it) R.string.filter_op_is_not else R.string.filter_op_is) },
|
||||
onSelect = onNegate,
|
||||
modifier = Modifier.width(NEGATE_WIDTH).padding(bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Room for the *is / is not* pair, its inset included. */
|
||||
private val NEGATE_WIDTH = 240.dp
|
||||
|
||||
@Composable
|
||||
internal fun ChoiceRow(
|
||||
title: String,
|
||||
position: Position,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
summary: String? = null,
|
||||
leading: @Composable (() -> Unit)? = null,
|
||||
) {
|
||||
GroupedRow(
|
||||
title = title,
|
||||
summary = summary,
|
||||
position = position,
|
||||
checked = selected,
|
||||
leading = leading,
|
||||
onClick = onClick,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun <T> Set<T>.toggle(item: T): Set<T> = if (item in this) this - item else this + item
|
||||
|
||||
/** A due condition's value, as in "Overdue" or "Next 7 days". */
|
||||
@Composable
|
||||
internal fun dueLabel(spec: DueSpec): String = when (spec) {
|
||||
is DueSpec.Window -> stringResource(
|
||||
when (spec.window) {
|
||||
DueWindow.OVERDUE -> R.string.smart_overdue
|
||||
DueWindow.TODAY -> R.string.smart_today
|
||||
DueWindow.UPCOMING -> R.string.smart_upcoming
|
||||
DueWindow.NO_DATE -> R.string.smart_no_date
|
||||
},
|
||||
)
|
||||
DueSpec.ThisWeek -> stringResource(R.string.filter_due_this_week)
|
||||
DueSpec.ThisMonth -> stringResource(R.string.filter_due_this_month)
|
||||
is DueSpec.NextDays -> pluralStringResource(R.plurals.filter_due_next_days, spec.days, spec.days)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun minPriorityLabel(priority: Priority): String = stringResource(
|
||||
when (priority) {
|
||||
Priority.NONE -> R.string.filter_priority_any
|
||||
Priority.LOW -> R.string.filter_priority_low
|
||||
Priority.MEDIUM -> R.string.filter_priority_medium
|
||||
Priority.HIGH -> R.string.filter_priority_high
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun priorityName(priority: Priority): String = stringResource(
|
||||
when (priority) {
|
||||
Priority.NONE -> R.string.priority_none
|
||||
Priority.LOW -> R.string.priority_low
|
||||
Priority.MEDIUM -> R.string.priority_medium
|
||||
Priority.HIGH -> R.string.priority_high
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,402 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ListAlt
|
||||
import androidx.compose.material.icons.rounded.Add
|
||||
import androidx.compose.material.icons.rounded.Bolt
|
||||
import androidx.compose.material.icons.rounded.CalendarMonth
|
||||
import androidx.compose.material.icons.rounded.CalendarViewWeek
|
||||
import androidx.compose.material.icons.rounded.Event
|
||||
import androidx.compose.material.icons.rounded.EventBusy
|
||||
import androidx.compose.material.icons.rounded.Flag
|
||||
import androidx.compose.material.icons.rounded.Schedule
|
||||
import androidx.compose.material.icons.rounded.Sell
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.ui.common.ListColorChip
|
||||
import de.jeanlucmakiola.agendula.ui.settings.CategoryIcon
|
||||
import de.jeanlucmakiola.agendula.ui.settings.ChipAccent
|
||||
import de.jeanlucmakiola.floret.components.CustomAmountEditor
|
||||
import de.jeanlucmakiola.floret.components.CustomExpandRow
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSurface
|
||||
import de.jeanlucmakiola.floret.components.InlineTextField
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
|
||||
/**
|
||||
* The "next N days" ranges: the presets, then a custom number. [withNone] leads
|
||||
* with a row that drops the range, for the simple editor, where it is optional.
|
||||
*/
|
||||
@Composable
|
||||
internal fun NextDaysPicker(
|
||||
selected: Int?,
|
||||
withNone: Boolean,
|
||||
onSelect: (Int?) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
FullScreenPicker(title = stringResource(R.string.filter_next_days_title), onDismiss = onDismiss) {
|
||||
val pick = { days: Int? ->
|
||||
onSelect(days)
|
||||
onDismiss()
|
||||
}
|
||||
if (withNone) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.filter_next_days_off),
|
||||
position = Position.Alone,
|
||||
checked = selected == null,
|
||||
onClick = { pick(null) },
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
NextDaysRows(selected, onPick = pick, first = 0, count = NEXT_DAYS_PRESETS.size + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The preset "next N days" rows and the custom one, at [first] of a run of
|
||||
* [count] rows; [onPick] gets the number of days.
|
||||
*/
|
||||
@Composable
|
||||
private fun NextDaysRows(selected: Int?, onPick: (Int) -> Unit, first: Int, count: Int) {
|
||||
NEXT_DAYS_PRESETS.forEachIndexed { index, days ->
|
||||
GroupedRow(
|
||||
title = dueLabel(DueSpec.NextDays(days)),
|
||||
position = positionOf(first + index, count),
|
||||
checked = selected == days,
|
||||
onClick = { onPick(days) },
|
||||
)
|
||||
}
|
||||
val custom = selected != null && selected !in NEXT_DAYS_PRESETS
|
||||
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||
var amountText by rememberSaveable { mutableStateOf(selected?.takeIf { custom }?.toString().orEmpty()) }
|
||||
val value = amountText.toIntOrNull()?.takeIf { it in 1..NEXT_DAYS_MAX }
|
||||
CustomExpandRow(
|
||||
title = if (custom) {
|
||||
stringResource(R.string.reminder_custom_with_value, dueLabel(DueSpec.NextDays(selected!!)))
|
||||
} else {
|
||||
stringResource(R.string.reminder_custom)
|
||||
},
|
||||
position = positionOf(first + NEXT_DAYS_PRESETS.size, count),
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = it },
|
||||
checked = custom,
|
||||
) {
|
||||
CustomAmountEditor(
|
||||
amountText = amountText,
|
||||
onAmountChange = { amountText = it },
|
||||
preview = value?.let { pluralStringResource(R.plurals.filter_due_next_days, it, it) }
|
||||
?: stringResource(R.string.filter_next_days_amount),
|
||||
setLabel = stringResource(R.string.reminder_custom_set),
|
||||
confirmEnabled = value != null,
|
||||
onConfirm = { value?.let(onPick) },
|
||||
placeholder = "7",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A due condition's value: a window, this week or month, or the next N days. */
|
||||
@Composable
|
||||
internal fun DuePicker(selected: DueSpec?, onSelect: (DueSpec) -> Unit, onDismiss: () -> Unit) {
|
||||
FullScreenPicker(title = stringResource(R.string.filter_field_due), onDismiss = onDismiss) {
|
||||
val pick = { spec: DueSpec ->
|
||||
onSelect(spec)
|
||||
onDismiss()
|
||||
}
|
||||
DUE_CHOICES.forEachIndexed { index, spec ->
|
||||
GroupedRow(
|
||||
title = dueLabel(spec),
|
||||
position = positionOf(index, DUE_CHOICES.size),
|
||||
checked = spec == selected,
|
||||
onClick = { pick(spec) },
|
||||
)
|
||||
}
|
||||
GroupedSectionHeader(stringResource(R.string.filter_next_days_title))
|
||||
NextDaysRows(
|
||||
selected = (selected as? DueSpec.NextDays)?.days,
|
||||
onPick = { pick(DueSpec.NextDays(it)) },
|
||||
first = 0,
|
||||
count = NEXT_DAYS_PRESETS.size + 1,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** What a new or changed condition checks. */
|
||||
@Composable
|
||||
internal fun FieldPicker(selected: RuleField?, onSelect: (RuleField) -> Unit, onDismiss: () -> Unit) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.filter_field_title),
|
||||
options = RuleField.entries,
|
||||
selected = selected,
|
||||
label = { fieldLabel(it!!) },
|
||||
leading = { Icon(fieldIcon(it!!), contentDescription = null) },
|
||||
onSelect = { it?.let(onSelect) },
|
||||
onDismiss = onDismiss,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The lists a list condition names, ticked on and off; [onDone] takes them, and
|
||||
* only while there is one.
|
||||
*/
|
||||
@Composable
|
||||
internal fun ListsPicker(
|
||||
lists: List<TaskList>,
|
||||
selected: Set<Long>,
|
||||
onDone: (Set<Long>) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var picked by remember { mutableStateOf(selected) }
|
||||
FullScreenPicker(
|
||||
title = stringResource(R.string.filter_section_lists),
|
||||
onDismiss = onDismiss,
|
||||
actions = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
onDone(picked)
|
||||
onDismiss()
|
||||
},
|
||||
enabled = picked.isNotEmpty(),
|
||||
modifier = Modifier.padding(end = 8.dp),
|
||||
) { Text(stringResource(R.string.picker_done)) }
|
||||
},
|
||||
) {
|
||||
if (lists.isEmpty()) {
|
||||
GroupedHint(stringResource(R.string.filter_lists_none))
|
||||
return@FullScreenPicker
|
||||
}
|
||||
val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1
|
||||
lists.forEachIndexed { index, list ->
|
||||
ChoiceRow(
|
||||
title = list.name,
|
||||
summary = list.accountName.takeIf { showAccount },
|
||||
position = positionOf(index, lists.size),
|
||||
selected = list.id in picked,
|
||||
leading = { ListColorChip(list.color) },
|
||||
onClick = { picked = picked.toggle(list.id) },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** The tag a tag condition names: one in use, or another one typed in. */
|
||||
@Composable
|
||||
internal fun TagPicker(tags: List<String>, selected: String?, onSelect: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
val options = remember(tags, selected) {
|
||||
(tags + listOfNotNull(selected)).distinct().sortedWith(String.CASE_INSENSITIVE_ORDER)
|
||||
}
|
||||
val pick = { tag: String ->
|
||||
onSelect(tag)
|
||||
onDismiss()
|
||||
}
|
||||
FullScreenPicker(title = stringResource(R.string.filter_section_tags), onDismiss = onDismiss) {
|
||||
if (options.isEmpty()) GroupedHint(stringResource(R.string.filter_tags_none))
|
||||
val count = options.size + 1
|
||||
options.forEachIndexed { index, tag ->
|
||||
GroupedRow(
|
||||
title = tag,
|
||||
position = positionOf(index, count),
|
||||
checked = tag == selected,
|
||||
onClick = { pick(tag) },
|
||||
)
|
||||
}
|
||||
OtherTagRow(position = positionOf(options.size, count), known = options, startExpanded = options.isEmpty(), onAdd = pick)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The "Other tag…" row closing a run of tag rows: it opens a field for a tag no
|
||||
* open task carries yet, and [onAdd] gets the tag typed, trimmed, in the
|
||||
* spelling of one of [known] that differs only in case.
|
||||
*/
|
||||
@Composable
|
||||
internal fun OtherTagRow(position: Position, known: List<String>, onAdd: (String) -> Unit, startExpanded: Boolean = false) {
|
||||
var expanded by rememberSaveable { mutableStateOf(startExpanded) }
|
||||
var typed by rememberSaveable { mutableStateOf("") }
|
||||
val add = {
|
||||
typed.trim().takeIf { it.isNotEmpty() }?.let { tag ->
|
||||
// Tags match exactly, so one differing only in case takes the spelling in use.
|
||||
onAdd(known.firstOrNull { it.equals(tag, ignoreCase = true) } ?: tag)
|
||||
typed = ""
|
||||
expanded = false
|
||||
}
|
||||
}
|
||||
CustomExpandRow(
|
||||
title = stringResource(R.string.filter_tag_other),
|
||||
position = position,
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = it },
|
||||
) {
|
||||
GroupedSurface(position = Position.Bottom, modifier = Modifier.padding(horizontal = GroupedListInset)) {
|
||||
Row(
|
||||
modifier = Modifier.padding(start = 16.dp, end = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
InlineTextField(
|
||||
value = typed,
|
||||
onValueChange = { typed = it },
|
||||
placeholder = stringResource(R.string.filter_tag_other_hint),
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
onImeAction = { add() },
|
||||
modifier = Modifier.weight(1f).padding(vertical = 12.dp),
|
||||
)
|
||||
TextButton(onClick = { add() }, enabled = typed.isNotBlank()) {
|
||||
Text(stringResource(R.string.reminder_custom_set))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The priority a priority condition asks for at least. */
|
||||
@Composable
|
||||
internal fun PriorityPicker(selected: Priority?, onSelect: (Priority) -> Unit, onDismiss: () -> Unit) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.filter_section_priority),
|
||||
options = PRIORITY_CHOICES,
|
||||
selected = selected,
|
||||
label = { priorityName(it!!) },
|
||||
onSelect = { it?.let(onSelect) },
|
||||
onDismiss = onDismiss,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Where new rules start: empty, or one of the [FilterTemplate]s. *Next actions*
|
||||
* first asks which of [lists] holds them, which can be skipped. [onStart] gets
|
||||
* the template (`null` for empty), that list, and the template's name for an
|
||||
* unnamed filter; [onDismiss] leaves without starting.
|
||||
*/
|
||||
@Composable
|
||||
internal fun TemplateChooser(
|
||||
title: String,
|
||||
lists: List<TaskList>,
|
||||
onStart: (template: FilterTemplate?, nextList: Long?, name: String?) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var askingList by rememberSaveable { mutableStateOf(false) }
|
||||
if (askingList) {
|
||||
val name = stringResource(templateName(FilterTemplate.NEXT_ACTIONS))
|
||||
NextListPicker(
|
||||
lists = lists,
|
||||
onPick = { onStart(FilterTemplate.NEXT_ACTIONS, it, name) },
|
||||
onDismiss = { askingList = false },
|
||||
)
|
||||
return
|
||||
}
|
||||
val names = FilterTemplate.entries.associateWith { stringResource(templateName(it)) }
|
||||
FullScreenPicker(title = title, onDismiss = onDismiss) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.filter_template_empty),
|
||||
summary = stringResource(R.string.filter_template_empty_hint),
|
||||
position = Position.Alone,
|
||||
leading = { CategoryIcon(Icons.Rounded.Add, ChipAccent.Primary) },
|
||||
onClick = { onStart(null, null, null) },
|
||||
)
|
||||
GroupedSectionHeader(stringResource(R.string.filter_templates_header))
|
||||
FilterTemplate.entries.forEachIndexed { index, template ->
|
||||
val (name, hint, icon) = templateLabels(template)
|
||||
GroupedRow(
|
||||
title = stringResource(name),
|
||||
summary = stringResource(hint),
|
||||
position = positionOf(index, FilterTemplate.entries.size),
|
||||
leading = { CategoryIcon(icon, ChipAccent.Primary) },
|
||||
onClick = {
|
||||
if (template == FilterTemplate.NEXT_ACTIONS) askingList = true else onStart(template, null, names[template])
|
||||
},
|
||||
)
|
||||
}
|
||||
GroupedHint(stringResource(R.string.filter_templates_note), verticalPadding = 8.dp)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** Which list holds the next actions; [onPick] gets `null` when skipped, for the tag alone. */
|
||||
@Composable
|
||||
private fun NextListPicker(lists: List<TaskList>, onPick: (Long?) -> Unit, onDismiss: () -> Unit) {
|
||||
FullScreenPicker(
|
||||
title = stringResource(R.string.filter_template_gtd_list_title),
|
||||
onDismiss = onDismiss,
|
||||
actions = {
|
||||
TextButton(onClick = { onPick(null) }, modifier = Modifier.padding(end = 8.dp)) {
|
||||
Text(stringResource(R.string.filter_template_gtd_skip))
|
||||
}
|
||||
},
|
||||
) {
|
||||
GroupedHint(stringResource(R.string.filter_template_gtd_list_hint))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val showAccount = lists.mapTo(HashSet()) { it.accountName }.size > 1
|
||||
lists.forEachIndexed { index, list ->
|
||||
GroupedRow(
|
||||
title = list.name,
|
||||
summary = list.accountName.takeIf { showAccount },
|
||||
position = positionOf(index, lists.size),
|
||||
leading = { ListColorChip(list.color) },
|
||||
onClick = { onPick(list.id) },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** The name a filter made from [template] starts with. */
|
||||
private fun templateName(template: FilterTemplate): Int =
|
||||
if (template == FilterTemplate.NEXT_ACTIONS) R.string.filter_template_gtd_name else templateLabels(template).first
|
||||
|
||||
private fun templateLabels(template: FilterTemplate): Triple<Int, Int, ImageVector> = when (template) {
|
||||
FilterTemplate.NEXT_ACTIONS -> Triple(R.string.filter_template_gtd, R.string.filter_template_gtd_hint, Icons.Rounded.Bolt)
|
||||
FilterTemplate.THIS_WEEK -> Triple(R.string.filter_template_week, R.string.filter_template_week_hint, Icons.Rounded.CalendarViewWeek)
|
||||
FilterTemplate.THIS_MONTH -> Triple(R.string.filter_template_month, R.string.filter_template_month_hint, Icons.Rounded.CalendarMonth)
|
||||
FilterTemplate.HIGH_PRIORITY -> Triple(R.string.filter_template_high, R.string.filter_template_high_hint, Icons.Rounded.Flag)
|
||||
FilterTemplate.WAITING_FOR -> Triple(R.string.filter_template_waiting, R.string.filter_template_waiting_hint, Icons.Rounded.Schedule)
|
||||
FilterTemplate.NO_DATE -> Triple(R.string.filter_template_no_date, R.string.filter_template_no_date_hint, Icons.Rounded.EventBusy)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun fieldLabel(field: RuleField): String = stringResource(
|
||||
when (field) {
|
||||
RuleField.LIST -> R.string.filter_field_list
|
||||
RuleField.TAG -> R.string.filter_field_tag
|
||||
RuleField.PRIORITY -> R.string.filter_field_priority
|
||||
RuleField.DUE -> R.string.filter_field_due
|
||||
},
|
||||
)
|
||||
|
||||
internal fun fieldIcon(field: RuleField): ImageVector = when (field) {
|
||||
RuleField.LIST -> Icons.AutoMirrored.Rounded.ListAlt
|
||||
RuleField.TAG -> Icons.Rounded.Sell
|
||||
RuleField.PRIORITY -> Icons.Rounded.Flag
|
||||
RuleField.DUE -> Icons.Rounded.Event
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
|
||||
/**
|
||||
* The advanced editor's view of a [Rule]: groups ([Rule.AllOf], [Rule.AnyOf],
|
||||
* either under a [Rule.Not]) holding conditions ([Rule.InList], [Rule.HasTag],
|
||||
* [Rule.MinPriority], [Rule.Due], each maybe under a [Rule.Not]) and further
|
||||
* groups. A path names a node by the child index at each group on the way down.
|
||||
*/
|
||||
typealias RulePath = List<Int>
|
||||
|
||||
/** What a condition checks. */
|
||||
enum class RuleField { LIST, TAG, PRIORITY, DUE }
|
||||
|
||||
/** Whether this is a group, negated or not. */
|
||||
val Rule.isGroup: Boolean
|
||||
get() = when (this) {
|
||||
is Rule.AllOf, is Rule.AnyOf -> true
|
||||
is Rule.Not -> child is Rule.AllOf || child is Rule.AnyOf
|
||||
else -> false
|
||||
}
|
||||
|
||||
/** Whether this group or condition is under a [Rule.Not]. */
|
||||
val Rule.negated: Boolean get() = this is Rule.Not
|
||||
|
||||
/** The group or condition itself, without its [Rule.Not]. */
|
||||
val Rule.positive: Rule get() = if (this is Rule.Not) child else this
|
||||
|
||||
/** A group's kind; `null` for a condition. */
|
||||
val Rule.groupMatch: Match?
|
||||
get() = when (positive) {
|
||||
is Rule.AllOf -> Match.ALL
|
||||
is Rule.AnyOf -> Match.ANY
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** A group's children; empty for a condition. */
|
||||
val Rule.groupChildren: List<Rule>
|
||||
get() = when (val group = positive) {
|
||||
is Rule.AllOf -> group.children
|
||||
is Rule.AnyOf -> group.children
|
||||
else -> emptyList()
|
||||
}
|
||||
|
||||
/** What a condition checks; `null` for a group. */
|
||||
val Rule.field: RuleField?
|
||||
get() = when (positive) {
|
||||
is Rule.InList -> RuleField.LIST
|
||||
is Rule.HasTag -> RuleField.TAG
|
||||
is Rule.MinPriority -> RuleField.PRIORITY
|
||||
is Rule.Due -> RuleField.DUE
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** This rule under a [Rule.Not], or out of it. */
|
||||
fun Rule.toggleNot(): Rule = if (this is Rule.Not) child else Rule.Not(this)
|
||||
|
||||
/** [positive] replaced by [transform]'s result, keeping the [Rule.Not]. */
|
||||
fun Rule.mapPositive(transform: (Rule) -> Rule): Rule =
|
||||
if (this is Rule.Not) Rule.Not(transform(child)) else transform(this)
|
||||
|
||||
/** This group as a group of [match], with the same children and negation. */
|
||||
fun Rule.withGroupMatch(match: Match): Rule = mapPositive { group ->
|
||||
val children = group.groupChildren
|
||||
if (match == Match.ALL) Rule.AllOf(children) else Rule.AnyOf(children)
|
||||
}
|
||||
|
||||
private fun Rule.withGroupChildren(children: List<Rule>): Rule = mapPositive { group ->
|
||||
if (group is Rule.AnyOf) Rule.AnyOf(children) else Rule.AllOf(children)
|
||||
}
|
||||
|
||||
/** The node at [path]; `null` when there is none. */
|
||||
fun Rule.at(path: RulePath): Rule? =
|
||||
if (path.isEmpty()) this else groupChildren.getOrNull(path.first())?.at(path.drop(1))
|
||||
|
||||
/** This rule with the node at [path] replaced by [transform]'s result; unchanged when there is none. */
|
||||
fun Rule.updateAt(path: RulePath, transform: (Rule) -> Rule): Rule {
|
||||
if (path.isEmpty()) return transform(this)
|
||||
val children = groupChildren
|
||||
val index = path.first()
|
||||
if (index !in children.indices) return this
|
||||
return withGroupChildren(children.toMutableList().also { it[index] = it[index].updateAt(path.drop(1), transform) })
|
||||
}
|
||||
|
||||
/** This rule without the node at [path]; the root can't be removed. */
|
||||
fun Rule.removeAt(path: RulePath): Rule {
|
||||
if (path.isEmpty()) return this
|
||||
return updateAt(path.dropLast(1)) { group ->
|
||||
val children = group.groupChildren
|
||||
val index = path.last()
|
||||
if (index in children.indices) group.withGroupChildren(children.filterIndexed { i, _ -> i != index }) else group
|
||||
}
|
||||
}
|
||||
|
||||
/** This rule with [child] added last to the group at [path]. */
|
||||
fun Rule.addTo(path: RulePath, child: Rule): Rule = updateAt(path) { group ->
|
||||
if (group.isGroup) group.withGroupChildren(group.groupChildren + child) else group
|
||||
}
|
||||
|
||||
/** A new, empty group for under [parent]: of the other kind, since one of the same adds nothing. */
|
||||
fun newGroupUnder(parent: Rule): Rule = if (parent.groupMatch == Match.ANY) Rule.AllOf(emptyList()) else Rule.AnyOf(emptyList())
|
||||
|
||||
/**
|
||||
* This rule as the advanced editor shows it: a group at the root (a lone
|
||||
* condition goes into an all-of group) and no `not(not(…))`, which reads as
|
||||
* what it holds. Both mean the same as before.
|
||||
*/
|
||||
fun Rule.forAdvanced(): Rule {
|
||||
val tidy = withoutDoubleNegation()
|
||||
return if (tidy.isGroup) tidy else Rule.AllOf(listOf(tidy))
|
||||
}
|
||||
|
||||
private fun Rule.withoutDoubleNegation(): Rule = when (this) {
|
||||
is Rule.Not -> if (child is Rule.Not) child.child.withoutDoubleNegation() else Rule.Not(child.withoutDoubleNegation())
|
||||
is Rule.AllOf -> Rule.AllOf(children.map { it.withoutDoubleNegation() })
|
||||
is Rule.AnyOf -> Rule.AnyOf(children.map { it.withoutDoubleNegation() })
|
||||
is Rule.InList, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> this
|
||||
}
|
||||
|
||||
/** Whether every task passes this rule by its shape alone, as an empty all-of group does. */
|
||||
val Rule.admitsEverything: Boolean
|
||||
get() = when (this) {
|
||||
is Rule.AllOf -> children.all { it.admitsEverything }
|
||||
is Rule.AnyOf -> children.any { it.admitsEverything }
|
||||
is Rule.Not -> child.matchesNothing
|
||||
is Rule.MinPriority -> priority == Priority.NONE
|
||||
is Rule.InList, is Rule.HasTag, is Rule.Due -> false
|
||||
}
|
||||
|
||||
/** Whether no task passes this rule by its shape alone, as an empty any-of group or a list condition naming no list. */
|
||||
val Rule.matchesNothing: Boolean
|
||||
get() = when (this) {
|
||||
is Rule.AllOf -> children.any { it.matchesNothing }
|
||||
is Rule.AnyOf -> children.all { it.matchesNothing }
|
||||
is Rule.Not -> child.admitsEverything
|
||||
is Rule.InList -> listIds.isEmpty() && elsewhere.isEmpty()
|
||||
is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> false
|
||||
}
|
||||
|
||||
/** The values a due condition offers, besides "next N days". */
|
||||
val DUE_CHOICES: List<DueSpec> = DueWindow.entries.map(DueSpec::Window) + listOf(DueSpec.ThisWeek, DueSpec.ThisMonth)
|
||||
|
||||
/** The "next N days" ranges offered before a custom one. */
|
||||
val NEXT_DAYS_PRESETS: List<Int> = listOf(3, 7, 14, 30)
|
||||
|
||||
/** The longest "next N days" range that can be entered. */
|
||||
const val NEXT_DAYS_MAX = 365
|
||||
|
||||
/** The priorities a condition can ask for at least. */
|
||||
val PRIORITY_CHOICES: List<Priority> = listOf(Priority.LOW, Priority.MEDIUM, Priority.HIGH)
|
||||
@@ -0,0 +1,202 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
|
||||
/** How the conditions of a group combine: every one ([ALL]) or at least one ([ANY]). */
|
||||
enum class Match { ALL, ANY }
|
||||
|
||||
/**
|
||||
* A rule as the simple editor shows it: up to four criteria joined by [match],
|
||||
* each of which can be turned round with *is not*. An empty criterion doesn't
|
||||
* narrow: no [due] means any due date, no lists any list, no [tags] any tag,
|
||||
* [Priority.NONE] any priority.
|
||||
*
|
||||
* [toRule] writes, in this order, the criteria that narrow:
|
||||
* - due: `or(due…)` over [due], under `not(…)` when [dueNegated];
|
||||
* - lists: `list(…)`, under `not(…)` when [listsNegated];
|
||||
* - priority: `prio(…)`;
|
||||
* - tags: `or(tag…)`, or `and(tag…)` for [TagMatch.ALL], under `not(…)` when [tagsNegated];
|
||||
*
|
||||
* all inside `and(…)` for [Match.ALL] or `or(…)` for [Match.ANY]. A form that
|
||||
* narrows by nothing is every task, whatever [match] says.
|
||||
*
|
||||
* [of] reads those rules back unchanged, plus a few shapes that mean the same
|
||||
* (see [of]); anything else needs the advanced editor.
|
||||
*/
|
||||
data class SimpleRule(
|
||||
val match: Match = Match.ALL,
|
||||
val due: Set<DueSpec> = emptySet(),
|
||||
val dueNegated: Boolean = false,
|
||||
val listIds: Set<Long> = emptySet(),
|
||||
val listsElsewhere: Set<String> = emptySet(),
|
||||
val listsNegated: Boolean = false,
|
||||
val tags: Set<String> = emptySet(),
|
||||
val tagMatch: TagMatch = TagMatch.ANY,
|
||||
val tagsNegated: Boolean = false,
|
||||
val minPriority: Priority = Priority.NONE,
|
||||
) {
|
||||
/** Whether the form narrows by list at all. */
|
||||
val anyList: Boolean get() = listIds.isEmpty() && listsElsewhere.isEmpty()
|
||||
|
||||
/** The "next N days" range among [due], if one is picked. */
|
||||
val nextDays: DueSpec.NextDays? get() = due.firstNotNullOfOrNull { it as? DueSpec.NextDays }
|
||||
|
||||
/** [due] with [spec] added, or taken out when it is there. A second "next N days" replaces the first. */
|
||||
fun toggleDue(spec: DueSpec): SimpleRule = when {
|
||||
spec in due -> copy(due = due - spec)
|
||||
spec is DueSpec.NextDays -> copy(due = due.filterNot { it is DueSpec.NextDays }.toSet() + spec)
|
||||
else -> copy(due = due + spec)
|
||||
}
|
||||
|
||||
/** [due] with the "next N days" range set to [spec], or dropped for `null`. */
|
||||
fun withNextDays(spec: DueSpec.NextDays?): SimpleRule =
|
||||
copy(due = due.filterNot { it is DueSpec.NextDays }.toSet() + listOfNotNull(spec))
|
||||
|
||||
/** This form with *is not* dropped from the sections that pick nothing, where it can't apply. */
|
||||
fun tidy(): SimpleRule = copy(
|
||||
dueNegated = dueNegated && due.isNotEmpty(),
|
||||
listsNegated = listsNegated && !anyList,
|
||||
tagsNegated = tagsNegated && tags.isNotEmpty(),
|
||||
)
|
||||
|
||||
fun toRule(): Rule {
|
||||
val parts = buildList {
|
||||
if (due.isNotEmpty()) add(Rule.AnyOf(due.sortedBy(::dueRank).map(Rule::Due)).negatedIf(dueNegated))
|
||||
if (!anyList) add(Rule.InList(listIds, listsElsewhere).negatedIf(listsNegated))
|
||||
if (minPriority != Priority.NONE) add(Rule.MinPriority(minPriority))
|
||||
if (tags.isNotEmpty()) {
|
||||
val each = tags.sorted().map(Rule::HasTag)
|
||||
add((if (tagMatch == TagMatch.ALL) Rule.AllOf(each) else Rule.AnyOf(each)).negatedIf(tagsNegated))
|
||||
}
|
||||
}
|
||||
return if (match == Match.ANY && parts.isNotEmpty()) Rule.AnyOf(parts) else Rule.AllOf(parts)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* [rule] as the simple form, or `null` when it has none. The form reads:
|
||||
* - what [toRule] writes, so `of(form.toRule()) == form` for any form that
|
||||
* narrows, and `of(rule)!!.toRule() == rule` for any rule [toRule] wrote;
|
||||
* - a lone criterion in place of the `and(…)`, as a pinned list's scope is;
|
||||
* - each criterion in any order, and as its bare condition (`tag(a)` for
|
||||
* `or(tag(a))`, `due(TODAY)` for `or(due(TODAY))`);
|
||||
* - several bare tags straight in the top group, read with its own
|
||||
* all/any, and several bare due conditions in an `or(…)` top group.
|
||||
*
|
||||
* Those read back written the canonical way, meaning the same. Not readable:
|
||||
* a criterion given twice in other ways, a negated priority, a `not(not(…))`,
|
||||
* an empty or doubled-up due/tag group, two "next N days", a list condition
|
||||
* naming no list, nested groups beyond these, and an empty `or()`, which
|
||||
* matches nothing.
|
||||
*/
|
||||
fun of(rule: Rule): SimpleRule? {
|
||||
val (match, parts) = when (rule) {
|
||||
is Rule.AllOf -> Match.ALL to rule.children
|
||||
is Rule.AnyOf -> if (rule.children.isEmpty()) return null else Match.ANY to rule.children
|
||||
else -> Match.ALL to listOf(rule)
|
||||
}
|
||||
val pieces = parts.map { piece(it) ?: return null }.groupBy { it::class }
|
||||
var form = SimpleRule(match = match)
|
||||
for ((_, kind) in pieces) {
|
||||
val merged = if (kind.size == 1) kind.single() else merge(kind, match) ?: return null
|
||||
form = when (merged) {
|
||||
is Piece.Due -> {
|
||||
if (merged.specs.count { it is DueSpec.NextDays } > 1) return null
|
||||
form.copy(due = merged.specs, dueNegated = merged.negated)
|
||||
}
|
||||
is Piece.Lists -> form.copy(
|
||||
listIds = merged.list.listIds,
|
||||
listsElsewhere = merged.list.elsewhere,
|
||||
listsNegated = merged.negated,
|
||||
)
|
||||
is Piece.Prio -> form.copy(minPriority = merged.priority)
|
||||
is Piece.Tags -> form.copy(
|
||||
tags = merged.tags,
|
||||
tagMatch = merged.match ?: TagMatch.ANY,
|
||||
tagsNegated = merged.negated,
|
||||
)
|
||||
}
|
||||
}
|
||||
return form
|
||||
}
|
||||
|
||||
/** One criterion of the top group; [bare] when it was a lone condition, not a group of them. */
|
||||
private sealed interface Piece {
|
||||
val negated: Boolean
|
||||
val bare: Boolean
|
||||
|
||||
data class Due(val specs: Set<DueSpec>, override val negated: Boolean, override val bare: Boolean) : Piece
|
||||
data class Lists(val list: Rule.InList, override val negated: Boolean) : Piece {
|
||||
override val bare get() = true
|
||||
}
|
||||
data class Prio(val priority: Priority) : Piece {
|
||||
override val negated get() = false
|
||||
override val bare get() = true
|
||||
}
|
||||
|
||||
/** [match] is `null` for a bare tag, which reads either way. */
|
||||
data class Tags(val tags: Set<String>, val match: TagMatch?, override val negated: Boolean, override val bare: Boolean) : Piece
|
||||
}
|
||||
|
||||
private fun piece(part: Rule): Piece? {
|
||||
val negated = part is Rule.Not
|
||||
val inner = if (part is Rule.Not) part.child else part
|
||||
return when (inner) {
|
||||
is Rule.Due -> Piece.Due(setOf(inner.spec), negated, bare = true)
|
||||
is Rule.InList -> if (inner.listIds.isEmpty() && inner.elsewhere.isEmpty()) null else Piece.Lists(inner, negated)
|
||||
is Rule.MinPriority -> if (negated || inner.priority == Priority.NONE) null else Piece.Prio(inner.priority)
|
||||
is Rule.HasTag -> Piece.Tags(setOf(inner.tag), null, negated, bare = true)
|
||||
is Rule.AnyOf -> group(inner.children, TagMatch.ANY, negated, dueAllowed = true)
|
||||
is Rule.AllOf -> group(inner.children, TagMatch.ALL, negated, dueAllowed = false)
|
||||
is Rule.Not -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** A group of due conditions (an `or` only) or of tags; `null` for anything else, or a repeat. */
|
||||
private fun group(children: List<Rule>, match: TagMatch, negated: Boolean, dueAllowed: Boolean): Piece? {
|
||||
if (children.isEmpty()) return null
|
||||
val specs = children.mapNotNull { (it as? Rule.Due)?.spec }
|
||||
val tags = children.mapNotNull { (it as? Rule.HasTag)?.tag }
|
||||
return when {
|
||||
dueAllowed && specs.size == children.size && specs.toSet().size == specs.size ->
|
||||
Piece.Due(specs.toSet(), negated, bare = false)
|
||||
tags.size == children.size && tags.toSet().size == tags.size ->
|
||||
Piece.Tags(tags.toSet(), match, negated, bare = false)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** Bare tags joined by the top group, or bare due conditions under an `or(…)` top. */
|
||||
private fun merge(pieces: List<Piece>, top: Match): Piece? {
|
||||
if (pieces.any { it.negated || !it.bare }) return null
|
||||
return when (val first = pieces.first()) {
|
||||
is Piece.Tags -> {
|
||||
val tags = pieces.flatMap { (it as Piece.Tags).tags }
|
||||
if (tags.toSet().size != tags.size) return null
|
||||
Piece.Tags(tags.toSet(), if (top == Match.ALL) TagMatch.ALL else TagMatch.ANY, negated = false, bare = false)
|
||||
}
|
||||
is Piece.Due -> {
|
||||
if (top != Match.ANY) return null
|
||||
val specs = pieces.flatMap { (it as Piece.Due).specs }
|
||||
if (specs.toSet().size != specs.size) return null
|
||||
first.copy(specs = specs.toSet(), bare = false)
|
||||
}
|
||||
is Piece.Lists, is Piece.Prio -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** The order [toRule] writes due conditions in: the windows as listed, then the ranges. */
|
||||
internal fun dueRank(spec: DueSpec): Int = when (spec) {
|
||||
is DueSpec.Window -> spec.window.ordinal
|
||||
DueSpec.ThisWeek -> DueWindow.entries.size
|
||||
DueSpec.ThisMonth -> DueWindow.entries.size + 1
|
||||
is DueSpec.NextDays -> DueWindow.entries.size + 2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun Rule.negatedIf(negated: Boolean): Rule = if (negated) Rule.Not(this) else this
|
||||
@@ -28,7 +28,6 @@ import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.ButtonGroup
|
||||
import androidx.compose.material3.ButtonGroupScope
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -60,6 +59,7 @@ import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import de.jeanlucmakiola.floret.components.BusyIndicator
|
||||
|
||||
private val PICK_TYPES = arrayOf("text/calendar", "text/x-vcalendar", "application/zip", "*/*")
|
||||
|
||||
@@ -312,7 +312,7 @@ private fun Progress(label: String) {
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
CircularProgressIndicator(Modifier.size(18.dp))
|
||||
BusyIndicator(Modifier.size(18.dp))
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
|
||||
@@ -0,0 +1,745 @@
|
||||
package de.jeanlucmakiola.agendula.ui.lists
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ListAlt
|
||||
import androidx.compose.material.icons.automirrored.rounded.ShortText
|
||||
import androidx.compose.material.icons.rounded.Add
|
||||
import androidx.compose.material.icons.rounded.Apps
|
||||
import androidx.compose.material.icons.rounded.CalendarViewWeek
|
||||
import androidx.compose.material.icons.rounded.Check
|
||||
import androidx.compose.material.icons.rounded.Checklist
|
||||
import androidx.compose.material.icons.rounded.ChevronRight
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.DragHandle
|
||||
import androidx.compose.material.icons.rounded.FilterList
|
||||
import androidx.compose.material.icons.rounded.History
|
||||
import androidx.compose.material.icons.rounded.Palette
|
||||
import androidx.compose.material.icons.rounded.Sell
|
||||
import androidx.compose.material.icons.rounded.Sort
|
||||
import androidx.compose.material.icons.rounded.SwapHoriz
|
||||
import androidx.compose.material.icons.rounded.TaskAlt
|
||||
import androidx.compose.material.icons.rounded.ViewAgenda
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.PathEffect
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.Block
|
||||
import de.jeanlucmakiola.agendula.domain.BlockOptions
|
||||
import de.jeanlucmakiola.agendula.domain.BlockType
|
||||
import de.jeanlucmakiola.agendula.domain.BlockWidth
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSortOrder
|
||||
import de.jeanlucmakiola.agendula.domain.TileColor
|
||||
import de.jeanlucmakiola.agendula.domain.canAdd
|
||||
import de.jeanlucmakiola.agendula.ui.common.ActionShapes
|
||||
import de.jeanlucmakiola.agendula.ui.common.NameField
|
||||
import de.jeanlucmakiola.agendula.ui.settings.CategoryIcon
|
||||
import de.jeanlucmakiola.agendula.ui.settings.ChipAccent
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.sortLabel
|
||||
import de.jeanlucmakiola.agendula.ui.views.ViewIconPicker
|
||||
import de.jeanlucmakiola.agendula.ui.views.label
|
||||
import de.jeanlucmakiola.agendula.ui.views.vector
|
||||
import de.jeanlucmakiola.agendula.ui.views.viewName
|
||||
import de.jeanlucmakiola.floret.components.ActionButton
|
||||
import de.jeanlucmakiola.floret.components.ConnectedChoiceRow
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GridSpan
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.ReorderableGrid
|
||||
import de.jeanlucmakiola.floret.components.inset
|
||||
import de.jeanlucmakiola.floret.components.SelectedCheck
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.identity.FloretDensity
|
||||
|
||||
/** The top bar while a layout is edited: ✕ to discard, its title, *Add block* and ✓ Done. */
|
||||
@Composable
|
||||
internal fun EditLayoutTopBar(onDiscard: () -> Unit, onAdd: () -> Unit, onDone: () -> Unit) {
|
||||
Surface(color = MaterialTheme.colorScheme.surface) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.windowInsetsPadding(TopAppBarDefaults.windowInsets)
|
||||
.height(72.dp)
|
||||
.padding(horizontal = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
ActionButton(
|
||||
shape = ActionShapes.DiscardLayout,
|
||||
icon = Icons.Rounded.Close,
|
||||
contentDescription = stringResource(R.string.edit_layout_discard),
|
||||
onClick = onDiscard,
|
||||
size = 48.dp,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
stringResource(R.string.view_edit_layout),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
ActionButton(
|
||||
shape = ActionShapes.AddBlock,
|
||||
morphTo = ActionShapes.AddListPressed,
|
||||
icon = Icons.Rounded.Add,
|
||||
contentDescription = stringResource(R.string.block_add),
|
||||
onClick = onAdd,
|
||||
size = 48.dp,
|
||||
)
|
||||
Button(onClick = onDone, modifier = Modifier.padding(start = 8.dp)) {
|
||||
Icon(Icons.Rounded.Check, contentDescription = null, modifier = Modifier.size(ButtonDefaults.IconSize))
|
||||
Spacer(Modifier.width(ButtonDefaults.IconSpacing))
|
||||
Text(stringResource(R.string.edit_layout_done))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The view's blocks to rearrange: dragged by their handle or after a long
|
||||
* press, made half or full width, removed, or tapped for their settings. *Add
|
||||
* block* closes the grid. The task list stays last and doesn't move.
|
||||
*/
|
||||
@Composable
|
||||
internal fun EditLayoutContent(
|
||||
state: ListsUiState.Content,
|
||||
onMove: (List<Long>) -> Unit,
|
||||
onResize: (Block, BlockWidth) -> Unit,
|
||||
onRemove: (Block) -> Unit,
|
||||
onOpenSettings: (Block) -> Unit,
|
||||
onAdd: () -> Unit,
|
||||
bottomPadding: Dp,
|
||||
) {
|
||||
val scroll = rememberScrollState()
|
||||
// Blocks show what they hold, but nothing in them opens while the layout is edited.
|
||||
val inert = BlockActions(
|
||||
openFilter = { _, _ -> },
|
||||
openTask = {},
|
||||
toggleDone = {},
|
||||
chooseSource = {},
|
||||
newList = {},
|
||||
newFilter = {},
|
||||
reorderLists = {},
|
||||
scopeFor = { null },
|
||||
)
|
||||
Column(Modifier.fillMaxSize().verticalScroll(scroll).padding(top = 8.dp, bottom = bottomPadding)) {
|
||||
ReorderableGrid(
|
||||
items = state.view.blocks,
|
||||
keyOf = { it.id },
|
||||
spanOf = { if (it.width == BlockWidth.HALF) GridSpan.Half else GridSpan.Full },
|
||||
onReorder = { blocks -> onMove(blocks.map { it.id }) },
|
||||
canDrag = { it.type != BlockType.TASK_LIST },
|
||||
scrollState = scroll,
|
||||
dragShape = { block, column ->
|
||||
val (start, end) = blockInsets(block, column)
|
||||
RoundedCornerShape(if (block.type in TILES) 22.dp else SectionCardRadius).inset(start, end)
|
||||
},
|
||||
moveEarlierLabel = stringResource(R.string.block_move_earlier),
|
||||
moveLaterLabel = stringResource(R.string.block_move_later),
|
||||
) { block, column, dragHandle, dragging ->
|
||||
EditBlockFrame(
|
||||
block = block,
|
||||
state = state,
|
||||
actions = inert,
|
||||
column = column,
|
||||
dragHandle = dragHandle,
|
||||
dragging = dragging,
|
||||
onResize = { onResize(block, it) },
|
||||
onRemove = { onRemove(block) },
|
||||
onOpenSettings = { onOpenSettings(block) },
|
||||
)
|
||||
}
|
||||
AddBlockTile(onAdd)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One block in the edit grid with its controls: a tile carries them in its
|
||||
* corner, a section on its title line. Tapping the block opens its settings.
|
||||
*/
|
||||
@Composable
|
||||
private fun EditBlockFrame(
|
||||
block: Block,
|
||||
state: ListsUiState.Content,
|
||||
actions: BlockActions,
|
||||
column: Int,
|
||||
dragHandle: Modifier,
|
||||
dragging: Boolean,
|
||||
onResize: (BlockWidth) -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
) {
|
||||
// A heading's own text shows as its content, under the name of its kind.
|
||||
val heading = block.type == BlockType.SECTION_HEADING
|
||||
val typeName = stringResource(block.type.label)
|
||||
val title = if (heading) typeName else blockTitle(block, state).ifBlank { typeName }
|
||||
val settingsLabel = stringResource(R.string.block_settings)
|
||||
// A long press belongs to the grid, which starts a drag; letting go of one doesn't open the settings.
|
||||
val tapTarget = Modifier
|
||||
.clickable(onClickLabel = settingsLabel) { if (!dragging) onOpenSettings() }
|
||||
.semantics { contentDescription = if (title == typeName) title else "$typeName, $title" }
|
||||
val controls: @Composable () -> Unit = {
|
||||
BlockControls(block, dragHandle, onResize, onRemove)
|
||||
}
|
||||
if (block.type in TILES) {
|
||||
val (start, end) = blockInsets(block, column)
|
||||
Box(Modifier.padding(start = start, end = end)) {
|
||||
Box(Modifier.clearAndSetSemantics {}) { Tile(block, state, actions, Modifier.fillMaxWidth()) }
|
||||
Box(Modifier.matchParentSize().clip(RoundedCornerShape(22.dp)).then(tapTarget))
|
||||
Row(Modifier.align(Alignment.TopEnd).padding(4.dp)) { controls() }
|
||||
}
|
||||
return
|
||||
}
|
||||
// A held section is lifted as a card, so the shadow has something to sit under.
|
||||
val card = MaterialTheme.colorScheme.surfaceContainerLow
|
||||
val lifted = if (dragging) {
|
||||
Modifier.drawBehind {
|
||||
val inset = SectionCardInset.toPx()
|
||||
drawRoundRect(
|
||||
color = card,
|
||||
topLeft = Offset(inset, 0f),
|
||||
size = Size(size.width - 2 * inset, size.height),
|
||||
cornerRadius = CornerRadius(SectionCardRadius.toPx()),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Modifier
|
||||
}
|
||||
Column(lifted.padding(bottom = if (dragging) 8.dp else 0.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 28.dp, end = 12.dp, top = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
controls()
|
||||
}
|
||||
Box {
|
||||
Box(Modifier.clearAndSetSemantics {}) {
|
||||
BlockBody(block, state, actions, editing = true, showHeader = heading)
|
||||
}
|
||||
Box(Modifier.matchParentSize().then(tapTarget))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How far a block's card sits in from the sides of its grid slot. */
|
||||
private fun blockInsets(block: Block, column: Int): Pair<Dp, Dp> = when {
|
||||
block.type !in TILES -> SectionCardInset to SectionCardInset
|
||||
block.width == BlockWidth.FULL -> GroupedListInset to GroupedListInset
|
||||
column == 0 -> GroupedListInset to 0.dp
|
||||
else -> 0.dp to GroupedListInset
|
||||
}
|
||||
|
||||
private val SectionCardInset = 8.dp
|
||||
private val SectionCardRadius = 28.dp
|
||||
|
||||
/** A block's drag handle, its half/full switch where its type has both, and ✕. */
|
||||
@Composable
|
||||
private fun BlockControls(
|
||||
block: Block,
|
||||
dragHandle: Modifier,
|
||||
onResize: (BlockWidth) -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (block.type != BlockType.TASK_LIST) {
|
||||
Box(
|
||||
modifier = dragHandle
|
||||
.size(36.dp)
|
||||
.clip(CircleShape)
|
||||
.background(MaterialTheme.colorScheme.surfaceContainerHighest.copy(alpha = 0.7f)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Rounded.DragHandle,
|
||||
contentDescription = stringResource(R.string.block_drag),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (block.type.widths.size > 1) {
|
||||
val toFull = block.width == BlockWidth.HALF
|
||||
ActionButton(
|
||||
shape = ActionShapes.ResizeBlock,
|
||||
icon = Icons.Rounded.SwapHoriz,
|
||||
contentDescription = stringResource(if (toFull) R.string.block_make_full else R.string.block_make_half),
|
||||
onClick = { onResize(if (toFull) BlockWidth.FULL else BlockWidth.HALF) },
|
||||
size = 36.dp,
|
||||
iconSize = 20.dp,
|
||||
)
|
||||
}
|
||||
ActionButton(
|
||||
shape = ActionShapes.RemoveBlock,
|
||||
icon = Icons.Rounded.Close,
|
||||
contentDescription = stringResource(R.string.block_remove),
|
||||
onClick = onRemove,
|
||||
size = 36.dp,
|
||||
iconSize = 20.dp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The dashed *Add block* tile that closes the edit grid. */
|
||||
@Composable
|
||||
private fun AddBlockTile(onAdd: () -> Unit) {
|
||||
val outline = MaterialTheme.colorScheme.outline
|
||||
Surface(
|
||||
onClick = onAdd,
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = GroupedListInset, vertical = 16.dp)
|
||||
.drawBehind {
|
||||
drawRoundRect(
|
||||
color = outline,
|
||||
cornerRadius = CornerRadius(22.dp.toPx()),
|
||||
style = Stroke(width = 1.5.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(8.dp.toPx(), 6.dp.toPx()))),
|
||||
)
|
||||
},
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.heightIn(min = FloretDensity.cardRowHeight),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.block_add), style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A block kind's name. */
|
||||
internal val BlockType.label: Int
|
||||
get() = when (this) {
|
||||
BlockType.PROGRESS -> R.string.block_progress
|
||||
BlockType.COUNT_TILE -> R.string.block_count
|
||||
BlockType.PREVIEW -> R.string.block_preview
|
||||
BlockType.RECENTLY_COMPLETED -> R.string.block_recent
|
||||
BlockType.WEEK_STRIP -> R.string.block_week
|
||||
BlockType.TASK_LIST -> R.string.block_task_list
|
||||
BlockType.LISTS -> R.string.lists_header
|
||||
BlockType.TAGS -> R.string.tags_header
|
||||
BlockType.FILTERS -> R.string.filters_header
|
||||
BlockType.SECTION_HEADING -> R.string.block_heading
|
||||
}
|
||||
|
||||
/** What a block kind shows, in a line. */
|
||||
private val BlockType.hint: Int
|
||||
get() = when (this) {
|
||||
BlockType.PROGRESS -> R.string.block_progress_hint
|
||||
BlockType.COUNT_TILE -> R.string.block_count_hint
|
||||
BlockType.PREVIEW -> R.string.block_preview_hint
|
||||
BlockType.RECENTLY_COMPLETED -> R.string.block_recent_hint
|
||||
BlockType.WEEK_STRIP -> R.string.block_week_hint
|
||||
BlockType.TASK_LIST -> R.string.block_task_list_hint
|
||||
BlockType.LISTS -> R.string.block_lists_hint
|
||||
BlockType.TAGS -> R.string.block_tags_hint
|
||||
BlockType.FILTERS -> R.string.block_filters_hint
|
||||
BlockType.SECTION_HEADING -> R.string.block_heading_hint
|
||||
}
|
||||
|
||||
private val BlockType.icon: ImageVector
|
||||
get() = when (this) {
|
||||
BlockType.PROGRESS -> Icons.Rounded.TaskAlt
|
||||
BlockType.COUNT_TILE -> Icons.Rounded.Apps
|
||||
BlockType.PREVIEW -> Icons.Rounded.ViewAgenda
|
||||
BlockType.RECENTLY_COMPLETED -> Icons.Rounded.History
|
||||
BlockType.WEEK_STRIP -> Icons.Rounded.CalendarViewWeek
|
||||
BlockType.TASK_LIST -> Icons.Rounded.Checklist
|
||||
BlockType.LISTS -> Icons.AutoMirrored.Rounded.ListAlt
|
||||
BlockType.TAGS -> Icons.Rounded.Sell
|
||||
BlockType.FILTERS -> Icons.Rounded.FilterList
|
||||
BlockType.SECTION_HEADING -> Icons.AutoMirrored.Rounded.ShortText
|
||||
}
|
||||
|
||||
/** The add picker's groups of block kinds, in order. */
|
||||
private val BlockGroups = listOf(
|
||||
R.string.block_group_tasks to listOf(
|
||||
BlockType.PROGRESS,
|
||||
BlockType.COUNT_TILE,
|
||||
BlockType.PREVIEW,
|
||||
BlockType.RECENTLY_COMPLETED,
|
||||
BlockType.WEEK_STRIP,
|
||||
BlockType.TASK_LIST,
|
||||
),
|
||||
R.string.block_group_browse to listOf(BlockType.LISTS, BlockType.TAGS, BlockType.FILTERS),
|
||||
R.string.block_group_layout to listOf(BlockType.SECTION_HEADING),
|
||||
)
|
||||
|
||||
/**
|
||||
* The block kinds to add, grouped; a second task list is offered but can't be
|
||||
* picked. Picking one closes the picker.
|
||||
*/
|
||||
@Composable
|
||||
internal fun AddBlockPicker(blocks: List<Block>, onPick: (BlockType) -> Unit, onDismiss: () -> Unit) {
|
||||
FullScreenPicker(title = stringResource(R.string.block_add), onDismiss = onDismiss) {
|
||||
BlockGroups.forEach { (header, types) ->
|
||||
GroupedSectionHeader(stringResource(header))
|
||||
types.forEachIndexed { index, type ->
|
||||
val addable = blocks.canAdd(type)
|
||||
GroupedRow(
|
||||
title = stringResource(type.label),
|
||||
summary = stringResource(if (addable) type.hint else R.string.block_task_list_taken),
|
||||
position = positionOf(index, types.size),
|
||||
dimmed = !addable,
|
||||
leading = { CategoryIcon(type.icon, ChipAccent.Primary) },
|
||||
onClick = if (addable) ({ onDismiss(); onPick(type) }) else null,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A block's settings, full screen: its title (or a heading's text), its source,
|
||||
* the options of its kind, *Ignore view scope* where the view has a scope, and
|
||||
* remove. Changes are kept until Save; back leaves them.
|
||||
*/
|
||||
@Composable
|
||||
internal fun BlockSettings(
|
||||
block: Block,
|
||||
state: ListsUiState.Content,
|
||||
onChange: ((Block) -> Block) -> Unit,
|
||||
onChooseSource: () -> Unit,
|
||||
onSave: () -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var choosing by rememberSaveable { mutableStateOf<BlockPicker?>(null) }
|
||||
fun options(transform: (BlockOptions) -> BlockOptions) = onChange { it.copy(options = transform(it.options)) }
|
||||
FullScreenPicker(
|
||||
title = stringResource(block.type.label),
|
||||
onDismiss = onDismiss,
|
||||
actions = {
|
||||
Button(onClick = onSave, modifier = Modifier.padding(end = 12.dp)) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
) {
|
||||
TitleSection(block, state, ::options)
|
||||
|
||||
if (block.type.takesSource) {
|
||||
GroupedSectionHeader(stringResource(R.string.block_section_tasks))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.block_source),
|
||||
// Gone only while it is still the stored source; a newly picked one is there.
|
||||
summary = block.source?.let { sourceLabel(it, state) }?.takeUnless {
|
||||
block.id in state.goneSources && block.source == state.view.blocks.firstOrNull { it.id == block.id }?.source
|
||||
} ?: stringResource(R.string.view_source_gone),
|
||||
position = Position.Alone,
|
||||
leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) },
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = onChooseSource,
|
||||
)
|
||||
}
|
||||
|
||||
TypeOptions(block, state, ::options, onPick = { choosing = it })
|
||||
|
||||
if (state.view.scope != null) {
|
||||
GroupedSectionHeader(stringResource(R.string.block_section_scope))
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.block_ignore_scope),
|
||||
summary = stringResource(R.string.block_ignore_scope_hint, viewName(state.view.name, state.view.id)),
|
||||
checked = block.ignoreScope,
|
||||
onCheckedChange = { on -> onChange { it.copy(ignoreScope = on) } },
|
||||
position = Position.Alone,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.block_remove),
|
||||
position = Position.Alone,
|
||||
contentColor = MaterialTheme.colorScheme.error,
|
||||
leading = { Icon(Icons.Rounded.Delete, contentDescription = null) },
|
||||
onClick = onRemove,
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
|
||||
when (choosing) {
|
||||
BlockPicker.COLOR -> (block.options as? BlockOptions.CountTile)?.let { tile ->
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.block_color),
|
||||
options = listOf<TileColor?>(null) + TileColor.entries,
|
||||
selected = tile.color,
|
||||
label = { stringResource(it?.label ?: R.string.block_automatic) },
|
||||
leading = { color ->
|
||||
val swatch = color?.let { tileColors(it).first } ?: MaterialTheme.colorScheme.surfaceContainerHighest
|
||||
Box(Modifier.size(24.dp).clip(CircleShape).background(swatch))
|
||||
},
|
||||
onSelect = { color -> options { (it as BlockOptions.CountTile).copy(color = color) } },
|
||||
onDismiss = { choosing = null },
|
||||
)
|
||||
}
|
||||
BlockPicker.ICON -> (block.options as? BlockOptions.CountTile)?.let { tile ->
|
||||
ViewIconPicker(
|
||||
current = tile.icon,
|
||||
onSelect = { icon -> options { (it as BlockOptions.CountTile).copy(icon = icon) } },
|
||||
onDismiss = { choosing = null },
|
||||
automatic = true,
|
||||
)
|
||||
}
|
||||
BlockPicker.SORT -> (block.options as? BlockOptions.TaskList)?.let { list ->
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.sort_title),
|
||||
options = listOf<TaskSortOrder?>(null) + TaskSortOrder.entries,
|
||||
selected = list.sort,
|
||||
label = { stringResource(it?.let(::sortLabel) ?: R.string.block_sort_default) },
|
||||
onSelect = { sort -> options { (it as BlockOptions.TaskList).copy(sort = sort) } },
|
||||
onDismiss = { choosing = null },
|
||||
)
|
||||
}
|
||||
null -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/** The pickers a block's settings open over themselves. */
|
||||
private enum class BlockPicker { COLOR, ICON, SORT }
|
||||
|
||||
/** A block's own title, a heading's text; nothing for the kinds that keep a fixed one. */
|
||||
@Composable
|
||||
private fun TitleSection(block: Block, state: ListsUiState.Content, options: ((BlockOptions) -> BlockOptions) -> Unit) {
|
||||
val current = when (val o = block.options) {
|
||||
is BlockOptions.Progress -> o.title
|
||||
is BlockOptions.CountTile -> o.title
|
||||
is BlockOptions.Preview -> o.title
|
||||
is BlockOptions.RecentlyCompleted -> o.title
|
||||
is BlockOptions.WeekStrip -> o.title
|
||||
is BlockOptions.SectionHeading -> o.text
|
||||
else -> return
|
||||
}
|
||||
val heading = block.type == BlockType.SECTION_HEADING
|
||||
// An empty title shows the default one, which the field offers as its placeholder.
|
||||
val fallback = if (heading) stringResource(R.string.block_heading_text_hint) else blockTitle(block.copy(options = BlockOptions.defaultFor(block.type)), state)
|
||||
GroupedSectionHeader(stringResource(if (heading) R.string.block_heading_text else R.string.block_title))
|
||||
NameField(
|
||||
name = current.orEmpty(),
|
||||
placeholder = fallback,
|
||||
autoFocus = heading && current.isNullOrEmpty(),
|
||||
onNameChange = { text ->
|
||||
val title = text.takeIf { it.isNotBlank() }
|
||||
options { o ->
|
||||
when (o) {
|
||||
is BlockOptions.Progress -> o.copy(title = title)
|
||||
is BlockOptions.CountTile -> o.copy(title = title)
|
||||
is BlockOptions.Preview -> o.copy(title = title)
|
||||
is BlockOptions.RecentlyCompleted -> o.copy(title = title)
|
||||
is BlockOptions.WeekStrip -> o.copy(title = title)
|
||||
is BlockOptions.SectionHeading -> o.copy(text = text)
|
||||
else -> o
|
||||
}
|
||||
}
|
||||
},
|
||||
onImeAction = {},
|
||||
)
|
||||
}
|
||||
|
||||
/** The options of the block's kind. */
|
||||
@Composable
|
||||
private fun TypeOptions(
|
||||
block: Block,
|
||||
state: ListsUiState.Content,
|
||||
options: ((BlockOptions) -> BlockOptions) -> Unit,
|
||||
onPick: (BlockPicker) -> Unit,
|
||||
) {
|
||||
when (val o = block.options) {
|
||||
is BlockOptions.Progress -> {
|
||||
GroupedSectionHeader(stringResource(R.string.block_section_options))
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.block_wave),
|
||||
summary = stringResource(R.string.block_wave_hint),
|
||||
checked = o.wave,
|
||||
onCheckedChange = { on -> options { (it as BlockOptions.Progress).copy(wave = on) } },
|
||||
position = Position.Alone,
|
||||
)
|
||||
}
|
||||
is BlockOptions.CountTile -> {
|
||||
GroupedSectionHeader(stringResource(R.string.block_section_look))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.block_color),
|
||||
summary = stringResource(o.color?.label ?: R.string.block_automatic),
|
||||
position = Position.Top,
|
||||
leading = { Icon(Icons.Rounded.Palette, contentDescription = null) },
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { onPick(BlockPicker.COLOR) },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.block_icon),
|
||||
summary = o.icon?.let { stringResource(it.label) } ?: stringResource(R.string.block_automatic),
|
||||
position = Position.Bottom,
|
||||
leading = { Icon(o.icon?.vector ?: Icons.Rounded.Apps, contentDescription = null) },
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { onPick(BlockPicker.ICON) },
|
||||
)
|
||||
}
|
||||
is BlockOptions.Preview -> {
|
||||
HowMany(o.count) { count -> options { (it as BlockOptions.Preview).copy(count = count) } }
|
||||
GroupedSectionHeader(stringResource(R.string.block_section_options))
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.block_show_all),
|
||||
summary = stringResource(R.string.block_show_all_hint),
|
||||
checked = o.showAll,
|
||||
onCheckedChange = { on -> options { (it as BlockOptions.Preview).copy(showAll = on) } },
|
||||
position = Position.Top,
|
||||
)
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.block_inline_done),
|
||||
summary = stringResource(R.string.block_inline_done_hint),
|
||||
checked = o.inlineDone,
|
||||
onCheckedChange = { on -> options { (it as BlockOptions.Preview).copy(inlineDone = on) } },
|
||||
position = Position.Bottom,
|
||||
)
|
||||
}
|
||||
is BlockOptions.RecentlyCompleted ->
|
||||
HowMany(o.count) { count -> options { (it as BlockOptions.RecentlyCompleted).copy(count = count) } }
|
||||
is BlockOptions.TaskList -> {
|
||||
GroupedSectionHeader(stringResource(R.string.block_section_options))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.sort_title),
|
||||
summary = stringResource(o.sort?.let(::sortLabel) ?: R.string.block_sort_default),
|
||||
position = Position.Top,
|
||||
leading = { Icon(Icons.Rounded.Sort, contentDescription = null) },
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { onPick(BlockPicker.SORT) },
|
||||
)
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.block_show_completed),
|
||||
summary = stringResource(R.string.block_show_completed_hint),
|
||||
checked = o.showCompleted,
|
||||
onCheckedChange = { on -> options { (it as BlockOptions.TaskList).copy(showCompleted = on) } },
|
||||
position = Position.Middle,
|
||||
)
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.block_inline_done),
|
||||
summary = stringResource(R.string.block_inline_done_hint),
|
||||
checked = o.inlineDone,
|
||||
onCheckedChange = { on -> options { (it as BlockOptions.TaskList).copy(inlineDone = on) } },
|
||||
position = Position.Bottom,
|
||||
)
|
||||
}
|
||||
is BlockOptions.Lists -> ListsOptions(o, state, options)
|
||||
is BlockOptions.SectionHeading, is BlockOptions.WeekStrip, BlockOptions.Tags, BlockOptions.Filters -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/** How many tasks a preview shows, as an inline choice. */
|
||||
@Composable
|
||||
private fun HowMany(count: Int, onSelect: (Int) -> Unit) {
|
||||
GroupedSectionHeader(stringResource(R.string.block_how_many))
|
||||
ConnectedChoiceRow(
|
||||
options = BlockOptions.PREVIEW_COUNTS,
|
||||
selected = count,
|
||||
label = { it.toString() },
|
||||
onSelect = onSelect,
|
||||
)
|
||||
}
|
||||
|
||||
/** Which accounts' lists the lists block shows, and whether with their open counts. */
|
||||
@Composable
|
||||
private fun ListsOptions(o: BlockOptions.Lists, state: ListsUiState.Content, options: ((BlockOptions) -> BlockOptions) -> Unit) {
|
||||
val accounts = state.lists.map { it.accountName }.distinct().sortedBy { it.lowercase() }
|
||||
// An account no longer there stays listed while the block names it, so it can be unticked.
|
||||
val shown = (accounts + o.accounts.orEmpty()).distinct()
|
||||
if (shown.size > 1 || o.accounts != null) {
|
||||
GroupedSectionHeader(stringResource(R.string.block_accounts))
|
||||
val total = shown.size + 1
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.block_accounts_all),
|
||||
position = positionOf(0, total),
|
||||
selected = o.accounts == null,
|
||||
trailing = if (o.accounts == null) ({ SelectedCheck() }) else null,
|
||||
onClick = { options { (it as BlockOptions.Lists).copy(accounts = null) } },
|
||||
)
|
||||
shown.forEachIndexed { index, account ->
|
||||
val chosen = o.accounts?.contains(account) == true
|
||||
GroupedRow(
|
||||
title = account,
|
||||
position = positionOf(index + 1, total),
|
||||
selected = chosen,
|
||||
trailing = if (chosen) ({ SelectedCheck() }) else null,
|
||||
onClick = {
|
||||
options {
|
||||
val lists = it as BlockOptions.Lists
|
||||
val now = lists.accounts.orEmpty().let { set -> if (account in set) set - account else set + account }
|
||||
lists.copy(accounts = now.takeIf { set -> set.isNotEmpty() })
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
GroupedSectionHeader(stringResource(R.string.block_section_options))
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.block_counts),
|
||||
summary = stringResource(R.string.block_counts_hint),
|
||||
checked = o.counts,
|
||||
onCheckedChange = { on -> options { (it as BlockOptions.Lists).copy(counts = on) } },
|
||||
position = Position.Alone,
|
||||
)
|
||||
}
|
||||
|
||||
/** A tile colour's name. */
|
||||
private val TileColor.label: Int
|
||||
get() = when (this) {
|
||||
TileColor.PRIMARY -> R.string.block_color_primary
|
||||
TileColor.SECONDARY -> R.string.block_color_secondary
|
||||
TileColor.TERTIARY -> R.string.block_color_tertiary
|
||||
TileColor.ERROR -> R.string.block_color_error
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
package de.jeanlucmakiola.agendula.ui.lists
|
||||
|
||||
import androidx.lifecycle.SavedStateHandle
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
@@ -9,32 +10,57 @@ import de.jeanlucmakiola.agendula.data.sync.RemoteLists
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import de.jeanlucmakiola.agendula.domain.AppliedScope
|
||||
import de.jeanlucmakiola.agendula.domain.Block
|
||||
import de.jeanlucmakiola.agendula.domain.BlockOptions
|
||||
import de.jeanlucmakiola.agendula.domain.BlockSource
|
||||
import de.jeanlucmakiola.agendula.domain.BlockType
|
||||
import de.jeanlucmakiola.agendula.domain.BlockWidth
|
||||
import de.jeanlucmakiola.agendula.domain.dueCounts
|
||||
import de.jeanlucmakiola.agendula.domain.progress
|
||||
import de.jeanlucmakiola.agendula.domain.recentlyCompleted
|
||||
import de.jeanlucmakiola.agendula.domain.reordered
|
||||
import de.jeanlucmakiola.agendula.domain.replaced
|
||||
import de.jeanlucmakiola.agendula.domain.resized
|
||||
import de.jeanlucmakiola.agendula.domain.restored
|
||||
import de.jeanlucmakiola.agendula.domain.weekDays
|
||||
import de.jeanlucmakiola.agendula.domain.withBlock
|
||||
import de.jeanlucmakiola.agendula.domain.without
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.SourceContext
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFiltering
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.UpcomingRange
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.appliedScope
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
||||
import de.jeanlucmakiola.agendula.domain.contains
|
||||
import de.jeanlucmakiola.agendula.domain.counts
|
||||
import de.jeanlucmakiola.agendula.domain.forBlock
|
||||
import de.jeanlucmakiola.agendula.domain.isGone
|
||||
import de.jeanlucmakiola.agendula.domain.tagsInUse
|
||||
import de.jeanlucmakiola.agendula.ui.views.ViewSession
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import javax.inject.Inject
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* What a list write failed at. The screens turn this into wording; the view
|
||||
@@ -86,51 +112,275 @@ internal fun RemoteLists.Outcome.asFailure(local: ListWriteFailure): ListWriteFa
|
||||
|
||||
data class ListOverview(val list: TaskList, val openCount: Int)
|
||||
data class AccountGroup(val accountName: String, val lists: List<ListOverview>)
|
||||
data class SmartCount(val smart: SmartList, val count: Int)
|
||||
data class TagOverview(val tag: String, val openCount: Int)
|
||||
data class FilterOverview(val filter: SavedFilter, val openCount: Int)
|
||||
|
||||
/** Done of total for a progress block. */
|
||||
data class BlockProgress(val done: Int, val total: Int)
|
||||
|
||||
/** A week strip's [days], which of them is [today], and how many open tasks are [due] on each. */
|
||||
data class WeekStripDays(val days: List<LocalDate>, val today: LocalDate, val due: Map<LocalDate, Int>)
|
||||
|
||||
/** A block just removed from view [viewId], from [index], until its undo lapses. */
|
||||
data class RemovedBlock(val viewId: Long, val block: Block, val index: Int)
|
||||
|
||||
/** The blocks of view [viewId] when its layout editing began, which a discard restores. */
|
||||
data class LayoutAtStart(val viewId: Long, val blocks: List<Block>)
|
||||
|
||||
/** What custom rules coming back from their editor are for. */
|
||||
sealed interface RulesRequest {
|
||||
/** A new [type] block of view [viewId]. */
|
||||
data class Add(val viewId: Long, val type: BlockType) : RulesRequest
|
||||
|
||||
/** The source of the block whose settings are open. */
|
||||
data object Draft : RulesRequest
|
||||
}
|
||||
|
||||
/** Block [block] of view [viewId] as its settings screen changes it, until saved. */
|
||||
data class BlockDraft(val viewId: Long, val block: Block)
|
||||
|
||||
/** What the lists, tags and filters blocks show, read through one scope. */
|
||||
data class HomeSections(
|
||||
val groups: List<AccountGroup>,
|
||||
/** Each tag on an open task, alphabetically. */
|
||||
val tags: List<TagOverview>,
|
||||
/** The saved filters, oldest first. */
|
||||
val filters: List<FilterOverview>,
|
||||
)
|
||||
|
||||
sealed interface ListsUiState {
|
||||
data object Loading : ListsUiState
|
||||
data object Failure : ListsUiState
|
||||
data class Content(
|
||||
val smartCounts: List<SmartCount>,
|
||||
val groups: List<AccountGroup>,
|
||||
/** Completed vs. total tasks *due today* — drives the progress ring. */
|
||||
val todayDone: Int,
|
||||
val todayTotal: Int,
|
||||
/** What each preview block of [view] shows, by block id. */
|
||||
val previews: Map<Long, List<Task>>,
|
||||
/** Every task (open and completed) — the corpus the home search filters. */
|
||||
val allTasks: List<Task>,
|
||||
/** Each tag on an open task, alphabetically. */
|
||||
val tags: List<TagOverview> = emptyList(),
|
||||
/** The saved filters, oldest first. */
|
||||
val filters: List<FilterOverview> = emptyList(),
|
||||
/** The view these are laid out by. */
|
||||
val view: View = View.home(),
|
||||
) : ListsUiState
|
||||
val view: View,
|
||||
/** Every view, for the switcher, Home first. */
|
||||
val views: List<View> = listOf(view),
|
||||
/** Each progress block's done of total, by block id; missing for a source it can't show. */
|
||||
val progress: Map<Long, BlockProgress> = emptyMap(),
|
||||
/** Each count tile's count, by block id. */
|
||||
val counts: Map<Long, Int> = emptyMap(),
|
||||
/** What each preview block shows, by block id. */
|
||||
val previews: Map<Long, List<Task>> = emptyMap(),
|
||||
/** What each recently completed block shows, latest first, by block id. */
|
||||
val recent: Map<Long, List<Task>> = emptyMap(),
|
||||
/** Each week strip's days, by block id. */
|
||||
val weeks: Map<Long, WeekStripDays> = emptyMap(),
|
||||
/** The blocks whose list or saved filter was deleted. */
|
||||
val goneSources: Set<Long> = emptySet(),
|
||||
/** The view's scope names a list since deleted, so that part of it matches nothing. */
|
||||
val scopeListsGone: Boolean = false,
|
||||
/**
|
||||
* The lists, tags and filters blocks within the view's scope, worked out
|
||||
* only once a block shows them.
|
||||
*/
|
||||
private val scopedSections: Lazy<HomeSections> = lazyOf(HomeSections(emptyList(), emptyList(), emptyList())),
|
||||
/** The same for every task, for a block that ignores the scope and the pickers; also only once read. */
|
||||
private val everySection: Lazy<HomeSections> = scopedSections,
|
||||
/** The saved filters' names by id, which a filter source goes by. */
|
||||
val filterNames: Map<Long, String> = emptyMap(),
|
||||
/** Every list, whatever the scope: whether there are any, and the names sources show. */
|
||||
val lists: List<TaskList> = emptyList(),
|
||||
/** Every task (open and completed) — the corpus the home search filters. */
|
||||
val allTasks: List<Task> = emptyList(),
|
||||
/** [allTasks] within the view's scope, where a search in a scoped view starts; filtered once searched. */
|
||||
private val scopedCorpus: Lazy<List<Task>> = lazyOf(allTasks),
|
||||
/** The view's scope as it applies, lists since deleted matching nothing; `null` for none. */
|
||||
val scopeRule: Rule? = null,
|
||||
) : ListsUiState {
|
||||
val sections: HomeSections get() = scopedSections.value
|
||||
val unscopedSections: HomeSections get() = everySection.value
|
||||
val scopedTasks: List<Task> get() = scopedCorpus.value
|
||||
|
||||
fun sectionsFor(block: Block): HomeSections = if (block.ignoreScope) unscopedSections else sections
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tasks each preview block of this view shows, by block id: the first of
|
||||
* [upcoming] for a preview of Upcoming. Other sources show nothing yet.
|
||||
* Home laid out by [view] over these tasks: each block reads its source through
|
||||
* the view's scope, unless it ignores it. A block whose list or filter is gone
|
||||
* shows nothing but says so; a scope list since deleted matches nothing.
|
||||
*/
|
||||
internal fun View.previews(upcoming: Sequence<Task>): Map<Long, List<Task>> {
|
||||
val counts = blocks
|
||||
.filter { it.type == BlockType.PREVIEW && it.source == BlockSource.Smart(SmartList.UPCOMING) }
|
||||
.associate { it.id to (it.options as BlockOptions.Preview).count }
|
||||
val next = upcoming.take(counts.values.maxOrNull() ?: 0).toList()
|
||||
return counts.mapValues { (_, count) -> next.take(count) }
|
||||
internal fun homeContent(
|
||||
view: View,
|
||||
views: List<View>,
|
||||
lists: List<TaskList>,
|
||||
openTasks: List<Task>,
|
||||
completedTasks: List<Task>,
|
||||
hidden: Set<Long>,
|
||||
savedFilters: List<SavedFilter>,
|
||||
clock: RuleClock,
|
||||
upcomingEnd: Instant?,
|
||||
): ListsUiState.Content {
|
||||
val listIds = lists.mapTo(HashSet()) { it.id }
|
||||
// Lists deleted since drop out, as they do when the filter is opened.
|
||||
val filters = savedFilters.map { it.withListsIn(listIds) }
|
||||
val context = SourceContext(clock, upcomingEnd, filters.associateBy { it.id })
|
||||
val scope = view.appliedScope(listIds)
|
||||
// Count only top-level tasks: a subtask is represented by its parent (and
|
||||
// its progress chip), and an open subtask under a *completed* parent must
|
||||
// not read as an open item here. Mirrors the task list collapsing subtasks.
|
||||
val topLevel = openTasks.filter { !it.isSubtask } + completedTasks.filter { !it.isSubtask }
|
||||
val filterIds = filters.mapTo(HashSet()) { it.id }
|
||||
val allOpenAndDone = openTasks + completedTasks
|
||||
|
||||
val progress = HashMap<Long, BlockProgress>()
|
||||
val counts = HashMap<Long, Int>()
|
||||
val previews = HashMap<Long, List<Task>>()
|
||||
val recent = HashMap<Long, List<Task>>()
|
||||
val weeks = HashMap<Long, WeekStripDays>()
|
||||
val gone = HashSet<Long>()
|
||||
view.blocks.forEach { block ->
|
||||
val within = scope.forBlock(block)
|
||||
// The smart lists leave out the hidden lists, but not one the scope names.
|
||||
val smartHidden = within.hiddenFromSmart(hidden)
|
||||
fun inView(task: Task) = task.listId !in smartHidden && within.admits(task, clock)
|
||||
when (block.type) {
|
||||
BlockType.RECENTLY_COMPLETED -> {
|
||||
val count = (block.options as BlockOptions.RecentlyCompleted).count
|
||||
recent[block.id] = recentlyCompleted(completedTasks.filter(::inView), count)
|
||||
return@forEach
|
||||
}
|
||||
BlockType.WEEK_STRIP -> {
|
||||
val days = weekDays(clock.today, clock.weekStart)
|
||||
weeks[block.id] = WeekStripDays(days, clock.today, dueCounts(openTasks.filter(::inView), days, clock.zone))
|
||||
return@forEach
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
val source = block.source ?: return@forEach
|
||||
if (source.isGone(listIds, filterIds)) {
|
||||
gone += block.id
|
||||
return@forEach
|
||||
}
|
||||
fun shows(task: Task) = source.counts(task, context, smartHidden) && within.admits(task, clock)
|
||||
when (block.type) {
|
||||
BlockType.PROGRESS -> source.progress(topLevel, context, smartHidden) { within.admits(it, clock) }
|
||||
.let { (done, total) -> progress[block.id] = BlockProgress(done, total) }
|
||||
BlockType.COUNT_TILE -> counts[block.id] = if (source is BlockSource.Smart) {
|
||||
topLevel.count(::shows)
|
||||
} else {
|
||||
// As the tags and filters count them: a subtask counts unless its parent does.
|
||||
val shown = allOpenAndDone.filter(::shows)
|
||||
val ids = shown.mapTo(HashSet()) { it.taskId }
|
||||
shown.count { !it.isSubtask || it.parentId !in ids }
|
||||
}
|
||||
BlockType.PREVIEW -> {
|
||||
val count = (block.options as BlockOptions.Preview).count
|
||||
previews[block.id] = topLevel.asSequence().filter(::shows).take(count).toList()
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
val allTasks = openTasks + completedTasks
|
||||
val every = lazy(LazyThreadSafetyMode.PUBLICATION) { homeSections(lists, openTasks, allTasks, filters, AppliedScope.None, clock) }
|
||||
return ListsUiState.Content(
|
||||
view = view,
|
||||
views = views,
|
||||
progress = progress,
|
||||
counts = counts,
|
||||
previews = previews,
|
||||
recent = recent,
|
||||
weeks = weeks,
|
||||
goneSources = gone,
|
||||
scopeListsGone = scope.narrowedByGone,
|
||||
scopedSections = if (scope == AppliedScope.None) {
|
||||
every
|
||||
} else {
|
||||
lazy(LazyThreadSafetyMode.PUBLICATION) { homeSections(lists, openTasks, allTasks, filters, scope, clock) }
|
||||
},
|
||||
everySection = every,
|
||||
filterNames = filters.associate { it.id to it.name },
|
||||
lists = lists,
|
||||
allTasks = allTasks,
|
||||
scopedCorpus = if (scope == AppliedScope.None) {
|
||||
lazyOf(allTasks)
|
||||
} else {
|
||||
lazy(LazyThreadSafetyMode.PUBLICATION) { allTasks.filter { scope.admits(it, clock) } }
|
||||
},
|
||||
scopeRule = scope.rule,
|
||||
)
|
||||
}
|
||||
|
||||
/** The home overview: smart lists with live counts, then user lists by account. */
|
||||
/** What home was last laid out from, to ask whether it would show a task. */
|
||||
internal data class HomeInputs(
|
||||
val view: View,
|
||||
val lists: List<TaskList>,
|
||||
val openTasks: List<Task>,
|
||||
val completedTasks: List<Task>,
|
||||
val hidden: Set<Long>,
|
||||
val savedFilters: List<SavedFilter>,
|
||||
val clock: RuleClock,
|
||||
val upcomingEnd: Instant?,
|
||||
) {
|
||||
/**
|
||||
* Whether a block of the view would show [task] as a row: the view's task
|
||||
* list, or a preview with it among the tasks it shows. A count or a ring
|
||||
* that only goes up doesn't show it. [task] counts once, whether these
|
||||
* tasks already hold it or not.
|
||||
*/
|
||||
fun shows(task: Task): Boolean {
|
||||
val open = (openTasks.filterNot { it.taskId == task.taskId } + task).sortedWith(TaskSorting.default())
|
||||
val content = homeContent(view, listOf(view), lists, open, completedTasks, hidden, savedFilters, clock, upcomingEnd)
|
||||
if (content.previews.values.any { tasks -> tasks.any { it.taskId == task.taskId } }) return true
|
||||
val block = view.blocks.lastOrNull { it.type == BlockType.TASK_LIST && it.id !in content.goneSources } ?: return false
|
||||
val source = block.source ?: return false
|
||||
val listIds = lists.mapTo(HashSet()) { it.id }
|
||||
val filters = savedFilters.map { it.withListsIn(listIds) }.associateBy { it.id }
|
||||
val within = view.appliedScope(listIds).forBlock(block)
|
||||
return within.admits(task, clock) &&
|
||||
source.counts(task, SourceContext(clock, upcomingEnd, filters), within.hiddenFromSmart(hidden))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lists, tags and filters within [scope], each with its open count. A scope
|
||||
* that keeps tasks to some lists shows only those.
|
||||
*/
|
||||
private fun homeSections(
|
||||
lists: List<TaskList>,
|
||||
openTasks: List<Task>,
|
||||
allTasks: List<Task>,
|
||||
filters: List<SavedFilter>,
|
||||
scope: AppliedScope,
|
||||
clock: RuleClock,
|
||||
): HomeSections {
|
||||
val open = if (scope == AppliedScope.None) openTasks else openTasks.filter { scope.admits(it, clock) }
|
||||
val openByList = open.filter { !it.isSubtask }.groupingBy { it.listId }.eachCount()
|
||||
val shown = scope.lists?.let { ids -> lists.filter { it.id in ids } } ?: lists
|
||||
val groups = shown
|
||||
.groupBy { it.accountName }
|
||||
.map { (account, accountLists) ->
|
||||
AccountGroup(account, accountLists.map { ListOverview(it, openByList[it.id] ?: 0) })
|
||||
}
|
||||
.sortedBy { it.accountName.lowercase() }
|
||||
// Counts the open rows the tag's own screen shows: a subtask folds under a
|
||||
// parent carrying the same tag, and stands on its own otherwise.
|
||||
val all = if (scope == AppliedScope.None) allTasks else allTasks.filter { scope.admits(it, clock) }
|
||||
val tags = tagsInUse(open).map { tag ->
|
||||
val tagged = all.filter { tag in it.tags }
|
||||
val ids = tagged.mapTo(HashSet()) { it.taskId }
|
||||
TagOverview(tag, tagged.count { !it.isClosed && (!it.isSubtask || it.parentId !in ids) })
|
||||
}
|
||||
// Same folding as the tags: a subtask counts only when its parent isn't in the filter too.
|
||||
val overviews = filters.map { filter ->
|
||||
val matching = open.filter { filter.matches(it, clock) }
|
||||
val ids = matching.mapTo(HashSet()) { it.taskId }
|
||||
FilterOverview(filter, matching.count { !it.isSubtask || it.parentId !in ids })
|
||||
}
|
||||
return HomeSections(groups, tags, overviews)
|
||||
}
|
||||
|
||||
/** The home overview: the active view's blocks with live counts. */
|
||||
@HiltViewModel
|
||||
class ListsViewModel @Inject constructor(
|
||||
private val repository: TasksRepository,
|
||||
private val remoteLists: RemoteLists,
|
||||
private val manualSync: ManualSync,
|
||||
settingsPrefs: SettingsPrefs,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val session: ViewSession,
|
||||
private val savedState: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
|
||||
/** Pull to sync (#73); off without an account. */
|
||||
@@ -157,6 +407,23 @@ class ListsViewModel @Inject constructor(
|
||||
accounts.map { ListDestination(it.id, it.displayName) }
|
||||
}
|
||||
|
||||
/** The views, and the one shown: the last used one, Home when it is gone. Nothing while a launch picks it. */
|
||||
private val shownView = combine(settingsPrefs.views, session.activeViewId, session.starting) { views, active, starting ->
|
||||
if (starting) null else (views.firstOrNull { it.id == active } ?: views.first()) to views
|
||||
}.distinctUntilChanged()
|
||||
|
||||
/** The view shown, again at each midnight, so the blocks that count today move on to the new day. */
|
||||
private val shownToday = combine(
|
||||
shownView,
|
||||
flow {
|
||||
while (true) {
|
||||
val window = DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
|
||||
emit(window)
|
||||
delay((window.second - Clock.System.now()).inWholeMilliseconds.coerceIn(0, 60_000) + 1)
|
||||
}
|
||||
}.distinctUntilChanged(),
|
||||
) { shown, _ -> shown }
|
||||
|
||||
val state: StateFlow<ListsUiState> =
|
||||
combine(
|
||||
repository.taskLists(),
|
||||
@@ -167,96 +434,248 @@ class ListsViewModel @Inject constructor(
|
||||
combine(
|
||||
settingsPrefs.settings.map { it.hiddenFromSmartLists to it.upcomingRange }.distinctUntilChanged(),
|
||||
settingsPrefs.firstDayOfWeek,
|
||||
// For now Home is always the view shown.
|
||||
settingsPrefs.views.map { views -> views.first { it.id == View.HOME_ID } }.distinctUntilChanged(),
|
||||
) { (hidden, range), weekStart, view -> Triple(hidden, range, weekStart) to view },
|
||||
settingsPrefs.savedFilters,
|
||||
) { lists, openTasks, completedTasks, (settings, view), filters ->
|
||||
val (hidden, upcomingRange, weekStart) = settings
|
||||
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters, weekStart, view) as ListsUiState
|
||||
settingsPrefs.savedFilters,
|
||||
::Triple,
|
||||
),
|
||||
shownToday,
|
||||
) { lists, openTasks, completedTasks, (settings, weekStart, filters), shown ->
|
||||
val (view, views) = shown ?: return@combine ListsUiState.Loading
|
||||
val (hidden, upcomingRange) = settings
|
||||
val now = Clock.System.now()
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(now, zone)
|
||||
val clock = RuleClock(todayStart, todayEnd, zone, weekStart)
|
||||
val upcomingEnd = upcomingRange.end(now, zone)
|
||||
inputs = HomeInputs(view, lists, openTasks, completedTasks, hidden, filters, clock, upcomingEnd)
|
||||
homeContent(
|
||||
view = view,
|
||||
views = views,
|
||||
lists = lists,
|
||||
openTasks = openTasks,
|
||||
completedTasks = completedTasks,
|
||||
hidden = hidden,
|
||||
savedFilters = filters,
|
||||
clock = clock,
|
||||
upcomingEnd = upcomingEnd,
|
||||
)
|
||||
}.recoveringFromProviderFailure { ListsUiState.Failure }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListsUiState.Loading)
|
||||
|
||||
private fun buildContent(
|
||||
lists: List<TaskList>,
|
||||
openTasks: List<Task>,
|
||||
completedTasks: List<Task>,
|
||||
hidden: Set<Long>,
|
||||
upcomingRange: UpcomingRange,
|
||||
savedFilters: List<SavedFilter>,
|
||||
weekStart: DayOfWeek,
|
||||
view: View,
|
||||
): ListsUiState.Content {
|
||||
val now = Clock.System.now()
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(now, zone)
|
||||
// Count only top-level tasks: a subtask is represented by its parent (and
|
||||
// its progress chip), and an open subtask under a *completed* parent must
|
||||
// not read as an open item here. Mirrors the task list collapsing subtasks.
|
||||
val topLevel = openTasks.filter { !it.isSubtask }
|
||||
// The smart counts leave out the hidden lists; each list's own count does not.
|
||||
val smartTopLevel = topLevel.filter { it.listId !in hidden }
|
||||
val upcomingEnd = upcomingRange.end(now, zone)
|
||||
fun inSmart(task: Task, smart: SmartList) =
|
||||
TaskFiltering.matches(task, TaskFilter.Smart(smart), todayStart, todayEnd, upcomingEnd = upcomingEnd)
|
||||
fun count(smart: SmartList) = smartTopLevel.count { inSmart(it, smart) }
|
||||
fun switchView(viewId: Long) = session.switchTo(viewId)
|
||||
|
||||
val smartCounts = listOf(
|
||||
SmartCount(SmartList.TODAY, count(SmartList.TODAY)),
|
||||
SmartCount(SmartList.OVERDUE, count(SmartList.OVERDUE)),
|
||||
SmartCount(SmartList.UPCOMING, count(SmartList.UPCOMING)),
|
||||
SmartCount(SmartList.ALL, smartTopLevel.size),
|
||||
)
|
||||
@Volatile
|
||||
private var inputs: HomeInputs? = null
|
||||
|
||||
// Today ring: the completed rows of the Today list against all of its rows.
|
||||
val openToday = count(SmartList.TODAY)
|
||||
val completedToday = completedTasks.count {
|
||||
!it.isSubtask && it.listId !in hidden && TaskFiltering.isToday(it, todayStart, todayEnd)
|
||||
/** Whether view [viewId], as last shown, shows [task] in one of its blocks (see [HomeInputs.shows]). */
|
||||
fun shows(viewId: Long, task: Task): Boolean = inputs?.takeIf { it.view.id == viewId }?.shows(task) == true
|
||||
|
||||
private val _viewSaveFailed = MutableStateFlow(false)
|
||||
|
||||
/** Set for a moment when a view couldn't be stored: the views are another version's. */
|
||||
val viewSaveFailed: StateFlow<Boolean> = _viewSaveFailed.asStateFlow()
|
||||
|
||||
/** Points the block [blockId] of view [viewId], whose source is gone, at [source] instead. */
|
||||
fun chooseSource(viewId: Long, blockId: Long, source: BlockSource) =
|
||||
editBlocks(viewId) { blocks -> blocks.map { if (it.id == blockId) it.copy(source = source) else it } }
|
||||
|
||||
/**
|
||||
* Changes the blocks of view [viewId] by [transform], read and written in one
|
||||
* go so nothing changed meanwhile is lost; says so when they can't be stored.
|
||||
*/
|
||||
private fun editBlocks(viewId: Long, transform: (List<Block>) -> List<Block>) = viewModelScope.launch {
|
||||
if (!settingsPrefs.updateView(viewId) { it.copy(blocks = transform(it.blocks)) }) flagSaveFailed()
|
||||
}
|
||||
|
||||
private suspend fun flagSaveFailed() {
|
||||
_viewSaveFailed.value = true
|
||||
delay(4_000)
|
||||
_viewSaveFailed.value = false
|
||||
}
|
||||
|
||||
/** Whether home shows the active view's blocks to rearrange. */
|
||||
val editingLayout: StateFlow<Boolean> = session.editingLayout
|
||||
|
||||
fun editLayout(viewId: Long) = session.editLayout(viewId)
|
||||
|
||||
/** Opens the layout of the view shown now; for a gesture that may outlive a switch of view. */
|
||||
fun editShownLayout() {
|
||||
(state.value as? ListsUiState.Content)?.view?.id?.let(session::editLayout)
|
||||
}
|
||||
|
||||
/** Leaves the layout editor keeping what was changed in it. */
|
||||
fun stopEditingLayout() {
|
||||
session.stopEditingLayout()
|
||||
dropDraftFilters()
|
||||
_blockDraft.value = null
|
||||
_layoutAtStart.value = null
|
||||
sessionFilters.clear()
|
||||
}
|
||||
|
||||
// Filters the rule editor saved for this editing session, and for the open block settings:
|
||||
// a discard, or settings left without Save, takes them back.
|
||||
private val sessionFilters = mutableListOf<Long>()
|
||||
private val draftFilters = mutableListOf<Long>()
|
||||
|
||||
private fun deleteFilters(ids: List<Long>) {
|
||||
if (ids.isEmpty()) return
|
||||
val gone = ids.toList()
|
||||
viewModelScope.launch { gone.forEach { runCatching { settingsPrefs.deleteFilter(it) } } }
|
||||
}
|
||||
|
||||
private fun dropDraftFilters() {
|
||||
deleteFilters(draftFilters)
|
||||
draftFilters.clear()
|
||||
}
|
||||
|
||||
private val _layoutAtStart = MutableStateFlow<LayoutAtStart?>(null)
|
||||
|
||||
/** The blocks of the view being edited as they were when its editing began. */
|
||||
val layoutAtStart: StateFlow<LayoutAtStart?> = _layoutAtStart.asStateFlow()
|
||||
|
||||
/**
|
||||
* Notes [view]'s blocks as the ones a discard goes back to, once per editing
|
||||
* session. Another view shown mid-session, by a shortcut, ends the session,
|
||||
* keeping its edits: a discard could no longer say which view it undoes.
|
||||
*/
|
||||
fun beginEditing(view: View) {
|
||||
val start = _layoutAtStart.value
|
||||
when {
|
||||
start == null -> _layoutAtStart.value = LayoutAtStart(view.id, view.blocks)
|
||||
start.viewId != view.id -> stopEditingLayout()
|
||||
}
|
||||
val todayTotal = openToday + completedToday
|
||||
}
|
||||
|
||||
// Upcoming preview: the next handful of open tasks due tomorrow onward,
|
||||
// already sorted by the repository's default ordering.
|
||||
val upcoming = smartTopLevel.asSequence().filter { inSmart(it, SmartList.UPCOMING) }
|
||||
val openByList = topLevel.groupingBy { it.listId }.eachCount()
|
||||
val groups = lists
|
||||
.groupBy { it.accountName }
|
||||
.map { (account, accountLists) ->
|
||||
AccountGroup(
|
||||
accountName = account,
|
||||
lists = accountLists.map { ListOverview(it, openByList[it.id] ?: 0) },
|
||||
)
|
||||
/** Leaves the layout editor and puts the blocks back as they were when it opened. */
|
||||
fun discardLayoutEdits() {
|
||||
val start = _layoutAtStart.value
|
||||
removedTimer?.cancel()
|
||||
_removed.value = null
|
||||
deleteFilters(sessionFilters)
|
||||
sessionFilters.clear()
|
||||
stopEditingLayout()
|
||||
if (start != null) editBlocks(start.viewId) { start.blocks }
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a [type] block reading [source] to view [viewId], before its task list.
|
||||
* A section heading opens its settings straight away, to be given its text.
|
||||
*/
|
||||
fun addBlock(viewId: Long, type: BlockType, source: BlockSource?) = viewModelScope.launch {
|
||||
var added: Block? = null
|
||||
val written = settingsPrefs.updateView(viewId) { view ->
|
||||
// The id of a block whose removal can still be undone stays its own.
|
||||
val reserved = setOfNotNull(_removed.value?.takeIf { it.viewId == viewId }?.block?.id)
|
||||
val blocks = view.blocks.withBlock(type, source, reserved)
|
||||
added = blocks.firstOrNull { block -> view.blocks.none { it.id == block.id } }
|
||||
view.copy(blocks = blocks)
|
||||
}
|
||||
if (!written) return@launch flagSaveFailed()
|
||||
val block = added
|
||||
if (block != null && type == BlockType.SECTION_HEADING) _blockDraft.value = BlockDraft(viewId, block)
|
||||
}
|
||||
|
||||
/** Puts the blocks of view [viewId] in the order of [ids]. */
|
||||
fun moveBlocks(viewId: Long, ids: List<Long>) = editBlocks(viewId) { it.reordered(ids) }
|
||||
|
||||
fun resizeBlock(viewId: Long, blockId: Long, width: BlockWidth) = editBlocks(viewId) { it.resized(blockId, width) }
|
||||
|
||||
private val _removed = MutableStateFlow<RemovedBlock?>(null)
|
||||
|
||||
/** The block just removed, while its removal can be undone. */
|
||||
val removed: StateFlow<RemovedBlock?> = _removed.asStateFlow()
|
||||
private var removedTimer: Job? = null
|
||||
|
||||
/** Removes [block] from view [viewId], with a moment to undo it. */
|
||||
fun removeBlock(viewId: Long, block: Block) {
|
||||
val view = (state.value as? ListsUiState.Content)?.views?.firstOrNull { it.id == viewId } ?: return
|
||||
val index = view.blocks.indexOfFirst { it.id == block.id }.takeIf { it >= 0 } ?: return
|
||||
if (_blockDraft.value?.block?.id == block.id) _blockDraft.value = null
|
||||
editBlocks(viewId) { it.without(block.id) }
|
||||
_removed.value = RemovedBlock(viewId, block, index)
|
||||
removedTimer?.cancel()
|
||||
removedTimer = viewModelScope.launch {
|
||||
delay(4_000)
|
||||
_removed.value = null
|
||||
}
|
||||
}
|
||||
|
||||
fun undoRemove() {
|
||||
val removed = _removed.value ?: return
|
||||
removedTimer?.cancel()
|
||||
_removed.value = null
|
||||
editBlocks(removed.viewId) { it.restored(removed.block, removed.index) }
|
||||
}
|
||||
|
||||
private val _blockDraft = MutableStateFlow<BlockDraft?>(null)
|
||||
|
||||
/** The block whose settings are open, as changed so far; `null` while none is. */
|
||||
val blockDraft: StateFlow<BlockDraft?> = _blockDraft.asStateFlow()
|
||||
|
||||
fun editBlock(viewId: Long, block: Block) {
|
||||
_blockDraft.value = BlockDraft(viewId, block)
|
||||
}
|
||||
|
||||
fun updateDraft(transform: (Block) -> Block) = _blockDraft.update { it?.copy(block = transform(it.block)) }
|
||||
|
||||
/** Stores the open block's settings over the block as it is stored now, and closes them. */
|
||||
fun saveDraft() {
|
||||
val draft = _blockDraft.value ?: return
|
||||
_blockDraft.value = null
|
||||
sessionFilters += draftFilters
|
||||
draftFilters.clear()
|
||||
editBlocks(draft.viewId) { it.replaced(draft.block) }
|
||||
}
|
||||
|
||||
fun closeDraft() {
|
||||
dropDraftFilters()
|
||||
_blockDraft.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
* What the custom rules the editor is opened for will go to. Kept in the saved
|
||||
* state, as the editor's result is, so a block being added survives the process.
|
||||
*/
|
||||
private var rulesRequest: RulesRequest?
|
||||
get() = savedState.get<String>(KEY_RULES_REQUEST)?.let { text ->
|
||||
when {
|
||||
text == "draft" -> RulesRequest.Draft
|
||||
else -> text.removePrefix("add:").split(':').takeIf { it.size == 2 }?.let { (view, type) ->
|
||||
val blockType = BlockType.entries.firstOrNull { it.name == type }
|
||||
view.toLongOrNull()?.let { id -> blockType?.let { RulesRequest.Add(id, it) } }
|
||||
}
|
||||
}
|
||||
.sortedBy { it.accountName.lowercase() }
|
||||
// Counts the open rows the tag's own screen shows: a subtask folds under a
|
||||
// parent carrying the same tag, and stands on its own otherwise.
|
||||
val allTasks = openTasks + completedTasks
|
||||
val tags = tagsInUse(openTasks).map { tag ->
|
||||
val tagged = allTasks.filter { tag in it.tags }
|
||||
val ids = tagged.mapTo(HashSet()) { it.taskId }
|
||||
TagOverview(tag, tagged.count { !it.isClosed && (!it.isSubtask || it.parentId !in ids) })
|
||||
}
|
||||
val clock = RuleClock(todayStart, todayEnd, zone, weekStart)
|
||||
// Lists deleted since drop out, as they do when the filter is opened.
|
||||
val listIds = lists.mapTo(HashSet()) { it.id }
|
||||
// Same folding as the tags: a subtask counts only when its parent isn't in the filter too.
|
||||
val filters = savedFilters.map { saved ->
|
||||
val filter = saved.withListsIn(listIds)
|
||||
val matching = openTasks.filter { filter.matches(it, clock) }
|
||||
val ids = matching.mapTo(HashSet()) { it.taskId }
|
||||
FilterOverview(saved, matching.count { !it.isSubtask || it.parentId !in ids })
|
||||
set(value) {
|
||||
savedState[KEY_RULES_REQUEST] = when (value) {
|
||||
is RulesRequest.Add -> "add:${value.viewId}:${value.type.name}"
|
||||
RulesRequest.Draft -> "draft"
|
||||
null -> null
|
||||
}
|
||||
}
|
||||
return ListsUiState.Content(
|
||||
view = view,
|
||||
smartCounts = smartCounts,
|
||||
filters = filters,
|
||||
groups = groups,
|
||||
todayDone = completedToday,
|
||||
todayTotal = todayTotal,
|
||||
previews = view.previews(upcoming),
|
||||
allTasks = allTasks,
|
||||
tags = tags,
|
||||
)
|
||||
|
||||
/** Notes what the custom rules the editor is opened for will go to. */
|
||||
fun awaitRulesFor(request: RulesRequest) {
|
||||
rulesRequest = request
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts [source], back from the rule editor, where [awaitRulesFor] said. A
|
||||
* filter it was saved as goes with what it went to, if that is thrown away.
|
||||
*/
|
||||
fun takeRulesResult(source: BlockSource) {
|
||||
val created = (source as? BlockSource.Filter)?.filterId
|
||||
when (val request = rulesRequest) {
|
||||
is RulesRequest.Add -> {
|
||||
addBlock(request.viewId, request.type, source)
|
||||
created?.let { sessionFilters += it }
|
||||
}
|
||||
RulesRequest.Draft -> if (_blockDraft.value != null) {
|
||||
updateDraft { it.copy(source = source) }
|
||||
created?.let { draftFilters += it }
|
||||
}
|
||||
null -> Unit
|
||||
}
|
||||
rulesRequest = null
|
||||
}
|
||||
|
||||
private val _writeFailure = MutableStateFlow<ListWriteFailure?>(null)
|
||||
@@ -291,3 +710,5 @@ class ListsViewModel @Inject constructor(
|
||||
_writeFailure.value = outcome.asFailure(ListWriteFailure.SAVE)
|
||||
}
|
||||
}
|
||||
|
||||
private const val KEY_RULES_REQUEST = "rules_request"
|
||||
@@ -0,0 +1,39 @@
|
||||
package de.jeanlucmakiola.agendula.ui.lists
|
||||
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedback
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
|
||||
/**
|
||||
* Calls [onLongPress] when the finger rests on this element for a long press,
|
||||
* whatever inside it takes taps: it watches before the content does, and once
|
||||
* it fires the rest of the press is its own, so nothing inside clicks or
|
||||
* scrolls. Moving past the touch slop first leaves the press to the content.
|
||||
*/
|
||||
internal fun Modifier.onLongPressOver(haptics: HapticFeedback, onLongPress: () -> Unit): Modifier =
|
||||
pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
|
||||
val slop = viewConfiguration.touchSlop
|
||||
val ended = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {
|
||||
var over = false
|
||||
while (!over) {
|
||||
val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id }
|
||||
over = change == null || !change.pressed || change.isConsumed ||
|
||||
(change.position - down.position).getDistance() > slop
|
||||
}
|
||||
true
|
||||
}
|
||||
if (ended != null) return@awaitEachGesture
|
||||
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
onLongPress()
|
||||
do {
|
||||
val event = awaitPointerEvent(PointerEventPass.Initial)
|
||||
event.changes.forEach { it.consume() }
|
||||
} while (event.changes.any { it.pressed })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package de.jeanlucmakiola.agendula.ui.lists
|
||||
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ListAlt
|
||||
import androidx.compose.material.icons.rounded.FilterList
|
||||
import androidx.compose.material.icons.rounded.Sell
|
||||
import androidx.compose.material.icons.rounded.Tune
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.BlockSource
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.ui.common.ListColorChip
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
|
||||
/**
|
||||
* A full-screen pick of what a block or screen shows: the lists by account, the
|
||||
* saved filters and the tags, each with its open count, led by the smart lists
|
||||
* when [withSmartLists], Completed among them unless not [withCompletedList].
|
||||
* *Lists & filters…* in the view menu opens it to push the picked one's screen;
|
||||
* a block whose source is gone, to choose another. With [onCustomRules] it leads
|
||||
* with *Custom rules…*, which opens the rule editor.
|
||||
*/
|
||||
@Composable
|
||||
internal fun SourcePicker(
|
||||
title: String,
|
||||
state: ListsUiState.Content,
|
||||
withSmartLists: Boolean,
|
||||
onPick: (BlockSource) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
withCompletedList: Boolean = true,
|
||||
onCustomRules: (() -> Unit)? = null,
|
||||
) {
|
||||
val sections = state.unscopedSections
|
||||
val pick = { source: BlockSource ->
|
||||
onDismiss()
|
||||
onPick(source)
|
||||
}
|
||||
FullScreenPicker(title = title, onDismiss = onDismiss) {
|
||||
if (onCustomRules != null) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.view_source_custom),
|
||||
summary = stringResource(R.string.view_source_custom_hint),
|
||||
position = Position.Alone,
|
||||
leading = { Icon(Icons.Rounded.Tune, contentDescription = null) },
|
||||
onClick = {
|
||||
onDismiss()
|
||||
onCustomRules()
|
||||
},
|
||||
)
|
||||
}
|
||||
if (withSmartLists) {
|
||||
GroupedSectionHeader(stringResource(R.string.view_source_smart))
|
||||
val smarts = if (withCompletedList) SmartList.entries else SmartList.entries - SmartList.COMPLETED
|
||||
smarts.forEachIndexed { index, smart ->
|
||||
GroupedRow(
|
||||
title = stringResource(smartListLabel(smart)),
|
||||
position = positionOf(index, smarts.size),
|
||||
leading = { Icon(Icons.AutoMirrored.Rounded.ListAlt, contentDescription = null) },
|
||||
onClick = { pick(BlockSource.Smart(smart)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
sections.groups.forEach { group ->
|
||||
GroupedSectionHeader(group.accountName)
|
||||
group.lists.forEachIndexed { index, overview ->
|
||||
GroupedRow(
|
||||
title = overview.list.name,
|
||||
position = positionOf(index, group.lists.size),
|
||||
leading = { ListColorChip(overview.list.color) },
|
||||
trailing = { Count(overview.openCount) },
|
||||
onClick = { pick(BlockSource.List(overview.list.id)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (sections.filters.isNotEmpty()) {
|
||||
GroupedSectionHeader(stringResource(R.string.filters_header))
|
||||
sections.filters.forEachIndexed { index, overview ->
|
||||
GroupedRow(
|
||||
title = overview.filter.name,
|
||||
position = positionOf(index, sections.filters.size),
|
||||
leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) },
|
||||
trailing = { Count(overview.openCount) },
|
||||
onClick = { pick(BlockSource.Filter(overview.filter.id)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (sections.tags.isNotEmpty()) {
|
||||
GroupedSectionHeader(stringResource(R.string.tags_header))
|
||||
sections.tags.forEachIndexed { index, overview ->
|
||||
GroupedRow(
|
||||
title = overview.tag,
|
||||
position = positionOf(index, sections.tags.size),
|
||||
leading = { Icon(Icons.Rounded.Sell, contentDescription = null) },
|
||||
trailing = { Count(overview.openCount) },
|
||||
onClick = { pick(BlockSource.Tag(overview.tag)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Count(count: Int) {
|
||||
Text(
|
||||
count.toString(),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
/** The name of a smart list. */
|
||||
internal fun smartListLabel(smart: SmartList): Int = when (smart) {
|
||||
SmartList.TODAY -> R.string.smart_today
|
||||
SmartList.OVERDUE -> R.string.smart_overdue
|
||||
SmartList.UPCOMING -> R.string.smart_upcoming
|
||||
SmartList.NO_DATE -> R.string.smart_no_date
|
||||
SmartList.COMPLETED -> R.string.smart_completed
|
||||
SmartList.ALL -> R.string.smart_all
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.domain.smartListNamed
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import kotlin.time.Instant
|
||||
@@ -31,11 +32,21 @@ import de.jeanlucmakiola.agendula.ui.edit.TaskEditScreen
|
||||
import de.jeanlucmakiola.agendula.ui.edit.TaskEditViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.filters.FilterEditScreen
|
||||
import de.jeanlucmakiola.agendula.ui.filters.FilterEditViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.filters.RuleEditResult
|
||||
import de.jeanlucmakiola.agendula.ui.filters.RuleEditScreen
|
||||
import de.jeanlucmakiola.agendula.ui.filters.RuleEditViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.filters.RulePurpose
|
||||
import de.jeanlucmakiola.agendula.ui.imports.ImportScreen
|
||||
import de.jeanlucmakiola.agendula.ui.lists.ListsScreen
|
||||
import de.jeanlucmakiola.agendula.ui.quickadd.NEW_TASK_SAVED
|
||||
import de.jeanlucmakiola.agendula.ui.quickadd.NewTaskSeed
|
||||
import de.jeanlucmakiola.agendula.ui.settings.SettingsScreen
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.TaskListScreen
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.TaskListViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.views.EditViewScreen
|
||||
import de.jeanlucmakiola.agendula.ui.views.EditViewViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.views.ManageViewsScreen
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.floret.identity.predictiveBackExit
|
||||
|
||||
/**
|
||||
@@ -70,6 +81,13 @@ fun AgendulaNavHost(
|
||||
}
|
||||
|
||||
LaunchedEffect(navRequest) {
|
||||
val startOverOther = (navRequest as? NavRequest.OpenList)?.overHomeOnly == true ||
|
||||
(navRequest as? NavRequest.OpenFilter)?.overHomeOnly == true
|
||||
// The start screen opens over home only, never over a screen opened while it was worked out.
|
||||
if (startOverOther && nav.currentDestination?.route != Dest.LISTS) {
|
||||
onNavRequestConsumed()
|
||||
return@LaunchedEffect
|
||||
}
|
||||
when (navRequest) {
|
||||
null -> return@LaunchedEffect
|
||||
is NavRequest.OpenTask ->
|
||||
@@ -99,6 +117,11 @@ fun AgendulaNavHost(
|
||||
launchSingleTop = true
|
||||
}
|
||||
is NavRequest.Import -> nav.navigate(Dest.Import.build(navRequest.uri))
|
||||
// The view was switched to as the request arrived. Home is uncovered unless
|
||||
// a form is open, whose draft that would throw away; then the view waits below it.
|
||||
is NavRequest.OpenView -> if (nav.currentDestination?.route !in FORMS) {
|
||||
nav.popBackStack(Dest.LISTS, inclusive = false)
|
||||
}
|
||||
}
|
||||
val returnHome = (navRequest as? NavRequest.NewTask)?.returnHome == true ||
|
||||
(navRequest as? NavRequest.OpenTask)?.returnHome == true
|
||||
@@ -120,14 +143,86 @@ fun AgendulaNavHost(
|
||||
popEnterTransition = { EnterTransition.None },
|
||||
popExitTransition = { overlayExit },
|
||||
) {
|
||||
composable(Dest.LISTS) {
|
||||
composable(Dest.LISTS) { entry ->
|
||||
// Custom rules handed back by the rule editor, for a block being added or set up.
|
||||
val rulesResult by entry.savedStateHandle.getStateFlow<String?>(RuleEditResult.KEY, null).collectAsStateWithLifecycle()
|
||||
val newTaskSaved by entry.savedStateHandle.getStateFlow(NEW_TASK_SAVED, false).collectAsStateWithLifecycle()
|
||||
ReadableWidth {
|
||||
ListsScreen(
|
||||
onOpenFilter = { filter -> nav.navigate(Dest.TaskList.build(filter)) },
|
||||
onOpenFilter = { filter, scopeViewId -> nav.navigate(Dest.TaskList.build(filter, scopeViewId)) },
|
||||
onOpenTask = { task -> nav.navigate(task.detailRoute()) },
|
||||
onNewTask = { nav.navigate(Dest.TaskEdit.buildNew()) },
|
||||
// The view's scope presets the task; its task list block's source adds its own presets.
|
||||
onNewTask = { seed -> nav.navigate(seed.route()) },
|
||||
onNewFilter = { nav.navigate(Dest.FilterEdit.build()) },
|
||||
onOpenSettings = { nav.navigate(Dest.SETTINGS) },
|
||||
onManageViews = { nav.navigate(Dest.MANAGE_VIEWS) },
|
||||
onEditView = { id -> nav.navigate(Dest.EditView.build(id)) },
|
||||
onEditBlockRules = { viewId, blockId -> nav.navigate(Dest.RuleEdit.forBlock(viewId, blockId)) },
|
||||
onEditRules = { initial -> nav.navigate(Dest.RuleEdit.forResult(RulePurpose.SOURCE, initial)) },
|
||||
rulesResult = rulesResult?.let(RuleEditResult::decode)?.source,
|
||||
onRulesResultTaken = { entry.savedStateHandle.remove<String>(RuleEditResult.KEY) },
|
||||
newTaskSaved = newTaskSaved,
|
||||
onNewTaskSavedTaken = { entry.savedStateHandle.remove<Boolean>(NEW_TASK_SAVED) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
composable(Dest.MANAGE_VIEWS) {
|
||||
ReadableWidth {
|
||||
ManageViewsScreen(
|
||||
onBack = { nav.popBackStack() },
|
||||
onEditView = { id -> nav.navigate(Dest.EditView.build(id)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
composable(Dest.EditView.route, arguments = Dest.EditView.arguments) { entry ->
|
||||
val viewId = entry.arguments?.getLong(Dest.EditView.ARG_VIEW_ID) ?: View.HOME_ID
|
||||
val vm: EditViewViewModel = hiltViewModel()
|
||||
LaunchedEffect(viewId) { vm.bind(viewId) }
|
||||
// The scope edited in the rule editor, handed back once the view has loaded.
|
||||
val scopeResult by entry.savedStateHandle.getStateFlow<String?>(RuleEditResult.KEY, null).collectAsStateWithLifecycle()
|
||||
val loaded by vm.draft.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(scopeResult, loaded != null) {
|
||||
val result = scopeResult ?: return@LaunchedEffect
|
||||
if (loaded == null) return@LaunchedEffect
|
||||
(RuleEditResult.decode(result) as? RuleEditResult.Rules)?.let { vm.setScope(it.rule) }
|
||||
entry.savedStateHandle.remove<String>(RuleEditResult.KEY)
|
||||
}
|
||||
ReadableWidth {
|
||||
EditViewScreen(
|
||||
viewModel = vm,
|
||||
onEditScope = { scope -> nav.navigate(Dest.RuleEdit.forResult(RulePurpose.SCOPE, scope)) },
|
||||
onBack = { nav.popBackStack() },
|
||||
// Home shows the view with its layout open, under whatever led here; not if
|
||||
// another screen was opened from here while the view saved.
|
||||
onEditLayout = { if (nav.currentBackStackEntry?.id == entry.id) nav.popBackStack(Dest.LISTS, inclusive = false) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
composable(Dest.RuleEdit.route, arguments = Dest.RuleEdit.arguments) { entry ->
|
||||
val args = entry.arguments
|
||||
val purpose = Dest.RuleEdit.purposeOf(args?.getString(Dest.RuleEdit.ARG_PURPOSE))
|
||||
val target = Dest.RuleEdit.targetOf(
|
||||
viewId = args?.getLong(Dest.RuleEdit.ARG_VIEW_ID) ?: Dest.NO_ID,
|
||||
blockId = args?.getLong(Dest.RuleEdit.ARG_BLOCK_ID) ?: Dest.NO_ID,
|
||||
rule = args?.getString(Dest.RuleEdit.ARG_RULE),
|
||||
)
|
||||
val vm: RuleEditViewModel = hiltViewModel()
|
||||
LaunchedEffect(target) { vm.bind(target, purpose) }
|
||||
ReadableWidth {
|
||||
RuleEditScreen(
|
||||
viewModel = vm,
|
||||
purpose = purpose,
|
||||
onDone = { result ->
|
||||
// Only while this editor is still the screen shown; the user may have left it.
|
||||
if (nav.currentBackStackEntry?.id == entry.id) {
|
||||
if (result != null) nav.previousBackStackEntry?.savedStateHandle?.set(RuleEditResult.KEY, result.encode())
|
||||
nav.popBackStack()
|
||||
}
|
||||
},
|
||||
onBack = { nav.popBackStack() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -158,28 +253,32 @@ fun AgendulaNavHost(
|
||||
listId = args?.getLong(Dest.TaskList.ARG_LIST_ID) ?: Dest.NO_ID,
|
||||
tag = args?.getString(Dest.TaskList.ARG_TAG),
|
||||
filterId = args?.getLong(Dest.TaskList.ARG_FILTER_ID) ?: Dest.NO_ID,
|
||||
day = args?.getString(Dest.TaskList.ARG_DAY),
|
||||
rule = args?.getString(Dest.TaskList.ARG_RULE),
|
||||
title = args?.getString(Dest.TaskList.ARG_TITLE),
|
||||
)
|
||||
val scopeViewId = args?.getLong(Dest.TaskList.ARG_VIEW)?.takeIf { it != Dest.NO_ID }
|
||||
val vm: TaskListViewModel = hiltViewModel()
|
||||
LaunchedEffect(filter) { vm.bind(filter) }
|
||||
LaunchedEffect(filter, scopeViewId) { vm.bind(filter, scopeViewId) }
|
||||
val newTaskSaved by entry.savedStateHandle.getStateFlow(NEW_TASK_SAVED, false).collectAsStateWithLifecycle()
|
||||
|
||||
val taskList: @Composable (onOpenTask: (Task) -> Unit, detailShown: Boolean) -> Unit = { onOpenTask, detailShown ->
|
||||
TaskListScreen(
|
||||
filter = filter,
|
||||
viewModel = vm,
|
||||
onOpenTask = onOpenTask,
|
||||
onNewTask = {
|
||||
nav.navigate(
|
||||
Dest.TaskEdit.buildNew(
|
||||
presetListId = (filter as? TaskFilter.OfList)?.listId,
|
||||
tag = (filter as? TaskFilter.Tagged)?.tag,
|
||||
filterId = (filter as? TaskFilter.Saved)?.id,
|
||||
smartList = (filter as? TaskFilter.Smart)?.list,
|
||||
),
|
||||
)
|
||||
},
|
||||
onNewTask = { seed -> nav.navigate(seed.copy(preset = filter).route()) },
|
||||
onEditFilter = { id -> nav.navigate(Dest.FilterEdit.build(id)) },
|
||||
onOpenList = { id -> nav.navigate(Dest.TaskList.build(TaskFilter.OfList(id))) },
|
||||
// The new view shows on home, so the screen it was pinned from goes.
|
||||
// Only while this screen is still the one shown; the user may have moved on.
|
||||
onPinned = {
|
||||
if (nav.currentBackStackEntry?.id == entry.id) nav.popBackStack(Dest.LISTS, inclusive = false)
|
||||
},
|
||||
onBack = { nav.popBackStack() },
|
||||
backClosesSearch = !detailShown,
|
||||
newTaskSaved = newTaskSaved,
|
||||
onNewTaskSavedTaken = { entry.savedStateHandle.remove<Boolean>(NEW_TASK_SAVED) },
|
||||
)
|
||||
}
|
||||
BoxWithConstraints {
|
||||
@@ -244,9 +343,14 @@ fun AgendulaNavHost(
|
||||
val parentId = args?.getLong(Dest.TaskEdit.ARG_PARENT_ID) ?: Dest.NO_ID
|
||||
val occurrence = args?.getLong(Dest.TaskEdit.ARG_OCCURRENCE)?.takeIf { it != Dest.NO_ID }
|
||||
val title = args?.getString(Dest.TaskEdit.ARG_TITLE)
|
||||
val tag = args?.getString(Dest.TaskEdit.ARG_TAG)
|
||||
val tags = Dest.TaskEdit.tagsOf(args?.getString(Dest.TaskEdit.ARG_TAG))
|
||||
val fromQuickAdd = args?.getBoolean(Dest.TaskEdit.ARG_FROM_QUICK_ADD) == true
|
||||
val filterId = args?.getLong(Dest.TaskEdit.ARG_FILTER_ID)?.takeIf { it != Dest.NO_ID }
|
||||
val smartList = smartListNamed(args?.getString(Dest.TaskEdit.ARG_SMART_LIST))
|
||||
val presetRule = args?.getString(Dest.TaskEdit.ARG_RULE)?.let { runCatching { Dest.TaskList.ruleOf(it) }.getOrNull() }
|
||||
val presetDue = args?.getString(Dest.TaskEdit.ARG_DUE)?.let { runCatching { java.time.LocalDate.parse(it) }.getOrNull() }
|
||||
val presetDueTime = args?.getString(Dest.TaskEdit.ARG_DUE_TIME)?.let { runCatching { java.time.LocalTime.parse(it) }.getOrNull() }
|
||||
val scopeViewId = args?.getLong(Dest.TaskEdit.ARG_VIEW)?.takeIf { it != Dest.NO_ID }
|
||||
val vm: TaskEditViewModel = hiltViewModel()
|
||||
LaunchedEffect(taskId, presetListId, parentId) {
|
||||
if (taskId != Dest.NO_ID) {
|
||||
@@ -256,9 +360,13 @@ fun AgendulaNavHost(
|
||||
presetListId = presetListId.takeIf { it != Dest.NO_ID },
|
||||
parentId = parentId.takeIf { it != Dest.NO_ID },
|
||||
initialTitle = title,
|
||||
presetTag = tag,
|
||||
presetTags = tags,
|
||||
presetFilterId = filterId,
|
||||
presetSmartList = smartList,
|
||||
presetDueDate = presetDue,
|
||||
presetRule = presetRule,
|
||||
scopeViewId = scopeViewId,
|
||||
presetDueTime = presetDueTime,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -266,7 +374,10 @@ fun AgendulaNavHost(
|
||||
ReadableWidth {
|
||||
TaskEditScreen(
|
||||
viewModel = vm,
|
||||
onSaved = { nav.popBackStack() },
|
||||
onSaved = {
|
||||
if (fromQuickAdd) nav.previousBackStackEntry?.savedStateHandle?.set(NEW_TASK_SAVED, true)
|
||||
nav.popBackStack()
|
||||
},
|
||||
onBack = { nav.popBackStack() },
|
||||
)
|
||||
}
|
||||
@@ -274,6 +385,24 @@ fun AgendulaNavHost(
|
||||
}
|
||||
}
|
||||
|
||||
/** The editor for a new task as [NewTaskSeed] has it; what it was typed into presets it too. */
|
||||
private fun NewTaskSeed.route(): String = Dest.TaskEdit.buildNew(
|
||||
presetListId = listId ?: (preset as? TaskFilter.OfList)?.listId,
|
||||
title = title,
|
||||
tag = (preset as? TaskFilter.Tagged)?.tag,
|
||||
filterId = (preset as? TaskFilter.Saved)?.id,
|
||||
smartList = (preset as? TaskFilter.Smart)?.list,
|
||||
due = due?.date ?: (preset as? TaskFilter.DueOn)?.date,
|
||||
rule = (preset as? TaskFilter.Matching)?.rule,
|
||||
scopeViewId = scopeViewId,
|
||||
dueTime = due?.time,
|
||||
tags = tags,
|
||||
fromQuickAdd = fromQuickAdd,
|
||||
)
|
||||
|
||||
/** Routes holding a draft that leaving would lose. */
|
||||
private val FORMS = setOf(Dest.TaskEdit.route, Dest.FilterEdit.route, Dest.EditView.route, Dest.RuleEdit.route)
|
||||
|
||||
/** A task's detail route, pinned to its occurrence when it is one of a series. */
|
||||
private fun Task.detailRoute(): String = Dest.TaskDetail.build(taskId, occurrenceStart?.toEpochMilliseconds())
|
||||
|
||||
|
||||
@@ -1,33 +1,134 @@
|
||||
package de.jeanlucmakiola.agendula.ui.navigation
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import androidx.compose.ui.graphics.PathFillType
|
||||
import androidx.compose.ui.graphics.asAndroidPath
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.vector.VectorGroup
|
||||
import androidx.compose.ui.graphics.vector.VectorPath
|
||||
import androidx.compose.ui.graphics.vector.toPath
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.content.pm.ShortcutInfoCompat
|
||||
import androidx.core.content.pm.ShortcutManagerCompat
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.core.graphics.withSave
|
||||
import androidx.core.graphics.drawable.IconCompat
|
||||
import de.jeanlucmakiola.agendula.MainActivity
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.ui.views.unnamedViewLabel
|
||||
import de.jeanlucmakiola.agendula.ui.views.vector
|
||||
|
||||
/**
|
||||
* The launcher's long-press shortcuts. Published at runtime rather than from a
|
||||
* static `shortcuts.xml`, whose intents would have to name the release package
|
||||
* and so break in the suffixed debug and releaseTest builds — and so the labels
|
||||
* follow the app language.
|
||||
* The launcher's long-press shortcuts: New task, Today, then every view (#59),
|
||||
* as many as the launcher takes. Published at runtime rather than from a static
|
||||
* `shortcuts.xml`, whose intents would have to name the release package and so
|
||||
* break in the suffixed debug and releaseTest builds — and so the labels follow
|
||||
* the app language.
|
||||
*/
|
||||
object AppShortcuts {
|
||||
|
||||
fun publish(context: Context) {
|
||||
val shortcuts = listOf(
|
||||
/** The views last published, for a republish that doesn't come with them; `null` before the first. */
|
||||
@Volatile private var lastViews: List<View>? = null
|
||||
@Volatile private var lastStored: Set<Long>? = null
|
||||
|
||||
/**
|
||||
* Publishes the shortcuts with [views]. Without them, before the views were
|
||||
* ever published, only the fixed shortcuts are refreshed and the views'
|
||||
* left as they are, rather than wiped.
|
||||
*/
|
||||
@Synchronized
|
||||
fun publish(context: Context, views: List<View>? = lastViews, stored: Set<Long>? = lastStored) {
|
||||
val fixed = listOf(
|
||||
ShortcutInfoCompat.Builder(context, "new_task")
|
||||
.setShortLabel(context.getString(R.string.shortcut_new_task))
|
||||
.setIcon(IconCompat.createWithResource(context, R.drawable.ic_shortcut_new_task))
|
||||
.setIntent(MainActivity.newTaskIntent(context))
|
||||
.setRank(0)
|
||||
.build(),
|
||||
ShortcutInfoCompat.Builder(context, "today")
|
||||
.setShortLabel(context.getString(R.string.shortcut_today))
|
||||
.setIcon(IconCompat.createWithResource(context, R.drawable.ic_shortcut_today))
|
||||
.setIntent(MainActivity.todayIntent(context))
|
||||
.setRank(1)
|
||||
.build(),
|
||||
)
|
||||
runCatching { ShortcutManagerCompat.setDynamicShortcuts(context, shortcuts) }
|
||||
if (views == null) {
|
||||
fixed.forEach { runCatching { ShortcutManagerCompat.pushDynamicShortcut(context, it) } }
|
||||
return
|
||||
}
|
||||
lastViews = views
|
||||
lastStored = stored
|
||||
val room = runCatching { ShortcutManagerCompat.getMaxShortcutCountPerActivity(context) }.getOrDefault(fixed.size)
|
||||
val all = views.mapIndexed { index, view ->
|
||||
val label = view.name.ifBlank { context.getString(unnamedViewLabel(view.id)) }
|
||||
ShortcutInfoCompat.Builder(context, "view_${view.id}")
|
||||
.setShortLabel(label)
|
||||
.setIcon(IconCompat.createWithBitmap(shortcutBitmap(context, view.icon.vector)))
|
||||
.setIntent(MainActivity.viewIntent(context, view.id))
|
||||
.setRank(fixed.size + index)
|
||||
.build()
|
||||
}
|
||||
runCatching { ShortcutManagerCompat.setDynamicShortcuts(context, fixed + all.take((room - fixed.size).coerceAtLeast(0))) }
|
||||
// Pinned to the home screen, a view's shortcut follows its renames, and is disabled once it is deleted.
|
||||
runCatching {
|
||||
val pinned = ShortcutManagerCompat.getShortcuts(context, ShortcutManagerCompat.FLAG_MATCH_PINNED)
|
||||
.map { it.id }
|
||||
.filter { it.startsWith("view_") }
|
||||
.toSet()
|
||||
val (present, missing) = pinned.partition { id -> all.any { it.id == id } }
|
||||
if (present.isNotEmpty()) {
|
||||
// One disabled while it didn't read comes back with its view.
|
||||
ShortcutManagerCompat.enableShortcuts(context, all.filter { it.id in present })
|
||||
ShortcutManagerCompat.updateShortcuts(context, all.filter { it.id in present })
|
||||
}
|
||||
// Only a view no longer stored at all is gone; while the views are another version's, none is.
|
||||
val gone = if (stored == null) emptyList() else missing.filter { it.removePrefix("view_").toLongOrNull() !in stored }
|
||||
if (gone.isNotEmpty()) {
|
||||
ShortcutManagerCompat.disableShortcuts(context, gone, context.getString(R.string.view_shortcut_gone))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Tells the launcher a view's shortcut was used, so it can rank it. */
|
||||
fun reportUsed(context: Context, viewId: Long) {
|
||||
runCatching { ShortcutManagerCompat.reportShortcutUsed(context, "view_$viewId") }
|
||||
}
|
||||
|
||||
/** [icon] white on the brand circle, as the drawn shortcut icons are; launchers don't tint them. */
|
||||
private fun shortcutBitmap(context: Context, icon: ImageVector): Bitmap {
|
||||
val size = (48 * context.resources.displayMetrics.density).toInt()
|
||||
val bitmap = createBitmap(size, size)
|
||||
val canvas = Canvas(bitmap)
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
paint.color = ContextCompat.getColor(context, R.color.ic_launcher_background)
|
||||
canvas.drawCircle(size / 2f, size / 2f, size / 2f, paint)
|
||||
paint.color = android.graphics.Color.WHITE
|
||||
// The glyph takes 58% of the circle, as in the drawn icons.
|
||||
val glyph = size * 0.58f
|
||||
canvas.translate((size - glyph) / 2f, (size - glyph) / 2f)
|
||||
canvas.scale(glyph / icon.viewportWidth, glyph / icon.viewportHeight)
|
||||
drawGroup(canvas, icon.root, paint)
|
||||
return bitmap
|
||||
}
|
||||
|
||||
private fun drawGroup(canvas: Canvas, group: VectorGroup, paint: Paint): Unit = canvas.withSave {
|
||||
translate(group.translationX + group.pivotX, group.translationY + group.pivotY)
|
||||
rotate(group.rotation)
|
||||
scale(group.scaleX, group.scaleY)
|
||||
translate(-group.pivotX, -group.pivotY)
|
||||
for (node in group) {
|
||||
when (node) {
|
||||
is VectorGroup -> drawGroup(this, node, paint)
|
||||
is VectorPath -> {
|
||||
val path = node.pathData.toPath().asAndroidPath()
|
||||
if (node.pathFillType == PathFillType.EvenOdd) path.fillType = android.graphics.Path.FillType.EVEN_ODD
|
||||
drawPath(path, paint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,13 @@ package de.jeanlucmakiola.agendula.ui.navigation
|
||||
|
||||
import androidx.navigation.NavType
|
||||
import androidx.navigation.navArgument
|
||||
import de.jeanlucmakiola.agendula.data.prefs.RuleCodec
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.ui.filters.RuleEditResult
|
||||
import de.jeanlucmakiola.agendula.ui.filters.RuleEditViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.filters.RulePurpose
|
||||
|
||||
/**
|
||||
* String-based route table for the app's [androidx.navigation.NavHost].
|
||||
@@ -17,6 +22,9 @@ import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
* being nullable, which sidesteps the lack of a nullable-Long [NavType].
|
||||
*/
|
||||
object Dest {
|
||||
/** The store a rule's lists are qualified by in a route: any one, the same both ways. */
|
||||
private const val ROUTE_STORE = "ROUTE"
|
||||
|
||||
|
||||
const val NO_ID = -1L
|
||||
|
||||
@@ -56,41 +64,82 @@ object Dest {
|
||||
/**
|
||||
* One [TaskFilter]'s tasks. Carries one of `listId` (a real list), `smart`
|
||||
* (a [SmartList] name), `tag` or `filterId` (a saved filter); whichever is
|
||||
* set decides the filter.
|
||||
* set decides the filter. `view` narrows it to that view's scope.
|
||||
*/
|
||||
object TaskList {
|
||||
const val ARG_LIST_ID = "listId"
|
||||
const val ARG_SMART = "smart"
|
||||
const val ARG_TAG = "tag"
|
||||
const val ARG_FILTER_ID = "filterId"
|
||||
const val ARG_VIEW = "view"
|
||||
const val ARG_DAY = "day"
|
||||
const val ARG_RULE = "rule"
|
||||
const val ARG_TITLE = "title"
|
||||
const val route = "taskList?$ARG_LIST_ID={$ARG_LIST_ID}&$ARG_SMART={$ARG_SMART}&$ARG_TAG={$ARG_TAG}" +
|
||||
"&$ARG_FILTER_ID={$ARG_FILTER_ID}"
|
||||
"&$ARG_FILTER_ID={$ARG_FILTER_ID}&$ARG_VIEW={$ARG_VIEW}&$ARG_DAY={$ARG_DAY}" +
|
||||
"&$ARG_RULE={$ARG_RULE}&$ARG_TITLE={$ARG_TITLE}"
|
||||
|
||||
val arguments = listOf(
|
||||
navArgument(ARG_LIST_ID) { type = NavType.LongType; defaultValue = NO_ID },
|
||||
navArgument(ARG_SMART) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_TAG) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_FILTER_ID) { type = NavType.LongType; defaultValue = NO_ID },
|
||||
navArgument(ARG_VIEW) { type = NavType.LongType; defaultValue = NO_ID },
|
||||
navArgument(ARG_DAY) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_RULE) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_TITLE) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
)
|
||||
|
||||
fun build(filter: TaskFilter): String = when (filter) {
|
||||
is TaskFilter.OfList -> "taskList?$ARG_LIST_ID=${filter.listId}"
|
||||
is TaskFilter.Smart -> "taskList?$ARG_SMART=${filter.list.name}"
|
||||
is TaskFilter.Tagged -> "taskList?$ARG_TAG=${android.net.Uri.encode(filter.tag)}"
|
||||
is TaskFilter.Saved -> "taskList?$ARG_FILTER_ID=${filter.id}"
|
||||
// Several lists at once only exists for the widget, which never routes here.
|
||||
is TaskFilter.OfLists -> error("OfLists has no task-list screen")
|
||||
fun build(filter: TaskFilter, scopeViewId: Long? = null): String {
|
||||
val base = when (filter) {
|
||||
is TaskFilter.OfList -> "taskList?$ARG_LIST_ID=${filter.listId}"
|
||||
is TaskFilter.Smart -> "taskList?$ARG_SMART=${filter.list.name}"
|
||||
is TaskFilter.Tagged -> "taskList?$ARG_TAG=${android.net.Uri.encode(filter.tag)}"
|
||||
is TaskFilter.Saved -> "taskList?$ARG_FILTER_ID=${filter.id}"
|
||||
is TaskFilter.DueOn -> "taskList?$ARG_DAY=${filter.date}"
|
||||
is TaskFilter.Matching -> "taskList?$ARG_RULE=${android.net.Uri.encode(RuleCodec.encode(filter.rule, ROUTE_STORE))}" +
|
||||
filter.title?.let { "&$ARG_TITLE=${android.net.Uri.encode(it)}" }.orEmpty()
|
||||
// Several lists at once only exists for the widget, which never routes here.
|
||||
is TaskFilter.OfLists -> error("OfLists has no task-list screen")
|
||||
}
|
||||
return if (scopeViewId == null) base else "$base&$ARG_VIEW=$scopeViewId"
|
||||
}
|
||||
|
||||
/** Reconstruct the filter from a destination's arguments. */
|
||||
fun filterOf(smart: String?, listId: Long, tag: String? = null, filterId: Long = NO_ID): TaskFilter = when {
|
||||
/** [text], a rule as a route carries it, read back. */
|
||||
fun ruleOf(text: String): Rule = RuleCodec.decode(text, ROUTE_STORE)
|
||||
|
||||
/** Reconstruct the filter from a destination's arguments; a rule that doesn't read shows All. */
|
||||
fun filterOf(
|
||||
smart: String?,
|
||||
listId: Long,
|
||||
tag: String? = null,
|
||||
filterId: Long = NO_ID,
|
||||
day: String? = null,
|
||||
rule: String? = null,
|
||||
title: String? = null,
|
||||
): TaskFilter = when {
|
||||
smart != null -> TaskFilter.Smart(SmartList.valueOf(smart))
|
||||
rule != null -> runCatching { ruleOf(rule) }.getOrNull()?.let { TaskFilter.Matching(it, title) }
|
||||
?: TaskFilter.Smart(SmartList.ALL)
|
||||
day != null -> TaskFilter.DueOn(java.time.LocalDate.parse(day))
|
||||
tag != null -> TaskFilter.Tagged(tag)
|
||||
filterId != NO_ID -> TaskFilter.Saved(filterId)
|
||||
else -> TaskFilter.OfList(listId)
|
||||
}
|
||||
}
|
||||
|
||||
/** The views: reorder, add, open one to edit. */
|
||||
const val MANAGE_VIEWS = "views"
|
||||
|
||||
/** One view's name, icon, scope and quick-add. */
|
||||
object EditView {
|
||||
const val ARG_VIEW_ID = "viewId"
|
||||
const val route = "views/{$ARG_VIEW_ID}"
|
||||
val arguments = listOf(navArgument(ARG_VIEW_ID) { type = NavType.LongType })
|
||||
|
||||
fun build(viewId: Long): String = "views/$viewId"
|
||||
}
|
||||
|
||||
/** Creates a saved filter, or edits the one `filterId` names. */
|
||||
object FilterEdit {
|
||||
const val ARG_FILTER_ID = "filterId"
|
||||
@@ -101,6 +150,47 @@ object Dest {
|
||||
if (filterId == null) "filterEdit" else "filterEdit?$ARG_FILTER_ID=$filterId"
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits a bare rule ([RuleEditScreen][de.jeanlucmakiola.agendula.ui.filters.RuleEditScreen]):
|
||||
* the source of a stored block, written in place ([forBlock]), or a rule handed
|
||||
* back to the opener under [RuleEditResult.KEY] in its saved state ([forResult]).
|
||||
*/
|
||||
object RuleEdit {
|
||||
const val ARG_PURPOSE = "purpose"
|
||||
const val ARG_VIEW_ID = "viewId"
|
||||
const val ARG_BLOCK_ID = "blockId"
|
||||
const val ARG_RULE = "rule"
|
||||
const val route = "ruleEdit?$ARG_PURPOSE={$ARG_PURPOSE}&$ARG_VIEW_ID={$ARG_VIEW_ID}" +
|
||||
"&$ARG_BLOCK_ID={$ARG_BLOCK_ID}&$ARG_RULE={$ARG_RULE}"
|
||||
|
||||
val arguments = listOf(
|
||||
navArgument(ARG_PURPOSE) { type = NavType.StringType; defaultValue = RulePurpose.SOURCE.name },
|
||||
navArgument(ARG_VIEW_ID) { type = NavType.LongType; defaultValue = NO_ID },
|
||||
navArgument(ARG_BLOCK_ID) { type = NavType.LongType; defaultValue = NO_ID },
|
||||
navArgument(ARG_RULE) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
)
|
||||
|
||||
/** Custom rules for block [blockId] of the stored view [viewId], saved into it. */
|
||||
fun forBlock(viewId: Long, blockId: Long): String =
|
||||
"ruleEdit?$ARG_PURPOSE=${RulePurpose.SOURCE.name}&$ARG_VIEW_ID=$viewId&$ARG_BLOCK_ID=$blockId"
|
||||
|
||||
/** [initial], or none, edited for [purpose] and handed back as a [RuleEditResult]. */
|
||||
fun forResult(purpose: RulePurpose, initial: Rule?): String {
|
||||
val base = "ruleEdit?$ARG_PURPOSE=${purpose.name}"
|
||||
return if (initial == null) base else "$base&$ARG_RULE=${android.net.Uri.encode(RuleEditResult.Rules(initial).encode())}"
|
||||
}
|
||||
|
||||
/** Where the editor opened with [viewId], [blockId] and [rule] saves to. */
|
||||
fun targetOf(viewId: Long, blockId: Long, rule: String?): RuleEditViewModel.Target =
|
||||
if (viewId != NO_ID && blockId != NO_ID) {
|
||||
RuleEditViewModel.Target.Block(viewId, blockId)
|
||||
} else {
|
||||
RuleEditViewModel.Target.Result((rule?.let(RuleEditResult::decode) as? RuleEditResult.Rules)?.rule)
|
||||
}
|
||||
|
||||
fun purposeOf(name: String?): RulePurpose = RulePurpose.entries.firstOrNull { it.name == name } ?: RulePurpose.SOURCE
|
||||
}
|
||||
|
||||
/** A single task's detail; `occ` (epoch millis) picks one occurrence of a series. */
|
||||
object TaskDetail {
|
||||
const val ARG_TASK_ID = "taskId"
|
||||
@@ -120,7 +210,8 @@ object Dest {
|
||||
/**
|
||||
* The create / edit form. `taskId` set ([NO_ID] otherwise) ⇒ edit; for a new
|
||||
* task, `presetListId` / `parentId` optionally seed the form, and `filterId`
|
||||
* (or `smartList`) fills it so the task lands in that view.
|
||||
* (or `smartList`) fills it so the task lands in that view; `view` adds the
|
||||
* presets of that view's scope, and `dueTime` puts a time on `due`.
|
||||
*/
|
||||
object TaskEdit {
|
||||
const val ARG_TASK_ID = "taskId"
|
||||
@@ -131,6 +222,17 @@ object Dest {
|
||||
const val ARG_TAG = "tag"
|
||||
const val ARG_FILTER_ID = "filterId"
|
||||
const val ARG_SMART_LIST = "smartList"
|
||||
const val ARG_DUE = "due"
|
||||
const val ARG_RULE = "rule"
|
||||
const val ARG_VIEW = "view"
|
||||
const val ARG_DUE_TIME = "dueTime"
|
||||
const val ARG_FROM_QUICK_ADD = "fromQuickAdd"
|
||||
|
||||
/** Between the tags of [ARG_TAG]; a tag can't hold a line break. */
|
||||
const val TAG_SEPARATOR = "\n"
|
||||
|
||||
/** The tags [ARG_TAG] holds. */
|
||||
fun tagsOf(arg: String?): List<String> = arg?.split(TAG_SEPARATOR)?.filter { it.isNotBlank() }.orEmpty()
|
||||
const val route =
|
||||
"taskEdit?$ARG_TASK_ID={$ARG_TASK_ID}" +
|
||||
"&$ARG_PRESET_LIST_ID={$ARG_PRESET_LIST_ID}" +
|
||||
@@ -139,7 +241,12 @@ object Dest {
|
||||
"&$ARG_TITLE={$ARG_TITLE}" +
|
||||
"&$ARG_TAG={$ARG_TAG}" +
|
||||
"&$ARG_FILTER_ID={$ARG_FILTER_ID}" +
|
||||
"&$ARG_SMART_LIST={$ARG_SMART_LIST}"
|
||||
"&$ARG_SMART_LIST={$ARG_SMART_LIST}" +
|
||||
"&$ARG_DUE={$ARG_DUE}" +
|
||||
"&$ARG_RULE={$ARG_RULE}" +
|
||||
"&$ARG_VIEW={$ARG_VIEW}" +
|
||||
"&$ARG_DUE_TIME={$ARG_DUE_TIME}" +
|
||||
"&$ARG_FROM_QUICK_ADD={$ARG_FROM_QUICK_ADD}"
|
||||
|
||||
val arguments = listOf(
|
||||
navArgument(ARG_TASK_ID) { type = NavType.LongType; defaultValue = NO_ID },
|
||||
@@ -150,6 +257,11 @@ object Dest {
|
||||
navArgument(ARG_TAG) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_FILTER_ID) { type = NavType.LongType; defaultValue = NO_ID },
|
||||
navArgument(ARG_SMART_LIST) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_DUE) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_RULE) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_VIEW) { type = NavType.LongType; defaultValue = NO_ID },
|
||||
navArgument(ARG_DUE_TIME) { type = NavType.StringType; nullable = true; defaultValue = null },
|
||||
navArgument(ARG_FROM_QUICK_ADD) { type = NavType.BoolType; defaultValue = false },
|
||||
)
|
||||
|
||||
fun buildEdit(taskId: Long, occurrenceStart: Long? = null): String =
|
||||
@@ -163,14 +275,26 @@ object Dest {
|
||||
tag: String? = null,
|
||||
filterId: Long? = null,
|
||||
smartList: SmartList? = null,
|
||||
due: java.time.LocalDate? = null,
|
||||
rule: Rule? = null,
|
||||
scopeViewId: Long? = null,
|
||||
dueTime: java.time.LocalTime? = null,
|
||||
tags: List<String> = emptyList(),
|
||||
fromQuickAdd: Boolean = false,
|
||||
): String {
|
||||
val allTags = (listOfNotNull(tag) + tags).filter { it.isNotBlank() }.distinct()
|
||||
val params = buildList {
|
||||
if (presetListId != null) add("$ARG_PRESET_LIST_ID=$presetListId")
|
||||
if (parentId != null) add("$ARG_PARENT_ID=$parentId")
|
||||
if (!title.isNullOrBlank()) add("$ARG_TITLE=${android.net.Uri.encode(title)}")
|
||||
if (!tag.isNullOrBlank()) add("$ARG_TAG=${android.net.Uri.encode(tag)}")
|
||||
if (allTags.isNotEmpty()) add("$ARG_TAG=${android.net.Uri.encode(allTags.joinToString(TAG_SEPARATOR))}")
|
||||
if (filterId != null) add("$ARG_FILTER_ID=$filterId")
|
||||
if (smartList != null) add("$ARG_SMART_LIST=${smartList.name}")
|
||||
if (due != null) add("$ARG_DUE=$due")
|
||||
if (rule != null) add("$ARG_RULE=${android.net.Uri.encode(RuleCodec.encode(rule, ROUTE_STORE))}")
|
||||
if (scopeViewId != null) add("$ARG_VIEW=$scopeViewId")
|
||||
if (due != null && dueTime != null) add("$ARG_DUE_TIME=$dueTime")
|
||||
if (fromQuickAdd) add("$ARG_FROM_QUICK_ADD=true")
|
||||
}
|
||||
return if (params.isEmpty()) "taskEdit" else "taskEdit?${params.joinToString("&")}"
|
||||
}
|
||||
|
||||
@@ -45,11 +45,14 @@ sealed interface NavRequest {
|
||||
/** One of the smart lists — the launcher's "Today" shortcut, a widget header. */
|
||||
data class OpenSmart(val list: SmartList) : NavRequest
|
||||
|
||||
/** One real list — a widget header. */
|
||||
data class OpenList(val listId: Long) : NavRequest
|
||||
/** One real list — a widget header. [overHomeOnly]: the start screen, dropped once something else is open. */
|
||||
data class OpenList(val listId: Long, val overHomeOnly: Boolean = false) : NavRequest
|
||||
|
||||
/** One saved filter — a widget header. */
|
||||
data class OpenFilter(val filterId: Long) : NavRequest
|
||||
/** One saved filter — a widget header. [overHomeOnly] as for [OpenList]. */
|
||||
data class OpenFilter(val filterId: Long, val overHomeOnly: Boolean = false) : NavRequest
|
||||
|
||||
/** One view — its launcher shortcut. The view is switched to as the request is made. */
|
||||
data class OpenView(val viewId: Long) : NavRequest
|
||||
|
||||
/** An `.ics` another app handed over. */
|
||||
data class Import(val uri: Uri) : NavRequest
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
package de.jeanlucmakiola.agendula.ui.quickadd
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.EnterTransition
|
||||
import androidx.compose.animation.ExitTransition
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
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.WindowInsets
|
||||
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||
import androidx.compose.foundation.layout.displayCutout
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.ime
|
||||
import androidx.compose.foundation.layout.isImeVisible
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
import androidx.compose.foundation.layout.only
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.union
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Add
|
||||
import androidx.compose.material.icons.rounded.Check
|
||||
import androidx.compose.material.icons.rounded.Event
|
||||
import androidx.compose.material.icons.rounded.OpenInFull
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import kotlinx.coroutines.delay
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.OffsetMapping
|
||||
import androidx.compose.ui.text.input.TransformedText
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddContext
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddKeywords
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddParse
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddSyntax
|
||||
import de.jeanlucmakiola.agendula.domain.QuickDue
|
||||
import de.jeanlucmakiola.agendula.domain.QuickToken
|
||||
import de.jeanlucmakiola.agendula.domain.ShortDateFormat
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.ui.common.ActionShapes
|
||||
import de.jeanlucmakiola.agendula.ui.common.LocalFirstDayOfWeek
|
||||
import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat
|
||||
import de.jeanlucmakiola.agendula.ui.common.formatMinuteOfDay
|
||||
import de.jeanlucmakiola.agendula.ui.common.rememberDayFormat
|
||||
import de.jeanlucmakiola.floret.components.ActionButton
|
||||
import de.jeanlucmakiola.floret.components.InlineTextField
|
||||
import de.jeanlucmakiola.floret.components.SnackChip
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import de.jeanlucmakiola.floret.identity.FloretDensity
|
||||
import de.jeanlucmakiola.floret.identity.byDensity
|
||||
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import java.time.Duration
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
/**
|
||||
* The quick-add bar at the bottom of a view or list: a field reading the `@date`
|
||||
* and `+list` syntax as it is typed (see [QuickAddSyntax]), its tokens marked and
|
||||
* what they stand for shown as chips above it. [onAdd] takes what was typed and
|
||||
* empties [text]; [onExpand] opens it in the full editor instead, leaving it in
|
||||
* the bar in case the editor is left without saving. Rides above the keyboard and
|
||||
* clears the navigation bar.
|
||||
*/
|
||||
@Composable
|
||||
fun QuickAddBar(
|
||||
text: String,
|
||||
onTextChange: (String) -> Unit,
|
||||
lists: List<TaskList>,
|
||||
onAdd: (QuickAddParse) -> Unit,
|
||||
onExpand: (QuickAddParse) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = rememberQuickAddContext(lists)
|
||||
val parse = remember(text, context) { QuickAddSyntax.parse(text, context) }
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.windowInsetsPadding(
|
||||
WindowInsets.ime
|
||||
.union(WindowInsets.navigationBars)
|
||||
.union(WindowInsets.displayCutout.only(WindowInsetsSides.Horizontal)),
|
||||
),
|
||||
) {
|
||||
QuickAddChips(parse, context.today)
|
||||
QuickAddField(
|
||||
text = text,
|
||||
onTextChange = onTextChange,
|
||||
canSubmit = parse.title.isNotBlank(),
|
||||
// Read again as it is sent, should the day or a lone time have moved on since it was typed.
|
||||
onSubmit = { onAdd(QuickAddSyntax.parse(text, context.atNow())) },
|
||||
onExpand = { onExpand(QuickAddSyntax.parse(text, context.atNow())) },
|
||||
tokens = parse.tokens,
|
||||
elevated = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What [QuickAddSyntax] reads against here: today, the week start, the locale's words and date form, and [lists]. */
|
||||
@Composable
|
||||
private fun rememberQuickAddContext(lists: List<TaskList>): QuickAddContext {
|
||||
val locale = currentLocale()
|
||||
val resources = LocalContext.current.resources
|
||||
val weekStart = LocalFirstDayOfWeek.current
|
||||
val keywords = remember(locale, resources) {
|
||||
QuickAddKeywords.English + QuickAddKeywords.fromTranslations { name -> KEYWORD_RESOURCES[name]?.let(resources::getString) }
|
||||
}
|
||||
val shortDate = remember(locale) { ShortDateFormat.of(locale) }
|
||||
// Ticks each minute, so the chips follow a lone @time to tomorrow, and the day past midnight.
|
||||
val minute by produceState(LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES)) {
|
||||
while (true) {
|
||||
val next = value.plusMinutes(1)
|
||||
delay(Duration.between(LocalDateTime.now(), next).toMillis().coerceAtLeast(0) + 1)
|
||||
value = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES)
|
||||
}
|
||||
}
|
||||
return remember(minute, weekStart, keywords, shortDate, lists) {
|
||||
QuickAddContext(minute.toLocalDate(), weekStart, keywords, shortDate, lists, minute.toLocalTime())
|
||||
}
|
||||
}
|
||||
|
||||
/** This context read at this moment. */
|
||||
private fun QuickAddContext.atNow(): QuickAddContext {
|
||||
val now = LocalDateTime.now()
|
||||
return copy(today = now.toLocalDate(), now = now.toLocalTime())
|
||||
}
|
||||
|
||||
private val KEYWORD_RESOURCES: Map<String, Int> = mapOf(
|
||||
QuickAddKeywords.TODAY to R.string.quick_add_keyword_today,
|
||||
QuickAddKeywords.TOMORROW to R.string.quick_add_keyword_tomorrow,
|
||||
QuickAddKeywords.NEXT_WEEK to R.string.quick_add_keyword_next_week,
|
||||
QuickAddKeywords.weekdayName(java.time.DayOfWeek.MONDAY) to R.string.quick_add_keyword_monday,
|
||||
QuickAddKeywords.weekdayName(java.time.DayOfWeek.TUESDAY) to R.string.quick_add_keyword_tuesday,
|
||||
QuickAddKeywords.weekdayName(java.time.DayOfWeek.WEDNESDAY) to R.string.quick_add_keyword_wednesday,
|
||||
QuickAddKeywords.weekdayName(java.time.DayOfWeek.THURSDAY) to R.string.quick_add_keyword_thursday,
|
||||
QuickAddKeywords.weekdayName(java.time.DayOfWeek.FRIDAY) to R.string.quick_add_keyword_friday,
|
||||
QuickAddKeywords.weekdayName(java.time.DayOfWeek.SATURDAY) to R.string.quick_add_keyword_saturday,
|
||||
QuickAddKeywords.weekdayName(java.time.DayOfWeek.SUNDAY) to R.string.quick_add_keyword_sunday,
|
||||
QuickAddKeywords.DAYS to R.string.quick_add_keyword_days,
|
||||
QuickAddKeywords.WEEKS to R.string.quick_add_keyword_weeks,
|
||||
QuickAddKeywords.MONTHS to R.string.quick_add_keyword_months,
|
||||
)
|
||||
|
||||
/** The due day and list [parse] found, as chips; announced as they change. */
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun QuickAddChips(parse: QuickAddParse, today: LocalDate) {
|
||||
val due = parse.due
|
||||
val list = parse.list
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
AnimatedVisibility(
|
||||
visible = due != null || list != null,
|
||||
enter = if (reduceMotion) EnterTransition.None else fadeIn() + expandVertically(),
|
||||
exit = if (reduceMotion) ExitTransition.None else fadeOut() + shrinkVertically(),
|
||||
) {
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp)
|
||||
.padding(top = 8.dp)
|
||||
.semantics { liveRegion = LiveRegionMode.Polite },
|
||||
) {
|
||||
if (due != null) {
|
||||
val label = dueLabel(due, today)
|
||||
QuickChip(
|
||||
label = label,
|
||||
description = stringResource(R.string.quick_add_due_chip, label),
|
||||
leading = { Icon(Icons.Rounded.Event, contentDescription = null, modifier = Modifier.size(18.dp)) },
|
||||
)
|
||||
}
|
||||
if (list != null) {
|
||||
val dot = pastelize(list.color, isSystemInDarkTheme())
|
||||
QuickChip(
|
||||
label = list.name,
|
||||
description = stringResource(R.string.quick_add_list_chip, list.name),
|
||||
leading = { Box(Modifier.size(10.dp).background(dot, CircleShape)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun dueLabel(due: QuickDue, today: LocalDate): String {
|
||||
val day = rememberDayFormat().format(due.date, today)
|
||||
val time = due.time ?: return day
|
||||
return "$day · ${formatMinuteOfDay(time.hour * 60 + time.minute, LocalUse24HourFormat.current, currentLocale())}"
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun QuickChip(label: String, description: String, leading: @Composable () -> Unit) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
color = MaterialTheme.colorScheme.secondaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
modifier = Modifier.clearAndSetSemantics { contentDescription = description },
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.heightIn(min = 32.dp).padding(horizontal = 8.dp),
|
||||
) {
|
||||
leading()
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(label, style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The rounded quick-add field: a title, [tokens] in it marked. [onExpand], when
|
||||
* set, adds a button to open the full editor. Shared with the onboarding step
|
||||
* that previews the bottom bar.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun QuickAddField(
|
||||
text: String,
|
||||
onTextChange: (String) -> Unit,
|
||||
canSubmit: Boolean,
|
||||
onSubmit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onExpand: (() -> Unit)? = null,
|
||||
tokens: List<QuickToken> = emptyList(),
|
||||
elevated: Boolean = false,
|
||||
) {
|
||||
// Compose keeps a TextField focused (cursor blinking) even after the keyboard
|
||||
// is dismissed by a tap outside it — so when the IME hides, drop focus too.
|
||||
val focusManager = LocalFocusManager.current
|
||||
val imeVisible = WindowInsets.isImeVisible
|
||||
LaunchedEffect(imeVisible) {
|
||||
if (!imeVisible) focusManager.clearFocus()
|
||||
}
|
||||
val tokenStyle = SpanStyle(color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Medium)
|
||||
val highlight = remember(tokens, tokenStyle) { TokenHighlight(tokens, tokenStyle) }
|
||||
Surface(
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
// Floating use (bottom quick-add) steps up to the brightest container tone
|
||||
// — a real step above the surfaceContainerHigh task cards — and lifts off
|
||||
// the list with a heavier shadow, so it doesn't blend into the rows.
|
||||
color = if (elevated) {
|
||||
MaterialTheme.colorScheme.surfaceContainerHighest
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceContainerHigh
|
||||
},
|
||||
shadowElevation = if (elevated) 8.dp else 0.dp,
|
||||
modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = FloretDensity.cardRowInset),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = byDensity(56.dp, 48.dp))
|
||||
.padding(start = 16.dp, end = 4.dp),
|
||||
) {
|
||||
Icon(Icons.Rounded.Add, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Box(modifier = Modifier.weight(1f)) {
|
||||
InlineTextField(
|
||||
value = text,
|
||||
onValueChange = onTextChange,
|
||||
placeholder = stringResource(R.string.add_task_hint),
|
||||
textStyle = MaterialTheme.typography.bodyLarge,
|
||||
imeAction = ImeAction.Done,
|
||||
onImeAction = { if (canSubmit) onSubmit() },
|
||||
visualTransformation = highlight,
|
||||
)
|
||||
}
|
||||
if (onExpand != null) {
|
||||
ActionButton(
|
||||
shape = ActionShapes.ExpandQuickAdd,
|
||||
icon = Icons.Rounded.OpenInFull,
|
||||
contentDescription = stringResource(R.string.quick_add_expand),
|
||||
onClick = onExpand,
|
||||
iconSize = 20.dp,
|
||||
)
|
||||
}
|
||||
if (canSubmit) {
|
||||
IconButton(onClick = onSubmit) {
|
||||
Icon(Icons.Rounded.Check, contentDescription = stringResource(R.string.cd_add_task))
|
||||
}
|
||||
} else if (onExpand == null) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Marks [tokens] in [style], leaving the text as it is. */
|
||||
private class TokenHighlight(private val tokens: List<QuickToken>, private val style: SpanStyle) : VisualTransformation {
|
||||
override fun filter(text: AnnotatedString): TransformedText {
|
||||
if (tokens.isEmpty()) return TransformedText(text, OffsetMapping.Identity)
|
||||
val marked = AnnotatedString.Builder(text).apply {
|
||||
tokens.forEach { if (it.end <= text.length) addStyle(style, it.start, it.end) }
|
||||
}.toAnnotatedString()
|
||||
return TransformedText(marked, OffsetMapping.Identity)
|
||||
}
|
||||
|
||||
override fun equals(other: Any?) = other is TokenHighlight && other.tokens == tokens && other.style == style
|
||||
|
||||
override fun hashCode() = 31 * tokens.hashCode() + style.hashCode()
|
||||
}
|
||||
|
||||
/** [receipt] as the screen's snack chip; a task that went elsewhere offers to open its list. */
|
||||
@Composable
|
||||
fun QuickAddReceiptChip(receipt: QuickAddReceipt, onOpenList: (Long) -> Unit) {
|
||||
when (receipt) {
|
||||
is QuickAddReceipt.NotShown -> SnackChip(
|
||||
visible = true,
|
||||
message = stringResource(R.string.quick_add_not_shown, receipt.listName),
|
||||
actionLabel = stringResource(R.string.quick_add_open),
|
||||
onAction = { onOpenList(receipt.listId) },
|
||||
onClick = { onOpenList(receipt.listId) },
|
||||
)
|
||||
is QuickAddReceipt.Added -> SnackChip(visible = true, message = stringResource(R.string.quick_add_added, receipt.listName))
|
||||
is QuickAddReceipt.Failed -> SnackChip(visible = true, message = stringResource(R.string.edit_save_failed))
|
||||
}
|
||||
}
|
||||
|
||||
/** A plain, unmarked quick-add field for a preview: nothing happens on it. */
|
||||
@Composable
|
||||
internal fun QuickAddFieldPreview(modifier: Modifier = Modifier) {
|
||||
var text by remember { mutableStateOf("") }
|
||||
QuickAddField(text = text, onTextChange = { text = it }, canSubmit = false, onSubmit = {}, modifier = modifier, elevated = true)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package de.jeanlucmakiola.agendula.ui.quickadd
|
||||
|
||||
import androidx.lifecycle.SavedStateHandle
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddParse
|
||||
import de.jeanlucmakiola.agendula.domain.QuickDue
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFiltering
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.NewTaskOrigin
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.asOpenTask
|
||||
import de.jeanlucmakiola.agendula.domain.matches
|
||||
import de.jeanlucmakiola.agendula.domain.namedListIds
|
||||
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.ZoneId
|
||||
import javax.inject.Inject
|
||||
import kotlin.time.Clock
|
||||
|
||||
/** What the full editor opens a new task with. */
|
||||
data class NewTaskSeed(
|
||||
/** The view whose scope the task should stay in. */
|
||||
val scopeViewId: Long? = null,
|
||||
/** What the screen shows, which presets the task as its own new-task action does. */
|
||||
val preset: TaskFilter? = null,
|
||||
val title: String? = null,
|
||||
val listId: Long? = null,
|
||||
val due: QuickDue? = null,
|
||||
/** Tags the screen is narrowed to. */
|
||||
val tags: List<String> = emptyList(),
|
||||
/** Opened from the quick-add bar, which lets go of its text once the task is saved. */
|
||||
val fromQuickAdd: Boolean = false,
|
||||
)
|
||||
|
||||
/** How a quick add went, when there is something to say. Not data classes: a repeat must still show. */
|
||||
sealed interface QuickAddReceipt {
|
||||
/** The view the task was added in, if any. */
|
||||
val viewId: Long?
|
||||
|
||||
/** Added to list [listId], [listName], which the view doesn't show. */
|
||||
class NotShown(val listId: Long, val listName: String, override val viewId: Long?) : QuickAddReceipt
|
||||
|
||||
/** Added to [listName] within the view; [task] as it was added, to tell whether a block shows it. */
|
||||
class Added(val listName: String, val task: Task, override val viewId: Long?) : QuickAddReceipt
|
||||
|
||||
class Failed(override val viewId: Long?) : QuickAddReceipt
|
||||
}
|
||||
|
||||
/** Where a task added from a screen showing [filter] starts; nothing for none. */
|
||||
suspend fun SettingsPrefs.newTaskOrigin(filter: TaskFilter?): NewTaskOrigin = when (filter) {
|
||||
is TaskFilter.OfList -> NewTaskOrigin(listId = filter.listId)
|
||||
is TaskFilter.Tagged -> NewTaskOrigin(tag = filter.tag)
|
||||
is TaskFilter.Saved -> NewTaskOrigin(filter = savedFilter(filter.id).first())
|
||||
is TaskFilter.Matching -> NewTaskOrigin(filter = SavedFilter(0, "", filter.rule))
|
||||
is TaskFilter.Smart -> NewTaskOrigin(smartList = filter.list)
|
||||
is TaskFilter.DueOn, is TaskFilter.OfLists, null -> NewTaskOrigin()
|
||||
}
|
||||
|
||||
/** Set on the screen below the editor once it saved a new task, so a bar that was expanded into it lets go of its text. */
|
||||
const val NEW_TASK_SAVED = "quick_add_new_task_saved"
|
||||
|
||||
private const val RECEIPT_MS = 4_000L
|
||||
private const val KEY_TEXT = "quick_add_text"
|
||||
private const val KEY_VIEW = "quick_add_view"
|
||||
|
||||
/** The quick-add bar of a view or list: the lists it can name, and the adding. */
|
||||
@HiltViewModel
|
||||
class QuickAddViewModel @Inject constructor(
|
||||
private val repository: TasksRepository,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
@ApplicationScope private val appScope: CoroutineScope,
|
||||
private val savedState: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
|
||||
/** The lists a task can be added to; `null` until read. */
|
||||
val lists: StateFlow<List<TaskList>?> = repository.taskLists()
|
||||
.map<List<TaskList>, List<TaskList>?> { lists -> lists.filter { it.acceptsWrites } }
|
||||
.recoveringFromProviderFailure { null }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
|
||||
|
||||
/** What is typed in the bar, kept here so a failed add can give it back. */
|
||||
var text by mutableStateOf(savedState.get<String>(KEY_TEXT).orEmpty())
|
||||
private set
|
||||
|
||||
fun onTextChange(value: String) {
|
||||
text = value
|
||||
savedState[KEY_TEXT] = value
|
||||
}
|
||||
|
||||
private val _receipt = MutableStateFlow<QuickAddReceipt?>(null)
|
||||
|
||||
/** Shown for a moment after an add that went elsewhere or failed. */
|
||||
val receipt: StateFlow<QuickAddReceipt?> = _receipt.asStateFlow()
|
||||
private var receiptTimer: Job? = null
|
||||
|
||||
/**
|
||||
* Adds what [parse], read from [typed], holds within [scope] (`null` for none),
|
||||
* from a screen showing [shows], as its new-task action would; says so when
|
||||
* the task falls outside the scope or what is shown, and otherwise hands the
|
||||
* screen the task to tell whether it shows it ([QuickAddReceipt.Added]). The write runs in the application scope,
|
||||
* so leaving the screen right after cannot cancel it; when it fails, an empty
|
||||
* bar gets [typed] back. [viewId] is the view it is added in, if any.
|
||||
*/
|
||||
fun add(typed: String, parse: QuickAddParse, scope: Rule?, shows: TaskFilter? = null, viewId: Long? = null) {
|
||||
if (parse.title.isBlank()) return
|
||||
onTextChange("")
|
||||
val write = appScope.async {
|
||||
runCatching {
|
||||
val settings = settingsPrefs.settings.first()
|
||||
val writable = repository.taskLists().first().filter { it.acceptsWrites }
|
||||
val now = Clock.System.now()
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(now, zone)
|
||||
val clock = RuleClock(todayStart, todayEnd, zone, settingsPrefs.firstDayOfWeek.first())
|
||||
val origin = settingsPrefs.newTaskOrigin(shows)
|
||||
val form = settings.quickAddTask(parse, scope, writable, clock, now, origin)
|
||||
?: return@runCatching QuickAddReceipt.Failed(viewId)
|
||||
val id = repository.createTask(form)
|
||||
val task = form.asOpenTask().copy(taskId = id, title = form.title, created = now)
|
||||
val inScope = scope == null || scope.matches(task, clock)
|
||||
// A smart list leaves out the lists kept from it, but not one the scope names.
|
||||
val hidden = settings.hiddenFromSmartLists - scope?.namedListIds().orEmpty()
|
||||
val inShown = shows == null || (shows !is TaskFilter.Smart || task.listId !in hidden) && TaskFiltering.matches(
|
||||
task, shows, todayStart, todayEnd,
|
||||
saved = origin.filter, upcomingEnd = settings.upcomingRange.end(now, zone), ruleClock = clock,
|
||||
)
|
||||
val listName = writable.firstOrNull { it.id == form.listId }?.name.orEmpty()
|
||||
if (inScope && inShown) {
|
||||
QuickAddReceipt.Added(listName, task, viewId)
|
||||
} else {
|
||||
QuickAddReceipt.NotShown(form.listId, listName, viewId)
|
||||
}
|
||||
}.getOrElse { QuickAddReceipt.Failed(viewId) }
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val receipt = write.await() ?: return@launch
|
||||
// The bar has moved on to another view meanwhile; this one's receipt and text are no business of it.
|
||||
if (receipt.viewId != shownViewId) return@launch
|
||||
if (receipt is QuickAddReceipt.Failed && text.isEmpty()) onTextChange(typed)
|
||||
show(receipt)
|
||||
}
|
||||
}
|
||||
|
||||
private var shownViewId: Long? = savedState[KEY_VIEW]
|
||||
|
||||
/** The bar now shows in view [viewId]; another view's text and receipt go. */
|
||||
fun onViewShown(viewId: Long?) {
|
||||
if (viewId == shownViewId) return
|
||||
shownViewId = viewId
|
||||
savedState[KEY_VIEW] = viewId
|
||||
onTextChange("")
|
||||
dismissReceipt()
|
||||
}
|
||||
|
||||
private fun show(receipt: QuickAddReceipt) {
|
||||
receiptTimer?.cancel()
|
||||
_receipt.value = receipt
|
||||
receiptTimer = viewModelScope.launch {
|
||||
delay(RECEIPT_MS)
|
||||
_receipt.value = null
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissReceipt() {
|
||||
receiptTimer?.cancel()
|
||||
_receipt.value = null
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,18 @@ import android.os.Build
|
||||
import android.text.format.DateFormat
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Add
|
||||
import androidx.compose.material.icons.rounded.Badge
|
||||
import androidx.compose.material.icons.rounded.Bolt
|
||||
import androidx.compose.material.icons.rounded.CalendarViewWeek
|
||||
import androidx.compose.material.icons.rounded.DarkMode
|
||||
import androidx.compose.material.icons.rounded.Palette
|
||||
import androidx.compose.material.icons.rounded.Schedule
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -14,28 +25,39 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.colorResource
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.graphics.shapes.RoundedPolygon
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.data.appname.LauncherName
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.data.prefs.TimeFormatPref
|
||||
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.agendula.ui.common.ActionShapes
|
||||
import de.jeanlucmakiola.agendula.ui.common.formatMinuteOfDay
|
||||
import de.jeanlucmakiola.agendula.domain.localeWeekStart
|
||||
import de.jeanlucmakiola.floret.components.ActionStylePreview
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.ConnectedChoiceRow
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.LauncherMark
|
||||
import de.jeanlucmakiola.floret.components.LauncherNameChooser
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.PreviewOptionRow
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import de.jeanlucmakiola.floret.prefs.ActionStyle
|
||||
import de.jeanlucmakiola.floret.prefs.LayoutDensity
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import java.time.DayOfWeek
|
||||
import java.time.format.TextStyle
|
||||
|
||||
/** How the app looks: the theme, wallpaper colours, and how times and weeks are written. */
|
||||
/** How the app looks: the theme, wallpaper colours, density, buttons, motion, and how times and weeks are written. */
|
||||
@Composable
|
||||
internal fun AppearanceScreen(
|
||||
state: SettingsUiState,
|
||||
@@ -58,53 +80,86 @@ internal fun AppearanceScreen(
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
GroupedSectionHeader(stringResource(R.string.settings_group_colours))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_theme),
|
||||
summary = stringResource(themeLabel(state.settings.themeMode)),
|
||||
position = Position.Top,
|
||||
leading = { Icon(Icons.Rounded.DarkMode, contentDescription = null) },
|
||||
onClick = { showTheme = true },
|
||||
)
|
||||
GroupedRow(
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_dynamic_color),
|
||||
summary = if (dynamicColorAvailable) {
|
||||
stringResource(R.string.settings_dynamic_color_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_dynamic_color_unavailable)
|
||||
},
|
||||
checked = state.settings.dynamicColor && dynamicColorAvailable,
|
||||
onCheckedChange = viewModel::setDynamicColor,
|
||||
position = Position.Bottom,
|
||||
trailing = {
|
||||
Switch(
|
||||
checked = state.settings.dynamicColor && dynamicColorAvailable,
|
||||
onCheckedChange = viewModel::setDynamicColor,
|
||||
enabled = dynamicColorAvailable,
|
||||
)
|
||||
},
|
||||
onClick = if (dynamicColorAvailable) {
|
||||
{ viewModel.setDynamicColor(!state.settings.dynamicColor) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
enabled = dynamicColorAvailable,
|
||||
leading = { Icon(Icons.Rounded.Palette, contentDescription = null) },
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(stringResource(R.string.settings_density))
|
||||
ConnectedChoiceRow(
|
||||
options = LayoutDensity.entries,
|
||||
selected = state.settings.density,
|
||||
label = { stringResource(densityLabel(it)) },
|
||||
onSelect = viewModel::setDensity,
|
||||
)
|
||||
GroupedHint(
|
||||
text = stringResource(R.string.settings_density_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(stringResource(R.string.settings_buttons))
|
||||
PreviewOptionRow(
|
||||
options = ActionStyle.entries,
|
||||
selected = state.settings.actionStyle,
|
||||
label = { stringResource(actionStyleLabel(it)) },
|
||||
onSelect = viewModel::setActionStyle,
|
||||
preview = { ActionStylePreview(PreviewActions, shaped = it == ActionStyle.SHAPES) },
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(stringResource(R.string.settings_motion))
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_reduce_motion),
|
||||
summary = stringResource(R.string.settings_reduce_motion_hint),
|
||||
checked = state.settings.reduceMotion,
|
||||
onCheckedChange = viewModel::setReduceMotion,
|
||||
position = Position.Alone,
|
||||
leading = { Icon(Icons.Rounded.Bolt, contentDescription = null) },
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(stringResource(R.string.settings_group_date_time))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_time_format),
|
||||
summary = timeFormatLabel(state.settings.timeFormat),
|
||||
position = Position.Top,
|
||||
leading = { Icon(Icons.Rounded.Schedule, contentDescription = null) },
|
||||
onClick = { showTimeFormat = true },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_week_start),
|
||||
summary = weekStartLabel(state.settings.weekStart),
|
||||
position = Position.Bottom,
|
||||
leading = { Icon(Icons.Rounded.CalendarViewWeek, contentDescription = null) },
|
||||
onClick = { showWeekStart = true },
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(stringResource(R.string.settings_group_launcher))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_app_name),
|
||||
summary = launcherNameLabel(launcherName),
|
||||
position = Position.Alone,
|
||||
leading = { Icon(Icons.Rounded.Badge, contentDescription = null) },
|
||||
onClick = { showAppName = true },
|
||||
)
|
||||
}
|
||||
@@ -211,6 +266,23 @@ private fun launcherNameLabel(name: LauncherName): String = stringResource(
|
||||
},
|
||||
)
|
||||
|
||||
private fun densityLabel(density: LayoutDensity): Int = when (density) {
|
||||
LayoutDensity.COMFORTABLE -> R.string.settings_density_comfortable
|
||||
LayoutDensity.COMPACT -> R.string.settings_density_compact
|
||||
}
|
||||
|
||||
private fun actionStyleLabel(style: ActionStyle): Int = when (style) {
|
||||
ActionStyle.ICONS -> R.string.settings_buttons_icons
|
||||
ActionStyle.SHAPES -> R.string.settings_buttons_shapes
|
||||
}
|
||||
|
||||
/** The home top bar's own actions, as the Buttons choice previews them. */
|
||||
private val PreviewActions: List<Pair<ImageVector, RoundedPolygon>> = listOf(
|
||||
Icons.Rounded.Search to ActionShapes.Search,
|
||||
Icons.Rounded.Settings to ActionShapes.Settings,
|
||||
Icons.Rounded.Add to ActionShapes.AddList,
|
||||
)
|
||||
|
||||
private fun themeLabel(mode: ThemeMode): Int = when (mode) {
|
||||
ThemeMode.SYSTEM -> R.string.settings_theme_system
|
||||
ThemeMode.LIGHT -> R.string.settings_theme_light
|
||||
|
||||
@@ -5,7 +5,6 @@ import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -40,6 +39,7 @@ import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.locale.relativeTimeAgo
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderUnit
|
||||
import de.jeanlucmakiola.floret.reminders.decomposeReminderMinutes
|
||||
import de.jeanlucmakiola.floret.components.BusyIndicator
|
||||
|
||||
/** Backup & restore: export, import and the automatic backup (after Calendula). */
|
||||
@Composable
|
||||
@@ -113,7 +113,7 @@ internal fun BackupScreen(
|
||||
title = stringResource(R.string.backup_auto_now),
|
||||
position = Position.Bottom,
|
||||
dimmed = state.running,
|
||||
trailing = if (state.running) ({ CircularProgressIndicator(Modifier.size(20.dp)) }) else null,
|
||||
trailing = if (state.running) ({ BusyIndicator(Modifier.size(20.dp)) }) else null,
|
||||
onClick = viewModel::backUpNow.takeUnless { state.running },
|
||||
)
|
||||
GroupedHint(backupStatusText(state), style = MaterialTheme.typography.bodySmall)
|
||||
|
||||
@@ -53,6 +53,7 @@ import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.LanguagePickerRow
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.agendula.ui.views.StartDestinationRow
|
||||
import de.jeanlucmakiola.floret.crash.CrashReportDialog
|
||||
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||
import de.jeanlucmakiola.floret.crash.openIssueTracker
|
||||
@@ -237,10 +238,11 @@ private fun SettingsHub(
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_section_reminders),
|
||||
summary = stringResource(R.string.settings_reminders_subtitle),
|
||||
position = Position.Bottom,
|
||||
position = Position.Middle,
|
||||
leading = { CategoryIcon(Icons.Default.Notifications, ChipAccent.Primary) },
|
||||
onClick = { onOpenSection(SettingsSection.Notifications) },
|
||||
)
|
||||
StartDestinationRow(position = Position.Bottom)
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(stringResource(R.string.settings_group_data))
|
||||
|
||||
@@ -10,7 +10,6 @@ import de.jeanlucmakiola.agendula.data.prefs.ListPersistence
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ReminderDescription
|
||||
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.data.prefs.TimeFormatPref
|
||||
import de.jeanlucmakiola.agendula.data.reminders.ReminderScheduler
|
||||
import de.jeanlucmakiola.agendula.data.reminders.TaskNotifier
|
||||
@@ -28,6 +27,9 @@ import de.jeanlucmakiola.agendula.domain.DefaultDueDate
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFormField
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.floret.prefs.ActionStyle
|
||||
import de.jeanlucmakiola.floret.prefs.LayoutDensity
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderLead
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.agendula.widget.TaskWidgetUpdater
|
||||
@@ -98,8 +100,8 @@ data class TransferUiState(
|
||||
)
|
||||
|
||||
/**
|
||||
* Drives both the Settings screen and the app theme (MainActivity collects the
|
||||
* same instance), so a theme change applies app-wide at once.
|
||||
* Drives the Settings screens. The app theme reads the stored settings itself,
|
||||
* so a change made here applies app-wide at once.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class SettingsViewModel @Inject constructor(
|
||||
@@ -116,9 +118,9 @@ class SettingsViewModel @Inject constructor(
|
||||
repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
// MainActivity collects this for the theme, above the permission gate and for
|
||||
// the whole Activity lifetime — so the list flow must survive the pre-grant
|
||||
// SecurityException and recover once permission is given, not die for good.
|
||||
// The list flow may be collected before the provider permission is granted, so
|
||||
// it must survive the pre-grant SecurityException and recover once permission
|
||||
// is given, not die for good.
|
||||
val state: StateFlow<SettingsUiState> =
|
||||
combine(
|
||||
prefs.settings,
|
||||
@@ -244,6 +246,9 @@ class SettingsViewModel @Inject constructor(
|
||||
|
||||
fun setThemeMode(mode: ThemeMode) = viewModelScope.launch { prefs.setThemeMode(mode) }
|
||||
fun setDynamicColor(enabled: Boolean) = viewModelScope.launch { prefs.setDynamicColor(enabled) }
|
||||
fun setDensity(density: LayoutDensity) = viewModelScope.launch { prefs.setDensity(density) }
|
||||
fun setActionStyle(style: ActionStyle) = viewModelScope.launch { prefs.setActionStyle(style) }
|
||||
fun setReduceMotion(enabled: Boolean) = viewModelScope.launch { prefs.setReduceMotion(enabled) }
|
||||
fun setDefaultList(id: Long?) = viewModelScope.launch { prefs.setDefaultListId(id) }
|
||||
fun setDefaultReminders(leads: List<ReminderLead>) = viewModelScope.launch {
|
||||
prefs.setDefaultReminders(leads)
|
||||
|
||||
@@ -18,7 +18,6 @@ import androidx.compose.material.icons.rounded.MoveDown
|
||||
import androidx.compose.material.icons.rounded.PhoneAndroid
|
||||
import androidx.compose.material.icons.rounded.SwapHoriz
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -47,6 +46,7 @@ import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.SelectedCheck
|
||||
import de.jeanlucmakiola.floret.components.BusyIndicator
|
||||
|
||||
/**
|
||||
* Where the tasks live: the store picker the resolver's `autoMode()` has always
|
||||
@@ -282,7 +282,7 @@ private fun TransferStatus(state: TransferUiState) {
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
CircularProgressIndicator(Modifier.size(18.dp))
|
||||
BusyIndicator(Modifier.size(18.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.settings_copy_running),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
|
||||
@@ -21,6 +21,7 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.ui.quickadd.QuickAddFieldPreview
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
@@ -32,7 +33,7 @@ import de.jeanlucmakiola.floret.components.positionOf
|
||||
* A task list as it will look, for a chooser that offers a choice about it —
|
||||
* today only the bottom quick-add bar against the floating "New task" button.
|
||||
*
|
||||
* Drawn from the screen's own [TaskRowContent] and [InlineAdd] over sample
|
||||
* Drawn from the screen's own [TaskRowContent] and [QuickAddFieldPreview] over sample
|
||||
* tasks, so what the preview shows cannot drift from what the app does. The
|
||||
* chrome around them (a title, the FAB) is a still of the real scaffold rather
|
||||
* than the scaffold itself: [TaskListScreen] needs a ViewModel, a list id and a
|
||||
@@ -67,7 +68,7 @@ internal fun TaskListPreview(bottomAddBar: Boolean, height: Dp) {
|
||||
|
||||
if (bottomAddBar) {
|
||||
Box(Modifier.align(Alignment.BottomCenter)) {
|
||||
InlineAdd(onAdd = {}, elevated = true)
|
||||
QuickAddFieldPreview()
|
||||
}
|
||||
} else {
|
||||
ExtendedFloatingActionButton(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -41,6 +41,7 @@ import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.identity.FloretDensity
|
||||
|
||||
/** What submitting a search does: reopen the completed task of that title, or add a new one. */
|
||||
internal sealed interface SearchSubmit {
|
||||
@@ -128,7 +129,7 @@ internal fun TaskSearchResults(
|
||||
position = Position.Alone,
|
||||
dimmed = result.adding,
|
||||
leading = { Icon(Icons.Rounded.Add, contentDescription = null, tint = MaterialTheme.colorScheme.primary) },
|
||||
minHeight = 64.dp,
|
||||
minHeight = FloretDensity.cardRowHeight,
|
||||
onClick = if (result.adding) null else ({ onCreate(q) }),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,14 @@ import de.jeanlucmakiola.agendula.data.tasks.FilteredTasks
|
||||
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
|
||||
import de.jeanlucmakiola.agendula.domain.AppliedScope
|
||||
import de.jeanlucmakiola.agendula.domain.ListSearchResult
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
import de.jeanlucmakiola.agendula.domain.appliedScope
|
||||
import de.jeanlucmakiola.agendula.ui.views.ViewSession
|
||||
import de.jeanlucmakiola.agendula.domain.pinnedViewOf
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
@@ -53,7 +60,6 @@ import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -107,6 +113,14 @@ sealed interface TaskListUiState {
|
||||
val filter: TaskFilter? = null,
|
||||
/** A real list's tasks before the tag filter narrows them, which its search looks through; empty elsewhere. */
|
||||
val searchable: List<Task> = emptyList(),
|
||||
/** The view whose scope narrows these tasks, shown as a chip that drops it; `null` when none does. */
|
||||
val scope: ScopeChip? = null,
|
||||
/** The lists a task in [scope] can be in; `null` when any. */
|
||||
val scopeLists: Set<Long>? = null,
|
||||
/** [scope]'s rule as it applies, which the rows are read through. */
|
||||
val appliedScope: AppliedScope? = null,
|
||||
/** The day [appliedScope] is read against. */
|
||||
val ruleClock: RuleClock? = null,
|
||||
) : TaskListUiState {
|
||||
/** Upcoming, narrowed to a time frame the user picked. */
|
||||
val upcomingLimited: Boolean
|
||||
@@ -134,6 +148,22 @@ sealed interface SearchReceipt {
|
||||
class Failed : SearchReceipt
|
||||
}
|
||||
|
||||
/** The view a task screen is narrowed to, by its scope. [listsGone]: the scope names a list since deleted. */
|
||||
data class ScopeChip(val viewId: Long, val name: String, val icon: ViewIcon, val listsGone: Boolean)
|
||||
|
||||
/**
|
||||
* What a task screen shows: [filter]'s tasks, within the scope of view
|
||||
* [scopeViewId] when set. [withCompleted] false leaves the completed tasks out;
|
||||
* otherwise they close the list in their own section, All's included (#140).
|
||||
* [sort] replaces the app's sort order when set.
|
||||
*/
|
||||
data class TaskListBinding(
|
||||
val filter: TaskFilter,
|
||||
val scopeViewId: Long? = null,
|
||||
val withCompleted: Boolean? = null,
|
||||
val sort: TaskSortOrder? = null,
|
||||
)
|
||||
|
||||
private const val PENDING_ADD_TIMEOUT_MS = 30_000L
|
||||
private const val KEY_SEARCH_ACTIVE = "task_search_active"
|
||||
private const val KEY_SEARCH_QUERY = "task_search_query"
|
||||
@@ -150,6 +180,7 @@ class TaskListViewModel @Inject constructor(
|
||||
private val widgetUpdater: TaskWidgetUpdater,
|
||||
@ApplicationScope private val appScope: CoroutineScope,
|
||||
private val savedState: SavedStateHandle,
|
||||
private val viewSession: ViewSession,
|
||||
) : ViewModel() {
|
||||
|
||||
/** Pull to sync (#73); off without an account. */
|
||||
@@ -159,7 +190,24 @@ class TaskListViewModel @Inject constructor(
|
||||
|
||||
fun syncAll() = manualSync.syncAll()
|
||||
|
||||
private val filter = MutableStateFlow<TaskFilter?>(null)
|
||||
private val binding = MutableStateFlow<TaskListBinding?>(null)
|
||||
|
||||
/** The binding last asked for; a repeat of it keeps a scope the user dropped dropped. */
|
||||
private var requested: TaskListBinding? = null
|
||||
|
||||
private val filter: TaskFilter? get() = binding.value?.filter
|
||||
|
||||
/**
|
||||
* The view whose scope narrows the rows, apart from [binding]: dropping or
|
||||
* switching it reads the rows already loaded through another scope, rather
|
||||
* than querying the tasks again.
|
||||
*/
|
||||
private val scopeViewId = MutableStateFlow<Long?>(null)
|
||||
|
||||
/** That view; a view since deleted, or left without a scope, narrows nothing. */
|
||||
private val scopeView: Flow<View?> = scopeViewId.flatMapLatest { id ->
|
||||
if (id == null) flowOf(null) else settingsPrefs.views.map { views -> views.firstOrNull { it.id == id && it.scope != null } }
|
||||
}
|
||||
|
||||
private val tagFilter = MutableStateFlow<Set<String>>(emptySet())
|
||||
|
||||
@@ -186,18 +234,28 @@ class TaskListViewModel @Inject constructor(
|
||||
}.distinctUntilChanged()
|
||||
|
||||
val state: StateFlow<TaskListUiState> =
|
||||
filter.filterNotNull()
|
||||
.flatMapLatest { f ->
|
||||
binding.filterNotNull()
|
||||
.map { it.copy(scopeViewId = null) }
|
||||
.distinctUntilChanged()
|
||||
.flatMapLatest { b ->
|
||||
val f = b.filter
|
||||
val source: Flow<FilteredTasks> = when (f) {
|
||||
is TaskFilter.Saved -> repository.filteredTasks(f)
|
||||
is TaskFilter.OfList, is TaskFilter.Smart, is TaskFilter.Tagged ->
|
||||
is TaskFilter.Saved, is TaskFilter.Matching -> repository.filteredTasks(f)
|
||||
is TaskFilter.Smart -> if (b.withCompleted != false && f.list == SmartList.ALL) {
|
||||
combine(repository.tasks(f), repository.tasks(TaskFilter.Smart(SmartList.COMPLETED))) { open, done ->
|
||||
FilteredTasks(open + done)
|
||||
}
|
||||
} else {
|
||||
repository.tasks(f).map { FilteredTasks(it) }
|
||||
}
|
||||
is TaskFilter.OfList, is TaskFilter.Tagged, is TaskFilter.DueOn -> repository.tasks(f).map { FilteredTasks(it) }
|
||||
// Several lists at once only exists for the widget, which never routes here.
|
||||
is TaskFilter.OfLists -> error("OfLists has no task-list screen")
|
||||
}
|
||||
// Each read carries the day it was made for, so rows and groups always agree.
|
||||
val rows = dayWindow.flatMapLatest { window -> source.map { window to it } }
|
||||
val content: Flow<TaskListUiState> = combine(rows, repository.taskLists()) { (window, found), lists ->
|
||||
val content: Flow<TaskListUiState> = combine(rows, repository.taskLists(), scopeView) { (window, found), lists, view ->
|
||||
val applied = view?.appliedScope(lists.mapTo(HashSet()) { it.id })
|
||||
TaskListUiState.Content(
|
||||
tasks = found.tasks,
|
||||
list = (f as? TaskFilter.OfList)?.let { of -> lists.firstOrNull { it.id == of.listId } },
|
||||
@@ -205,6 +263,9 @@ class TaskListViewModel @Inject constructor(
|
||||
listOrder = lists.map { it.id },
|
||||
todayStart = window.first,
|
||||
todayEnd = window.second,
|
||||
scope = view?.let { ScopeChip(it.id, it.name, it.icon, applied?.narrowedByGone == true) },
|
||||
scopeLists = applied?.lists,
|
||||
appliedScope = applied,
|
||||
)
|
||||
}
|
||||
// Drop rows pending an undoable delete so the row vanishes on swipe
|
||||
@@ -213,8 +274,16 @@ class TaskListViewModel @Inject constructor(
|
||||
combine(content, pendingDeletes, settingsPrefs.settings, tagFilter) { st, pending, settings, tags ->
|
||||
if (st is TaskListUiState.Content) {
|
||||
val now = Clock.System.now()
|
||||
val (inView, hiddenByRange) = settings.viewOf(f, st.tasks, now)
|
||||
val visible = inView.filter { it.occurrenceKey !in pending }
|
||||
val scope = st.appliedScope
|
||||
// A scope that names a list shows it even where the smart lists leave it out.
|
||||
val shownBy = scope?.let { settings.copy(hiddenFromSmartLists = it.hiddenFromSmart(settings.hiddenFromSmartLists)) }
|
||||
?: settings
|
||||
val (inView, hiddenByRange) = shownBy.viewOf(f, st.tasks, now)
|
||||
val clock = RuleClock(st.todayStart, st.todayEnd, ZoneId.systemDefault(), settings.effectiveWeekStart)
|
||||
val present = inView.filter { it.occurrenceKey !in pending }
|
||||
val visible = present.filter {
|
||||
(scope == null || scope.admits(it, clock)) && (b.withCompleted != false || !it.isCompleted)
|
||||
}
|
||||
val available = tagsInUse(visible) - setOfNotNull((f as? TaskFilter.Tagged)?.tag)
|
||||
// A tag that vanished can no longer be unticked, so it is dropped
|
||||
// for good rather than narrowing again when it comes back.
|
||||
@@ -225,13 +294,15 @@ class TaskListViewModel @Inject constructor(
|
||||
filter = f,
|
||||
tasks = visible
|
||||
.filter { TaskFiltering.hasAllTags(it, selected) }
|
||||
.sortedWith(settings.sortOrder.comparator()),
|
||||
.sortedWith((b.sort ?: settings.sortOrder).comparator()),
|
||||
availableTags = available,
|
||||
selectedTags = selected,
|
||||
searchable = if (f is TaskFilter.OfList) visible else emptyList(),
|
||||
// The whole list, not just its scoped rows: search mustn't offer to add a task it already has.
|
||||
searchable = if (f is TaskFilter.OfList) present else emptyList(),
|
||||
showAddSubtaskRow = settings.showAddSubtaskRow,
|
||||
bottomAddBar = settings.bottomAddBar,
|
||||
sortOrder = settings.sortOrder,
|
||||
sortOrder = b.sort ?: settings.sortOrder,
|
||||
ruleClock = clock,
|
||||
upcomingRange = settings.upcomingRange,
|
||||
hiddenByRange = hiddenByRange,
|
||||
grouping = settings.groupingFor(f).takeIf { it in groupings } ?: TaskGrouping.DUE,
|
||||
@@ -272,6 +343,13 @@ class TaskListViewModel @Inject constructor(
|
||||
combine(ids.map { id -> repository.subtasks(id).map { id to it } }) { it.toMap() }
|
||||
}
|
||||
}
|
||||
// Subtasks outside the view's scope stay out, as they do from the rows.
|
||||
.combine(state) { children, st ->
|
||||
val content = st as? TaskListUiState.Content
|
||||
val scope = content?.appliedScope
|
||||
val clock = content?.ruleClock
|
||||
if (scope == null || clock == null) children else children.mapValues { (_, tasks) -> tasks.filter { scope.admits(it, clock) } }
|
||||
}
|
||||
// Without this an exception here escapes stateIn's coroutine, past
|
||||
// viewModelScope's SupervisorJob, and crashes the process.
|
||||
.recoveringFromProviderFailure { emptyMap() }
|
||||
@@ -280,12 +358,56 @@ class TaskListViewModel @Inject constructor(
|
||||
/** The screen reports which expanded parents need their children fetched. */
|
||||
fun setLazyChildParents(ids: Set<Long>) { lazyChildParents.value = ids }
|
||||
|
||||
fun bind(taskFilter: TaskFilter) {
|
||||
if (filter.value != null && filter.value != taskFilter) {
|
||||
/**
|
||||
* Shows [taskFilter]'s tasks, within the scope of view [scopeViewId] when set
|
||||
* (see [TaskListBinding]). Binding again what is already bound changes
|
||||
* nothing, so a scope dropped with [dropScope] stays dropped.
|
||||
*/
|
||||
fun bind(
|
||||
taskFilter: TaskFilter,
|
||||
scopeViewId: Long? = null,
|
||||
withCompleted: Boolean? = null,
|
||||
sort: TaskSortOrder? = null,
|
||||
) {
|
||||
val next = TaskListBinding(taskFilter, scopeViewId, withCompleted, sort)
|
||||
if (next == requested) return
|
||||
if (filter != null && filter != taskFilter) {
|
||||
closeSearch()
|
||||
pendingAdds.clear()
|
||||
}
|
||||
filter.value = taskFilter
|
||||
requested = next
|
||||
this.scopeViewId.value = scopeViewId
|
||||
binding.value = next
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes this list or saved filter a view of its own (#59) and switches to it,
|
||||
* then calls [onPinned]. Nothing happens on a screen that is neither.
|
||||
*/
|
||||
fun pinAsView(onPinned: () -> Unit) {
|
||||
val content = state.value as? TaskListUiState.Content ?: return
|
||||
val view = pinnedViewOf(content.list, content.savedFilter) ?: return
|
||||
viewModelScope.launch {
|
||||
val id = settingsPrefs.saveView(view)
|
||||
if (id == null) {
|
||||
_pinFailed.value = true
|
||||
delay(UNDO_WINDOW_MS)
|
||||
_pinFailed.value = false
|
||||
return@launch
|
||||
}
|
||||
viewSession.switchTo(id)
|
||||
onPinned()
|
||||
}
|
||||
}
|
||||
|
||||
private val _pinFailed = MutableStateFlow(false)
|
||||
|
||||
/** Set for a moment when a pin couldn't be stored: the views are another version's. */
|
||||
val pinFailed: StateFlow<Boolean> = _pinFailed.asStateFlow()
|
||||
|
||||
/** Drops the view's scope, the chip's ✕: the screen shows all of its tasks. */
|
||||
fun dropScope() {
|
||||
scopeViewId.value = null
|
||||
}
|
||||
|
||||
fun toggleTagFilter(tag: String) {
|
||||
@@ -378,7 +500,7 @@ class TaskListViewModel @Inject constructor(
|
||||
viewModelScope.launch { settingsPrefs.setGroupCollapsed(id, collapsed) }
|
||||
|
||||
fun setGrouping(grouping: TaskGrouping) {
|
||||
val f = filter.value ?: return
|
||||
val f = filter ?: return
|
||||
viewModelScope.launch { settingsPrefs.setGrouping(f, grouping) }
|
||||
}
|
||||
|
||||
@@ -390,14 +512,12 @@ class TaskListViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes every completed task in [listId]. A completed occurrence goes on its
|
||||
* own, a series that is closed as a whole goes whole, and a parent that still
|
||||
* has open subtasks stays — deleting it would take them along.
|
||||
* Deletes the completed tasks this screen shows that [clearableCompleted] lets
|
||||
* go. A completed occurrence goes on its own, a series that is closed as a
|
||||
* whole goes whole, and a parent that still has open subtasks stays.
|
||||
*/
|
||||
fun clearCompleted(listId: Long) {
|
||||
val done = (state.value as? TaskListUiState.Content)?.tasks
|
||||
?.filter { it.listId == listId && it.isCompleted && it.subtaskDone == it.subtaskTotal }
|
||||
.orEmpty()
|
||||
fun clearCompleted() {
|
||||
val done = (state.value as? TaskListUiState.Content)?.clearableCompleted().orEmpty()
|
||||
appScope.launch {
|
||||
done.forEach { task ->
|
||||
val wholeSeries = task.isOccurrence && task.taskId == task.seriesId
|
||||
@@ -431,7 +551,7 @@ class TaskListViewModel @Inject constructor(
|
||||
private fun searchable(): List<Task> = searchableIn(state.value)
|
||||
|
||||
private fun searchableIn(state: TaskListUiState): List<Task> =
|
||||
(state as? TaskListUiState.Content)?.takeIf { it.filter == filter.value }?.searchable.orEmpty()
|
||||
(state as? TaskListUiState.Content)?.takeIf { it.filter == filter }?.searchable.orEmpty()
|
||||
|
||||
/** The list search for the current query (#95); idle while the query is blank. */
|
||||
val search: StateFlow<ListSearchResult> =
|
||||
@@ -528,12 +648,6 @@ class TaskListViewModel @Inject constructor(
|
||||
withContext(Dispatchers.Main) { showSearchReceipt(receipt) }
|
||||
}
|
||||
|
||||
/** Inline "add task" — a title into [listId], with the default dates. */
|
||||
fun quickAdd(title: String, listId: Long) = viewModelScope.launch {
|
||||
if (title.isBlank() || listId <= 0L) return@launch
|
||||
runCatching { repository.createTask(settingsPrefs.settings.first().quickTask(title, listId)) }
|
||||
}
|
||||
|
||||
private val _listWriteFailure = MutableStateFlow<ListWriteFailure?>(null)
|
||||
|
||||
/** Set when a list write is refused; the screen shows it and clears it. */
|
||||
@@ -608,3 +722,10 @@ class TaskListViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The completed tasks a Clear in the Completed section deletes: those shown that
|
||||
* can be written and have no open subtask left.
|
||||
*/
|
||||
fun TaskListUiState.Content.clearableCompleted(): List<Task> =
|
||||
tasks.filter { it.isCompleted && !it.isReadOnly && it.subtaskDone == it.subtaskTotal }
|
||||
@@ -5,7 +5,8 @@ import android.app.UiModeManager
|
||||
import android.os.Build
|
||||
import androidx.annotation.StyleRes
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.isPureBlack
|
||||
|
||||
/**
|
||||
* Hands the app's theme setting to the system, which draws the launch window
|
||||
|
||||
@@ -2,7 +2,12 @@ package de.jeanlucmakiola.agendula.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
||||
import de.jeanlucmakiola.floret.identity.FloretExpressiveTheme
|
||||
import de.jeanlucmakiola.floret.prefs.ActionStyle
|
||||
import de.jeanlucmakiola.floret.prefs.LayoutDensity
|
||||
import de.jeanlucmakiola.floret.prefs.isDark
|
||||
import de.jeanlucmakiola.floret.prefs.isPureBlack
|
||||
|
||||
/**
|
||||
* Agendula's theme: the family's [FloretExpressiveTheme] machinery (dynamic
|
||||
@@ -16,6 +21,9 @@ fun AgendulaTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
dynamicColor: Boolean = true,
|
||||
pureBlack: Boolean = false,
|
||||
compactLayout: Boolean = false,
|
||||
shapedActions: Boolean = false,
|
||||
reduceMotion: Boolean = false,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
FloretExpressiveTheme(
|
||||
@@ -25,6 +33,21 @@ fun AgendulaTheme(
|
||||
dynamicColor = dynamicColor,
|
||||
pureBlack = pureBlack,
|
||||
typography = AgendulaTypography,
|
||||
compactLayout = compactLayout,
|
||||
shapedActions = shapedActions,
|
||||
reduceMotion = reduceMotion,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
|
||||
/** [AgendulaTheme] as the stored [settings] ask for it: theme mode, colours, density, buttons and motion. */
|
||||
@Composable
|
||||
fun AgendulaTheme(settings: Settings, content: @Composable () -> Unit) = AgendulaTheme(
|
||||
darkTheme = settings.themeMode.isDark(isSystemInDarkTheme()),
|
||||
dynamicColor = settings.dynamicColor,
|
||||
pureBlack = settings.themeMode.isPureBlack,
|
||||
compactLayout = settings.density == LayoutDensity.COMPACT,
|
||||
shapedActions = settings.actionStyle == ActionStyle.SHAPES,
|
||||
reduceMotion = settings.reduceMotion,
|
||||
content = content,
|
||||
)
|
||||
@@ -0,0 +1,258 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
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.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.ChevronRight
|
||||
import androidx.compose.material.icons.rounded.Dashboard
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.FilterList
|
||||
import androidx.compose.material.icons.rounded.PostAdd
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
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.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
import de.jeanlucmakiola.agendula.domain.deletable
|
||||
import de.jeanlucmakiola.agendula.ui.common.NameField
|
||||
import de.jeanlucmakiola.agendula.ui.settings.CategoryIcon
|
||||
import de.jeanlucmakiola.agendula.ui.settings.ChipAccent
|
||||
import de.jeanlucmakiola.agendula.ui.settings.SettingsHint
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
|
||||
/**
|
||||
* A view's settings: its name, icon and scope, the quick-add switch, and delete
|
||||
* for any view but Home. The scope opens in the rule editor ([onEditScope]), and
|
||||
* comes back through [EditViewViewModel.setScope].
|
||||
*/
|
||||
@Composable
|
||||
fun EditViewScreen(
|
||||
viewModel: EditViewViewModel,
|
||||
onEditScope: (Rule?) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
onEditLayout: () -> Unit = {},
|
||||
) {
|
||||
val draft by viewModel.draft.collectAsStateWithLifecycle()
|
||||
val listNames by viewModel.listNames.collectAsStateWithLifecycle()
|
||||
val quickAddTarget by viewModel.quickAddTarget.collectAsStateWithLifecycle()
|
||||
val saveFailed by viewModel.saveFailed.collectAsStateWithLifecycle()
|
||||
val view = draft
|
||||
val isNew = view?.id == 0L
|
||||
var choosingIcon by rememberSaveable { mutableStateOf(false) }
|
||||
var confirmDelete by rememberSaveable { mutableStateOf(false) }
|
||||
val save = { viewModel.save(onBack) }
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(if (isNew) R.string.view_new_title else R.string.view_edit_title),
|
||||
onBack = onBack,
|
||||
largeTopBar = false,
|
||||
actions = {
|
||||
Button(
|
||||
onClick = save,
|
||||
enabled = view != null && (view.id == View.HOME_ID || view.name.isNotBlank()),
|
||||
modifier = Modifier.padding(end = 12.dp),
|
||||
) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
) {
|
||||
if (view == null) return@CollapsingScaffold
|
||||
|
||||
val homeLabel = stringResource(R.string.view_home)
|
||||
LaunchedEffect(view.id) { viewModel.fillHomeName(homeLabel) }
|
||||
NameField(
|
||||
name = view.name,
|
||||
placeholder = if (view.id == View.HOME_ID) homeLabel else stringResource(R.string.view_name_hint),
|
||||
autoFocus = isNew,
|
||||
onNameChange = viewModel::rename,
|
||||
onImeAction = save,
|
||||
)
|
||||
if (saveFailed) {
|
||||
Text(
|
||||
stringResource(R.string.view_save_failed),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = GroupedListInset).padding(top = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
GroupedSectionHeader(stringResource(R.string.view_section_icon))
|
||||
GroupedRow(
|
||||
title = stringResource(view.icon.label),
|
||||
position = Position.Alone,
|
||||
leading = { CategoryIcon(view.icon.vector, ChipAccent.Primary) },
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { choosingIcon = true },
|
||||
)
|
||||
|
||||
GroupedSectionHeader(stringResource(R.string.view_section_scope))
|
||||
GroupedRow(
|
||||
title = scopeSummary(view.scope, listNames),
|
||||
summary = stringResource(if (view.scope == null) R.string.view_scope_none_hint else R.string.view_scope_hint),
|
||||
position = Position.Alone,
|
||||
leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) },
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { onEditScope(view.scope) },
|
||||
)
|
||||
SettingsHint(stringResource(R.string.view_scope_blocks_hint))
|
||||
|
||||
GroupedSectionHeader(stringResource(R.string.view_section_layout))
|
||||
// A new view has no layout stored to open yet.
|
||||
if (!isNew) {
|
||||
// Opening it saves the view first, which a blank name can't be.
|
||||
val canSave = view.id == View.HOME_ID || view.name.isNotBlank()
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.view_edit_layout),
|
||||
summary = pluralStringResource(R.plurals.view_blocks, view.blocks.size, view.blocks.size),
|
||||
position = Position.Top,
|
||||
leading = { Icon(Icons.Rounded.Dashboard, contentDescription = null) },
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
dimmed = !canSave,
|
||||
onClick = if (canSave) ({ viewModel.saveAndEditLayout(onEditLayout) }) else null,
|
||||
)
|
||||
}
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.view_quick_add),
|
||||
checked = view.quickAdd,
|
||||
onCheckedChange = viewModel::setQuickAdd,
|
||||
position = if (isNew) Position.Alone else Position.Bottom,
|
||||
summary = quickAddTarget?.takeIf { view.quickAdd }?.let { stringResource(R.string.view_quick_add_target, it) }
|
||||
?: stringResource(R.string.view_quick_add_hint),
|
||||
leading = { Icon(Icons.Rounded.PostAdd, contentDescription = null) },
|
||||
)
|
||||
|
||||
if (view.deletable && !isNew) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.view_delete),
|
||||
position = Position.Alone,
|
||||
contentColor = MaterialTheme.colorScheme.error,
|
||||
leading = { Icon(Icons.Rounded.Delete, contentDescription = null) },
|
||||
onClick = { confirmDelete = true },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
|
||||
if (choosingIcon && view != null) {
|
||||
ViewIconPicker(
|
||||
current = view.icon,
|
||||
onSelect = { icon -> icon?.let(viewModel::setIcon) },
|
||||
onDismiss = { choosingIcon = false },
|
||||
)
|
||||
}
|
||||
|
||||
if (confirmDelete && view != null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = false },
|
||||
title = { Text(stringResource(R.string.view_delete_title, viewName(view.name, view.id))) },
|
||||
text = { Text(stringResource(R.string.view_delete_body)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { confirmDelete = false; viewModel.delete(onBack) }) {
|
||||
Text(stringResource(R.string.delete))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmDelete = false }) { Text(stringResource(R.string.dialog_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** How many icons lead the picker as suggestions. */
|
||||
private const val SUGGESTED_ICONS = 10
|
||||
private const val ICONS_PER_ROW = 5
|
||||
private val IconGap = 12.dp
|
||||
|
||||
/**
|
||||
* The curated view icons in a full-screen grid; picking one closes it. With
|
||||
* [automatic] a row on top picks none, for a tile that takes its source's icon.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun ViewIconPicker(
|
||||
current: ViewIcon?,
|
||||
onSelect: (ViewIcon?) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
automatic: Boolean = false,
|
||||
) {
|
||||
FullScreenPicker(title = stringResource(R.string.view_icon_title), onDismiss = onDismiss) {
|
||||
if (automatic) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.block_automatic),
|
||||
position = Position.Alone,
|
||||
checked = current == null,
|
||||
onClick = {
|
||||
onSelect(null)
|
||||
onDismiss()
|
||||
},
|
||||
)
|
||||
}
|
||||
val (suggested, more) = ViewIcon.entries.withIndex().partition { it.index < SUGGESTED_ICONS }
|
||||
listOf(R.string.view_icon_suggested to suggested, R.string.view_icon_more to more).forEach { (header, icons) ->
|
||||
GroupedSectionHeader(stringResource(header))
|
||||
BoxWithConstraints(Modifier.fillMaxWidth().padding(horizontal = GroupedListInset)) {
|
||||
val tile = (maxWidth - IconGap * (ICONS_PER_ROW - 1)) / ICONS_PER_ROW
|
||||
FlowRow(
|
||||
maxItemsInEachRow = ICONS_PER_ROW,
|
||||
horizontalArrangement = Arrangement.spacedBy(IconGap),
|
||||
verticalArrangement = Arrangement.spacedBy(IconGap),
|
||||
) {
|
||||
icons.forEach { (_, icon) ->
|
||||
val chosen = icon == current
|
||||
Surface(
|
||||
onClick = {
|
||||
onSelect(icon)
|
||||
onDismiss()
|
||||
},
|
||||
shape = if (chosen) CircleShape else RoundedCornerShape(20.dp),
|
||||
color = if (chosen) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
contentColor = if (chosen) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.size(tile).semantics { selected = chosen },
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(icon.vector, contentDescription = stringResource(icon.label), modifier = Modifier.size(28.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Add
|
||||
import androidx.compose.material.icons.rounded.ChevronRight
|
||||
import androidx.compose.material.icons.rounded.DragHandle
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.ReadOnlyComposable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.ui.common.ActionShapes
|
||||
import de.jeanlucmakiola.agendula.ui.settings.ChipAccent
|
||||
import de.jeanlucmakiola.agendula.ui.settings.CategoryIcon
|
||||
import de.jeanlucmakiola.floret.components.ActionButton
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.ReorderableColumn
|
||||
import de.jeanlucmakiola.floret.identity.byDensity
|
||||
|
||||
/** A view's row, room for a two-line scope summary; tighter when compact. */
|
||||
private val ViewRowHeight: Dp
|
||||
@Composable @ReadOnlyComposable get() = byDensity(88.dp, 80.dp)
|
||||
|
||||
/**
|
||||
* The views in the order the view menu lists them: Home first, the others
|
||||
* dragged into place by their handle. A row opens the view's settings; the add
|
||||
* action starts a new view.
|
||||
*/
|
||||
@Composable
|
||||
fun ManageViewsScreen(
|
||||
onBack: () -> Unit,
|
||||
onEditView: (Long) -> Unit,
|
||||
viewModel: ManageViewsViewModel = hiltViewModel(),
|
||||
) {
|
||||
val views by viewModel.views.collectAsStateWithLifecycle()
|
||||
val listNames by viewModel.listNames.collectAsStateWithLifecycle()
|
||||
val reorderFailed by viewModel.reorderFailed.collectAsStateWithLifecycle()
|
||||
val home = views.firstOrNull()
|
||||
val others = views.drop(1)
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.view_manage),
|
||||
onBack = onBack,
|
||||
largeTopBar = false,
|
||||
actions = {
|
||||
ActionButton(
|
||||
shape = ActionShapes.AddView,
|
||||
morphTo = ActionShapes.AddListPressed,
|
||||
icon = Icons.Rounded.Add,
|
||||
contentDescription = stringResource(R.string.view_add),
|
||||
onClick = { onEditView(0) },
|
||||
)
|
||||
},
|
||||
) {
|
||||
if (home == null) return@CollapsingScaffold
|
||||
ViewRow(
|
||||
view = home,
|
||||
listNames = listNames,
|
||||
position = if (others.isEmpty()) Position.Alone else Position.Top,
|
||||
handle = null,
|
||||
dragging = false,
|
||||
onClick = { onEditView(home.id) },
|
||||
)
|
||||
// Home heads the run, so the others continue it rather than start their own.
|
||||
ReorderableColumn(
|
||||
items = others,
|
||||
keyOf = { it.id },
|
||||
onReorder = { ordered -> viewModel.reorder(listOf(home.id) + ordered.map { it.id }) },
|
||||
rowHeight = ViewRowHeight,
|
||||
) { view, position, dragHandle, isDragging ->
|
||||
ViewRow(
|
||||
view = view,
|
||||
listNames = listNames,
|
||||
position = when (position) {
|
||||
Position.Top, Position.Middle -> Position.Middle
|
||||
Position.Bottom, Position.Alone -> Position.Bottom
|
||||
},
|
||||
handle = { DragHandle(dragHandle) },
|
||||
dragging = isDragging,
|
||||
gapBelow = false,
|
||||
onClick = { onEditView(view.id) },
|
||||
)
|
||||
}
|
||||
if (reorderFailed) {
|
||||
Text(
|
||||
stringResource(R.string.view_save_failed),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = GroupedListInset).padding(top = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ViewRow(
|
||||
view: View,
|
||||
listNames: Map<Long, String>,
|
||||
position: Position,
|
||||
handle: (@Composable () -> Unit)?,
|
||||
dragging: Boolean,
|
||||
onClick: () -> Unit,
|
||||
gapBelow: Boolean = true,
|
||||
) {
|
||||
val blocks = pluralStringResource(R.plurals.view_blocks, view.blocks.size, view.blocks.size)
|
||||
GroupedRow(
|
||||
title = viewName(view.name, view.id),
|
||||
summary = stringResource(R.string.view_summary, scopeSummary(view.scope, listNames), blocks),
|
||||
position = position,
|
||||
minHeight = ViewRowHeight,
|
||||
gapBelow = gapBelow,
|
||||
container = if (dragging) MaterialTheme.colorScheme.secondaryContainer else null,
|
||||
leading = { CategoryIcon(view.icon.vector, ChipAccent.Primary) },
|
||||
// Home has no handle: it stays first.
|
||||
trailing = handle ?: { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = onClick,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DragHandle(modifier: Modifier) {
|
||||
Box(modifier = modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
Icons.Rounded.DragHandle,
|
||||
contentDescription = stringResource(R.string.view_reorder_handle),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.ui.filters.minPriorityLabel
|
||||
|
||||
/**
|
||||
* A view's scope in a line: "Everything" without one, else its conditions, as in
|
||||
* "List Work and tag next". [lists] names the lists by id; one missing from it
|
||||
* reads as deleted.
|
||||
*/
|
||||
@Composable
|
||||
fun scopeSummary(scope: Rule?, lists: Map<Long, String>): String =
|
||||
if (scope == null || scope == Rule.Everything) stringResource(R.string.view_scope_everything) else ruleSummary(scope, lists)
|
||||
|
||||
@Composable
|
||||
private fun ruleSummary(rule: Rule, lists: Map<Long, String>): String = when (rule) {
|
||||
is Rule.AllOf -> joined(rule.children, lists, R.string.view_scope_and, R.string.view_scope_everything)
|
||||
is Rule.AnyOf -> joined(rule.children, lists, R.string.view_scope_or, R.string.view_scope_nothing)
|
||||
is Rule.Not -> stringResource(R.string.view_scope_not, ruleSummary(rule.child, lists))
|
||||
is Rule.InList -> {
|
||||
val deleted = stringResource(R.string.view_scope_list_deleted)
|
||||
val names = rule.listIds.map { lists[it] ?: deleted }.sorted() +
|
||||
List(rule.elsewhere.size) { stringResource(R.string.view_scope_list_elsewhere) }
|
||||
if (names.isEmpty()) stringResource(R.string.view_scope_nothing) else stringResource(R.string.view_scope_list, names.joinToString(", "))
|
||||
}
|
||||
is Rule.HasTag -> stringResource(R.string.view_scope_tag, rule.tag)
|
||||
is Rule.MinPriority -> minPriorityLabel(rule.priority)
|
||||
is Rule.Due -> when (val spec = rule.spec) {
|
||||
is DueSpec.Window -> stringResource(
|
||||
when (spec.window) {
|
||||
DueWindow.OVERDUE -> R.string.view_scope_due_overdue
|
||||
DueWindow.TODAY -> R.string.view_scope_due_today
|
||||
DueWindow.UPCOMING -> R.string.view_scope_due_upcoming
|
||||
DueWindow.NO_DATE -> R.string.view_scope_due_none
|
||||
},
|
||||
)
|
||||
DueSpec.ThisWeek -> stringResource(R.string.view_scope_due_week)
|
||||
DueSpec.ThisMonth -> stringResource(R.string.view_scope_due_month)
|
||||
is DueSpec.NextDays -> pluralStringResource(R.plurals.view_scope_due_next_days, spec.days, spec.days)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun joined(children: List<Rule>, lists: Map<Long, String>, join: Int, empty: Int): String {
|
||||
if (children.isEmpty()) return stringResource(empty)
|
||||
var text = ruleSummary(children.first(), lists)
|
||||
children.drop(1).forEach { text = stringResource(join, text, ruleSummary(it, lists)) }
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.FilterList
|
||||
import androidx.compose.material.icons.rounded.History
|
||||
import androidx.compose.material.icons.rounded.RocketLaunch
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDestination
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.StartDestination
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.ui.common.ListColorChip
|
||||
import de.jeanlucmakiola.agendula.ui.settings.CategoryIcon
|
||||
import de.jeanlucmakiola.agendula.ui.settings.ChipAccent
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/** What the start destination can be, and what it is. */
|
||||
data class StartChoices(
|
||||
val selected: StartDestination = DefaultStartDestination,
|
||||
val views: List<View> = emptyList(),
|
||||
val lists: List<TaskList> = emptyList(),
|
||||
val filters: List<SavedFilter> = emptyList(),
|
||||
)
|
||||
|
||||
@HiltViewModel
|
||||
class StartDestinationViewModel @Inject constructor(
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
val choices: StateFlow<StartChoices> = combine(
|
||||
settingsPrefs.startDestination,
|
||||
settingsPrefs.views,
|
||||
repository.taskLists().catch { emit(emptyList()) },
|
||||
settingsPrefs.savedFilters,
|
||||
::StartChoices,
|
||||
).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), StartChoices())
|
||||
|
||||
fun select(destination: StartDestination) = viewModelScope.launch { settingsPrefs.setStartDestination(destination) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings row for where the app opens (#141), and its full-screen picker:
|
||||
* *Last used view*, then the views, lists and saved filters.
|
||||
*/
|
||||
@Composable
|
||||
fun StartDestinationRow(position: Position, viewModel: StartDestinationViewModel = hiltViewModel()) {
|
||||
val choices by viewModel.choices.collectAsStateWithLifecycle()
|
||||
var picking by rememberSaveable { mutableStateOf(false) }
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.start_destination),
|
||||
summary = startLabel(choices.selected, choices),
|
||||
position = position,
|
||||
leading = { CategoryIcon(Icons.Rounded.RocketLaunch, ChipAccent.Tertiary) },
|
||||
onClick = { picking = true },
|
||||
)
|
||||
if (picking) {
|
||||
StartDestinationPicker(choices, onSelect = viewModel::select, onDismiss = { picking = false })
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StartDestinationPicker(
|
||||
choices: StartChoices,
|
||||
onSelect: (StartDestination) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val pick = { destination: StartDestination ->
|
||||
onSelect(destination)
|
||||
onDismiss()
|
||||
}
|
||||
FullScreenPicker(title = stringResource(R.string.start_destination), onDismiss = onDismiss) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.start_last_used),
|
||||
summary = stringResource(R.string.start_last_used_hint),
|
||||
position = Position.Alone,
|
||||
leading = { Icon(Icons.Rounded.History, contentDescription = null) },
|
||||
checked = choices.selected == StartDestination.LastUsed,
|
||||
onClick = { pick(StartDestination.LastUsed) },
|
||||
)
|
||||
GroupedSectionHeader(stringResource(R.string.start_section_views))
|
||||
choices.views.forEachIndexed { index, view ->
|
||||
val destination = StartDestination.View(view.id)
|
||||
GroupedRow(
|
||||
title = viewName(view.name, view.id),
|
||||
position = positionOf(index, choices.views.size),
|
||||
leading = { Icon(view.icon.vector, contentDescription = null) },
|
||||
checked = choices.selected == destination,
|
||||
onClick = { pick(destination) },
|
||||
)
|
||||
}
|
||||
if (choices.lists.isNotEmpty()) {
|
||||
GroupedSectionHeader(stringResource(R.string.start_section_lists))
|
||||
val showAccount = choices.lists.mapTo(HashSet()) { it.accountName }.size > 1
|
||||
choices.lists.forEachIndexed { index, list ->
|
||||
val destination = StartDestination.List(list.id)
|
||||
GroupedRow(
|
||||
title = list.name,
|
||||
summary = list.accountName.takeIf { showAccount },
|
||||
position = positionOf(index, choices.lists.size),
|
||||
leading = { ListColorChip(list.color) },
|
||||
checked = choices.selected == destination,
|
||||
onClick = { pick(destination) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (choices.filters.isNotEmpty()) {
|
||||
GroupedSectionHeader(stringResource(R.string.start_section_filters))
|
||||
choices.filters.forEachIndexed { index, filter ->
|
||||
val destination = StartDestination.Filter(filter.id)
|
||||
GroupedRow(
|
||||
title = filter.name,
|
||||
position = positionOf(index, choices.filters.size),
|
||||
leading = { Icon(Icons.Rounded.FilterList, contentDescription = null) },
|
||||
checked = choices.selected == destination,
|
||||
onClick = { pick(destination) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** What [destination] is called; one since deleted reads as Home, where the app then opens. */
|
||||
@Composable
|
||||
private fun startLabel(destination: StartDestination, choices: StartChoices): String? {
|
||||
val home = choices.views.firstOrNull()?.let { viewName(it.name, it.id) } ?: stringResource(R.string.view_home)
|
||||
return when (destination) {
|
||||
StartDestination.LastUsed -> stringResource(R.string.start_last_used)
|
||||
is StartDestination.View -> choices.views.firstOrNull { it.id == destination.id }?.let { viewName(it.name, it.id) } ?: home
|
||||
// Lists may not have loaded, or may not read: no name rather than a wrong one.
|
||||
is StartDestination.List -> choices.lists.firstOrNull { it.id == destination.id }?.name
|
||||
?: home.takeIf { choices.lists.isNotEmpty() }
|
||||
is StartDestination.Filter -> choices.filters.firstOrNull { it.id == destination.id }?.name ?: home
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.StartDestination
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.plan
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Which view home shows. A switch shows at once and is stored as the last used
|
||||
* view behind it; [start] picks the view a fresh launch opens on (#141).
|
||||
*/
|
||||
@Singleton
|
||||
class ViewSession @Inject constructor(
|
||||
private val prefs: SettingsPrefs,
|
||||
private val repository: TasksRepository,
|
||||
@ApplicationScope private val appScope: CoroutineScope,
|
||||
) {
|
||||
private val chosen = MutableStateFlow<Long?>(null)
|
||||
private val _starting = MutableStateFlow(false)
|
||||
|
||||
/** Set while a launch works out its start destination; home waits rather than flash the last view. */
|
||||
val starting: StateFlow<Boolean> = _starting.asStateFlow()
|
||||
|
||||
/** The view shown: the one just picked, else the last used one stored. It may since have been deleted. */
|
||||
val activeViewId: Flow<Long> =
|
||||
combine(prefs.activeViewId, chosen) { stored, picked -> picked ?: stored }.distinctUntilChanged()
|
||||
|
||||
fun switchTo(viewId: Long) {
|
||||
chosen.value = viewId
|
||||
appScope.launch { prefs.setActiveView(viewId) }
|
||||
}
|
||||
|
||||
private val _editingLayout = MutableStateFlow(false)
|
||||
|
||||
/** Home shows its blocks to rearrange, until [stopEditingLayout]. Held here so a rotation keeps it. */
|
||||
val editingLayout: StateFlow<Boolean> = _editingLayout.asStateFlow()
|
||||
|
||||
/** Shows view [viewId] with its layout open for editing. */
|
||||
fun editLayout(viewId: Long) {
|
||||
switchTo(viewId)
|
||||
_editingLayout.value = true
|
||||
}
|
||||
|
||||
fun stopEditingLayout() {
|
||||
_editingLayout.value = false
|
||||
}
|
||||
|
||||
private val _startPush = MutableStateFlow<TaskFilter?>(null)
|
||||
|
||||
/**
|
||||
* The list or filter the start destination opens over home, until [takeStartPush].
|
||||
* Held here so an activity recreated meanwhile still opens it.
|
||||
*/
|
||||
val startPush: StateFlow<TaskFilter?> = _startPush.asStateFlow()
|
||||
|
||||
fun takeStartPush() {
|
||||
_startPush.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the start destination on a fresh launch, before its first frame:
|
||||
* switches to its view, then sets [startPush] when it is a list or filter
|
||||
* that still exists. Runs in the app scope, so a rotation doesn't cut it short.
|
||||
*/
|
||||
fun beginStart() {
|
||||
_starting.value = true
|
||||
appScope.launch { _startPush.value = start() }
|
||||
}
|
||||
|
||||
private suspend fun start(): TaskFilter? {
|
||||
val picked = chosen.value
|
||||
try {
|
||||
val destination = prefs.startDestination.first()
|
||||
val views = prefs.views.first().mapTo(HashSet()) { it.id }
|
||||
val filters = prefs.savedFilters.first().mapTo(HashSet()) { it.id }
|
||||
val lastUsed = prefs.activeViewId.first()
|
||||
// Only a list needs the lists read; home waits for it, so the list can't land over a screen opened meanwhile.
|
||||
val lists = if (destination is StartDestination.List) {
|
||||
withTimeoutOrNull(LISTS_TIMEOUT_MS) {
|
||||
runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull()
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val plan = destination.plan(views, lastUsed, lists, filters)
|
||||
// A view picked while this ran, by a shortcut, wins.
|
||||
if (picked != chosen.value) return null
|
||||
if (plan.viewId != lastUsed || picked != null) switchTo(plan.viewId)
|
||||
return plan.push
|
||||
} finally {
|
||||
_starting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val LISTS_TIMEOUT_MS = 2_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Dashboard
|
||||
import androidx.compose.material.icons.rounded.ExpandMore
|
||||
import androidx.compose.material.icons.rounded.Checklist
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.floret.components.FloretMenu
|
||||
import de.jeanlucmakiola.floret.components.FloretMenuItem
|
||||
|
||||
/**
|
||||
* The view's name in the home top bar, which opens the view menu: every view,
|
||||
* the shown one checked, then *Lists & filters…* and *Manage views*. There is
|
||||
* no drawer and no swiping between views (#59).
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
fun ViewSwitcher(
|
||||
title: String,
|
||||
views: List<View>,
|
||||
activeViewId: Long?,
|
||||
onSwitchView: (Long) -> Unit,
|
||||
onListsAndFilters: () -> Unit,
|
||||
onManageViews: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
val switcherLabel = stringResource(R.string.view_switch)
|
||||
Box(modifier) {
|
||||
Surface(
|
||||
onClick = { open = true },
|
||||
shape = CircleShape,
|
||||
color = if (open) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent,
|
||||
modifier = Modifier.semantics { role = Role.DropdownList },
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.heightIn(min = 48.dp).padding(start = 12.dp, end = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
Icon(Icons.Rounded.ExpandMore, contentDescription = switcherLabel)
|
||||
}
|
||||
}
|
||||
FloretMenu(
|
||||
expanded = open,
|
||||
onDismissRequest = { open = false },
|
||||
groups = listOf(
|
||||
views.map { view ->
|
||||
FloretMenuItem(
|
||||
text = viewName(view.name, view.id),
|
||||
icon = view.icon.vector,
|
||||
selected = view.id == activeViewId,
|
||||
onClick = { onSwitchView(view.id) },
|
||||
)
|
||||
},
|
||||
listOf(
|
||||
FloretMenuItem(stringResource(R.string.view_lists_and_filters_menu), Icons.Rounded.Checklist, onClick = onListsAndFilters),
|
||||
FloretMenuItem(stringResource(R.string.view_manage), Icons.Rounded.Dashboard, onClick = onManageViews),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.MenuBook
|
||||
import androidx.compose.material.icons.rounded.AccountTree
|
||||
import androidx.compose.material.icons.rounded.Alarm
|
||||
import androidx.compose.material.icons.rounded.Apps
|
||||
import androidx.compose.material.icons.rounded.Archive
|
||||
import androidx.compose.material.icons.rounded.Bolt
|
||||
import androidx.compose.material.icons.rounded.BugReport
|
||||
import androidx.compose.material.icons.rounded.Build
|
||||
import androidx.compose.material.icons.rounded.CalendarMonth
|
||||
import androidx.compose.material.icons.rounded.Checklist
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.Code
|
||||
import androidx.compose.material.icons.rounded.Dashboard
|
||||
import androidx.compose.material.icons.rounded.Description
|
||||
import androidx.compose.material.icons.rounded.Devices
|
||||
import androidx.compose.material.icons.rounded.Favorite
|
||||
import androidx.compose.material.icons.rounded.FilterList
|
||||
import androidx.compose.material.icons.rounded.FitnessCenter
|
||||
import androidx.compose.material.icons.rounded.Flag
|
||||
import androidx.compose.material.icons.rounded.Flight
|
||||
import androidx.compose.material.icons.rounded.Folder
|
||||
import androidx.compose.material.icons.rounded.Group
|
||||
import androidx.compose.material.icons.rounded.History
|
||||
import androidx.compose.material.icons.rounded.Home
|
||||
import androidx.compose.material.icons.rounded.Inbox
|
||||
import androidx.compose.material.icons.rounded.Lightbulb
|
||||
import androidx.compose.material.icons.rounded.Notifications
|
||||
import androidx.compose.material.icons.rounded.Palette
|
||||
import androidx.compose.material.icons.rounded.Payments
|
||||
import androidx.compose.material.icons.rounded.Person
|
||||
import androidx.compose.material.icons.rounded.Pets
|
||||
import androidx.compose.material.icons.rounded.Place
|
||||
import androidx.compose.material.icons.rounded.Public
|
||||
import androidx.compose.material.icons.rounded.Restaurant
|
||||
import androidx.compose.material.icons.rounded.School
|
||||
import androidx.compose.material.icons.rounded.Sell
|
||||
import androidx.compose.material.icons.rounded.ShoppingCart
|
||||
import androidx.compose.material.icons.rounded.Star
|
||||
import androidx.compose.material.icons.rounded.TaskAlt
|
||||
import androidx.compose.material.icons.rounded.Today
|
||||
import androidx.compose.material.icons.rounded.Work
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.InputChip
|
||||
import androidx.compose.material3.InputChipDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
|
||||
/** The glyph a [ViewIcon] stands for. */
|
||||
val ViewIcon.vector: ImageVector
|
||||
get() = when (this) {
|
||||
ViewIcon.HOME -> Icons.Rounded.Home
|
||||
ViewIcon.DASHBOARD -> Icons.Rounded.Dashboard
|
||||
ViewIcon.WORK -> Icons.Rounded.Work
|
||||
ViewIcon.HEART -> Icons.Rounded.Favorite
|
||||
ViewIcon.BOLT -> Icons.Rounded.Bolt
|
||||
ViewIcon.CALENDAR -> Icons.Rounded.CalendarMonth
|
||||
ViewIcon.TODAY -> Icons.Rounded.Today
|
||||
ViewIcon.INBOX -> Icons.Rounded.Inbox
|
||||
ViewIcon.LIST -> Icons.Rounded.Checklist
|
||||
ViewIcon.DONE -> Icons.Rounded.TaskAlt
|
||||
ViewIcon.FLAG -> Icons.Rounded.Flag
|
||||
ViewIcon.PERSON -> Icons.Rounded.Person
|
||||
ViewIcon.GROUP -> Icons.Rounded.Group
|
||||
ViewIcon.STAR -> Icons.Rounded.Star
|
||||
ViewIcon.FILTER -> Icons.Rounded.FilterList
|
||||
ViewIcon.TAG -> Icons.Rounded.Sell
|
||||
ViewIcon.FOLDER -> Icons.Rounded.Folder
|
||||
ViewIcon.ARCHIVE -> Icons.Rounded.Archive
|
||||
ViewIcon.ALARM -> Icons.Rounded.Alarm
|
||||
ViewIcon.NOTIFICATIONS -> Icons.Rounded.Notifications
|
||||
ViewIcon.LIGHTBULB -> Icons.Rounded.Lightbulb
|
||||
ViewIcon.SCHOOL -> Icons.Rounded.School
|
||||
ViewIcon.BOOK -> Icons.AutoMirrored.Rounded.MenuBook
|
||||
ViewIcon.SHOPPING -> Icons.Rounded.ShoppingCart
|
||||
ViewIcon.MONEY -> Icons.Rounded.Payments
|
||||
ViewIcon.FITNESS -> Icons.Rounded.FitnessCenter
|
||||
ViewIcon.PETS -> Icons.Rounded.Pets
|
||||
ViewIcon.RESTAURANT -> Icons.Rounded.Restaurant
|
||||
ViewIcon.FLIGHT -> Icons.Rounded.Flight
|
||||
ViewIcon.PLACE -> Icons.Rounded.Place
|
||||
ViewIcon.GLOBE -> Icons.Rounded.Public
|
||||
ViewIcon.PALETTE -> Icons.Rounded.Palette
|
||||
ViewIcon.DEVICES -> Icons.Rounded.Devices
|
||||
ViewIcon.CODE -> Icons.Rounded.Code
|
||||
ViewIcon.BUG -> Icons.Rounded.BugReport
|
||||
ViewIcon.BUILD -> Icons.Rounded.Build
|
||||
ViewIcon.NOTE -> Icons.Rounded.Description
|
||||
ViewIcon.HISTORY -> Icons.Rounded.History
|
||||
ViewIcon.GRID -> Icons.Rounded.Apps
|
||||
ViewIcon.TREE -> Icons.Rounded.AccountTree
|
||||
}
|
||||
|
||||
/** What a [ViewIcon] is called, for the icon row and screen readers. */
|
||||
@get:StringRes
|
||||
val ViewIcon.label: Int
|
||||
get() = when (this) {
|
||||
ViewIcon.HOME -> R.string.view_icon_home
|
||||
ViewIcon.DASHBOARD -> R.string.view_icon_dashboard
|
||||
ViewIcon.WORK -> R.string.view_icon_work
|
||||
ViewIcon.HEART -> R.string.view_icon_heart
|
||||
ViewIcon.BOLT -> R.string.view_icon_bolt
|
||||
ViewIcon.CALENDAR -> R.string.view_icon_calendar
|
||||
ViewIcon.TODAY -> R.string.view_icon_today
|
||||
ViewIcon.INBOX -> R.string.view_icon_inbox
|
||||
ViewIcon.LIST -> R.string.view_icon_list
|
||||
ViewIcon.DONE -> R.string.view_icon_done
|
||||
ViewIcon.FLAG -> R.string.view_icon_flag
|
||||
ViewIcon.PERSON -> R.string.view_icon_person
|
||||
ViewIcon.GROUP -> R.string.view_icon_group
|
||||
ViewIcon.STAR -> R.string.view_icon_star
|
||||
ViewIcon.FILTER -> R.string.view_icon_filter
|
||||
ViewIcon.TAG -> R.string.view_icon_tag
|
||||
ViewIcon.FOLDER -> R.string.view_icon_folder
|
||||
ViewIcon.ARCHIVE -> R.string.view_icon_archive
|
||||
ViewIcon.ALARM -> R.string.view_icon_alarm
|
||||
ViewIcon.NOTIFICATIONS -> R.string.view_icon_notifications
|
||||
ViewIcon.LIGHTBULB -> R.string.view_icon_lightbulb
|
||||
ViewIcon.SCHOOL -> R.string.view_icon_school
|
||||
ViewIcon.BOOK -> R.string.view_icon_book
|
||||
ViewIcon.SHOPPING -> R.string.view_icon_shopping
|
||||
ViewIcon.MONEY -> R.string.view_icon_money
|
||||
ViewIcon.FITNESS -> R.string.view_icon_fitness
|
||||
ViewIcon.PETS -> R.string.view_icon_pets
|
||||
ViewIcon.RESTAURANT -> R.string.view_icon_restaurant
|
||||
ViewIcon.FLIGHT -> R.string.view_icon_flight
|
||||
ViewIcon.PLACE -> R.string.view_icon_place
|
||||
ViewIcon.GLOBE -> R.string.view_icon_globe
|
||||
ViewIcon.PALETTE -> R.string.view_icon_palette
|
||||
ViewIcon.DEVICES -> R.string.view_icon_devices
|
||||
ViewIcon.CODE -> R.string.view_icon_code
|
||||
ViewIcon.BUG -> R.string.view_icon_bug
|
||||
ViewIcon.BUILD -> R.string.view_icon_build
|
||||
ViewIcon.NOTE -> R.string.view_icon_note
|
||||
ViewIcon.HISTORY -> R.string.view_icon_history
|
||||
ViewIcon.GRID -> R.string.view_icon_grid
|
||||
ViewIcon.TREE -> R.string.view_icon_tree
|
||||
}
|
||||
|
||||
/**
|
||||
* A view's name as shown. Home's stored name is empty until the user renames it,
|
||||
* and shows the translated "Home"; another view left without a name shows "View".
|
||||
*/
|
||||
@Composable
|
||||
fun viewName(name: String, viewId: Long): String = name.ifBlank { stringResource(unnamedViewLabel(viewId)) }
|
||||
|
||||
/** What a view left without a name is called: Home's translated name, or "View". */
|
||||
@StringRes
|
||||
fun unnamedViewLabel(viewId: Long): Int = if (viewId == View.HOME_ID) R.string.view_home else R.string.view_unnamed
|
||||
|
||||
/** [ScopeInputChip] on its own row, at the inset of the content below it. */
|
||||
@Composable
|
||||
fun ScopeChipRow(name: String, icon: ViewIcon, onDrop: () -> Unit) {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 8.dp)) {
|
||||
ScopeInputChip(name = name, icon = icon, onDrop = onDrop)
|
||||
}
|
||||
}
|
||||
|
||||
/** The removable chip a scope shows as: the view's icon and name, ✕ to drop it. */
|
||||
@Composable
|
||||
fun ScopeInputChip(name: String, icon: ViewIcon, onDrop: () -> Unit, modifier: Modifier = Modifier) {
|
||||
InputChip(
|
||||
selected = true,
|
||||
onClick = onDrop,
|
||||
label = { Text(name) },
|
||||
avatar = { Icon(icon.vector, contentDescription = null, modifier = Modifier.size(InputChipDefaults.AvatarSize)) },
|
||||
trailingIcon = {
|
||||
Icon(
|
||||
Icons.Rounded.Close,
|
||||
contentDescription = stringResource(R.string.view_scope_drop),
|
||||
modifier = Modifier.size(InputChipDefaults.IconSize),
|
||||
)
|
||||
},
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
import de.jeanlucmakiola.agendula.domain.BlockType
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddParse
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.isGone
|
||||
import de.jeanlucmakiola.agendula.domain.taskFilter
|
||||
import de.jeanlucmakiola.agendula.ui.quickadd.newTaskOrigin
|
||||
import de.jeanlucmakiola.agendula.domain.appliedScope
|
||||
import de.jeanlucmakiola.agendula.domain.newView
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Clock
|
||||
import de.jeanlucmakiola.agendula.ui.filters.admitsEverything
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/** The names of the lists by id, for scope summaries; empty while they can't be read. */
|
||||
private fun TasksRepository.listNames() = taskLists()
|
||||
.map { lists -> lists.associate { it.id to it.name } }
|
||||
.catch { emit(emptyMap()) }
|
||||
|
||||
/** The views in order, to reorder them and open one. */
|
||||
@HiltViewModel
|
||||
class ManageViewsViewModel @Inject constructor(
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
val views: StateFlow<List<View>> = settingsPrefs.views
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
|
||||
|
||||
val listNames: StateFlow<Map<Long, String>> = repository.listNames()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())
|
||||
|
||||
/** Puts the views in the order of [ids]; Home stays first. */
|
||||
fun reorder(ids: List<Long>) = viewModelScope.launch {
|
||||
if (!settingsPrefs.reorderViews(ids)) _reorderFailed.value = true
|
||||
}
|
||||
|
||||
private val _reorderFailed = MutableStateFlow(false)
|
||||
|
||||
/** Set once a reorder couldn't be stored: the views are another version's. */
|
||||
val reorderFailed: StateFlow<Boolean> = _reorderFailed.asStateFlow()
|
||||
}
|
||||
|
||||
/**
|
||||
* One view's name, icon and quick-add switch until saved; [bind] with an id of 0
|
||||
* starts a new view. Its scope shows read-only here for now.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class EditViewViewModel @Inject constructor(
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val session: ViewSession,
|
||||
repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _draft = MutableStateFlow<View?>(null)
|
||||
|
||||
/** `null` until [bind] has loaded the view. An id of 0 is a new one. */
|
||||
val draft: StateFlow<View?> = _draft.asStateFlow()
|
||||
|
||||
val listNames: StateFlow<Map<Long, String>> = repository.listNames()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())
|
||||
|
||||
/** The name of the list the quick-add bar puts a task in, as the scope stands; `null` with no list to put it in. */
|
||||
val quickAddTarget: StateFlow<String?> = combine(
|
||||
_draft,
|
||||
repository.taskLists().recoveringFromProviderFailure { emptyList() },
|
||||
settingsPrefs.settings,
|
||||
settingsPrefs.firstDayOfWeek,
|
||||
settingsPrefs.savedFilters,
|
||||
) { draft, lists, settings, weekStart, savedFilters ->
|
||||
if (draft == null) return@combine null
|
||||
val writable = lists.filter { it.acceptsWrites }
|
||||
val now = Clock.System.now()
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(now, zone)
|
||||
val clock = RuleClock(todayStart, todayEnd, zone, weekStart)
|
||||
// Worked out as the bar does: the view's task list presets the task, and keeps to the scope unless it ignores it.
|
||||
val listIds = lists.mapTo(HashSet()) { it.id }
|
||||
val filterIds = savedFilters.mapTo(HashSet()) { it.id }
|
||||
val taskBlock = draft.blocks.lastOrNull { block ->
|
||||
block.type == BlockType.TASK_LIST && block.source?.isGone(listIds, filterIds) != true
|
||||
}
|
||||
val scope = draft.appliedScope(listIds).rule?.takeUnless { taskBlock?.ignoreScope == true }
|
||||
val origin = settingsPrefs.newTaskOrigin(taskBlock?.source?.taskFilter)
|
||||
val id = settings.quickAddTask(QuickAddParse("-"), scope, writable, clock, now, origin)?.listId
|
||||
writable.firstOrNull { it.id == id }?.name
|
||||
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
|
||||
|
||||
private var bound = false
|
||||
private var saving = false
|
||||
private var homeLabel: String? = null
|
||||
|
||||
private val _saveFailed = MutableStateFlow(false)
|
||||
|
||||
/** Set when the views are stored in a form this version can't write; the screen says so. */
|
||||
val saveFailed: StateFlow<Boolean> = _saveFailed.asStateFlow()
|
||||
|
||||
fun bind(viewId: Long) {
|
||||
if (bound) return
|
||||
bound = true
|
||||
if (viewId <= 0) {
|
||||
_draft.value = newView(0, "")
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
_draft.value = settingsPrefs.views.first().firstOrNull { it.id == viewId } ?: newView(0, "")
|
||||
}
|
||||
}
|
||||
|
||||
fun rename(name: String) = _draft.update { it?.copy(name = name) }
|
||||
|
||||
/**
|
||||
* Shows Home's translated [label] as its name while it has none of its own;
|
||||
* saved unchanged, it stays unnamed so it keeps following the app's language.
|
||||
*/
|
||||
fun fillHomeName(label: String) {
|
||||
if (homeLabel != null) return
|
||||
val draft = _draft.value ?: return
|
||||
if (draft.id != View.HOME_ID) return
|
||||
homeLabel = label
|
||||
if (draft.name.isBlank()) rename(label)
|
||||
}
|
||||
|
||||
fun setIcon(icon: ViewIcon) = _draft.update { it?.copy(icon = icon) }
|
||||
|
||||
fun setQuickAdd(on: Boolean) = _draft.update { it?.copy(quickAdd = on) }
|
||||
|
||||
/** Sets the scope; one that admits every task, however it is written, is none. */
|
||||
fun setScope(scope: Rule?) = _draft.update { it?.copy(scope = scope?.takeUnless { s -> s.admitsEverything }) }
|
||||
|
||||
/**
|
||||
* Stores the name, icon, scope and quick-add switch over the view as it is
|
||||
* stored now, so a block changed meanwhile stays changed. A new view is shown next.
|
||||
*/
|
||||
fun save(onSaved: () -> Unit) {
|
||||
val draft = _draft.value ?: return
|
||||
if (saving || (draft.id != View.HOME_ID && draft.name.isBlank())) return
|
||||
saving = true
|
||||
viewModelScope.launch {
|
||||
val stored = settingsPrefs.views.first().firstOrNull { it.id == draft.id }
|
||||
// A view deleted while it was open stays deleted.
|
||||
if (stored == null && draft.id != 0L) {
|
||||
onSaved()
|
||||
return@launch
|
||||
}
|
||||
val name = draft.name.trim().takeUnless { draft.id == View.HOME_ID && it == homeLabel }.orEmpty()
|
||||
val view = stored?.copy(name = name, icon = draft.icon, scope = draft.scope, quickAdd = draft.quickAdd)
|
||||
?: draft.copy(name = name)
|
||||
val id = settingsPrefs.saveView(view)
|
||||
if (id == null) {
|
||||
saving = false
|
||||
_saveFailed.value = true
|
||||
return@launch
|
||||
}
|
||||
// Stays saving: the screen is leaving, and a second tap mustn't add the view again.
|
||||
if (stored == null) session.switchTo(id)
|
||||
onSaved()
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves the view as [save] does, then shows it with its layout open for editing. */
|
||||
fun saveAndEditLayout(onDone: () -> Unit) {
|
||||
val id = _draft.value?.id?.takeIf { it > 0 } ?: return
|
||||
save {
|
||||
viewModelScope.launch {
|
||||
// A view deleted while this was open stays deleted; there is no layout to open.
|
||||
if (settingsPrefs.views.first().any { it.id == id }) session.editLayout(id)
|
||||
onDone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(onDeleted: () -> Unit) {
|
||||
val id = _draft.value?.id?.takeIf { it > 0 && it != View.HOME_ID } ?: return
|
||||
viewModelScope.launch {
|
||||
if (settingsPrefs.deleteView(id)) onDeleted() else _saveFailed.value = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,6 +170,8 @@ private fun TaskWidgetBody(
|
||||
val title = when (filter) {
|
||||
is TaskFilter.Smart -> context.getString(smartListLabel(filter.list))
|
||||
is TaskFilter.Tagged -> filter.tag
|
||||
is TaskFilter.DueOn -> filter.date.toString()
|
||||
is TaskFilter.Matching -> filter.title.orEmpty()
|
||||
is TaskFilter.Saved -> if (ready == null) {
|
||||
context.getString(R.string.widget_tasks_label)
|
||||
} else {
|
||||
@@ -297,7 +299,7 @@ private fun TaskWidgetHeader(title: String, filter: TaskFilter, singleListId: Lo
|
||||
// still opens straight to it, otherwise this just raises the app.
|
||||
is TaskFilter.OfLists -> filter.listIds.singleOrNull()?.let { MainActivity.listIntent(context, it) }
|
||||
?: Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
is TaskFilter.Tagged -> Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
is TaskFilter.Tagged, is TaskFilter.DueOn, is TaskFilter.Matching -> Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
is TaskFilter.Saved -> MainActivity.filterIntent(context, filter.id)
|
||||
}
|
||||
WidgetHeader(
|
||||
|
||||
@@ -55,6 +55,7 @@ import de.jeanlucmakiola.floret.components.pastelize
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.glance.WidgetBackground
|
||||
import de.jeanlucmakiola.floret.glance.WidgetThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.isDark
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.emptyFlow
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -135,11 +136,7 @@ class TaskWidgetConfigActivity : ComponentActivity() {
|
||||
selectedListIds = parseWidgetListIds(state[WIDGET_LIST_IDS_KEY])
|
||||
}
|
||||
val dark = settings.themeMode.isDark(isSystemInDarkTheme())
|
||||
AgendulaTheme(
|
||||
darkTheme = dark,
|
||||
dynamicColor = settings.dynamicColor,
|
||||
pureBlack = settings.themeMode.isPureBlack,
|
||||
) {
|
||||
AgendulaTheme(settings) {
|
||||
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {}
|
||||
WidgetFilterPicker(
|
||||
kind = kind,
|
||||
@@ -225,7 +222,7 @@ private fun WidgetFilterPicker(
|
||||
when (selected) {
|
||||
is TaskFilter.OfList -> setOf(selected.listId)
|
||||
is TaskFilter.OfLists -> selected.listIds
|
||||
is TaskFilter.Smart, is TaskFilter.Tagged, is TaskFilter.Saved -> emptySet()
|
||||
is TaskFilter.Smart, is TaskFilter.Tagged, is TaskFilter.Saved, is TaskFilter.DueOn, is TaskFilter.Matching -> emptySet()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.agendula.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.text.format.DateFormat
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
@@ -14,6 +13,7 @@ import de.jeanlucmakiola.agendula.domain.calendarDate
|
||||
import de.jeanlucmakiola.agendula.domain.comparator
|
||||
import de.jeanlucmakiola.floret.glance.WidgetBackground
|
||||
import de.jeanlucmakiola.floret.glance.WidgetThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
@@ -102,6 +102,8 @@ internal fun TaskFilter.widgetStorageValue(): String = when (this) {
|
||||
is TaskFilter.OfLists -> "lists:${listIds.sorted().joinToString(",")}"
|
||||
is TaskFilter.Smart -> "smart:${list.name}"
|
||||
is TaskFilter.Tagged -> error("A tag has no widget")
|
||||
is TaskFilter.DueOn -> error("A day has no widget")
|
||||
is TaskFilter.Matching -> error("A block's rules have no widget")
|
||||
is TaskFilter.Saved -> "filter:$id"
|
||||
}
|
||||
|
||||
@@ -173,7 +175,7 @@ sealed interface TaskWidgetData {
|
||||
val singleListId: Long? = when (filter) {
|
||||
is TaskFilter.OfList -> filter.listId
|
||||
is TaskFilter.OfLists -> filter.listIds.singleOrNull()
|
||||
is TaskFilter.Smart, is TaskFilter.Tagged, is TaskFilter.Saved -> null
|
||||
is TaskFilter.Smart, is TaskFilter.Tagged, is TaskFilter.Saved, is TaskFilter.DueOn, is TaskFilter.Matching -> null
|
||||
}
|
||||
|
||||
/** [singleListId]'s name. */
|
||||
|
||||
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.agendula.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.text.format.DateFormat
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
@@ -12,6 +11,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFiltering
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
||||
import de.jeanlucmakiola.agendula.domain.comparator
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
|
||||
@@ -1,3 +1,347 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Agendula</string>
|
||||
<string name="app_name_tasks_alias">Tareas</string>
|
||||
<string name="task_untitled">Tarea sin título</string>
|
||||
<string name="back">Atrás</string>
|
||||
<string name="save">Guardar</string>
|
||||
<string name="delete">Eliminar</string>
|
||||
<string name="tasks_title">Tareas</string>
|
||||
<string name="task_list_empty">Aún no hay tareas.</string>
|
||||
<string name="task_list_failure">No se pudieron cargar esas tareas.</string>
|
||||
<string name="smart_no_date">Sin fecha</string>
|
||||
<string name="smart_completed">Completada</string>
|
||||
<string name="task_detail_title">Tarea</string>
|
||||
<string name="task_detail_not_found">Esta tarea ya no existe.</string>
|
||||
<string name="edit">Editar</string>
|
||||
<string name="field_description">Descripción</string>
|
||||
<string name="edit_save_failed">No se pudo guardar. Inténtalo otra vez.</string>
|
||||
<string name="add_task_hint">Añadir una tarea</string>
|
||||
<string name="add_subtask_hint">Añadir una subtarea</string>
|
||||
<string name="cd_add_task">Añadir tarea</string>
|
||||
<string name="cd_complete">Completa</string>
|
||||
<string name="cd_reopen">Reabrir</string>
|
||||
<string name="task_deleted">Eliminada</string>
|
||||
<string name="task_completed">Completada</string>
|
||||
<string name="cd_repeats">Repeticiones</string>
|
||||
<string name="shortcut_new_task">Nueva tarea</string>
|
||||
<string name="shortcut_today">Hoy</string>
|
||||
<string name="qs_tile_new_task">Nueva tarea</string>
|
||||
<string name="lists_reorder">Reordenar listas</string>
|
||||
<string name="lists_reorder_done">Reordenación completada</string>
|
||||
<string name="lists_reorder_handle">Arrastra para reordenar</string>
|
||||
<string name="sort_title">Ordenar por</string>
|
||||
<string name="view_options_title">Ordenar y filtrar</string>
|
||||
<string name="view_filter_tags">Filtrar por etiqueta</string>
|
||||
<string name="upcoming_range_title">Mostrar tareas con fecha límite</string>
|
||||
<string name="upcoming_range_all">En cualquier momento</string>
|
||||
<string name="upcoming_range_week">La próxima semana</string>
|
||||
<string name="upcoming_range_two_weeks">Las próximas 2 semanas</string>
|
||||
<string name="upcoming_range_month">El próximo mes</string>
|
||||
<string name="upcoming_range_three_months">Los próximos 3 meses</string>
|
||||
<string name="upcoming_range_year">El próximo año</string>
|
||||
<string name="upcoming_range_empty">No hay nada con fecha de vencimiento en este intervalo. Amplíalo en las opciones de visualización.</string>
|
||||
<string name="view_filter_clear">Limpiar filtro</string>
|
||||
<string name="sort_due">Fecha de vencimiento</string>
|
||||
<string name="sort_priority">Prioridad</string>
|
||||
<string name="sort_title_alpha">Título</string>
|
||||
<string name="sort_created">Añadidas recientemente</string>
|
||||
<string name="group_title">Agrupar por</string>
|
||||
<string name="group_due">Fecha de vencimiento</string>
|
||||
<string name="group_due_summary">Vencido, hoy, próximo</string>
|
||||
<string name="group_day">Día</string>
|
||||
<string name="group_day_summary">Un grupo para cada día</string>
|
||||
<string name="group_priority">Prioridad</string>
|
||||
<string name="group_priority_summary">Alta prioridad primero</string>
|
||||
<string name="group_list">Lista</string>
|
||||
<string name="group_list_summary">Un grupo para cada lista</string>
|
||||
<string name="group_tomorrow">Mañana</string>
|
||||
<string name="group_priority_high">Alta prioridad</string>
|
||||
<string name="group_priority_medium">Prioridad media</string>
|
||||
<string name="group_priority_low">Baja prioridad</string>
|
||||
<string name="group_priority_none">Sin prioridad</string>
|
||||
<string name="group_list_unnamed">Lista sin nombre</string>
|
||||
<string name="group_list_in_account">%1$s (%2$s)</string>
|
||||
<string name="clear_completed_action">Eliminar</string>
|
||||
<string name="clear_completed_title">¿Eliminar las tareas completadas?</string>
|
||||
<plurals name="clear_completed_body">
|
||||
<item quantity="one">Se eliminará %1$d tarea completada en esta lista.</item>
|
||||
<item quantity="many">Se eliminarán %1$d tareas completadas en esta lista.</item>
|
||||
<item quantity="other">Se eliminarán %1$d tareas completadas en esta lista.</item>
|
||||
</plurals>
|
||||
<string name="clear_completed_confirm">Borrar</string>
|
||||
<string name="undo">Deshacer</string>
|
||||
<string name="cd_expand_subtasks">Mostrar subtareas</string>
|
||||
<string name="cd_collapse_subtasks">Ocultar subtareas</string>
|
||||
<string name="section_overdue">Vencidas</string>
|
||||
<string name="section_today">Hoy</string>
|
||||
<string name="section_upcoming">Próximas</string>
|
||||
<string name="section_no_date">Sin fecha</string>
|
||||
<string name="section_completed">Completadas</string>
|
||||
<string name="priority_none">Ninguna</string>
|
||||
<string name="priority_low">Baja</string>
|
||||
<string name="priority_medium">Media</string>
|
||||
<string name="priority_high">Alta</string>
|
||||
<string name="detail_list">Lista</string>
|
||||
<string name="detail_due">Pendientes</string>
|
||||
<string name="detail_priority">Prioridad</string>
|
||||
<string name="detail_progress">Progreso</string>
|
||||
<string name="detail_subtasks">Subtareas</string>
|
||||
<string name="detail_parent">Tarea principal</string>
|
||||
<string name="detail_part_of">Parte de</string>
|
||||
<string name="percent_complete">%1$d%%</string>
|
||||
<string name="edit_list_label">Lista</string>
|
||||
<string name="edit_start_label">Comienza</string>
|
||||
<string name="edit_due_label">Pendiente</string>
|
||||
<string name="edit_priority_label">Prioridad</string>
|
||||
<string name="edit_progress_label">Progreso</string>
|
||||
<string name="edit_parent_label">Tarea principal</string>
|
||||
<string name="edit_parent_none">Ninguna (nivel superior)</string>
|
||||
<string name="edit_parent_search">Buscar tareas</string>
|
||||
<string name="edit_parent_empty">No hay tareas que coincidan en esta lista.</string>
|
||||
<string name="edit_reminder_label">Recordatorio</string>
|
||||
<string name="edit_set">Configurar</string>
|
||||
<string name="edit_clear">Eliminar</string>
|
||||
<string name="edit_title_hint">Título de la tarea</string>
|
||||
<string name="edit_when">Cuándo</string>
|
||||
<string name="edit_more_fields">Más campos</string>
|
||||
<string name="picker_section_date">Fecha</string>
|
||||
<string name="picker_section_time">Hora</string>
|
||||
<string name="picker_date_today">Hoy</string>
|
||||
<string name="picker_date_tomorrow">Mañana</string>
|
||||
<string name="picker_date_next_week">La próxima semana</string>
|
||||
<string name="picker_date_pick">Escoge una fecha</string>
|
||||
<string name="picker_time_morning">Mañana</string>
|
||||
<string name="picker_time_noon">Mediodía</string>
|
||||
<string name="picker_time_afternoon">Tarde</string>
|
||||
<string name="picker_time_evening">Noche</string>
|
||||
<string name="picker_time_custom">Hora personalizada</string>
|
||||
<string name="picker_time_none">Sin hora</string>
|
||||
<string name="picker_time_linked_due">Tu aplicación de tareas utiliza un único ajuste de hora para ambas fechas, de modo que la fecha de vencimiento adquiere o pierde una hora junto con esta</string>
|
||||
<string name="picker_time_linked_start">Tu aplicación de tareas utiliza un único ajuste de hora para ambas fechas, de modo que la fecha de inicio adquiere o pierde una hora junto con esta</string>
|
||||
<string name="picker_done">Hecho</string>
|
||||
<string name="close">Cerrar</string>
|
||||
<string name="dialog_cancel">Cancelar</string>
|
||||
<string name="edit_conflict_title">La tarea ha sido modificada en otro lugar</string>
|
||||
<string name="edit_conflict_body">Esta tarea se ha actualizado en otro lugar (mediante una sincronización o en otra aplicación) desde que la abriste. ¿Quieres sobrescribir esos cambios con tus ediciones?</string>
|
||||
<string name="edit_conflict_overwrite">Sobreescribir</string>
|
||||
<string name="reminder_none">Ninguno</string>
|
||||
<string name="reminder_at_due">A la hora de la tarea</string>
|
||||
<string name="reminder_on_the_day">En el día</string>
|
||||
<string name="detail_pane_empty">Selecciona una tarea para verla aquí</string>
|
||||
<string name="reminder_custom">Personalizado</string>
|
||||
<string name="reminder_custom_with_value">Personalizado (%1$s)</string>
|
||||
<string name="reminder_custom_set">Configurar</string>
|
||||
<string name="reminder_custom_amount">Introduce una cantidad</string>
|
||||
<string name="reminder_use_default">Usar el predeterminado</string>
|
||||
<string name="reminder_unit_minutes">Minutos</string>
|
||||
<string name="reminder_unit_hours">Horas</string>
|
||||
<string name="reminder_unit_days">Días</string>
|
||||
<string name="reminder_unit_weeks">Semanas</string>
|
||||
<string name="settings_list_reminders_title">Recordatorios por lista</string>
|
||||
<string name="settings_list_reminders_hint">Anula la configuración predeterminada para cada lista, de forma independiente para las tareas con hora específica y las tareas de todo el día. Una lista puede mantener la configuración predeterminada, descartarla o establecer la suya propia.</string>
|
||||
<string name="settings_list_notifications">Sonido y vibración</string>
|
||||
<string name="settings_list_notifications_hint">Sonido, vibración e importancia para los recordatorios de esta lista</string>
|
||||
<string name="settings_list_reminder_inherits">Predeterminado (%1$s)</string>
|
||||
<string name="settings_list_reminder_own">Recordatorios predeterminados propios</string>
|
||||
<string name="settings_list_reminder_follows">Según el predeterminado</string>
|
||||
<plurals name="settings_list_reminders_own_count">
|
||||
<item quantity="one">La lista %1$d tiene sus propios recordatorios predeterminados</item>
|
||||
<item quantity="many">Las listas %1$d tienen sus propios recordatorios predeterminados</item>
|
||||
<item quantity="other">Las listas %1$d tienen sus propios recordatorios predeterminados</item>
|
||||
</plurals>
|
||||
<plurals name="settings_default_reminder_lists_own">
|
||||
<item quantity="one">La lista %1$d utiliza el suyo propio</item>
|
||||
<item quantity="many">Las listas %1$d utilizan los suyos propios</item>
|
||||
<item quantity="other">Las listas %1$d utilizan los suyos propios</item>
|
||||
</plurals>
|
||||
<string name="recurrence_title">Repetir</string>
|
||||
<string name="recurrence_generic">Tarea recurrente</string>
|
||||
<string name="recurrence_daily">Cada día</string>
|
||||
<string name="recurrence_weekly">Cada semana</string>
|
||||
<string name="recurrence_monthly">Cada mes</string>
|
||||
<string name="recurrence_yearly">Cada año</string>
|
||||
<plurals name="recurrence_every_n_days">
|
||||
<item quantity="one">Cada %1$d día</item>
|
||||
<item quantity="many">Cada %1$d días</item>
|
||||
<item quantity="other">Cada %1$d días</item>
|
||||
</plurals>
|
||||
<plurals name="recurrence_every_n_weeks">
|
||||
<item quantity="one">Cada %1$d semana</item>
|
||||
<item quantity="many">Cada %1$d semanas</item>
|
||||
<item quantity="other">Cada %1$d semanas</item>
|
||||
</plurals>
|
||||
<plurals name="recurrence_every_n_months">
|
||||
<item quantity="one">Cada %1$d mes</item>
|
||||
<item quantity="many">Cada %1$d meses</item>
|
||||
<item quantity="other">Cada %1$d meses</item>
|
||||
</plurals>
|
||||
<plurals name="recurrence_every_n_years">
|
||||
<item quantity="one">Cada %1$d año</item>
|
||||
<item quantity="many">Cada %1$d años</item>
|
||||
<item quantity="other">Cada %1$d años</item>
|
||||
</plurals>
|
||||
<string name="recurrence_on_days">%1$s en %2$s</string>
|
||||
<string name="recurrence_with_until">%1$s hasta %2$s</string>
|
||||
<plurals name="recurrence_with_count">
|
||||
<item quantity="one">%1$s, %2$d vez</item>
|
||||
<item quantity="many">%1$s, %2$d veces</item>
|
||||
<item quantity="other">%1$s, %2$d veces</item>
|
||||
</plurals>
|
||||
<string name="recurrence_none">No se repite</string>
|
||||
<string name="recurrence_custom">Personalizado</string>
|
||||
<string name="recurrence_every">Cada</string>
|
||||
<string name="recurrence_unit_days">días</string>
|
||||
<string name="recurrence_unit_weeks">semanas</string>
|
||||
<string name="recurrence_unit_months">meses</string>
|
||||
<string name="recurrence_unit_years">años</string>
|
||||
<string name="recurrence_incomplete">Introduce un número del 1 al 999</string>
|
||||
<string name="recurrence_next">Siguiente: %1$s</string>
|
||||
<string name="recurrence_next_none">Esta regla nunca se repite</string>
|
||||
<string name="recurrence_ends">Finaliza</string>
|
||||
<string name="recurrence_end_never">Nunca</string>
|
||||
<string name="recurrence_end_until">En una fecha</string>
|
||||
<string name="recurrence_end_count">Después de un número de veces</string>
|
||||
<string name="recurrence_times">veces</string>
|
||||
<string name="recurrence_repeat_from">Repetir desde</string>
|
||||
<string name="recurrence_from_due">Fecha de vencimiento</string>
|
||||
<string name="recurrence_from_due_summary">Cumple con el horario, sin importar lo tarde que termines</string>
|
||||
<string name="recurrence_from_completion">Fecha de finalización</string>
|
||||
<string name="recurrence_from_completion_summary">La siguiente fecha cuenta a partir del día en que la marcas</string>
|
||||
<string name="recurrence_from_completion_note">Se repite a partir de la fecha de finalización</string>
|
||||
<string name="recurring_scope_occurrence">Sólo esta tarea</string>
|
||||
<string name="recurring_scope_following">Esta tarea y las siguientes</string>
|
||||
<string name="recurring_scope_series">Todas las tareas de la serie</string>
|
||||
<string name="error_blank_title">Introduce un título.</string>
|
||||
<string name="error_no_list">Escoger una lista.</string>
|
||||
<string name="error_due_before_start">La fecha de vencimiento no puede ser anterior al inicio.</string>
|
||||
<string name="error_reminder_without_date">Establece una fecha de inicio o de vencimiento para usar un recordatorio.</string>
|
||||
<string name="error_recurrence_without_date">Una tarea recurrente requiere de una fecha de inicio o de una fecha de vencimiento.</string>
|
||||
<string name="edit_recurrence_label">Repetir</string>
|
||||
<string name="edit_recurrence_none">No se repite</string>
|
||||
<string name="edit_location_label">Localización</string>
|
||||
<string name="edit_url_label">Enlace</string>
|
||||
<string name="edit_url_hint">https://…</string>
|
||||
<string name="edit_tags_label">Etiquetas</string>
|
||||
<string name="edit_tags_hint">Añadir una etiqueta</string>
|
||||
<string name="edit_tag_remove">Eliminar la etiqueta %1$s</string>
|
||||
<string name="edit_discard_title">¿Descartar cambios?</string>
|
||||
<string name="edit_discard_body">Los cambios que has realizado en esta tarea no se han guardado.</string>
|
||||
<string name="edit_discard_confirm">Descartar</string>
|
||||
<string name="edit_keep_editing">Seguir editando</string>
|
||||
<string name="edit_scope_title">Guardar los cambios en una tarea recurrente</string>
|
||||
<string name="edit_reminder_add">Añadir un recordatorio</string>
|
||||
<string name="edit_reminder_add_first">Añadir un recordatorio (de lo contrario, se aplica el predeterminado)</string>
|
||||
<string name="edit_reminder_remove">Eliminar el recordatorio</string>
|
||||
<string name="edit_reminder_list_defaults">Recordatorios predeterminados de la lista %1$s</string>
|
||||
<string name="edit_reminder_list_defaults_none">La lista %1$s no establece ningún recordatorio predeterminado para esta tarea</string>
|
||||
<string name="reminder_at_start">A la hora del inicio</string>
|
||||
<string name="reminder_at_due_time">A la hora del vencimiento</string>
|
||||
<string name="reminder_on_start_date">En la fecha del inicio</string>
|
||||
<string name="reminder_on_due_date">En la fecha del vencimiento</string>
|
||||
<string name="reminder_at_time">%1$s a las %2$s</string>
|
||||
<string name="reminder_anchor_start">Desde el inicio</string>
|
||||
<string name="reminder_anchor_due">Desde la fecha de vencimiento</string>
|
||||
<string name="reminder_time">Hora</string>
|
||||
<string name="subtask_progress">%1$d / %2$d</string>
|
||||
<string name="progress_fraction_compact">%1$d/%2$d</string>
|
||||
<string name="detail_delete_title">¿Eliminar tarea?</string>
|
||||
<string name="detail_delete_body">Esta tarea se eliminará.</string>
|
||||
<plurals name="detail_delete_body_subtasks">
|
||||
<item quantity="one">Esta tarea y su subtarea serán eliminadas.</item>
|
||||
<item quantity="many">Esta tarea y sus %1$d subtareas serán eliminadas.</item>
|
||||
<item quantity="other">Esta tarea y sus %1$d subtareas serán eliminadas.</item>
|
||||
</plurals>
|
||||
<string name="detail_delete_recurring_title">Eliminar tarea recurrente</string>
|
||||
<string name="detail_status_cancelled">Cancelado</string>
|
||||
<string name="detail_status_in_process">En progreso</string>
|
||||
<string name="more_options">Más opciones</string>
|
||||
<string name="detail_cancel_task">Cancelar tarea</string>
|
||||
<string name="detail_restore">Restaurar tarea</string>
|
||||
<string name="detail_duplicate">Duplicar</string>
|
||||
<string name="lists_header">Listas</string>
|
||||
<string name="tags_header">Etiquetas</string>
|
||||
<string name="filters_header">Filtros</string>
|
||||
<string name="filters_empty_hint">Combinar fechas límite, listas, etiquetas y prioridades en una vista a tu medida</string>
|
||||
<string name="filter_new_title">Nuevo filtro</string>
|
||||
<string name="filter_edit_title">Editar filtro</string>
|
||||
<string name="filter_name_hint">Nombre del filtro</string>
|
||||
<string name="filter_section_due">Vencimiento</string>
|
||||
<string name="filter_section_priority">Prioridad</string>
|
||||
<string name="filter_section_lists">Listas</string>
|
||||
<string name="filter_section_tags">Etiquetas</string>
|
||||
<string name="filter_any_due">Cualquier fecha de vencimiento</string>
|
||||
<string name="filter_any_list">Cualquier lista</string>
|
||||
<string name="filter_any_tag">Cualquier etiqueta, o ninguna</string>
|
||||
<string name="filter_priority_any">Cualquier prioridad</string>
|
||||
<string name="filter_priority_low">Baja y alta</string>
|
||||
<string name="filter_priority_medium">Media y alta</string>
|
||||
<string name="filter_priority_high">Sólo alta</string>
|
||||
<string name="filter_match_all_tags">Coincidir con todas las etiquetas</string>
|
||||
<string name="filter_match_all_on">Una tarea requiere de todas las etiquetas que has seleccionado</string>
|
||||
<string name="filter_match_all_off">Una tarea necesita una de las etiquetas que has elegido</string>
|
||||
<string name="filter_delete">Eliminar filtro</string>
|
||||
<string name="filter_delete_title">¿Eliminar «%1$s»?</string>
|
||||
<string name="filter_delete_body">Sólo se elimina el filtro. Sus tareas permanecen donde están.</string>
|
||||
<string name="filter_delete_confirm">Eliminar</string>
|
||||
<string name="filter_missing">Filtro eliminado</string>
|
||||
<string name="new_task">Nueva tarea</string>
|
||||
<string name="lists_failure">No se pudieron leer tus tareas.</string>
|
||||
<string name="lists_empty">Todavía no hay listas de tareas.</string>
|
||||
<string name="lists_empty_action">Crear una lista</string>
|
||||
<string name="list_add">Nueva lista</string>
|
||||
<string name="list_new_title">Nueva lista</string>
|
||||
<string name="list_edit_title">Editar lista</string>
|
||||
<string name="list_name_hint">Nombre de la lista</string>
|
||||
<string name="list_in_smart_lists">Mostrar en listas inteligentes</string>
|
||||
<string name="list_in_smart_lists_hint">Incluir las tareas de esta lista en Hoy, Próximos eventos, Todas las tareas y las demás listas inteligentes</string>
|
||||
<string name="list_color">Color</string>
|
||||
<string name="list_delete">Eliminar lista</string>
|
||||
<string name="list_save_failed">No se pudo guardar la lista.</string>
|
||||
<string name="list_delete_failed">No se pudo eliminar la lista.</string>
|
||||
<string name="list_delete_failed_account_home">Esa lista es la cuenta del calendario en sí.</string>
|
||||
<string name="list_delete_account_home">Esta lista es la cuenta calendario de en sí, por lo que no se puede eliminar desde aquí. Si se elimina, también se borrarán los eventos del calendario.</string>
|
||||
<string name="list_delete_confirm_title">¿Eliminar lista?</string>
|
||||
<string name="list_where">Dónde</string>
|
||||
<string name="list_where_device">Sólo en este dispositivo</string>
|
||||
<string name="list_read_only">Esta lista se comparte contigo en modo de sólo lectura, por lo que su nombre y color sólo pueden ser modificados por el propietario.</string>
|
||||
<string name="list_delete_confirm_message_synced">«%1$s» y todas sus tareas se eliminarán del servidor y de cualquier otro dispositivo que haya iniciado sesión en esta cuenta. Esta acción no se puede deshacer.</string>
|
||||
<string name="list_save_failed_server">El servidor no aceptaría ese cambio.</string>
|
||||
<string name="list_save_failed_offline">No se pudo conectar con el servidor. Inténtalo de nuevo cuando vuelvas a tener conexión a internet.</string>
|
||||
<string name="list_save_failed_read_only">Esa lista se comparte contigo en modo de sólo lectura.</string>
|
||||
<string name="list_save_failed_unsupported">Esa cuenta no permite que las aplicaciones creen listas de tareas.</string>
|
||||
<string name="list_delete_confirm_message">«%1$s» y todas sus tareas se eliminarán. Esta acción no se puede deshacer.</string>
|
||||
<string name="list_color_mauve">Malva</string>
|
||||
<string name="list_color_red">Rojo</string>
|
||||
<string name="list_color_orange">Naranja</string>
|
||||
<string name="list_color_amber">Ámbar</string>
|
||||
<string name="list_color_olive">Oliva</string>
|
||||
<string name="list_color_green">Verde</string>
|
||||
<string name="list_color_teal">Turquesa</string>
|
||||
<string name="list_color_cyan">Cian</string>
|
||||
<string name="list_color_blue">Azul</string>
|
||||
<string name="list_color_indigo">Índigo</string>
|
||||
<string name="list_color_purple">Púrpura</string>
|
||||
<string name="list_color_pink">Rosa</string>
|
||||
<string name="smart_today">Hoy</string>
|
||||
<string name="smart_overdue">Vencidas</string>
|
||||
<string name="smart_upcoming">Próximas</string>
|
||||
<string name="smart_all">Todas</string>
|
||||
<plurals name="home_today_progress_count">
|
||||
<item quantity="one">%1$d de %2$d hecha</item>
|
||||
<item quantity="many">%1$d de %2$d hechas</item>
|
||||
<item quantity="other">%1$d de %2$d hechas</item>
|
||||
</plurals>
|
||||
<plurals name="home_today_remaining_count">
|
||||
<item quantity="one">%1$d pendiente</item>
|
||||
<item quantity="many">%1$d pendientes</item>
|
||||
<item quantity="other">%1$d pendientes</item>
|
||||
</plurals>
|
||||
<string name="home_today_all_done">¡Listo! 🎉</string>
|
||||
<string name="home_today_empty">Hoy no hay nada pendiente 🎉</string>
|
||||
<string name="home_upcoming_view_all">Ver todo</string>
|
||||
<string name="home_due_today">Hoy</string>
|
||||
<string name="home_due_tomorrow">Mañana</string>
|
||||
<string name="home_search_hint">Buscar tareas</string>
|
||||
<string name="home_search_clear">Borrar búsqueda</string>
|
||||
</resources>
|
||||
@@ -189,7 +189,7 @@
|
||||
<string name="reminder_at_time">%1$s en %2$s</string>
|
||||
<string name="reminder_anchor_start">Dende o inicio</string>
|
||||
<string name="reminder_anchor_due">Dende a data de vencemento</string>
|
||||
<string name="reminder_time">Tempo</string>
|
||||
<string name="reminder_time">Hora</string>
|
||||
<string name="subtask_progress">%1$d / %2$d</string>
|
||||
<string name="progress_fraction_compact">%1$d/%2$d</string>
|
||||
<string name="detail_delete_title">Eliminar tarefa?</string>
|
||||
@@ -271,4 +271,695 @@
|
||||
<string name="smart_overdue">Vencida</string>
|
||||
<string name="smart_upcoming">Próxima</string>
|
||||
<string name="smart_all">Todo</string>
|
||||
<plurals name="home_today_progress_count">
|
||||
<item quantity="one">Feito %1$d de %2$d</item>
|
||||
<item quantity="other">Feitos %1$d de %2$d</item>
|
||||
</plurals>
|
||||
<plurals name="home_today_remaining_count">
|
||||
<item quantity="one">Queda %1$d</item>
|
||||
<item quantity="other">Quedan %1$d</item>
|
||||
</plurals>
|
||||
<string name="home_today_all_done">Xa está 🎉</string>
|
||||
<string name="home_today_empty">Non hai nada pendente hoxe 🎉</string>
|
||||
<string name="home_upcoming_view_all">Ver todo</string>
|
||||
<string name="home_due_today">Hoxe</string>
|
||||
<string name="home_due_tomorrow">Mañá</string>
|
||||
<string name="home_search_hint">Procurar tarefas</string>
|
||||
<string name="home_search_clear">Limpar a busca</string>
|
||||
<string name="home_search_empty">Ningunha tarefa coincide con «%1$s»</string>
|
||||
<string name="reminder_due_at">Vence o %1$s</string>
|
||||
<string name="reminder_day_today">hoxe</string>
|
||||
<string name="reminder_day_tomorrow">mañá</string>
|
||||
<string name="reminder_day_yesterday">onte</string>
|
||||
<string name="reminder_action_done">Feito</string>
|
||||
<string name="reminder_action_snooze">Adiar %1$d min</string>
|
||||
<string name="reminder_channel_name">Recordatorios de tarefas</string>
|
||||
<string name="reminder_channel_desc">Notificacións de tarefas con prazo vencido.</string>
|
||||
<string name="onboarding_no_provider_title">Faise necesaria unha aplicación de tarefas</string>
|
||||
<string name="onboarding_no_provider_body">Escolleches manter as tarefas noutra aplicación, pero non hai ningunha compatible instalada. Instala OpenTasks ou tasks.org, ou volve empregar a almacenaxe propio de Agendula.</string>
|
||||
<string name="onboarding_permission_title">Permitir o acceso ás túas tarefas</string>
|
||||
<string name="onboarding_permission_body">Agendula precisa permiso para ler e escribir as túas tarefas. É o único que solicita.</string>
|
||||
<string name="onboarding_permission_button">Garantir acceso á tarefa</string>
|
||||
<string name="onboarding_welcome_title">Todo o que tiñas intención de facer</string>
|
||||
<string name="onboarding_welcome_body">Un espazo apracíbel para as túas tarefas, nun teléfono que segue sendo teu. Imos configuralo; só leva un minuto.</string>
|
||||
<string name="onboarding_welcome_button">Comezar</string>
|
||||
<string name="onboarding_welcome_lists_title">Listas e tarefas secundarias</string>
|
||||
<string name="onboarding_welcome_lists_body">Manter separados o traballo, o fogar e os proxectos, e divide os grandes en partes máis pequenas.</string>
|
||||
<string name="onboarding_welcome_reminders_title">Recordatorios que chegan</string>
|
||||
<string name="onboarding_welcome_reminders_body">Unha notificación cando algo vence, segundo o teu calendario.</string>
|
||||
<string name="onboarding_welcome_sync_title">O teu servidor, ou ningún</string>
|
||||
<string name="onboarding_welcome_sync_body">Sincroniza mediante CalDAV cun servidor que elixas, ou mantén todo neste dispositivo.</string>
|
||||
<string name="onboarding_welcome_offline_title">Sen internet, por deseño</string>
|
||||
<string name="onboarding_welcome_offline_body">Esta versión de Agendula non ten acceso á rede, polo que non se pode sincronizar nin conectar a nada por si mesma.</string>
|
||||
<string name="onboarding_sync_title">Sincronizar co teu propio servidor?</string>
|
||||
<string name="onboarding_sync_body">Agendula emprega CalDAV: Nextcloud, Radicale, Posteo, Fastmail e calquera outra opción que o empregue. Sen ningunha conta nosa, nunca.</string>
|
||||
<string name="onboarding_sync_connect">Conectar unha conta</string>
|
||||
<string name="onboarding_sync_skip">Agora non</string>
|
||||
<string name="onboarding_sync_devices_title">Todos os dispositivos á vez</string>
|
||||
<string name="onboarding_sync_devices_body">Marca algo aquí e quedará marcado en todas partes.</string>
|
||||
<string name="onboarding_sync_copy_title">Unha copia que sobrevive ao teléfono</string>
|
||||
<string name="onboarding_sync_copy_body">As túas tarefas tamén residen no servidor; polo tanto, a perda dun dispositivo non supón a perda do traballo.</string>
|
||||
<string name="onboarding_sync_yours_title">A túa elección</string>
|
||||
<string name="onboarding_sync_yours_body">Autoaloxado ou un provedor ao que xa pagas: Agendula só almacena o contrasinal.</string>
|
||||
<string name="onboarding_list_title">A túa primeira lista</string>
|
||||
<string name="onboarding_list_body">As listas manteñen as cousas separadas. Comeza cunha; podes engadir máis e renomear esta en calquera intre.</string>
|
||||
<string name="onboarding_list_default_name">Persoal</string>
|
||||
<string name="onboarding_list_create">Crear lista</string>
|
||||
<string name="onboarding_backup_title">Manter unha copia</string>
|
||||
<string name="onboarding_backup_body_later">Sen unha conta, as túas listas só residen neste dispositivo. Podes gardalas como ficheiros iCalendar —que calquera outra aplicación de tarefas ou calendario pode ler— en calquera momento, desde Configuración → Copia de seguridade e restauración → Exportar.</string>
|
||||
<string name="onboarding_backup_continue">Continuar</string>
|
||||
<string name="onboarding_quick_add_title">Como queres engadir tarefas?</string>
|
||||
<string name="onboarding_quick_add_bar">Barra de adición rápida</string>
|
||||
<string name="onboarding_quick_add_bar_hint">Un campo ao final de cada lista: escribe, preme Intro, continúa coa seguinte.</string>
|
||||
<string name="onboarding_quick_add_button">Botón de nova tarefa</string>
|
||||
<string name="onboarding_quick_add_button_hint">Un botón flotante que abre o formulario completo.</string>
|
||||
<string name="onboarding_quick_add_done">Rematar</string>
|
||||
<string name="reminder_onboarding_title">Mantén as túas tarefas baixo control</string>
|
||||
<string name="reminder_onboarding_body">Agendula avísache cando chega o momento de facer algo, para que non teñas que gardar nada na cabeza.</string>
|
||||
<string name="reminder_onboarding_enable_button">Activar recordatorios</string>
|
||||
<string name="reminder_onboarding_skip_button">Agora non</string>
|
||||
<string name="reminder_benefit_delivery_title">Un empurrón cando importa</string>
|
||||
<string name="reminder_benefit_delivery_body">Cada tarefa cunha data límite recibe a súa propia notificación.</string>
|
||||
<string name="reminder_benefit_timing_title">Segundo o teu horario</string>
|
||||
<string name="reminder_benefit_timing_body">Escolle con canta antelación queres recibir os recordatorios: para todo ou por lista.</string>
|
||||
<string name="reminder_benefit_reversible_title">Cámbiao en calquera intre</string>
|
||||
<string name="reminder_benefit_reversible_body">Desactiva os recordatorios cando queiras; só tes que accionar un interruptor.</string>
|
||||
<string name="onboarding_exact_alarms_title">Xusto a tempo</string>
|
||||
<string name="onboarding_exact_alarms_body">Android solicita permiso antes de que unha aplicación poida enviarte unha notificación nun minuto exacto. Se o concedes, os recordatorios chegarán no momento preciso; sen el, poderían atrasarse uns minutos.</string>
|
||||
<string name="onboarding_exact_alarms_allow">Permitir unha temporización exacta</string>
|
||||
<string name="settings_title">Configuración</string>
|
||||
<string name="settings_group_look">Aspecto e comportamento</string>
|
||||
<string name="settings_group_data">Datos</string>
|
||||
<string name="settings_group_app">Aplicación</string>
|
||||
<string name="settings_group_about">En canto a</string>
|
||||
<string name="settings_section_appearance">Aparencia</string>
|
||||
<string name="settings_appearance_subtitle">Tema, cores, formato da hora</string>
|
||||
<string name="settings_section_task_form">Formulario de nova tarefa</string>
|
||||
<string name="settings_task_form_subtitle">Campos e comportamento predeterminados</string>
|
||||
<string name="settings_reminders_subtitle">Recordatorios e entrega</string>
|
||||
<string name="settings_form_fields_hint">Campos que se mostran de forma predeterminada nunha tarefa nova. O resto atópanse detrás de \"Máis campos\".</string>
|
||||
<string name="settings_dynamic_color_unavailable">Dispoñible en Android 12 e versións posteriores</string>
|
||||
<string name="settings_autofocus_title">Centrar no título na nova tarefa</string>
|
||||
<string name="settings_autofocus_title_hint">Cando inicies unha tarefa nova, coloca o cursor no título e abre o teclado decontado.</string>
|
||||
<string name="settings_time_format">Formato da hora</string>
|
||||
<string name="settings_time_format_auto">Automático</string>
|
||||
<string name="settings_time_format_12h">12-horas (2:00 PM)</string>
|
||||
<string name="settings_time_format_24h">24-horas (14:00)</string>
|
||||
<string name="settings_time_format_auto_summary">Segundo o sistema: %1$s</string>
|
||||
<string name="settings_week_start">A semana comeza no</string>
|
||||
<string name="settings_week_start_auto">Automático</string>
|
||||
<string name="settings_week_start_auto_summary">Actualmente %1$s</string>
|
||||
<string name="settings_about_author">por Jean-Luc Makiola</string>
|
||||
<string name="settings_about_source">Fonte</string>
|
||||
<string name="settings_license">Licenza</string>
|
||||
<string name="settings_about_support">Apoiar o desenvolvemento</string>
|
||||
<string name="settings_licences">Licenzas de código aberto</string>
|
||||
<string name="settings_licences_subtitle">Os proxectos sobre os que se basea Agendula</string>
|
||||
<string name="licences_title">Licenzas de código aberto</string>
|
||||
<string name="licences_intro">Agendula inclúe o traballo que aparece a continuación. Preme en calquera entrada para obter o seu código fonte.</string>
|
||||
<string name="licences_footer">Parte deste código inclúese de forma modificada. Cando é o caso, todos os cambios figuran no repositorio de código fonte ligado arriba.</string>
|
||||
<string name="settings_privacy">Política de privacidade</string>
|
||||
<string name="settings_about_version">Versión %1$s</string>
|
||||
<string name="settings_about_logo_desc">Icona da aplicación Agendula</string>
|
||||
<string name="settings_language">Idioma da aplicación</string>
|
||||
<string name="settings_language_auto">Predeterminado do sistema</string>
|
||||
<string name="settings_translate">Axuda a traducir</string>
|
||||
<string name="settings_translate_hint">Engadir ou mellorar un idioma en Weblate</string>
|
||||
<string name="settings_report_problem">Informar dun problema</string>
|
||||
<string name="settings_report_problem_hint">Abrir o xestor de incidencias</string>
|
||||
<string name="crash_report_issue_title">Informe de erro</string>
|
||||
<string name="settings_theme">Tema</string>
|
||||
<string name="settings_theme_system">Segundo o sistema</string>
|
||||
<string name="settings_theme_light">Claro</string>
|
||||
<string name="settings_theme_dark">Escuro</string>
|
||||
<string name="settings_theme_black">Negro</string>
|
||||
<string name="settings_theme_black_summary">Escuro con fondos de cor negra pura, para pantallas AMOLED</string>
|
||||
<string name="settings_app_name">Nome da aplicación</string>
|
||||
<string name="settings_app_name_hint">Amosar Agendula como «Tarefas» no teu lanzador. Só cambia o nome no lanzador; a icona podería desprazarse a outra posición. Agendula péchase ao realizar o cambio, así que ábrea de novo dende o lanzador.</string>
|
||||
<string name="settings_dynamic_color">Cor dinámica</string>
|
||||
<string name="settings_dynamic_color_hint">Empregar as cores do teu fondo de pantalla</string>
|
||||
<string name="settings_section_reminders">Notificacións</string>
|
||||
<string name="settings_reminders">Recordatorios de tarefa</string>
|
||||
<string name="settings_reminders_hint">Notifícame cando venza unha tarefa</string>
|
||||
<string name="settings_notifications_blocked">As notificacións están desactivadas</string>
|
||||
<string name="settings_notifications_blocked_hint">Os recordatorios non poden chegar a ti. Premer para permitir as notificacións de Agendula.</string>
|
||||
<string name="settings_default_reminder">Recordatorio predeterminado</string>
|
||||
<string name="upcoming_range_title">Amosar tarefas con vencemento dentro de</string>
|
||||
<string name="upcoming_range_all">En calquera intre</string>
|
||||
<string name="upcoming_range_week">A vindeira semana</string>
|
||||
<string name="upcoming_range_two_weeks">As vindeiras 2 semanas</string>
|
||||
<string name="upcoming_range_month">O vindeiro mes</string>
|
||||
<string name="upcoming_range_three_months">Os vindeiros 3 meses</string>
|
||||
<string name="upcoming_range_year">O vindeiro ano</string>
|
||||
<string name="upcoming_range_empty">Non hai nada pendente neste período. Amplía o intervalo nas opcións de visualización.</string>
|
||||
<string name="group_title">Agrupar por</string>
|
||||
<string name="group_due">Data de vencemento</string>
|
||||
<string name="group_due_summary">Atrasado, hoxe, próximo</string>
|
||||
<string name="group_day">Día</string>
|
||||
<string name="group_day_summary">Un grupo para cada día</string>
|
||||
<string name="group_priority">Prioridade</string>
|
||||
<string name="group_priority_summary">Alta prioridade primeiro</string>
|
||||
<string name="group_list">Lista</string>
|
||||
<string name="group_list_summary">Un grupo para cada lista</string>
|
||||
<string name="group_tomorrow">Mañá</string>
|
||||
<string name="group_priority_high">Prioridade alta</string>
|
||||
<string name="group_priority_medium">Prioridade media</string>
|
||||
<string name="group_priority_low">Prioridade baixa</string>
|
||||
<string name="group_priority_none">Sen prioridade</string>
|
||||
<string name="group_list_unnamed">Lista sen nome</string>
|
||||
<string name="group_list_in_account">%1$s (%2$s)</string>
|
||||
<string name="picker_section_date">Data</string>
|
||||
<string name="picker_section_time">Hora</string>
|
||||
<string name="picker_date_today">Hoxe</string>
|
||||
<string name="picker_date_tomorrow">Mañá</string>
|
||||
<string name="picker_date_next_week">A vindeira semana</string>
|
||||
<string name="picker_date_pick">Escolle unha data</string>
|
||||
<string name="picker_time_morning">Mañá</string>
|
||||
<string name="picker_time_noon">Mediodía</string>
|
||||
<string name="picker_time_afternoon">Serán</string>
|
||||
<string name="picker_time_evening">Noitiña</string>
|
||||
<string name="picker_time_custom">Hora personalizada</string>
|
||||
<string name="picker_time_none">Sen hora</string>
|
||||
<string name="picker_time_linked_due">A túa aplicación de tarefas mantén un único axuste de horario para ambas as datas, polo que a data de vencemento adquire ou perde un horario xunto con esta</string>
|
||||
<string name="picker_time_linked_start">A túa aplicación de tarefas mantén un único axuste de horario para ambas as datas, polo que a data de inicio adquire ou perde un horario xunto con esta</string>
|
||||
<string name="picker_done">Feito</string>
|
||||
<string name="recurrence_repeat_from">Repetir dende</string>
|
||||
<string name="recurrence_from_due">Data de vencemento</string>
|
||||
<string name="recurrence_from_due_summary">Mantén o horario, por moi tarde que remates</string>
|
||||
<string name="recurrence_from_completion">Data de finalización</string>
|
||||
<string name="recurrence_from_completion_summary">A seguinte data cóntase a partir do día en que a marcas</string>
|
||||
<string name="recurrence_from_completion_note">Repítese a partir da data de vencemento</string>
|
||||
<string name="list_delete_failed_account_home">Esa lista é o propio calendario da conta.</string>
|
||||
<string name="list_delete_account_home">Esta lista é o propio calendario da conta, polo que non se pode eliminar dende aquí. Eliminala suporía tamén borrar os eventos do calendario.</string>
|
||||
<string name="task_search_action">Procurar nesta lista</string>
|
||||
<string name="task_search_hint">Procura ou engadir unha tarefa</string>
|
||||
<string name="task_search_prompt">Atopa calquera tarefa nesta lista, incluídas as completadas. Se aínda non está, engádea desde aquí.</string>
|
||||
<string name="task_search_add">Engadir «%1$s»</string>
|
||||
<string name="task_search_open">Abrir</string>
|
||||
<string name="task_search_added">Engadida «%1$s»</string>
|
||||
<string name="task_search_reopened">Reabriu «%1$s»</string>
|
||||
<string name="task_search_already_open">«%1$s» xa está aberta</string>
|
||||
<string name="settings_allday_reminder_time">Hora do recordatorio para todo o día</string>
|
||||
<string name="settings_allday_reminder_time_summary">As tarefas de todo o día contan cara atrás dende %1$s</string>
|
||||
<string name="settings_default_reminder_allday">Tarefas de todo o día</string>
|
||||
<string name="settings_allday_reminder_fires_at">Notifica ás %1$s</string>
|
||||
<string name="settings_exact_alarms">Momento exacto</string>
|
||||
<string name="settings_exact_alarms_allowed">Os recordatorios actívanse no momento exacto</string>
|
||||
<string name="settings_exact_alarms_blocked">Bloqueado — preme para permitir recordatorios exactos</string>
|
||||
<string name="settings_reliable_delivery">Entrega fiábel</string>
|
||||
<string name="settings_snooze_duration">Duración da pospoñición</string>
|
||||
<string name="settings_persistent_reminders">Recordatorios persistentes</string>
|
||||
<string name="settings_persistent_reminders_hint">Un recordatorio descartado volve aparecer ata que marcas a tarefa como completada ou a pospoñas</string>
|
||||
<string name="settings_list_persistent_on">Persistente</string>
|
||||
<string name="settings_list_persistent_off">Non persistente</string>
|
||||
<string name="settings_list_persistent_on_summary">Os recordatorios eliminados volven aparecer</string>
|
||||
<string name="settings_list_persistent_off_summary">Os recordatorios eliminados por un esvaramento permanecen eliminados</string>
|
||||
<plurals name="settings_list_persistent_own_count">
|
||||
<item quantity="one">%1$d lista establece a súa propia persistencia</item>
|
||||
<item quantity="other">%1$d listas establecen a súa propia persistencia</item>
|
||||
</plurals>
|
||||
<string name="settings_reliable_delivery_hint">Android pode atrasar os recordatorios para aforrar batería. Exclúe Agendula para que cheguen a tempo.</string>
|
||||
<string name="settings_reliable_delivery_exempt">Exento da optimización da batería: os recordatorios chegan a tempo.</string>
|
||||
<string name="settings_reminder_description">Descrición nos recordatorios</string>
|
||||
<string name="settings_remind_past_on_save">Lembrar inmediatamente cando pase</string>
|
||||
<string name="settings_remind_past_on_save_hint">Ao gardar unha tarefa cuxa hora de recordatorio xa pasou, envíase unha notificación decontado no lugar de omitila</string>
|
||||
<string name="settings_reminder_description_hidden">Agochado</string>
|
||||
<string name="settings_reminder_description_short">Curta</string>
|
||||
<string name="settings_reminder_description_full">Completa</string>
|
||||
<string name="settings_reminder_description_hidden_summary">Só o título e o prazo</string>
|
||||
<string name="settings_reminder_description_short_summary">Unha breve vista previa da descrición</string>
|
||||
<string name="settings_reminder_description_full_summary">A descrición completa</string>
|
||||
<string name="settings_default_list">Lista predeterminada</string>
|
||||
<string name="settings_default_list_first">A primeira lista dispoñible</string>
|
||||
<string name="settings_add_subtask_row">Amosar a fila «engadir unha tarefa secundaria»</string>
|
||||
<string name="settings_add_subtask_row_hint">Un campo de engadido ao final das tarefas secundarias dunha tarefa expandida</string>
|
||||
<string name="settings_default_due_date">Data de vencemento predeterminada</string>
|
||||
<string name="settings_default_due_none">Sen data de vencemento</string>
|
||||
<string name="settings_default_due_today">Hoxe</string>
|
||||
<string name="settings_default_due_tomorrow">Mañá</string>
|
||||
<string name="settings_default_due_day_after_tomorrow">Pasadomañá</string>
|
||||
<string name="settings_default_due_next_week">Nunha semana</string>
|
||||
<string name="settings_default_due_next_month">Nun mes</string>
|
||||
<string name="settings_default_start_date">Data de inicio predeterminada</string>
|
||||
<string name="settings_default_start_none">Sen data de inicio</string>
|
||||
<string name="settings_default_start_today_option">Hoxe</string>
|
||||
<string name="settings_default_start_due_date">Na data de vencemento</string>
|
||||
<string name="settings_default_start_day_before_due">Un día antes da data de vencemento</string>
|
||||
<string name="settings_default_start_week_before_due">Unha semana antes da data de vencemento</string>
|
||||
<string name="settings_default_start_needs_due">Só para unha tarefa cunha data de vencemento</string>
|
||||
<string name="settings_default_start_without_due">%1$s · só para unha tarefa cunha data de vencemento</string>
|
||||
<string name="settings_bottom_add_bar">Barra inferior de engadido rápido</string>
|
||||
<string name="settings_bottom_add_bar_hint">Engadir tarefas dende unha barra fixada na parte inferior dunha lista, no lugar de empregar o botón flotante</string>
|
||||
<string name="onboarding_use_own_store">Empregar a almacenaxe deste dispositivo no seu lugar</string>
|
||||
<string name="settings_section_storage">Almacenaxe</string>
|
||||
<string name="settings_storage_subtitle">Onde se gardan as túas tarefas</string>
|
||||
<string name="settings_section_backup">Copia de seguridade e restauración</string>
|
||||
<string name="settings_backup_subtitle">Exportación, importación e copia de seguridade automática</string>
|
||||
<string name="settings_task_store">Almacenaxe de tarefas</string>
|
||||
<string name="settings_task_store_hint">Cada almacenaxe mantén as súas propias tarefas. Ao cambiar de almacenaxe, estas non se trasladan automaticamente; cópieas primeiro ou expórteas dende a opción de copia de seguridade e restauración.</string>
|
||||
<string name="settings_store_own">Neste dispositivo</string>
|
||||
<string name="settings_store_own_hint">Almacenaxe propia de Agendula. Non hai que instalar nada máis.</string>
|
||||
<string name="settings_store_external">Outra aplicación de tarefas</string>
|
||||
<string name="settings_store_external_hint">Comparte as tarefas coa aplicación que as sincroniza</string>
|
||||
<string name="settings_store_external_missing">Non hai ningunha aplicación de tarefas compatible instalada</string>
|
||||
<string name="settings_store_permission_denied">Permiso denegado</string>
|
||||
<string name="settings_store_permission_denied_hint">As tarefas da outra aplicación permanecen inaccesibles ata que permitas o acceso. Preme para abrir a configuración da aplicación.</string>
|
||||
<string name="settings_store_switch_title">Cambiar de almacén de tarefas?</string>
|
||||
<string name="settings_store_switch_to_own">As túas tarefas permanecen en %1$s; non se moven. Agendula amosará a súa propia almacenaxe, que ao principio está baleiro, de non ser que copies nel os elementos.</string>
|
||||
<string name="settings_store_switch_to_external">As túas tarefas permanecen en %1$s; non se moven. No seu lugar, Agendula amosará as tarefas da outra aplicación.</string>
|
||||
<string name="settings_store_switch_confirm">Cambiar</string>
|
||||
<string name="settings_copy_from_external">Copiar as tarefas de %1$s</string>
|
||||
<string name="settings_copy_from_external_hint">Lévaos á propia almacenaxe de Agendula. Trátase dunha copia puntual; os orixinais permanecen onde están.</string>
|
||||
<string name="settings_copy_confirm_title">Copiar as tarefas?</string>
|
||||
<string name="settings_copy_counting">Contando o que hai que copiar…</string>
|
||||
<string name="settings_copy_confirm_empty">%1$s non contén tarefas para copiar.</string>
|
||||
<plurals name="settings_copy_confirm_message">
|
||||
<item quantity="one">%1$d tarefa de %2$s copiarase na almacenaxe propia de Agendula. Os orixinais permanecen onde están e, a partir de agora, ambos os dous deixan de estar sincronizados; por iso, esta opción ofrécese unha soa vez.</item>
|
||||
<item quantity="other">%1$d tarefas de %2$s copiaranse na almacenaxe propia de Agendula. Os orixinais permanecen onde están e, a partir de agora, ambos os dous deixan de estar sincronizados; por iso, esta opción ofrécese unha soa vez.</item>
|
||||
</plurals>
|
||||
<string name="settings_copy_confirm_action">Copiar</string>
|
||||
<string name="settings_copy_running">Copiando tarefas…</string>
|
||||
<plurals name="settings_copy_done">
|
||||
<item quantity="one">Copiouse %1$d tarefa na lista %2$d. Selecciona «Neste dispositivo» arriba para velas.</item>
|
||||
<item quantity="other">Copiáronse %1$d tarefas na lista %2$d. Selecciona «Neste dispositivo» arriba para velas.</item>
|
||||
</plurals>
|
||||
<string name="settings_copy_nothing">Non había nada que copiar</string>
|
||||
<string name="settings_copy_failed">Non foi posible copiar as tarefas. Non se modificou nada; os teus orixinais permanecen intactos.</string>
|
||||
<string name="settings_legacy_import_failed">As túas tarefas anteriores non se puideron mover</string>
|
||||
<string name="settings_legacy_import_failed_hint">Seguen gardados e non se perdeu nada. Preme para tentar movelos de novo.</string>
|
||||
<string name="settings_legacy_import_retrying">Movéndoos agora…</string>
|
||||
<string name="settings_export">Exportar tarefas</string>
|
||||
<string name="settings_export_hint">Garda as túas listas como ficheiros iCalendar</string>
|
||||
<string name="export_hint">Un ficheiro .ics por lista, lexible por outras aplicacións de tarefas e calendarios. As listas seleccionadas gárdanse nun cartafol que elixas, ou nun único ficheiro zip.</string>
|
||||
<string name="export_no_lists">Non hai listas para exportar</string>
|
||||
<string name="export_to_folder">Gardar nun cartafol</string>
|
||||
<string name="export_to_zip">Gardar como ficheiro zip</string>
|
||||
<string name="export_running">Exportando…</string>
|
||||
<string name="export_open">Abrir</string>
|
||||
<plurals name="add_account_summary_lists">
|
||||
<item quantity="one">Sincronizando %1$d lista</item>
|
||||
<item quantity="other">Sincronizando %1$d listas</item>
|
||||
</plurals>
|
||||
<plurals name="export_done">
|
||||
<item quantity="one">Exportada %1$d lista</item>
|
||||
<item quantity="other">Exportadas %1$d listas</item>
|
||||
</plurals>
|
||||
<string name="export_failed">Non foi posible escribir a exportación</string>
|
||||
<string name="export_failed_folder">Non foi posible abrir o cartafol escollido</string>
|
||||
<string name="export_failed_read_only">Non é posible escribir no cartafol escollido</string>
|
||||
<string name="export_failed_create">Non foi posible crear un ficheiro no cartafol escollido</string>
|
||||
<string name="export_failed_access">Perdeuse o acceso á localización escollida</string>
|
||||
<string name="backup_auto_header">Copia de seguridade automática</string>
|
||||
<string name="backup_auto">Facer copias de seguridade automaticamente</string>
|
||||
<string name="backup_auto_hint">Garda todas as túas listas nun ficheiro zip con data, nun cartafol que ti elixas. Restaura unha delas por medio da opción de importar tarefas.</string>
|
||||
<string name="backup_auto_folder">Cartafol</string>
|
||||
<string name="backup_auto_folder_unset">Escoller un cartafol</string>
|
||||
<string name="backup_auto_folder_rejected">Ese cartafol non se pode usar para copias de seguridade en segundo plano. Escolle outro.</string>
|
||||
<string name="backup_auto_interval">Frecuencia</string>
|
||||
<string name="backup_auto_interval_hint">Android pode facer unha copia de seguridade un pouco máis tarde para aforrar batería.</string>
|
||||
<plurals name="backup_every_hours">
|
||||
<item quantity="one">Cada hora</item>
|
||||
<item quantity="other">Cada %1$d horas</item>
|
||||
</plurals>
|
||||
<plurals name="backup_every_days">
|
||||
<item quantity="one">Cada día</item>
|
||||
<item quantity="other">Cada %1$d días</item>
|
||||
</plurals>
|
||||
<plurals name="backup_every_weeks">
|
||||
<item quantity="one">Cada semana</item>
|
||||
<item quantity="other">Cada %1$d semanas</item>
|
||||
</plurals>
|
||||
<string name="backup_auto_keep">Copias de seguridade a conservar</string>
|
||||
<string name="backup_auto_keep_hint">Unha vez que se garda unha nova copia de seguridade, as anteriores que haxa no cartafol elimínanse. Os demais ficheiros que alí se atopen permanecen intactos.</string>
|
||||
<plurals name="backup_keep_count">
|
||||
<item quantity="one">Só o máis recente</item>
|
||||
<item quantity="other">Os %1$d últimos</item>
|
||||
</plurals>
|
||||
<string name="backup_auto_now">Facer unha copia de seguridade agora</string>
|
||||
<string name="backup_auto_status_running">Facendo copia de seguridade…</string>
|
||||
<string name="backup_auto_status_never">Aínda non hai copia de seguridade</string>
|
||||
<string name="backup_auto_status_ok">Última copia de seguridade %1$s</string>
|
||||
<string name="backup_auto_status_failed">A copia de seguridade fallou %1$s. %2$s</string>
|
||||
<string name="backup_auto_status_failed_last_ok">A copia de seguridade fallou %1$s. %2$s. Última copia de seguridade correcta %3$s</string>
|
||||
<string name="backup_failed_read">Non foi posible ler as túas tarefas</string>
|
||||
<string name="backup_failed_no_lists">Non había listas para facer copias de seguridade</string>
|
||||
<string name="backup_channel_name">Copia de seguridade automática</string>
|
||||
<string name="backup_channel_description">Cando as copias de seguridade automáticas erran constantemente</string>
|
||||
<string name="backup_failed_title">Fallou a copia de seguridade automática</string>
|
||||
<string name="backup_failed_text">Non se están a facer copias de seguridade das túas tarefas. Toca para ver por que.</string>
|
||||
<string name="import_title">Importar tarefas</string>
|
||||
<string name="settings_import_hint">Importar tarefas dende un ficheiro iCalendar</string>
|
||||
<string name="import_hint">Escolle un ficheiro .ics, ou un ficheiro zip que os conteña —tal como se xeran na exportación—. Inclúense as repeticións, as subtarefas e todo o demais que levan asociado as tarefas. As tarefas que xa estean na lista elixida ignoraranse.</string>
|
||||
<string name="import_own_store_only">A importación garda os datos no propio almacenaxe de Agendula. Para realizar a importación, cambia o lugar de almacenaxe das tarefas a «Neste dispositivo».</string>
|
||||
<string name="import_open_storage">Almacenaxe</string>
|
||||
<string name="import_pick">Escoller un ficheiro</string>
|
||||
<string name="import_pick_other">Escolle outro ficheiro</string>
|
||||
<string name="import_pick_another">Importar outro ficheiro</string>
|
||||
<string name="import_reading">Lendo o ficheiro…</string>
|
||||
<string name="import_running">Importando…</string>
|
||||
<string name="import_picked_file">Ficheiro escollido</string>
|
||||
<plurals name="import_found">
|
||||
<item quantity="one">%1$d tarefa</item>
|
||||
<item quantity="other">%1$d tarefas</item>
|
||||
</plurals>
|
||||
<plurals name="import_events_left_out">
|
||||
<item quantity="one">%1$d evento do calendario omitido</item>
|
||||
<item quantity="other">%1$d eventos do calendario omitidos</item>
|
||||
</plurals>
|
||||
<string name="import_target_label">Importar en</string>
|
||||
<string name="import_new_list">Nova lista: %1$s</string>
|
||||
<string name="import_new_list_hint">Unha nova lista neste dispositivo</string>
|
||||
<string name="import_new_list_default_name">Tarefas importadas</string>
|
||||
<string name="import_button">Importar</string>
|
||||
<plurals name="import_done">
|
||||
<item quantity="one">Importouse %1$d tarefa en %2$s</item>
|
||||
<item quantity="other">Importáronse %1$d tarefas en %2$s</item>
|
||||
</plurals>
|
||||
<plurals name="import_done_skipped_existing">
|
||||
<item quantity="one">%1$d xa presente, omitido</item>
|
||||
<item quantity="other">%1$d xa presentes, omitidos</item>
|
||||
</plurals>
|
||||
<string name="import_failed_unreadable">Non foi posible ler o ficheiro como iCalendar</string>
|
||||
<string name="import_failed_no_tasks">O ficheiro non contén tarefas</string>
|
||||
<string name="import_failed_write">Non se puideron gardar as tarefas</string>
|
||||
<plurals name="duration_minutes">
|
||||
<item quantity="one">%d minuto</item>
|
||||
<item quantity="other">%d minutos</item>
|
||||
</plurals>
|
||||
<plurals name="duration_hours">
|
||||
<item quantity="one">%d hora</item>
|
||||
<item quantity="other">%d horas</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_minutes">
|
||||
<item quantity="one">%1$d minuto antes</item>
|
||||
<item quantity="other">%1$d minutos antes</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_hours">
|
||||
<item quantity="one">%1$d hora antes</item>
|
||||
<item quantity="other">%1$d horas antes</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_days">
|
||||
<item quantity="one">%1$d día antes</item>
|
||||
<item quantity="other">%1$d días antes</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_weeks">
|
||||
<item quantity="one">%1$d semana antes</item>
|
||||
<item quantity="other">%1$d semanas antes</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_minutes_before_start">
|
||||
<item quantity="one">%1$d minuto antes do comezo</item>
|
||||
<item quantity="other">%1$d minutos antes do comezo</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_hours_before_start">
|
||||
<item quantity="one">%1$d hora antes do comezo</item>
|
||||
<item quantity="other">%1$d horas antes do comezo</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_days_before_start">
|
||||
<item quantity="one">%1$d día antes do comezo</item>
|
||||
<item quantity="other">%1$d días antes do comezo</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_weeks_before_start">
|
||||
<item quantity="one">%1$d semana antes do comezo</item>
|
||||
<item quantity="other">%1$d semanas antes do comezo</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_minutes_before_due">
|
||||
<item quantity="one">%1$d minuto antes da data de vencemento</item>
|
||||
<item quantity="other">%1$d minutos antes da data de vencemento</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_hours_before_due">
|
||||
<item quantity="one">%1$d hora antes da data de vencemento</item>
|
||||
<item quantity="other">%1$d horas antes da data de vencemento</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_days_before_due">
|
||||
<item quantity="one">%1$d día antes da data de vencemento</item>
|
||||
<item quantity="other">%1$d días antes da data de vencemento</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_weeks_before_due">
|
||||
<item quantity="one">%1$d semana antes da data de vencemento</item>
|
||||
<item quantity="other">%1$d semanas antes da data de vencemento</item>
|
||||
</plurals>
|
||||
<string name="settings_section_accounts">Contas</string>
|
||||
<string name="settings_accounts_subtitle">Sincroniza as túas tarefas cun servidor CalDAV</string>
|
||||
<string name="accounts_empty_title">Aínda non hai contas</string>
|
||||
<string name="accounts_empty_body">Engade unha conta CalDAV e Agendula manterá as túas listas de tarefas sincronizadas con ela: Nextcloud, Radicale, Baïkal e calquera outra opción compatíbel con este protocolo.</string>
|
||||
<string name="accounts_add">Engadir unha conta</string>
|
||||
<string name="accounts_sync_interval">Sincronizar automaticamente</string>
|
||||
<string name="accounts_sync_interval_manual">Só cando sincronices</string>
|
||||
<string name="accounts_sync_interval_hint">A frecuencia con que cada conta se sincroniza nun segundo plano. Os cambios que fagas envíanse nun prazo dun minuto, en ambos os sentidos. Android pode ampliar este intervalo para aforrar batería.</string>
|
||||
<plurals name="accounts_sync_every_minutes">
|
||||
<item quantity="one">Cada %d minuto</item>
|
||||
<item quantity="other">Cada %d minutos</item>
|
||||
</plurals>
|
||||
<plurals name="accounts_sync_every_hours">
|
||||
<item quantity="one">Cada hora</item>
|
||||
<item quantity="other">Cada %d horas</item>
|
||||
</plurals>
|
||||
<string name="accounts_push">Push</string>
|
||||
<string name="accounts_push_off">Desactivado</string>
|
||||
<string name="accounts_push_via">Os cambios chegan ao instante, a través de %1$s</string>
|
||||
<plurals name="accounts_push_partial">
|
||||
<item quantity="one">Instantáneo para %1$d de %2$d lista, a través de %3$s</item>
|
||||
<item quantity="other">Instantáneo para %1$d de %2$d listas, a través de %3$s</item>
|
||||
</plurals>
|
||||
<string name="accounts_push_unsupported">O teu servidor aínda non ofrece envíos push</string>
|
||||
<string name="accounts_push_pending">Configurando a función push co teu servidor…</string>
|
||||
<string name="accounts_push_no_distributor">Instala unha aplicación UnifiedPush para obter cambios ao instante</string>
|
||||
<string name="accounts_push_choose">Escolle a aplicación que fai o envío</string>
|
||||
<string name="accounts_push_hint">Cunha aplicación UnifiedPush como ntfy instalada, os cambios realizados noutros dispositivos chegan en cuestión de segundos en lugar de na seguinte sincronización. O teu servidor ten que ofrecer WebDAV-Push; en Nextcloud, é dicir, a aplicación WebDAV Push.</string>
|
||||
<string name="accounts_push_none_installed">Non hai instalada ningunha aplicación UnifiedPush. Instala unha (por exemplo, ntfy, NextPush ou Sunup) e aparecerá aquí.</string>
|
||||
<string name="accounts_push_account_on">Os cambios chegan no instante</string>
|
||||
<plurals name="accounts_push_account_partial">
|
||||
<item quantity="one">Instantáneo para %1$d de %2$d lista</item>
|
||||
<item quantity="other">Instantáneo para %1$d de %2$d listas</item>
|
||||
</plurals>
|
||||
<string name="accounts_push_account_unsupported">Este servidor non ofrece envío push</string>
|
||||
<string name="accounts_remove">Eliminar a conta</string>
|
||||
<string name="accounts_remove_body">%1$s deixa de sincronizarse con este dispositivo. Non se elimina nada do servidor.</string>
|
||||
<string name="accounts_remove_keep">Eliminar, manter as tarefas</string>
|
||||
<string name="accounts_remove_keep_body">As súas listas permanecen neste dispositivo como listas exclusivas do dispositivo.</string>
|
||||
<string name="accounts_remove_wipe">Retira e elimina as tarefas</string>
|
||||
<string name="accounts_remove_wipe_body">Tamén elimina as listas e tarefas desta conta deste dispositivo.</string>
|
||||
<string name="accounts_never_synced">Nunca foi sincronizado</string>
|
||||
<string name="accounts_last_sync">Última sincronización</string>
|
||||
<string name="accounts_name">Nome</string>
|
||||
<string name="accounts_name_hint">Como se mostra esta conta en Agendula. Déixao baleiro para usar «%1$s».</string>
|
||||
<string name="accounts_connection">Conexión</string>
|
||||
<string name="accounts_connection_cleartext">Sen cifrar (http)</string>
|
||||
<string name="accounts_trusted_certificate">Certificado de confianza</string>
|
||||
<string name="accounts_generic_provider">Conta CalDAV</string>
|
||||
<string name="accounts_sync_failed">A última sincronización non rematou</string>
|
||||
<string name="accounts_failed_sign_in">A sincronización fallou: o servidor non aceptou o contrasinal</string>
|
||||
<string name="accounts_failed_unreachable">A sincronización fallou: non foi posible conectar co servidor</string>
|
||||
<string name="accounts_failed_certificate">A sincronización fallou: o certificado do servidor non é de confianza</string>
|
||||
<string name="accounts_failed_server">A sincronización fallou: o servidor informou dun erro</string>
|
||||
<string name="accounts_failed_server_code">A sincronización fallou: o servidor informou dun erro (%1$d)</string>
|
||||
<string name="accounts_failed_misconfigured">A sincronización fallou: a conta está incompleta; elimínaa e vólvea engadir</string>
|
||||
<string name="accounts_sync_now">Sincronizar agora</string>
|
||||
<string name="accounts_removing">Eliminando…</string>
|
||||
<string name="accounts_lists">Listas</string>
|
||||
<string name="accounts_lists_summary">Escolle as listas a sincronizar</string>
|
||||
<string name="accounts_lists_loading">Lendo listas dende o servidor…</string>
|
||||
<string name="accounts_lists_drop_title">Deixar de sincronizar listas</string>
|
||||
<string name="accounts_lists_drop_body">As listas que desmarcaches deixan de sincronizarse con este dispositivo. Non se elimina nada do servidor.</string>
|
||||
<string name="accounts_lists_drop_keep">Deixar de sincronizar, conservar as tarefas</string>
|
||||
<string name="accounts_lists_drop_keep_body">Permanecen neste dispositivo como listas exclusivas do dispositivo.</string>
|
||||
<string name="accounts_lists_drop_wipe">Deixar de sincronizar e eliminar as tarefas</string>
|
||||
<string name="accounts_lists_drop_wipe_body">Tamén eliminar esas listas e as súas tarefas deste dispositivo.</string>
|
||||
<string name="accounts_external_storage_title">As contas precisan do almacenaxe propio de Agendula</string>
|
||||
<string name="accounts_external_storage">As contas sincronízanse no almacenaxe propio de Agendula, o cal non se utiliza mentres as túas tarefas proveñan doutra aplicación. Podes cambialo en Configuración → Almacenaxe.</string>
|
||||
<string name="add_account_browser_failed_title">O inicio de sesión non rematou</string>
|
||||
<string name="add_account_step_of">Paso %1$d de %2$d</string>
|
||||
<string name="add_account_provider_title">Onde están as túas tarefas?</string>
|
||||
<string name="add_account_provider_body">Escolle o servizo onde residen as túas listas de tarefas. Agendula sincronízase con calquera sistema compatible con CalDAV.</string>
|
||||
<string name="add_account_provider_self_hosted">Ti executas o servidor</string>
|
||||
<string name="add_account_provider_unsupported">Non admite tarefas a través de CalDAV</string>
|
||||
<string name="add_account_provider_other_header">Calquera servidor CalDAV</string>
|
||||
<string name="add_account_provider_other">Outro servidor CalDAV</string>
|
||||
<string name="add_account_provider_other_summary">Baïkal, DAViCal, SOGo, Radicale ou un que xestiones ti mesmo</string>
|
||||
<string name="add_account_email_title">Cal é o teu enderezo alí?</string>
|
||||
<string name="add_account_email_body">O enderezo de correo electrónico que utilizas con este servizo. Agendula atopa o servidor por si mesma.</string>
|
||||
<string name="add_account_email_label">Enderezo de correo electrónico</string>
|
||||
<string name="add_account_summary_title">Xa o tes todo listo</string>
|
||||
<string name="add_account_summary_body">A partir de agora, Agendula manterá estas listas sincronizadas. Podes modificar o que se sincroniza na configuración.</string>
|
||||
<string name="add_account_summary_done">Feito</string>
|
||||
<string name="add_account_server_title">Onde están as túas tarefas?</string>
|
||||
<string name="add_account_server_fallback_body">Agendula non puido atopar o servidor a partir do teu enderezo de correo electrónico. No seu lugar, introduce o enderezo do servidor CalDAV que o teu provedor facilita para os calendarios.</string>
|
||||
<string name="add_account_server_body">Introduce o enderezo do teu servidor CalDAV. Tamén serve un enderezo de correo electrónico, se o servidor se publica a si mesmo baixo o seu dominio.</string>
|
||||
<string name="add_account_credentials_title">Iniciar sesión</string>
|
||||
<string name="add_account_credentials_body">Usar un contrasinal de aplicación se o teu provedor ofrece un; pódese revogar sen cambiar o contrasinal da túa conta.</string>
|
||||
<string name="add_account_lists_body">Escolle as listas de tarefas que queres manter sincronizadas. Podes modificalo máis tarde.</string>
|
||||
<string name="add_account_error_not_an_address">Iso non parece un enderezo web. Proba con algo coma cloud.exemplo.com.</string>
|
||||
<string name="add_account_error_not_dav">Esa dirección respondeu, pero non é un servidor CalDAV. Se pegaches o enderezo do sitio web, proba co enderezo do servidor que o teu provedor facilita para os calendarios.</string>
|
||||
<string name="add_account_error_no_calendar">Ese servidor non ofrece calendarios. Comproba o enderezo co teu provedor.</string>
|
||||
<string name="add_account_error_unreachable">Non foi posible conectar con ese servidor. Comproba o enderezo e a túa conexión.</string>
|
||||
<string name="add_account_error_insecure">Ese enderezo non está cifrado. Agendula só envía o teu contrasinal a través de https.</string>
|
||||
<string name="add_account_error_no_calendars">Sesión iniciada, pero esta conta non ten listas de tarefas.</string>
|
||||
<string name="add_account_error_server">O servidor atopou un problema. Téntao de novo nun intre.</string>
|
||||
<string name="add_account_error_tls">Non foi posible establecer unha conexión segura con ese servidor.</string>
|
||||
<string name="add_account_working_discovering">Buscando un servidor CalDAV</string>
|
||||
<string name="add_account_working_signing_in">Iniciando sesión</string>
|
||||
<string name="add_account_working_reading_lists">Lendo as túas listas de tarefas</string>
|
||||
<string name="add_account_working_saving">Engadindo a conta</string>
|
||||
<string name="add_account_error_google_unsupported">Google Calendar non admite tarefas a través de CalDAV —a súa propia documentación así o indica—, polo que Agendula non pode sincronizarse con el.</string>
|
||||
<string name="add_account_error_cross_domain">Este servidor mantén algunhas listas de tarefas en %1$s, ás que Agendula aínda non pode iniciar sesión.</string>
|
||||
<string name="add_account_error_already_exists">Esa conta xa está configurada.</string>
|
||||
<string name="add_account_error_no_usable_lists">Sesión iniciada, pero esta conta non ten listas de tarefas que Agendula poida empregar.</string>
|
||||
<string name="add_account_error_not_saved">Non se puido gardar a conta.</string>
|
||||
<string name="add_account_error_keystore">Este dispositivo non almacenaría o contrasinal.</string>
|
||||
<string name="add_account_error_credentials_rejected">Ese nome de usuario ou contrasinal non foi aceptado.</string>
|
||||
<string name="add_account_browser_error_expired">A fiestra de aprobación pechouse antes de que o servidor respondese.</string>
|
||||
<string name="add_account_browser_error_rate_limited">O servidor está a rexeitar intentos repetidos. Agarda uns minutos e téntao de novo.</string>
|
||||
<string name="add_account_browser_error_maintenance">O servidor está en modo de mantemento. Téntao de novo unha vez que volva estar dispoñible.</string>
|
||||
<string name="add_account_browser_error_failed">O servidor non rematou de iniciar a túa sesión. Téntao de novo nun momento.</string>
|
||||
<string name="add_account_browser_error_unavailable">Este dispositivo non dispón dun navegador que poida abrir a páxina do inicio de sesión. Emprega un contrasinal no seu lugar.</string>
|
||||
<string name="add_account_quirk_hint_fastmail">Fastmail require un contrasinal de aplicación, non o contrasinal da túa conta; ademais, CalDAV non está incluído no plan Basic.</string>
|
||||
<string name="add_account_quirk_hint_icloud">iCloud require un contrasinal específico para a aplicación, que se crea en appleid.apple.com coa autenticación de dous factores activada.</string>
|
||||
<string name="add_account_setup_body">Farás isto no teu navegador e despois volverás aquí para rematar.</string>
|
||||
<string name="add_account_setup_icloud_title">iCloud precisa dun contrasinal específico para a aplicación</string>
|
||||
<string name="add_account_setup_icloud_footnote">As tarefas gardadas en iCloud non aparecerán na aplicación Recordatorios de Apple.</string>
|
||||
<string name="add_account_setup_fastmail_title">Fastmail precisa dun contrasinal de aplicación</string>
|
||||
<string name="add_account_setup_fastmail_footnote">CalDAV non está incluído no plan Basic de Fastmail.</string>
|
||||
<string name="add_account_quirk_google">Google Calendar non admite tarefas a través de CalDAV.</string>
|
||||
<string name="accounts_needs_sign_in">Inicia sesión de novo para seguir sincronizando</string>
|
||||
<string name="accounts_sign_in_again">Inicia sesión de novo</string>
|
||||
<string name="accounts_summary">%1$s · %2$s</string>
|
||||
<string name="sync_notice_channel_name">Informes de sincronización</string>
|
||||
<string name="sync_notice_channel_desc">Cando unha sincronización substitúe unha das túas edicións pola copia do servidor, ou deixa de intentar sincronizar unha tarefa.</string>
|
||||
<string name="sync_notice_body">%1$s</string>
|
||||
<string name="sync_notice_line">%1$s · %2$s</string>
|
||||
<string name="sync_notices_title">O que cambiou a última sincronización</string>
|
||||
<string name="sync_notices_dismiss">Entendido</string>
|
||||
<string name="sync_notice_retry">Tentar de novo</string>
|
||||
<string name="sync_notice_cause_server_newer">Substituído pola copia máis recente do servidor</string>
|
||||
<string name="sync_notice_cause_deleted_on_server">Eliminado no servidor mentres o editabas</string>
|
||||
<string name="sync_notice_cause_delete_lost">Borráchelo aquí, pero o servidor cambiouno despois</string>
|
||||
<string name="sync_notice_cause_quarantined">Sincronización detida: o servidor segue rexeitando isto</string>
|
||||
<string name="sync_sign_in_channel_name">É preciso iniciar sesión</string>
|
||||
<string name="sync_sign_in_channel_desc">Cando unha conta deixa de sincronizarse ata que volvas iniciar sesión.</string>
|
||||
<string name="sync_sign_in_title">Volver iniciar sesión en %1$s</string>
|
||||
<string name="sync_sign_in_body">O servidor deixou de aceptar o contrasinal de Agendula, polo que esta conta deixou de sincronizarse.</string>
|
||||
<string name="sync_notification_channel">Sincronizando</string>
|
||||
<string name="sync_notification_title">Sincronizando tarefas</string>
|
||||
<string name="add_account_server_label">Enderezo do servidor</string>
|
||||
<string name="add_account_server_hint">https://cloud.exemplo.com</string>
|
||||
<string name="add_account_continue">Proseguir</string>
|
||||
<string name="add_account_start_over">Comezar de novo</string>
|
||||
<string name="add_account_username_label">Nome de usuario</string>
|
||||
<string name="add_account_password_label">Contrasinal</string>
|
||||
<string name="add_account_password_hint">Empregar un contrasinal de aplicación se o teu servidor ofrece un; pódese revogar sen cambiar o contrasinal da túa conta.</string>
|
||||
<string name="add_account_sign_in">Iniciar sesión</string>
|
||||
<string name="add_account_browser_title">Agardando polo teu navegador</string>
|
||||
<string name="add_account_browser_body">Aproba Agendula no navegador e despois volve aquí. O teu contrasinal nunca se envía a esta aplicación; o servidor xera un contrasinal específico para a aplicación que podes revogar en calquera intre.</string>
|
||||
<string name="add_account_browser_use_password">Empregar un contrasinal no seu lugar</string>
|
||||
<string name="add_account_browser_retry">Téntao de novo</string>
|
||||
<string name="add_account_browser_confirm_title">Comproba isto antes de iniciar sesión</string>
|
||||
<string name="add_account_browser_confirm_body">A páxina de inicio de sesión está no teu servidor, non en Agendula; polo tanto, convén botarlle unha ollada antes de introducir nela o contrasinal da túa conta.</string>
|
||||
<string name="add_account_browser_open">Abre a páxina de inicio de sesión</string>
|
||||
<string name="add_account_browser_insecure">Esa páxina de inicio de sesión non está cifrada (http). Todo o que escribas nela, incluído o contrasinal da túa conta, transmítese sen cifrar.</string>
|
||||
<string name="add_account_browser_host_mismatch">O servidor enviounos a %1$s, pero ti escribiches %2$s. Iso adoita significar que o seu axuste overwrite.cli.url é incorrecto.</string>
|
||||
<string name="add_account_origin_mismatch">O servidor informou de que o seu enderezo é %1$s, ao cal este dispositivo non pode acceder, polo que se empregou %2$s no seu lugar. É probable que a configuración de overwrite.cli.url ou de trusted_proxies sexa incorrecta.</string>
|
||||
<string name="add_account_cleartext_title">Conectar sen cifrado?</string>
|
||||
<string name="add_account_cleartext_body">Este enderezo emprega http, non https. O teu contrasinal e as túas tarefas viaxarían sen cifrar, e calquera persoa na rede entre este teléfono e o servidor podería lelos.</string>
|
||||
<string name="add_account_cleartext_note">Iso pode estar ben para un servidor ao que só accedes a través dunha VPN ou da túa rede doméstica. En calquera outro caso, configura HTTPS no servidor.</string>
|
||||
<string name="add_account_cleartext_connect">Conectar de todos os xeitos</string>
|
||||
<string name="add_account_change_address">Cambia o enderezo</string>
|
||||
<string name="add_account_certificate_title">Confiar neste certificado?</string>
|
||||
<string name="add_account_certificate_body">O certificado deste servidor non está asinado por unha autoridade na que o teu teléfono confía. Se xestionas ti mesmo este servidor, compara a pegada dixital que aparece a continuación co certificado do teu servidor antes de confiar nel.</string>
|
||||
<string name="add_account_certificate_fingerprint">Pegada dixital SHA-256</string>
|
||||
<string name="add_account_certificate_subject">Emitido a</string>
|
||||
<string name="add_account_certificate_issuer">Emitido por</string>
|
||||
<string name="add_account_certificate_expires">Válido ata</string>
|
||||
<string name="add_account_certificate_trust">Confía neste certificado</string>
|
||||
<string name="add_account_certificate_decline">Non confiar</string>
|
||||
<string name="add_account_lists_title">Que listas deberían de sincronizar?</string>
|
||||
<string name="add_account_lists_read_only">Só de lectura</string>
|
||||
<string name="add_account_lists_shared">Compartido contigo</string>
|
||||
<string name="add_account_save">Engadir unha conta</string>
|
||||
<string name="add_account_no_lists_selected">Escolle polo menos unha lista</string>
|
||||
<plurals name="sync_notice_discarded_title">
|
||||
<item quantity="one">Unha edición foi substituída polo servidor</item>
|
||||
<item quantity="other">%1$d edicións foron substituídas polo servidor</item>
|
||||
</plurals>
|
||||
<plurals name="sync_notice_quarantined_title">
|
||||
<item quantity="one">Unha tarefa deixou de sincronizarse</item>
|
||||
<item quantity="other">%1$d tarefas deixáronse de sincronizar</item>
|
||||
</plurals>
|
||||
<plurals name="accounts_notices">
|
||||
<item quantity="one">1 informe de sincronización por ler</item>
|
||||
<item quantity="other">%1$d informes de sincronización por ler</item>
|
||||
</plurals>
|
||||
<plurals name="sync_notice_more">
|
||||
<item quantity="one">e %1$d máis</item>
|
||||
<item quantity="other">e %1$d máis</item>
|
||||
</plurals>
|
||||
<string name="widget_tasks_label">Tarefas</string>
|
||||
<string name="widget_tasks_description">As tarefas de hoxe, ou calquera lista, que podes marcar cun premido</string>
|
||||
<string name="widget_empty">Xa estou ao día</string>
|
||||
<string name="widget_empty_hint">Xa non queda nada por facer, disfrútao</string>
|
||||
<string name="widget_unavailable">Abre Agendula para rematar a configuración</string>
|
||||
<string name="widget_complete_task">Completar %1$s</string>
|
||||
<string name="widget_config_title">Amosar no widget</string>
|
||||
<string name="widget_config_smart_lists">Listas intelixentes</string>
|
||||
<string name="widget_config_group_by_list">Agrupar por lista</string>
|
||||
<string name="widget_config_group_by_list_hint">Amosar as tarefas de cada lista baixo o seu propio encabezado</string>
|
||||
<string name="widget_section_overdue">Vencido</string>
|
||||
<string name="widget_section_later">Máis tarde</string>
|
||||
<string name="widget_section_no_date">Sen data</string>
|
||||
<string name="widget_config_background">Fondo</string>
|
||||
<string name="widget_config_background_solid">Sólido</string>
|
||||
<string name="widget_config_background_solid_hint">Enche o widget coa cor de superficie do tema</string>
|
||||
<string name="widget_config_background_tinted">Tingxido</string>
|
||||
<string name="widget_config_background_tinted_hint">Un recheo tonal máis suave</string>
|
||||
<string name="widget_config_background_transparent">Transparente</string>
|
||||
<string name="widget_config_background_transparent_hint">Sen recheo: as tarefas permanecen lexibles nos seus propios contedores</string>
|
||||
<string name="widget_config_theme">Tema</string>
|
||||
<string name="widget_config_theme_follow_app">Segundo a aplicación</string>
|
||||
<string name="widget_config_theme_light">Claro</string>
|
||||
<string name="widget_config_theme_dark">Escuro</string>
|
||||
<string name="widget_config_row_color">Cor da fila</string>
|
||||
<string name="widget_config_row_color_neutral">Neutro</string>
|
||||
<string name="widget_config_row_color_neutral_hint">Cada fila emprega o mesmo recheo tonal</string>
|
||||
<string name="widget_config_row_color_by_list">Por lista</string>
|
||||
<string name="widget_config_row_color_by_list_hint">Cada fila está tinguida coa cor propia da súa lista</string>
|
||||
<string name="widget_today_label">Hoxe</string>
|
||||
<string name="widget_today_description">Un anel de progreso para as tarefas de hoxe</string>
|
||||
<string name="widget_today_all_done">Xa está</string>
|
||||
<string name="widget_today_nothing_due">Non hai nada pendente hoxe</string>
|
||||
<plurals name="widget_today_progress_cd">
|
||||
<item quantity="one">%1$d de %2$d feito</item>
|
||||
<item quantity="other">%1$d de %2$d feitos</item>
|
||||
</plurals>
|
||||
<string name="widget_up_next_label">De seguido</string>
|
||||
<string name="widget_up_next_description">A túa única tarefa pendente máis próxima</string>
|
||||
<string name="widget_up_next_empty">Nada pendente</string>
|
||||
<string name="widget_up_next_soon">Axiña</string>
|
||||
<string name="widget_up_next_tomorrow">Mañá</string>
|
||||
<string name="widget_up_next_then">Entón</string>
|
||||
<string name="widget_up_next_any_list">Todas as listas</string>
|
||||
<plurals name="widget_up_next_in_hours">
|
||||
<item quantity="one">en %1$d h</item>
|
||||
<item quantity="other">en %1$d h</item>
|
||||
</plurals>
|
||||
<plurals name="widget_up_next_in_days">
|
||||
<item quantity="one">en %1$d d</item>
|
||||
<item quantity="other">en %1$d d</item>
|
||||
</plurals>
|
||||
<plurals name="widget_up_next_overdue_hours">
|
||||
<item quantity="one">%1$d h atrasado</item>
|
||||
<item quantity="other">%1$d h atrasado</item>
|
||||
</plurals>
|
||||
<plurals name="widget_up_next_overdue_days">
|
||||
<item quantity="one">%1$d d atrasado</item>
|
||||
<item quantity="other">%1$d d atrasado</item>
|
||||
</plurals>
|
||||
<string name="widget_lists_label">Listas</string>
|
||||
<string name="widget_lists_description">Unha tesela de atallo por lista, co seu reconto de aperturas</string>
|
||||
<string name="widget_lists_empty">Non hai listas a amosar</string>
|
||||
<string name="widget_lists_config_title">Listas a amosar</string>
|
||||
<string name="widget_week_label">Semana</string>
|
||||
<string name="widget_week_description">Unha franxa de sete días de conta de tarefas</string>
|
||||
<string name="permission_read_tasks_label">ler tarefas de Agendula</string>
|
||||
<string name="permission_read_tasks_description">Permite que a aplicación lea as túas listas de tarefas e as tarefas almacenadas en Agendula, incluídos os seus recordatorios e etiquetas.</string>
|
||||
<string name="permission_write_tasks_label">engadir, cambiar e eliminar tarefas de Agendula</string>
|
||||
<string name="permission_write_tasks_description">Permite á aplicación engadir, modificar, completar e eliminar tarefas almacenadas en Agendula, incluídos os seus recordatorios e etiquetas. Non pode modificar nin eliminar listas de tarefas.</string>
|
||||
</resources>
|
||||
@@ -77,6 +77,10 @@
|
||||
<item quantity="one">%1$d completed task in this list will be deleted.</item>
|
||||
<item quantity="other">%1$d completed tasks in this list will be deleted.</item>
|
||||
</plurals>
|
||||
<plurals name="clear_completed_shown_body">
|
||||
<item quantity="one">%1$d completed task shown here will be deleted.</item>
|
||||
<item quantity="other">%1$d completed tasks shown here will be deleted.</item>
|
||||
</plurals>
|
||||
<string name="clear_completed_confirm">Delete</string>
|
||||
<string name="undo">Undo</string>
|
||||
<string name="cd_expand_subtasks">Show subtasks</string>
|
||||
@@ -308,7 +312,79 @@
|
||||
<string name="filter_delete_body">Only the filter goes. Its tasks stay where they are.</string>
|
||||
<string name="filter_delete_confirm">Delete</string>
|
||||
<string name="filter_missing">Filter deleted</string>
|
||||
<string name="filter_rules_not_editable">This filter uses rules that can’t be edited here yet. You can still rename or delete it.</string>
|
||||
<string name="filter_match_title">Show tasks that match</string>
|
||||
<string name="filter_match_all">All rules</string>
|
||||
<string name="filter_match_any">Any rule</string>
|
||||
<string name="filter_op_is">is</string>
|
||||
<string name="filter_op_is_not">is not</string>
|
||||
<string name="filter_op_at_least">at least</string>
|
||||
<string name="filter_op_below">below</string>
|
||||
<string name="filter_due_this_week">This week</string>
|
||||
<string name="filter_due_this_month">This month</string>
|
||||
<plurals name="filter_due_next_days">
|
||||
<item quantity="one">Next %d day</item>
|
||||
<item quantity="other">Next %d days</item>
|
||||
</plurals>
|
||||
<string name="filter_due_next_days_any">Next days…</string>
|
||||
<string name="filter_next_days_off">Off</string>
|
||||
<string name="filter_next_days_title">Within the next days</string>
|
||||
<string name="filter_next_days_amount">Enter a number of days</string>
|
||||
<string name="filter_advanced">Advanced editor</string>
|
||||
<string name="filter_advanced_hint">Nested groups with all / any / not</string>
|
||||
<string name="filter_advanced_note">Rules the simple editor can’t show, like nested groups or “not” on a group, always open here.</string>
|
||||
<string name="filter_simple">Simple editor</string>
|
||||
<string name="filter_simple_hint">Lists, tags, due date and priority</string>
|
||||
<string name="filter_simple_unavailable">These rules need the advanced editor</string>
|
||||
<string name="filter_group_all">All of</string>
|
||||
<string name="filter_group_any">Any of</string>
|
||||
<string name="filter_group_not">Not</string>
|
||||
<string name="filter_group_all_hint">every rule must match</string>
|
||||
<string name="filter_group_any_hint">one is enough</string>
|
||||
<string name="filter_group_not_all_hint">leaves out tasks matching every rule</string>
|
||||
<string name="filter_group_not_any_hint">leaves out tasks matching any rule</string>
|
||||
<string name="filter_group_empty_all">No rules yet: every task matches.</string>
|
||||
<string name="filter_group_empty_any">No rules yet: no task matches.</string>
|
||||
<string name="filter_group_menu">Group options</string>
|
||||
<string name="filter_group_negate">Negate group (not)</string>
|
||||
<string name="filter_group_negate_off">Remove “not”</string>
|
||||
<string name="filter_group_delete">Delete group</string>
|
||||
<string name="filter_add_rule">Rule</string>
|
||||
<string name="filter_add_group">Group</string>
|
||||
<string name="filter_rule_remove">Remove rule</string>
|
||||
<string name="filter_field_title">Rule on</string>
|
||||
<string name="filter_field_list">List</string>
|
||||
<string name="filter_field_tag">Tag</string>
|
||||
<string name="filter_field_priority">Priority</string>
|
||||
<string name="filter_field_due">Due</string>
|
||||
<string name="filter_value_no_list">No list</string>
|
||||
<string name="filter_lists_none">No lists yet.</string>
|
||||
<string name="filter_tags_none">No open task has a tag yet.</string>
|
||||
<string name="filter_tag_other">Other tag…</string>
|
||||
<string name="filter_tag_other_hint">Tag</string>
|
||||
<string name="filter_template_empty">Start empty</string>
|
||||
<string name="filter_template_empty_hint">Pick every rule yourself</string>
|
||||
<string name="filter_templates_header">Templates</string>
|
||||
<string name="filter_templates_note">A template fills in the rules and a name. You can change everything afterwards.</string>
|
||||
<string name="filter_template_gtd">Next actions (GTD)</string>
|
||||
<string name="filter_template_gtd_hint">A list of your choice, or tag nextAction</string>
|
||||
<string name="filter_template_gtd_name">Next actions</string>
|
||||
<string name="filter_template_gtd_list_title">Next actions list</string>
|
||||
<string name="filter_template_gtd_list_hint">Which list holds your next actions? Tasks tagged nextAction show too. Skip to go by the tag alone.</string>
|
||||
<string name="filter_template_gtd_skip">Skip</string>
|
||||
<string name="filter_template_week">This week</string>
|
||||
<string name="filter_template_week_hint">Due this week, overdue included</string>
|
||||
<string name="filter_template_month">This month</string>
|
||||
<string name="filter_template_month_hint">Due this month</string>
|
||||
<string name="filter_template_high">High priority</string>
|
||||
<string name="filter_template_high_hint">Priority high, any list</string>
|
||||
<string name="filter_template_waiting">Waiting for</string>
|
||||
<string name="filter_template_waiting_hint">Tag waiting</string>
|
||||
<string name="filter_template_no_date">No date</string>
|
||||
<string name="filter_template_no_date_hint">Open tasks without a due date</string>
|
||||
<string name="rule_scope_title">Edit scope</string>
|
||||
<string name="rule_source_title">Custom rules</string>
|
||||
<string name="rule_save_as_filter">Save as filter</string>
|
||||
<string name="rule_save_as_filter_hint">Keep these rules as a filter, and show the filter here</string>
|
||||
<string name="new_task">New task</string>
|
||||
<string name="lists_failure">Could not read your tasks.</string>
|
||||
<string name="lists_empty">No task lists yet.</string>
|
||||
@@ -526,6 +602,19 @@
|
||||
<string name="settings_app_name_hint">Show Agendula as “Tasks” in your launcher. Only the launcher name changes; the icon may move to a new spot. Agendula closes when you switch, so reopen it from the launcher.</string>
|
||||
<string name="settings_dynamic_color">Dynamic colour</string>
|
||||
<string name="settings_dynamic_color_hint">Use colours from your wallpaper</string>
|
||||
<string name="settings_density">Density</string>
|
||||
<string name="settings_density_comfortable">Comfortable</string>
|
||||
<string name="settings_density_compact">Compact</string>
|
||||
<string name="settings_density_hint">Compact uses shorter rows, so more fits on the screen.</string>
|
||||
<string name="settings_buttons">Buttons</string>
|
||||
<string name="settings_buttons_icons">Icons only</string>
|
||||
<string name="settings_buttons_shapes">Expressive shapes</string>
|
||||
<string name="settings_motion">Motion</string>
|
||||
<string name="settings_reduce_motion">Reduce motion</string>
|
||||
<string name="settings_reduce_motion_hint">Screens fade instead of sliding, and looping animations like the progress wave stay still. The system “Remove animations” setting does the same.</string>
|
||||
<string name="settings_group_colours">Colours</string>
|
||||
<string name="settings_group_date_time">Date & time</string>
|
||||
<string name="settings_group_launcher">Launcher</string>
|
||||
<string name="settings_section_reminders">Notifications</string>
|
||||
<string name="settings_reminders">Task reminders</string>
|
||||
<string name="settings_reminders_hint">Notify me when a task is due</string>
|
||||
@@ -1074,4 +1163,234 @@
|
||||
<!-- Permission another app requests to add, change or delete Agendula's tasks -->
|
||||
<string name="permission_write_tasks_label">add, change and delete Agendula tasks</string>
|
||||
<string name="permission_write_tasks_description">Allows the app to add, change, complete and delete tasks stored in Agendula, including their reminders and tags. It cannot change or delete task lists.</string>
|
||||
<!-- Views (#59): stored home layouts the top bar switches between -->
|
||||
<string name="view_home">Home</string>
|
||||
<string name="view_unnamed">View</string>
|
||||
<string name="view_switch">Switch view</string>
|
||||
<string name="view_lists_and_filters_menu">Lists & filters…</string>
|
||||
<string name="view_lists_and_filters">Lists & filters</string>
|
||||
<string name="view_manage">Manage views</string>
|
||||
<string name="view_add">New view</string>
|
||||
<string name="view_reorder_handle">Drag to reorder</string>
|
||||
<plurals name="view_blocks">
|
||||
<item quantity="one">%d block</item>
|
||||
<item quantity="other">%d blocks</item>
|
||||
</plurals>
|
||||
<!-- A view's summary in Manage views: its scope, then how many blocks it has -->
|
||||
<string name="view_summary">%1$s · %2$s</string>
|
||||
<string name="view_new_title">New view</string>
|
||||
<string name="view_edit_title">Edit view</string>
|
||||
<string name="view_name_hint">Name</string>
|
||||
<string name="view_section_icon">Icon</string>
|
||||
<string name="view_section_scope">Scope</string>
|
||||
<string name="view_section_layout">Layout</string>
|
||||
<string name="view_scope_hint">Only tasks that match show in this view</string>
|
||||
<string name="view_scope_none_hint">Every task shows in this view</string>
|
||||
<string name="view_scope_blocks_hint">Every block shows its own tasks that also match the scope. A block can ignore the scope.</string>
|
||||
<string name="view_quick_add">Quick-add bar</string>
|
||||
<string name="view_quick_add_hint">A bar at the bottom of the view to add tasks</string>
|
||||
<!-- %1$s is the list a task added through the bar goes to. -->
|
||||
<string name="view_quick_add_target">New tasks go to %1$s</string>
|
||||
|
||||
<!-- Quick-add: the words typed after @ for a due date, e.g. "Call mum @tomorrow".
|
||||
Each is a comma-separated list of lowercase words without spaces; the English ones always work as well.
|
||||
A word must not stand for two things, e.g. the same abbreviation for two weekdays. -->
|
||||
<string name="quick_add_keyword_today">today</string>
|
||||
<string name="quick_add_keyword_tomorrow">tomorrow</string>
|
||||
<!-- The first day of next week. -->
|
||||
<string name="quick_add_keyword_next_week">nextweek</string>
|
||||
<string name="quick_add_keyword_monday">monday,mon</string>
|
||||
<string name="quick_add_keyword_tuesday">tuesday,tue</string>
|
||||
<string name="quick_add_keyword_wednesday">wednesday,wed</string>
|
||||
<string name="quick_add_keyword_thursday">thursday,thu</string>
|
||||
<string name="quick_add_keyword_friday">friday,fri</string>
|
||||
<string name="quick_add_keyword_saturday">saturday,sat</string>
|
||||
<string name="quick_add_keyword_sunday">sunday,sun</string>
|
||||
<!-- Units after a number, as in "@3d" (in 3 days), "@2w" (in 2 weeks), "@1m" (in a month). -->
|
||||
<string name="quick_add_keyword_days">d</string>
|
||||
<string name="quick_add_keyword_weeks">w</string>
|
||||
<string name="quick_add_keyword_months">m</string>
|
||||
<!-- %1$s is a list's name. -->
|
||||
<string name="quick_add_not_shown">Added to %1$s, not shown in this view</string>
|
||||
<string name="quick_add_open">Open</string>
|
||||
<!-- %1$s is a list's name; said when nothing on the screen shows the task just added. -->
|
||||
<string name="quick_add_added">Added to %1$s</string>
|
||||
<string name="quick_add_expand">Open in the full editor</string>
|
||||
<!-- %1$s is a day, maybe with a time. -->
|
||||
<string name="quick_add_due_chip">Due %1$s</string>
|
||||
<!-- %1$s is a list's name. -->
|
||||
<string name="quick_add_list_chip">In %1$s</string>
|
||||
<string name="view_delete">Delete view</string>
|
||||
<string name="view_delete_title">Delete “%1$s”?</string>
|
||||
<string name="view_delete_body">The view and its layout go. Its tasks, lists and filters stay.</string>
|
||||
<string name="view_save_failed">The views were saved by another version of Agendula and can’t be changed here.</string>
|
||||
<string name="view_shortcut_gone">This view was deleted</string>
|
||||
<string name="view_icon_title">View icon</string>
|
||||
<string name="view_icon_suggested">Suggested</string>
|
||||
<string name="view_icon_more">More</string>
|
||||
<string name="view_pin">Pin as view</string>
|
||||
<string name="view_scope_drop">Show all tasks, not just this view’s</string>
|
||||
<string name="view_source_gone">This block’s list or filter was deleted.</string>
|
||||
<string name="view_choose_source">Choose source</string>
|
||||
<string name="view_source_smart">Smart lists</string>
|
||||
<string name="view_source_custom">Custom rules…</string>
|
||||
<string name="view_source_custom_hint">Lists, tags, due dates and priority</string>
|
||||
<string name="view_scope_list_gone">A list in this view’s scope was deleted. That part of the scope now matches nothing.</string>
|
||||
<string name="view_edit_scope">Edit scope</string>
|
||||
<!-- A view's scope in one line, built from these pieces -->
|
||||
<string name="view_scope_everything">Everything</string>
|
||||
<string name="view_scope_nothing">Nothing</string>
|
||||
<string name="view_scope_and">%1$s and %2$s</string>
|
||||
<string name="view_scope_or">%1$s or %2$s</string>
|
||||
<string name="view_scope_not">not %1$s</string>
|
||||
<string name="view_scope_list">List %1$s</string>
|
||||
<string name="view_scope_list_deleted">(deleted)</string>
|
||||
<string name="view_scope_list_elsewhere">(other task store)</string>
|
||||
<string name="view_scope_tag">Tag %1$s</string>
|
||||
<string name="view_scope_due_overdue">Overdue</string>
|
||||
<string name="view_scope_due_today">Due today</string>
|
||||
<string name="view_scope_due_upcoming">Due later</string>
|
||||
<string name="view_scope_due_none">No due date</string>
|
||||
<string name="view_scope_due_week">Due this week</string>
|
||||
<string name="view_scope_due_month">Due this month</string>
|
||||
<plurals name="view_scope_due_next_days">
|
||||
<item quantity="one">Due within %d day</item>
|
||||
<item quantity="other">Due within %d days</item>
|
||||
</plurals>
|
||||
<string name="view_icon_home">Home</string>
|
||||
<string name="view_icon_dashboard">Dashboard</string>
|
||||
<string name="view_icon_work">Briefcase</string>
|
||||
<string name="view_icon_heart">Heart</string>
|
||||
<string name="view_icon_bolt">Lightning</string>
|
||||
<string name="view_icon_calendar">Calendar</string>
|
||||
<string name="view_icon_today">Today</string>
|
||||
<string name="view_icon_inbox">Inbox</string>
|
||||
<string name="view_icon_list">Checklist</string>
|
||||
<string name="view_icon_done">Done</string>
|
||||
<string name="view_icon_flag">Flag</string>
|
||||
<string name="view_icon_person">Person</string>
|
||||
<string name="view_icon_group">People</string>
|
||||
<string name="view_icon_star">Star</string>
|
||||
<string name="view_icon_filter">Filter</string>
|
||||
<string name="view_icon_tag">Tag</string>
|
||||
<string name="view_icon_folder">Folder</string>
|
||||
<string name="view_icon_archive">Archive</string>
|
||||
<string name="view_icon_alarm">Alarm clock</string>
|
||||
<string name="view_icon_notifications">Bell</string>
|
||||
<string name="view_icon_lightbulb">Light bulb</string>
|
||||
<string name="view_icon_school">School</string>
|
||||
<string name="view_icon_book">Book</string>
|
||||
<string name="view_icon_shopping">Shopping cart</string>
|
||||
<string name="view_icon_money">Money</string>
|
||||
<string name="view_icon_fitness">Fitness</string>
|
||||
<string name="view_icon_pets">Pets</string>
|
||||
<string name="view_icon_restaurant">Restaurant</string>
|
||||
<string name="view_icon_flight">Plane</string>
|
||||
<string name="view_icon_place">Place</string>
|
||||
<string name="view_icon_globe">Globe</string>
|
||||
<string name="view_icon_palette">Palette</string>
|
||||
<string name="view_icon_devices">Devices</string>
|
||||
<string name="view_icon_code">Code</string>
|
||||
<string name="view_icon_bug">Bug</string>
|
||||
<string name="view_icon_build">Wrench</string>
|
||||
<string name="view_icon_note">Note</string>
|
||||
<string name="view_icon_history">History</string>
|
||||
<string name="view_icon_grid">Grid</string>
|
||||
<string name="view_icon_tree">Tree</string>
|
||||
<!-- Editing a view's layout of blocks -->
|
||||
<string name="view_edit_layout">Edit layout</string>
|
||||
<string name="edit_layout_done">Done</string>
|
||||
<string name="edit_layout_discard">Discard changes</string>
|
||||
<string name="edit_layout_discard_title">Discard layout changes?</string>
|
||||
<string name="edit_layout_discard_body">The blocks go back to how they were when you started editing.</string>
|
||||
<string name="edit_layout_discard_confirm">Discard</string>
|
||||
<string name="block_add">Add block</string>
|
||||
<string name="block_settings">Block settings</string>
|
||||
<string name="block_drag">Drag to move</string>
|
||||
<string name="block_move_earlier">Move earlier</string>
|
||||
<string name="block_move_later">Move later</string>
|
||||
<string name="block_make_full">Make full width</string>
|
||||
<string name="block_make_half">Make half width</string>
|
||||
<string name="block_remove">Remove block</string>
|
||||
<string name="block_removed">Block removed</string>
|
||||
<string name="block_group_tasks">Tasks</string>
|
||||
<string name="block_group_browse">Browse</string>
|
||||
<string name="block_group_layout">Layout</string>
|
||||
<string name="block_progress">Progress</string>
|
||||
<string name="block_progress_hint">Ring with how much is done</string>
|
||||
<string name="block_count">Count tile</string>
|
||||
<string name="block_count_hint">One number, half or full width</string>
|
||||
<string name="block_preview">Preview</string>
|
||||
<string name="block_preview_hint">The next 3, 5 or 10 tasks</string>
|
||||
<string name="block_recent">Recently completed</string>
|
||||
<string name="block_recent_hint">What you finished, with undo</string>
|
||||
<string name="block_week">Week strip</string>
|
||||
<string name="block_week_hint">This week with due dots</string>
|
||||
<string name="block_task_list">Task list</string>
|
||||
<string name="block_task_list_hint">Every task, always at the bottom</string>
|
||||
<string name="block_task_list_taken">This view has one already</string>
|
||||
<string name="block_lists_hint">Your lists by account</string>
|
||||
<string name="block_tags_hint">Every tag with counts</string>
|
||||
<string name="block_filters_hint">Your saved filters</string>
|
||||
<string name="block_heading">Section heading</string>
|
||||
<string name="block_heading_hint">A title to group blocks</string>
|
||||
<string name="block_source_title">Show tasks from</string>
|
||||
<string name="block_source_rules">Custom rules</string>
|
||||
<string name="block_gone_while_editing">This block was removed meanwhile, so there is nothing to save these rules to.</string>
|
||||
<string name="block_empty">Nothing to show right now</string>
|
||||
<string name="block_recent_empty">Nothing completed yet</string>
|
||||
<string name="block_heading_empty">No text yet</string>
|
||||
<!-- The task list block while the layout is edited; %1$s is its source, e.g. "All" -->
|
||||
<string name="block_task_list_summary">Tasks from %1$s</string>
|
||||
<string name="block_ignores_scope">Shows tasks outside this view</string>
|
||||
<string name="block_week_title">This week</string>
|
||||
<!-- A day in the week strip, for screen readers: %1$s is the day, %2$d the open tasks due -->
|
||||
<plurals name="block_week_day">
|
||||
<item quantity="one">%1$s, %2$d task due</item>
|
||||
<item quantity="other">%1$s, %2$d tasks due</item>
|
||||
</plurals>
|
||||
<!-- A recently completed task's time, e.g. "Done 10 minutes ago" -->
|
||||
<string name="block_recent_done_at">Done %1$s</string>
|
||||
<!-- A half-width progress tile: done of total -->
|
||||
<string name="block_progress_short">%1$d of %2$d</string>
|
||||
<string name="block_progress_empty">Nothing to do 🎉</string>
|
||||
<string name="block_title">Title</string>
|
||||
<string name="block_heading_text">Text</string>
|
||||
<string name="block_heading_text_hint">Heading</string>
|
||||
<string name="block_section_tasks">Tasks</string>
|
||||
<string name="block_source">Source</string>
|
||||
<string name="block_section_options">Options</string>
|
||||
<string name="block_section_look">Look</string>
|
||||
<string name="block_section_scope">View scope</string>
|
||||
<string name="block_how_many">How many</string>
|
||||
<string name="block_show_all">“View all” link</string>
|
||||
<string name="block_show_all_hint">Opens the full list</string>
|
||||
<string name="block_inline_done">Check off here</string>
|
||||
<string name="block_inline_done_hint">Tap the box to complete a task</string>
|
||||
<string name="block_ignore_scope">Ignore view scope</string>
|
||||
<!-- %1$s is the view's name -->
|
||||
<string name="block_ignore_scope_hint">Also show tasks outside “%1$s”</string>
|
||||
<string name="block_wave">Moving wave</string>
|
||||
<string name="block_wave_hint">The ring’s wave moves, unless motion is reduced</string>
|
||||
<string name="block_color">Colour</string>
|
||||
<string name="block_icon">Icon</string>
|
||||
<string name="block_automatic">Automatic</string>
|
||||
<string name="block_color_primary">Primary</string>
|
||||
<string name="block_color_secondary">Secondary</string>
|
||||
<string name="block_color_tertiary">Tertiary</string>
|
||||
<string name="block_color_error">Alert</string>
|
||||
<string name="block_sort_default">As set for the app</string>
|
||||
<string name="block_show_completed">Completed tasks</string>
|
||||
<string name="block_show_completed_hint">In their own section at the end</string>
|
||||
<string name="block_accounts">Accounts</string>
|
||||
<string name="block_accounts_all">All accounts</string>
|
||||
<string name="block_counts">Counts</string>
|
||||
<string name="block_counts_hint">Open tasks next to each list</string>
|
||||
<!-- Where the app opens (#141) -->
|
||||
<string name="start_destination">Start screen</string>
|
||||
<string name="start_last_used">Last used view</string>
|
||||
<string name="start_last_used_hint">Opens on the view you had open last</string>
|
||||
<string name="start_section_views">Views</string>
|
||||
<string name="start_section_lists">Lists</string>
|
||||
<string name="start_section_filters">Filters</string>
|
||||
</resources>
|
||||
@@ -15,4 +15,5 @@
|
||||
<locale android:name="cs" />
|
||||
<locale android:name="ru" />
|
||||
<locale android:name="gl" />
|
||||
<locale android:name="es" />
|
||||
</locale-config>
|
||||
@@ -0,0 +1,93 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import androidx.datastore.preferences.core.mutablePreferencesOf
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.floret.prefs.ActionStyle
|
||||
import de.jeanlucmakiola.floret.prefs.LayoutDensity
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
/** Density, button style and reduce motion as [Settings] carries them; the stored keys are floret-kit's to test. */
|
||||
class AppearanceSettingsTest {
|
||||
|
||||
private class MemoryDataStore(initial: Preferences = emptyPreferences()) : DataStore<Preferences> {
|
||||
override val data = MutableStateFlow(initial)
|
||||
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) =
|
||||
transform(data.value).also { data.value = it }
|
||||
}
|
||||
|
||||
private object NoProviders : ProviderEnvironment {
|
||||
override fun packageDeclaring(authority: String): String? = null
|
||||
override fun isGranted(permission: String) = false
|
||||
override fun appLabel(packageName: String): String? = null
|
||||
}
|
||||
|
||||
private fun prefs(dataStore: DataStore<Preferences> = MemoryDataStore()) =
|
||||
SettingsPrefs(dataStore, ProviderResolver(NoProviders))
|
||||
|
||||
@Test
|
||||
fun `a fresh install is comfortable, icons only, with motion on`() = runBlocking<Unit> {
|
||||
val settings = prefs().settings.first()
|
||||
|
||||
assertThat(Triple(settings.density, settings.actionStyle, settings.reduceMotion))
|
||||
.isEqualTo(Triple(LayoutDensity.COMFORTABLE, ActionStyle.ICONS, false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an existing install gets icons only too`() = runBlocking<Unit> {
|
||||
val upgraded = MemoryDataStore(
|
||||
mutablePreferencesOf(
|
||||
stringPreferencesKey("theme_mode") to "DARK",
|
||||
booleanPreferencesKey("dynamic_color") to false,
|
||||
),
|
||||
)
|
||||
|
||||
assertThat(prefs(upgraded).settings.first().actionStyle).isEqualTo(ActionStyle.ICONS)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the choices are kept`() = runBlocking<Unit> {
|
||||
val prefs = prefs()
|
||||
|
||||
prefs.setDensity(LayoutDensity.COMPACT)
|
||||
prefs.setActionStyle(ActionStyle.SHAPES)
|
||||
prefs.setReduceMotion(true)
|
||||
|
||||
val settings = prefs.settings.first()
|
||||
assertThat(Triple(settings.density, settings.actionStyle, settings.reduceMotion))
|
||||
.isEqualTo(Triple(LayoutDensity.COMPACT, ActionStyle.SHAPES, true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a theme stored before floret-kit took the keys over is kept`() = runBlocking<Unit> {
|
||||
val upgraded = MemoryDataStore(
|
||||
mutablePreferencesOf(
|
||||
stringPreferencesKey("theme_mode") to "BLACK",
|
||||
booleanPreferencesKey("dynamic_color") to false,
|
||||
),
|
||||
)
|
||||
|
||||
val settings = prefs(upgraded).settings.first()
|
||||
|
||||
assertThat(settings.themeMode to settings.dynamicColor).isEqualTo(ThemeMode.BLACK to false)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a theme choice is written where earlier versions read it`() = runBlocking<Unit> {
|
||||
val dataStore = MemoryDataStore()
|
||||
|
||||
prefs(dataStore).setThemeMode(ThemeMode.DARK)
|
||||
|
||||
assertThat(dataStore.data.value[stringPreferencesKey("theme_mode")]).isEqualTo("DARK")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultDueDate
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.FilterCriteria
|
||||
import de.jeanlucmakiola.agendula.domain.LocalAccount
|
||||
import de.jeanlucmakiola.agendula.domain.NewTaskOrigin
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddParse
|
||||
import de.jeanlucmakiola.agendula.domain.QuickDue
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
|
||||
import de.jeanlucmakiola.agendula.domain.asOpenTask
|
||||
import de.jeanlucmakiola.agendula.domain.matches
|
||||
import de.jeanlucmakiola.agendula.domain.startOfDay
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
class QuickAddTaskTest {
|
||||
|
||||
private val zone = ZoneId.of("Europe/Berlin")
|
||||
private val today = LocalDate.of(2026, 11, 27)
|
||||
private val clock = RuleClock(startOfDay(today, zone), startOfDay(today.plusDays(1), zone), zone, DayOfWeek.MONDAY)
|
||||
private val now = at(today, LocalTime.of(10, 0))
|
||||
|
||||
private fun at(date: LocalDate, time: LocalTime) =
|
||||
Instant.fromEpochSeconds(LocalDateTime.of(date, time).atZone(zone).toEpochSecond())
|
||||
|
||||
private fun list(id: Long, name: String, local: Boolean = false, readOnly: Boolean = false) = TaskList(
|
||||
id, name, 0, if (local) "Local" else "me",
|
||||
if (local) LocalAccount.TYPE else "bitfire.at.davdroid",
|
||||
isSynced = !local, isVisible = true, owner = null, isReadOnly = readOnly,
|
||||
)
|
||||
|
||||
private val work = list(1, "Work")
|
||||
private val errands = list(2, "Errands")
|
||||
private val inbox = list(3, "Inbox", local = true)
|
||||
private val writable = listOf(work, errands, inbox)
|
||||
private val settings = Settings(defaultListId = 2)
|
||||
|
||||
private fun add(
|
||||
parse: QuickAddParse,
|
||||
scope: Rule? = null,
|
||||
settings: Settings = this.settings,
|
||||
lists: List<de.jeanlucmakiola.agendula.domain.TaskList> = writable,
|
||||
origin: NewTaskOrigin = NewTaskOrigin(),
|
||||
) = settings.quickAddTask(parse, scope, lists, clock, now, origin)
|
||||
|
||||
@Test
|
||||
fun `without a list or scope the task goes to the default list`() {
|
||||
val form = add(QuickAddParse("Buy milk"))!!
|
||||
assertThat(form.title).isEqualTo("Buy milk")
|
||||
assertThat(form.listId).isEqualTo(2L)
|
||||
assertThat(form.due).isNull()
|
||||
assertThat(form.tags).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a default list gone or read-only falls back to the first synced list`() {
|
||||
assertThat(add(QuickAddParse("x"), settings = Settings(defaultListId = 9))!!.listId).isEqualTo(1L)
|
||||
assertThat(add(QuickAddParse("x"), lists = listOf(inbox, work))!!.listId).isEqualTo(1L)
|
||||
assertThat(add(QuickAddParse("x"), lists = listOf(inbox))!!.listId).isEqualTo(3L)
|
||||
assertThat(add(QuickAddParse("x"), lists = emptyList())).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a named list wins over the scope's and the default`() {
|
||||
val form = add(QuickAddParse("x", list = inbox), scope = Rule.InList(setOf(1L)))!!
|
||||
assertThat(form.listId).isEqualTo(3L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the scope's one list comes before the default`() {
|
||||
assertThat(add(QuickAddParse("x"), scope = Rule.InList(setOf(1L)))!!.listId).isEqualTo(1L)
|
||||
assertThat(add(QuickAddParse("x"), scope = Rule.InList(setOf(1L, 3L)))!!.listId).isEqualTo(1L)
|
||||
assertThat(add(QuickAddParse("x"), scope = Rule.InList(setOf(2L, 3L)))!!.listId).isEqualTo(2L)
|
||||
// A scope list the task can't go to isn't one.
|
||||
assertThat(add(QuickAddParse("x"), scope = Rule.InList(setOf(9L)))!!.listId).isEqualTo(2L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `scopes with any-of or not fall back to the default list`() {
|
||||
val gtd = Rule.AnyOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("next")))
|
||||
val form = add(QuickAddParse("x"), scope = gtd)!!
|
||||
assertThat(form.listId).isEqualTo(2L)
|
||||
assertThat(form.tags).isEmpty()
|
||||
assertThat(gtd.matches(form.asOpenTask(), clock)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the scope's tags and priority come along`() {
|
||||
val scope = Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x"), Rule.MinPriority(Priority.MEDIUM)))
|
||||
val form = add(QuickAddParse("x"), scope = scope)!!
|
||||
assertThat(form.listId).isEqualTo(1L)
|
||||
assertThat(form.tags).containsExactly("x")
|
||||
assertThat(form.priority).isEqualTo(Priority.MEDIUM)
|
||||
assertThat(scope.matches(form.asOpenTask(), clock)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a scope on due dates presets one, unless the default due date already fits`() {
|
||||
val upcoming = Rule.Due(DueSpec.Window(DueWindow.UPCOMING))
|
||||
val form = add(QuickAddParse("x"), scope = upcoming)!!
|
||||
assertThat(form.due).isEqualTo(allDayInstantOf(today.plusDays(1)))
|
||||
assertThat(form.isAllDay).isTrue()
|
||||
assertThat(upcoming.matches(form.asOpenTask(), clock)).isTrue()
|
||||
|
||||
val nextWeek = Settings(defaultListId = 2, defaultDueDate = DefaultDueDate.NEXT_WEEK)
|
||||
assertThat(add(QuickAddParse("x"), scope = upcoming, settings = nextWeek)!!.due).isEqualTo(allDayInstantOf(today.plusWeeks(1)))
|
||||
val todayOnly = Rule.Due(DueSpec.Window(DueWindow.TODAY))
|
||||
assertThat(add(QuickAddParse("x"), scope = todayOnly, settings = nextWeek)!!.due).isEqualTo(allDayInstantOf(today))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without a scope the default due date applies`() {
|
||||
val tomorrow = Settings(defaultListId = 2, defaultDueDate = DefaultDueDate.TOMORROW)
|
||||
assertThat(add(QuickAddParse("x"), settings = tomorrow)!!.due).isEqualTo(allDayInstantOf(today.plusDays(1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a typed date is all day, and wins over the scope's and the default`() {
|
||||
val tomorrow = Settings(defaultListId = 2, defaultDueDate = DefaultDueDate.TOMORROW)
|
||||
val form = add(QuickAddParse("x", due = QuickDue(today.plusDays(5))), scope = Rule.Due(DueSpec.Window(DueWindow.TODAY)), settings = tomorrow)!!
|
||||
assertThat(form.due).isEqualTo(allDayInstantOf(today.plusDays(5)))
|
||||
assertThat(form.isAllDay).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a typed time makes the due timed, with the default start at that time`() {
|
||||
val due = QuickDue(today.plusDays(2), LocalTime.of(14, 30))
|
||||
val plain = add(QuickAddParse("x", due = due))!!
|
||||
assertThat(plain.due).isEqualTo(at(today.plusDays(2), LocalTime.of(14, 30)))
|
||||
assertThat(plain.isAllDay).isFalse()
|
||||
assertThat(plain.start).isNull()
|
||||
|
||||
val dayBefore = Settings(defaultListId = 2, defaultStartDate = DefaultStartDate.DAY_BEFORE_DUE)
|
||||
assertThat(add(QuickAddParse("x", due = due), settings = dayBefore)!!.start).isEqualTo(at(today.plusDays(1), LocalTime.of(14, 30)))
|
||||
|
||||
val startToday = Settings(defaultListId = 2, defaultStartDate = DefaultStartDate.TODAY)
|
||||
val form = add(QuickAddParse("x", due = due), settings = startToday)!!
|
||||
assertThat(form.start).isEqualTo(now)
|
||||
assertThat(form.startsNow).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a time already past today never puts the start after the due`() {
|
||||
val startToday = Settings(defaultListId = 2, defaultStartDate = DefaultStartDate.TODAY)
|
||||
val form = add(QuickAddParse("x", due = QuickDue(today, LocalTime.of(8, 0))), settings = startToday)!!
|
||||
assertThat(form.start).isEqualTo(form.due)
|
||||
assertThat(form.validate()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a start counted back to today at a time already past starts now`() {
|
||||
val weekBefore = Settings(defaultListId = 2, defaultStartDate = DefaultStartDate.WEEK_BEFORE_DUE)
|
||||
val form = add(QuickAddParse("x", due = QuickDue(today.plusDays(3), LocalTime.of(9, 0))), settings = weekBefore)!!
|
||||
assertThat(form.start).isEqualTo(now)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the list a screen shows comes before the scope's`() {
|
||||
val form = add(QuickAddParse("x"), scope = Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.InList(setOf(3L)))), origin = NewTaskOrigin(listId = 3))!!
|
||||
assertThat(form.listId).isEqualTo(3L)
|
||||
assertThat(add(QuickAddParse("x", list = errands), origin = NewTaskOrigin(listId = 3))!!.listId).isEqualTo(2L)
|
||||
// A read-only one isn't.
|
||||
assertThat(add(QuickAddParse("x"), origin = NewTaskOrigin(listId = 9))!!.listId).isEqualTo(2L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a saved filter shown presets as the editor does, any-of tags included`() {
|
||||
val filter = SavedFilter(5, "Shop", FilterCriteria(listIds = setOf(1L, 3L), tags = setOf("shopping", "errands"), tagMatch = TagMatch.ANY))
|
||||
val form = add(QuickAddParse("x"), origin = NewTaskOrigin(filter = filter))!!
|
||||
assertThat(form.listId).isEqualTo(1L)
|
||||
assertThat(form.tags).containsExactly("errands")
|
||||
assertThat(filter.matches(form.asOpenTask(), clock)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a tag or smart list shown presets the tag or due`() {
|
||||
assertThat(add(QuickAddParse("x"), origin = NewTaskOrigin(tag = "home"))!!.tags).containsExactly("home")
|
||||
assertThat(add(QuickAddParse("x"), origin = NewTaskOrigin(smartList = SmartList.TODAY))!!.due).isEqualTo(allDayInstantOf(today))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a task the scope won't show is told apart`() {
|
||||
val scope = Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.Due(DueSpec.Window(DueWindow.TODAY))))
|
||||
val shown = add(QuickAddParse("x"), scope = scope)!!
|
||||
assertThat(scope.matches(shown.asOpenTask(), clock)).isTrue()
|
||||
val elsewhere = add(QuickAddParse("x", list = errands), scope = scope)!!
|
||||
assertThat(scope.matches(elsewhere.asOpenTask(), clock)).isFalse()
|
||||
val later = add(QuickAddParse("x", due = QuickDue(today.plusDays(3))), scope = scope)!!
|
||||
assertThat(scope.matches(later.asOpenTask(), clock)).isFalse()
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,12 @@ class SettingsVisibilityTest {
|
||||
assertThat(settings.visibleIn(TaskFilter.Smart(SmartList.ALL), tasks).map { it.taskId }).containsExactly(1L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a day of the week strip leaves out a hidden list, as its dots do`() {
|
||||
val day = TaskFilter.DueOn(java.time.LocalDate.of(2026, 11, 26))
|
||||
assertThat(settings.visibleIn(day, tasks).map { it.taskId }).containsExactly(1L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the hidden list still shows its own tasks`() {
|
||||
assertThat(settings.visibleIn(TaskFilter.OfList(2), tasks)).isEqualTo(tasks)
|
||||
|
||||
@@ -16,6 +16,11 @@ import de.jeanlucmakiola.agendula.domain.TaskSortOrder
|
||||
import de.jeanlucmakiola.agendula.domain.TileColor
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
import de.jeanlucmakiola.agendula.domain.replaced
|
||||
import de.jeanlucmakiola.agendula.domain.reordered
|
||||
import de.jeanlucmakiola.agendula.domain.without
|
||||
import de.jeanlucmakiola.agendula.domain.resized
|
||||
import de.jeanlucmakiola.agendula.domain.withBlock
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
@@ -34,13 +39,13 @@ class ViewCodecTest {
|
||||
Block(1, BlockType.PROGRESS, BlockSource.Smart(SmartList.TODAY), BlockWidth.HALF, options = BlockOptions.Progress(wave = false, title = "Mine | today; a=b")),
|
||||
Block(2, BlockType.COUNT_TILE, BlockSource.List(9), BlockWidth.HALF, ignoreScope = true, options = BlockOptions.CountTile("Tile", TileColor.TERTIARY, ViewIcon.BOLT)),
|
||||
Block(3, BlockType.COUNT_TILE, BlockSource.Tag("größe,x"), BlockWidth.FULL),
|
||||
Block(4, BlockType.PREVIEW, BlockSource.Filter(12), options = BlockOptions.Preview(count = 10, showAll = false, inlineDone = true)),
|
||||
Block(4, BlockType.PREVIEW, BlockSource.Filter(12), options = BlockOptions.Preview(count = 10, showAll = false, inlineDone = true, title = "Next; up=1")),
|
||||
Block(5, BlockType.LISTS, options = BlockOptions.Lists(accounts = setOf("me@example.org", "a,b;c"), counts = false)),
|
||||
Block(6, BlockType.TAGS),
|
||||
Block(7, BlockType.FILTERS),
|
||||
Block(8, BlockType.SECTION_HEADING, options = BlockOptions.SectionHeading("Work = 100%")),
|
||||
Block(9, BlockType.WEEK_STRIP, ignoreScope = true),
|
||||
Block(10, BlockType.RECENTLY_COMPLETED, options = BlockOptions.RecentlyCompleted(5)),
|
||||
Block(9, BlockType.WEEK_STRIP, ignoreScope = true, options = BlockOptions.WeekStrip("This week")),
|
||||
Block(10, BlockType.RECENTLY_COMPLETED, options = BlockOptions.RecentlyCompleted(5, title = "Done")),
|
||||
Block(11, BlockType.TASK_LIST, BlockSource.Rules(rule), options = BlockOptions.TaskList(TaskSortOrder.PRIORITY, showCompleted = false, inlineDone = false)),
|
||||
)
|
||||
|
||||
@@ -50,6 +55,27 @@ class ViewCodecTest {
|
||||
View(id = 3, name = "Empty", icon = ViewIcon.STAR, scope = Rule.Everything, blocks = emptyList()),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `an edited layout is stored with its new blocks, widths and options`() {
|
||||
val raw = ViewCodec.encode(views, "OWN")
|
||||
val work = views[1]
|
||||
val edited = work.copy(
|
||||
blocks = work.blocks
|
||||
.withBlock(BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING))
|
||||
.resized(2, BlockWidth.FULL)
|
||||
.without(6)
|
||||
.reordered(listOf(10, 1))
|
||||
.let { blocks ->
|
||||
val preview = blocks.last { it.type == BlockType.PREVIEW }
|
||||
blocks.replaced(preview.copy(ignoreScope = true, options = BlockOptions.Preview(count = 5, inlineDone = true, title = "Soon")))
|
||||
},
|
||||
)
|
||||
val stored = ViewCodec.decode(ViewCodec.upsert(raw, edited, "OWN"), "OWN").first { it.id == work.id }
|
||||
assertThat(stored).isEqualTo(edited)
|
||||
assertThat(stored.problems).isEmpty()
|
||||
assertThat(stored.blocks.first().id).isEqualTo(10L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `views round-trip with every block, source and option`() {
|
||||
val raw = ViewCodec.encode(views, "OWN")
|
||||
@@ -164,4 +190,61 @@ class ViewCodecTest {
|
||||
val stored = preferencesOf(ViewsMigration.KEY to ViewCodec.encode(views.drop(1), "OWN"))
|
||||
assertThat(ViewsMigration.shouldMigrate(stored)).isFalse()
|
||||
}
|
||||
@Test
|
||||
fun `a view is written in its place, or after the others`() {
|
||||
val raw = ViewCodec.encode(views, "OWN")
|
||||
val renamed = views[1].copy(name = "Job", scope = null)
|
||||
val replaced = ViewCodec.upsert(raw, renamed, "OWN")
|
||||
assertThat(ViewCodec.decode(replaced, "OWN")).containsExactly(views[0], renamed, views[2]).inOrder()
|
||||
|
||||
val added = View(9, "New", ViewIcon.STAR, null, View.home().blocks)
|
||||
assertThat(ViewCodec.decode(ViewCodec.upsert(raw, added, "OWN"), "OWN").map { it.id })
|
||||
.containsExactly(1L, 2L, 3L, 9L).inOrder()
|
||||
assertThat(ViewCodec.decode(ViewCodec.upsert(null, added, "OWN"), "OWN")).containsExactly(added)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `writing a view keeps the lines that don't read`() {
|
||||
val raw = listOf(
|
||||
"v1",
|
||||
"garbage",
|
||||
"view|1|Home|HOME|1|",
|
||||
"block|1|TAGS|FULL|0||",
|
||||
"block|2|NOPE|FULL|0||",
|
||||
"view|x|Broken|HOME|1|",
|
||||
"block|6|TAGS|FULL|0||",
|
||||
"view|3|Fine|STAR|1|",
|
||||
).joinToString("\n")
|
||||
val home = ViewCodec.decode(raw, "OWN").first().copy(name = "Mine")
|
||||
val written = ViewCodec.upsert(raw, home, "OWN")
|
||||
assertThat(written.lines()).containsExactly(
|
||||
"v1",
|
||||
"garbage",
|
||||
"view|1|Mine|HOME|1|",
|
||||
"block|1|TAGS|FULL|0||",
|
||||
"block|2|NOPE|FULL|0||",
|
||||
"view|x|Broken|HOME|1|",
|
||||
"block|6|TAGS|FULL|0||",
|
||||
"view|3|Fine|STAR|1|",
|
||||
).inOrder()
|
||||
assertThat(ViewCodec.remove(written, 3).lines()).doesNotContain("view|3|Fine|STAR|1|")
|
||||
assertThat(ViewCodec.remove(written, 3).lines()).contains("view|x|Broken|HOME|1|")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `views reorder by id, those not named keeping their slot`() {
|
||||
val raw = ViewCodec.encode(views + View(4, "Four", ViewIcon.BOLT, null, emptyList()), "OWN")
|
||||
val reordered = ViewCodec.reorder(raw, listOf(1L, 4L, 2L))
|
||||
assertThat(ViewCodec.decode(reordered, "OWN").map { it.id }).containsExactly(1L, 4L, 3L, 2L).inOrder()
|
||||
assertThat(ViewCodec.decode(reordered, "OWN").single { it.id == 2L }).isEqualTo(views[1])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `another version's layout is never written over`() {
|
||||
val newer = "v2\nview|1|x|HOME|1|"
|
||||
val view = View(5, "x", ViewIcon.HOME, null, emptyList())
|
||||
assertThat(ViewCodec.upsert(newer, view, "OWN")).isEqualTo(newer)
|
||||
assertThat(ViewCodec.remove(newer, 1)).isEqualTo(newer)
|
||||
assertThat(ViewCodec.reorder(newer, listOf(1L))).isEqualTo(newer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDestination
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.StartDestination
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.newView
|
||||
import de.jeanlucmakiola.agendula.domain.pinnedView
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ViewPrefsTest {
|
||||
|
||||
private class MemoryDataStore : DataStore<Preferences> {
|
||||
override val data = MutableStateFlow(emptyPreferences())
|
||||
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) =
|
||||
transform(data.value).also { data.value = it }
|
||||
}
|
||||
|
||||
private object NoProviders : ProviderEnvironment {
|
||||
override fun packageDeclaring(authority: String): String? = null
|
||||
override fun isGranted(permission: String) = false
|
||||
override fun appLabel(packageName: String): String? = null
|
||||
}
|
||||
|
||||
private val prefs = SettingsPrefs(MemoryDataStore(), ProviderResolver(NoProviders))
|
||||
|
||||
@Test
|
||||
fun `a new view gets an id never handed out before`() = runBlocking<Unit> {
|
||||
prefs.setStorageMode(StorageMode.OWN)
|
||||
val first = prefs.saveView(newView(0, "A"))
|
||||
val second = prefs.saveView(pinnedView(0, "B", ViewIcon.LIST, Rule.InList(setOf(3L))))
|
||||
assertThat(first).isEqualTo(2L)
|
||||
assertThat(second).isEqualTo(3L)
|
||||
prefs.deleteView(second!!)
|
||||
assertThat(prefs.saveView(newView(0, "C"))).isEqualTo(4L)
|
||||
assertThat(prefs.views.first().map { it.name }).containsExactly("", "A", "C").inOrder()
|
||||
assertThat(prefs.views.first()[1]).isEqualTo(newView(2, "A"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `saving a view replaces it in place`() = runBlocking<Unit> {
|
||||
val id = prefs.saveView(newView(0, "A"))
|
||||
prefs.saveView(newView(0, "B"))
|
||||
prefs.saveView(newView(id!!, "Renamed"))
|
||||
assertThat(prefs.views.first().map { it.name }).containsExactly("", "Renamed", "B").inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Home stays first and can't be deleted`() = runBlocking<Unit> {
|
||||
val a = prefs.saveView(newView(0, "A"))!!
|
||||
val b = prefs.saveView(newView(0, "B"))!!
|
||||
prefs.reorderViews(listOf(b, a, View.HOME_ID))
|
||||
assertThat(prefs.views.first().map { it.id }).containsExactly(View.HOME_ID, b, a).inOrder()
|
||||
prefs.deleteView(View.HOME_ID)
|
||||
assertThat(prefs.views.first().first().id).isEqualTo(View.HOME_ID)
|
||||
prefs.saveView(View.home().copy(name = "Mine"))
|
||||
assertThat(prefs.views.first().first().name).isEqualTo("Mine")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `deleting the last used or start view falls back to Home`() = runBlocking<Unit> {
|
||||
val id = prefs.saveView(newView(0, "A"))!!
|
||||
prefs.setActiveView(id)
|
||||
prefs.setStartDestination(StartDestination.View(id))
|
||||
assertThat(prefs.activeViewId.first()).isEqualTo(id)
|
||||
prefs.deleteView(id)
|
||||
assertThat(prefs.activeViewId.first()).isEqualTo(View.HOME_ID)
|
||||
assertThat(prefs.startDestination.first()).isEqualTo(DefaultStartDestination)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the start destination round-trips, a list only in its own store`() = runBlocking<Unit> {
|
||||
assertThat(prefs.startDestination.first()).isEqualTo(StartDestination.View(View.HOME_ID))
|
||||
prefs.setStorageMode(StorageMode.OWN)
|
||||
listOf(StartDestination.LastUsed, StartDestination.View(3), StartDestination.Filter(4), StartDestination.List(5))
|
||||
.forEach { destination ->
|
||||
prefs.setStartDestination(destination)
|
||||
assertThat(prefs.startDestination.first()).isEqualTo(destination)
|
||||
}
|
||||
prefs.setStorageMode(StorageMode.EXTERNAL)
|
||||
assertThat(prefs.startDestination.first()).isEqualTo(DefaultStartDestination)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a stored start destination that doesn't read is the default`() {
|
||||
assertThat(decodeStart(null, "OWN")).isEqualTo(DefaultStartDestination)
|
||||
assertThat(decodeStart("view:x", "OWN")).isEqualTo(DefaultStartDestination)
|
||||
assertThat(decodeStart("nope", "OWN")).isEqualTo(DefaultStartDestination)
|
||||
assertThat(decodeStart(encodeStart(StartDestination.List(5), "OWN"), "OWN")).isEqualTo(StartDestination.List(5))
|
||||
assertThat(encodeStart(StartDestination.List(5), "OWN")).isEqualTo("list:OWN:5")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new id passes a stored view that doesn't read, and another version's views aren't written`() = runBlocking<Unit> {
|
||||
val store = MemoryDataStore()
|
||||
val prefs = SettingsPrefs(store, ProviderResolver(NoProviders))
|
||||
store.data.value = androidx.datastore.preferences.core.preferencesOf(
|
||||
ViewsMigration.KEY to "v1\nview|1|Home|HOME|1|\nview|7|broken",
|
||||
)
|
||||
assertThat(prefs.saveView(newView(0, "A"))).isEqualTo(8L)
|
||||
|
||||
store.data.value = androidx.datastore.preferences.core.preferencesOf(ViewsMigration.KEY to "v2\nview|1|x|HOME|1|")
|
||||
assertThat(prefs.saveView(newView(0, "B"))).isNull()
|
||||
assertThat(store.data.value[ViewsMigration.KEY]).isEqualTo("v2\nview|1|x|HOME|1|")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `views change in one edit, and not at all when another version's`() = runBlocking<Unit> {
|
||||
val id = prefs.saveView(newView(0, "A"))!!
|
||||
assertThat(prefs.updateView(id) { it.copy(name = "B") }).isTrue()
|
||||
assertThat(prefs.views.first()[1].name).isEqualTo("B")
|
||||
assertThat(prefs.updateView(99) { it }).isFalse()
|
||||
assertThat(prefs.storedViewIds.first()).containsExactly(View.HOME_ID, id)
|
||||
|
||||
val store = MemoryDataStore()
|
||||
val other = SettingsPrefs(store, ProviderResolver(NoProviders))
|
||||
store.data.value = androidx.datastore.preferences.core.preferencesOf(ViewsMigration.KEY to "v2\nview|5|x|HOME|1|")
|
||||
assertThat(other.deleteView(5)).isFalse()
|
||||
assertThat(other.reorderViews(listOf(5L))).isFalse()
|
||||
assertThat(other.updateView(View.HOME_ID) { it }).isFalse()
|
||||
assertThat(other.storedViewIds.first()).isNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.util.Locale
|
||||
|
||||
class QuickAddSyntaxTest {
|
||||
|
||||
// A Friday.
|
||||
private val today = LocalDate.of(2026, 11, 27)
|
||||
|
||||
private fun list(id: Long, name: String) =
|
||||
TaskList(id, name, 0, "Local", "local", isSynced = false, isVisible = true, owner = null)
|
||||
|
||||
private val work = list(1, "Work")
|
||||
private val errands = list(2, "Errands")
|
||||
private val household = list(3, "Shared household")
|
||||
private val shopping = list(4, "Shopping")
|
||||
private val workshop = list(5, "Workshop")
|
||||
private val lists = listOf(work, errands, household, shopping, workshop)
|
||||
|
||||
private val german = ShortDateFormat(dayFirst = true, separator = '.')
|
||||
private val us = ShortDateFormat(dayFirst = false, separator = '/')
|
||||
|
||||
private fun parse(
|
||||
input: String,
|
||||
on: LocalDate = today,
|
||||
weekStart: DayOfWeek = DayOfWeek.MONDAY,
|
||||
shortDate: ShortDateFormat = german,
|
||||
keywords: QuickAddKeywords = QuickAddKeywords.English,
|
||||
lists: List<TaskList> = this.lists,
|
||||
now: LocalTime = LocalTime.of(10, 0),
|
||||
) = QuickAddSyntax.parse(input, QuickAddContext(on, weekStart, keywords, shortDate, lists, now))
|
||||
|
||||
private fun due(input: String, on: LocalDate = today, shortDate: ShortDateFormat = german) = parse(input, on, shortDate = shortDate).due
|
||||
|
||||
@Test
|
||||
fun `plain text is the title, trimmed`() {
|
||||
val result = parse(" Buy milk ")
|
||||
assertThat(result).isEqualTo(QuickAddParse(title = "Buy milk"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a date token is taken out of the title and marked`() {
|
||||
val result = parse("Call bob @tomorrow")
|
||||
assertThat(result.title).isEqualTo("Call bob")
|
||||
assertThat(result.due).isEqualTo(QuickDue(today.plusDays(1)))
|
||||
assertThat(result.tokens).containsExactly(QuickToken(9, 18, QuickToken.Kind.DATE))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tokens only start a word`() {
|
||||
assertThat(parse("Mail bob@example.com").due).isNull()
|
||||
assertThat(parse("Mail bob@example.com").title).isEqualTo("Mail bob@example.com")
|
||||
assertThat(parse("x@today").due).isNull()
|
||||
assertThat(parse("(@today)").due).isNull()
|
||||
assertThat(parse("Read C++ book").list).isNull()
|
||||
assertThat(parse("a+Work").list).isNull()
|
||||
assertThat(parse("Tab\t@today").due).isEqualTo(QuickDue(today))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a lone trigger stays text`() {
|
||||
assertThat(parse("@").tokens).isEmpty()
|
||||
assertThat(parse("+").tokens).isEmpty()
|
||||
assertThat(parse("a @ b + c").title).isEqualTo("a @ b + c")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the gap a token leaves closes up, wherever it is`() {
|
||||
assertThat(parse("Buy milk @today please").title).isEqualTo("Buy milk please")
|
||||
assertThat(parse("@today Buy milk").title).isEqualTo("Buy milk")
|
||||
assertThat(parse("Buy milk @today").title).isEqualTo("Buy milk")
|
||||
assertThat(parse("@today +work").title).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the last date and the last list are taken, earlier ones stay text`() {
|
||||
val result = parse("a @today b @tomorrow +work c +errands")
|
||||
assertThat(result.due).isEqualTo(QuickDue(today.plusDays(1)))
|
||||
assertThat(result.list).isEqualTo(errands)
|
||||
assertThat(result.title).isEqualTo("a @today b +work c")
|
||||
assertThat(result.tokens).containsExactly(
|
||||
QuickToken(11, 20, QuickToken.Kind.DATE),
|
||||
QuickToken(29, 37, QuickToken.Kind.LIST),
|
||||
).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a later token that reads as nothing leaves the earlier one taken`() {
|
||||
val result = parse("a @tomorrow +work b @someday +garden")
|
||||
assertThat(result.due).isEqualTo(QuickDue(today.plusDays(1)))
|
||||
assertThat(result.list).isEqualTo(work)
|
||||
assertThat(result.title).isEqualTo("a b @someday +garden")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a token that reads as nothing stays text and doesn't stop a later one`() {
|
||||
val result = parse("a @someday @today")
|
||||
assertThat(result.due).isEqualTo(QuickDue(today))
|
||||
assertThat(result.title).isEqualTo("a @someday")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `keywords ignore case`() {
|
||||
assertThat(due("@today")).isEqualTo(QuickDue(today))
|
||||
assertThat(due("@TODAY")).isEqualTo(QuickDue(today))
|
||||
assertThat(due("@Tomorrow")).isEqualTo(QuickDue(today.plusDays(1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `next week starts on the week start`() {
|
||||
assertThat(parse("@nextweek", weekStart = DayOfWeek.MONDAY).due?.date).isEqualTo(LocalDate.of(2026, 11, 30))
|
||||
assertThat(parse("@nextweek", weekStart = DayOfWeek.SUNDAY).due?.date).isEqualTo(LocalDate.of(2026, 11, 29))
|
||||
assertThat(parse("@nextweek", weekStart = DayOfWeek.SATURDAY).due?.date).isEqualTo(LocalDate.of(2026, 11, 28))
|
||||
// On the week's first day itself, next week is a week on.
|
||||
assertThat(parse("@nextweek", on = LocalDate.of(2026, 11, 30)).due?.date).isEqualTo(LocalDate.of(2026, 12, 7))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a weekday is the next one, today's a week ahead`() {
|
||||
assertThat(due("@fri")?.date).isEqualTo(LocalDate.of(2026, 12, 4))
|
||||
assertThat(due("@friday")?.date).isEqualTo(LocalDate.of(2026, 12, 4))
|
||||
assertThat(due("@sat")?.date).isEqualTo(LocalDate.of(2026, 11, 28))
|
||||
assertThat(due("@mon")?.date).isEqualTo(LocalDate.of(2026, 11, 30))
|
||||
assertThat(due("@thursday")?.date).isEqualTo(LocalDate.of(2026, 12, 3))
|
||||
assertThat(due("@frid")).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `relative days, weeks and months`() {
|
||||
assertThat(due("@3d")?.date).isEqualTo(LocalDate.of(2026, 11, 30))
|
||||
assertThat(due("@2w")?.date).isEqualTo(LocalDate.of(2026, 12, 11))
|
||||
assertThat(due("@1m")?.date).isEqualTo(LocalDate.of(2026, 12, 27))
|
||||
assertThat(due("@0d")?.date).isEqualTo(today)
|
||||
assertThat(due("@3D")?.date).isEqualTo(LocalDate.of(2026, 11, 30))
|
||||
assertThat(due("@1m", on = LocalDate.of(2027, 1, 31))?.date).isEqualTo(LocalDate.of(2027, 2, 28))
|
||||
assertThat(due("@3x")).isNull()
|
||||
assertThat(due("@1000d")).isNull()
|
||||
assertThat(due("@d")).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an ISO date is taken as it is, past or not`() {
|
||||
assertThat(due("@2026-11-20")?.date).isEqualTo(LocalDate.of(2026, 11, 20))
|
||||
assertThat(due("@2027-01-05")?.date).isEqualTo(LocalDate.of(2027, 1, 5))
|
||||
assertThat(due("@2026-02-30")).isNull()
|
||||
assertThat(due("@2026-1-5")).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the locale's short form, a past day rolling over to next year`() {
|
||||
assertThat(due("@28.11.")?.date).isEqualTo(LocalDate.of(2026, 11, 28))
|
||||
assertThat(due("@28.11")?.date).isEqualTo(LocalDate.of(2026, 11, 28))
|
||||
assertThat(due("@27.11.")?.date).isEqualTo(today)
|
||||
assertThat(due("@20.11.")?.date).isEqualTo(LocalDate.of(2027, 11, 20))
|
||||
assertThat(due("@1.1.")?.date).isEqualTo(LocalDate.of(2027, 1, 1))
|
||||
assertThat(due("@20.11.26")?.date).isEqualTo(LocalDate.of(2026, 11, 20))
|
||||
assertThat(due("@20.11.2028")?.date).isEqualTo(LocalDate.of(2028, 11, 20))
|
||||
assertThat(due("@31.2.")).isNull()
|
||||
assertThat(due("@20.13.")).isNull()
|
||||
// The other order's separator isn't this locale's.
|
||||
assertThat(due("@11/20")).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `month first where the locale writes it so`() {
|
||||
assertThat(due("@11/20", shortDate = us)?.date).isEqualTo(LocalDate.of(2027, 11, 20))
|
||||
assertThat(due("@12/1", shortDate = us)?.date).isEqualTo(LocalDate.of(2026, 12, 1))
|
||||
assertThat(due("@12/1/", shortDate = us)?.date).isEqualTo(LocalDate.of(2026, 12, 1))
|
||||
assertThat(due("@12/1/27", shortDate = us)?.date).isEqualTo(LocalDate.of(2027, 12, 1))
|
||||
assertThat(due("@20.11.", shortDate = us)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the year first where the locale writes it so`() {
|
||||
val swedish = ShortDateFormat(dayFirst = false, separator = '-', yearFirst = true)
|
||||
assertThat(due("@12-01", shortDate = swedish)?.date).isEqualTo(LocalDate.of(2026, 12, 1))
|
||||
assertThat(due("@11-20", shortDate = swedish)?.date).isEqualTo(LocalDate.of(2027, 11, 20))
|
||||
assertThat(due("@26-12-01", shortDate = swedish)?.date).isEqualTo(LocalDate.of(2026, 12, 1))
|
||||
assertThat(due("@2027-1-5", shortDate = swedish)?.date).isEqualTo(LocalDate.of(2027, 1, 5))
|
||||
assertThat(ShortDateFormat.of(Locale.forLanguageTag("sv-SE"))).isEqualTo(swedish)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dates across the year's end and a leap day`() {
|
||||
val newYearsEve = LocalDate.of(2026, 12, 31)
|
||||
assertThat(due("@tomorrow", on = newYearsEve)?.date).isEqualTo(LocalDate.of(2027, 1, 1))
|
||||
assertThat(due("@1.1.", on = newYearsEve)?.date).isEqualTo(LocalDate.of(2027, 1, 1))
|
||||
assertThat(due("@31.12.", on = newYearsEve)?.date).isEqualTo(newYearsEve)
|
||||
assertThat(due("@fri", on = newYearsEve)?.date).isEqualTo(LocalDate.of(2027, 1, 1))
|
||||
assertThat(due("@29.2.", on = LocalDate.of(2027, 3, 1))?.date).isEqualTo(LocalDate.of(2028, 2, 29))
|
||||
assertThat(due("@29.2.", on = LocalDate.of(2028, 1, 10))?.date).isEqualTo(LocalDate.of(2028, 2, 29))
|
||||
// Next year has no such day.
|
||||
assertThat(due("@29.2.")).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a time after a second at, in 24 or 12 hours`() {
|
||||
assertThat(due("@tomorrow@9")).isEqualTo(QuickDue(today.plusDays(1), LocalTime.of(9, 0)))
|
||||
assertThat(due("@fri@14:30")).isEqualTo(QuickDue(LocalDate.of(2026, 12, 4), LocalTime.of(14, 30)))
|
||||
assertThat(due("@3d@2pm")).isEqualTo(QuickDue(LocalDate.of(2026, 11, 30), LocalTime.of(14, 0)))
|
||||
assertThat(due("@today@2:30PM")?.time).isEqualTo(LocalTime.of(14, 30))
|
||||
assertThat(due("@today@9am")?.time).isEqualTo(LocalTime.of(9, 0))
|
||||
assertThat(due("@today@12am")?.time).isEqualTo(LocalTime.MIDNIGHT)
|
||||
assertThat(due("@today@12pm")?.time).isEqualTo(LocalTime.NOON)
|
||||
assertThat(due("@today@0")?.time).isEqualTo(LocalTime.MIDNIGHT)
|
||||
assertThat(due("@today@23:59")?.time).isEqualTo(LocalTime.of(23, 59))
|
||||
assertThat(due("@today@14h30")?.time).isEqualTo(LocalTime.of(14, 30))
|
||||
assertThat(due("@today@09:05")?.time).isEqualTo(LocalTime.of(9, 5))
|
||||
assertThat(due("@2026-12-24@18")).isEqualTo(QuickDue(LocalDate.of(2026, 12, 24), LocalTime.of(18, 0)))
|
||||
assertThat(due("@24.12.@18")).isEqualTo(QuickDue(LocalDate.of(2026, 12, 24), LocalTime.of(18, 0)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a time that doesn't read leaves the whole token as text`() {
|
||||
listOf("@today@24", "@today@13pm", "@today@0am", "@today@9:60", "@today@", "@today@9:5", "@today@noon", "@today@9@10")
|
||||
.forEach { token ->
|
||||
val result = parse("Ring $token")
|
||||
assertThat(result.due).isNull()
|
||||
assertThat(result.title).isEqualTo("Ring $token")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a time alone is today's, or tomorrow's once it has passed`() {
|
||||
// It is 10:00.
|
||||
assertThat(due("@14:30")).isEqualTo(QuickDue(today, LocalTime.of(14, 30)))
|
||||
assertThat(due("@9pm")).isEqualTo(QuickDue(today, LocalTime.of(21, 0)))
|
||||
assertThat(due("@20")).isEqualTo(QuickDue(today, LocalTime.of(20, 0)))
|
||||
assertThat(due("@9")).isEqualTo(QuickDue(today.plusDays(1), LocalTime.of(9, 0)))
|
||||
assertThat(due("@10")).isEqualTo(QuickDue(today.plusDays(1), LocalTime.of(10, 0)))
|
||||
assertThat(due("@10:01")).isEqualTo(QuickDue(today, LocalTime.of(10, 1)))
|
||||
assertThat(parse("@0", on = LocalDate.of(2026, 12, 31)).due).isEqualTo(QuickDue(LocalDate.of(2027, 1, 1), LocalTime.MIDNIGHT))
|
||||
assertThat(parse("Ring @14:30").title).isEqualTo("Ring")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a date reads before a lone time`() {
|
||||
// Day and month in the locale's form, not 20 o'clock with a dot.
|
||||
assertThat(due("@20.11")).isEqualTo(QuickDue(LocalDate.of(2027, 11, 20)))
|
||||
assertThat(due("@12/1", shortDate = us)).isEqualTo(QuickDue(LocalDate.of(2026, 12, 1)))
|
||||
assertThat(due("@3d")).isEqualTo(QuickDue(LocalDate.of(2026, 11, 30)))
|
||||
assertThat(due("@1m")).isEqualTo(QuickDue(LocalDate.of(2026, 12, 27)))
|
||||
// Neither a date nor a time.
|
||||
assertThat(due("@14.30")).isNull()
|
||||
assertThat(due("@25")).isNull()
|
||||
assertThat(due("@2026")).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a list by its name, ignoring case`() {
|
||||
assertThat(parse("Stamps +errands").list).isEqualTo(errands)
|
||||
assertThat(parse("Stamps +ERRANDS").list).isEqualTo(errands)
|
||||
assertThat(parse("Stamps +Errands").title).isEqualTo("Stamps")
|
||||
assertThat(parse("Stamps +Errands").tokens).containsExactly(QuickToken(7, 15, QuickToken.Kind.LIST))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an exact name wins over a longer one starting with it`() {
|
||||
assertThat(parse("+work").list).isEqualTo(work)
|
||||
assertThat(parse("+works").list).isEqualTo(workshop)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a unique start of a name names the list, spaces left out`() {
|
||||
assertThat(parse("+err").list).isEqualTo(errands)
|
||||
assertThat(parse("+shared").list).isEqualTo(household)
|
||||
assertThat(parse("+sharedhou").list).isEqualTo(household)
|
||||
assertThat(parse("+sharedhousehold").list).isEqualTo(household)
|
||||
assertThat(parse("+shop").list).isEqualTo(shopping)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a start of one letter names nothing, a one-letter name does`() {
|
||||
assertThat(parse("+e").list).isNull()
|
||||
assertThat(parse("+er").list).isEqualTo(errands)
|
||||
val x = list(9, "X")
|
||||
assertThat(parse("+x", lists = lists + x).list).isEqualTo(x)
|
||||
assertThat(parse("+X", lists = listOf(x, list(10, "Xmas"))).list).isEqualTo(x)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a start several names share, or no name, stays text`() {
|
||||
assertThat(parse("+sh").list).isNull()
|
||||
assertThat(parse("+wor").list).isNull()
|
||||
assertThat(parse("+garden").list).isNull()
|
||||
assertThat(parse("Call +garden").title).isEqualTo("Call +garden")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a name two lists have names neither`() {
|
||||
val twins = listOf(list(10, "Inbox"), list(11, "inbox"))
|
||||
assertThat(parse("+inbox", lists = twins).list).isNull()
|
||||
assertThat(parse("+\"Inbox\"", lists = twins).list).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a quoted name with spaces, exactly`() {
|
||||
val result = parse("Fix tap +\"shared household\" @tomorrow")
|
||||
assertThat(result.list).isEqualTo(household)
|
||||
assertThat(result.title).isEqualTo("Fix tap")
|
||||
assertThat(result.tokens.first()).isEqualTo(QuickToken(8, 27, QuickToken.Kind.LIST))
|
||||
assertThat(result.due?.date).isEqualTo(today.plusDays(1))
|
||||
assertThat(parse("+\" Shared household \"").list).isEqualTo(household)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a quoted name that isn't a whole list name, or isn't closed, stays text`() {
|
||||
assertThat(parse("+\"Shared\" x").list).isNull()
|
||||
assertThat(parse("+\"Shared household x").list).isNull()
|
||||
assertThat(parse("+\"Shared household\"x").list).isNull()
|
||||
assertThat(parse("+\"\"").list).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only the lists given can be named`() {
|
||||
assertThat(parse("+work", lists = listOf(errands)).list).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `date, time and list together`() {
|
||||
val result = parse("Call supplier @fri@14 +Errands")
|
||||
assertThat(result.title).isEqualTo("Call supplier")
|
||||
assertThat(result.due).isEqualTo(QuickDue(LocalDate.of(2026, 12, 4), LocalTime.of(14, 0)))
|
||||
assertThat(result.list).isEqualTo(errands)
|
||||
assertThat(result.tokens.map { it.kind }).containsExactly(QuickToken.Kind.DATE, QuickToken.Kind.LIST).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `translated words work beside the English ones`() {
|
||||
val german = QuickAddKeywords.English + QuickAddKeywords.fromTranslations { name ->
|
||||
mapOf(
|
||||
QuickAddKeywords.TOMORROW to "morgen",
|
||||
QuickAddKeywords.weekdayName(DayOfWeek.FRIDAY) to "freitag, fr",
|
||||
QuickAddKeywords.DAYS to "t",
|
||||
)[name]
|
||||
}
|
||||
assertThat(parse("@morgen", keywords = german).due?.date).isEqualTo(today.plusDays(1))
|
||||
assertThat(parse("@Fr", keywords = german).due?.date).isEqualTo(LocalDate.of(2026, 12, 4))
|
||||
assertThat(parse("@freitag", keywords = german).due?.date).isEqualTo(LocalDate.of(2026, 12, 4))
|
||||
assertThat(parse("@3t", keywords = german).due?.date).isEqualTo(LocalDate.of(2026, 11, 30))
|
||||
assertThat(parse("@tomorrow", keywords = german).due?.date).isEqualTo(today.plusDays(1))
|
||||
assertThat(parse("@3d", keywords = german).due?.date).isEqualTo(LocalDate.of(2026, 11, 30))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a translation's words drop empty entries and ones with spaces`() {
|
||||
assertThat(QuickAddKeywords.words(" Morgen , ,next week,x ")).containsExactly("morgen", "x").inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the short form follows the locale's own pattern`() {
|
||||
assertThat(ShortDateFormat.of(Locale.GERMANY)).isEqualTo(ShortDateFormat(dayFirst = true, separator = '.'))
|
||||
assertThat(ShortDateFormat.of(Locale.US)).isEqualTo(ShortDateFormat(dayFirst = false, separator = '/'))
|
||||
assertThat(ShortDateFormat.of(Locale.UK)).isEqualTo(ShortDateFormat(dayFirst = true, separator = '/'))
|
||||
assertThat(ShortDateFormat.of(Locale.forLanguageTag("nl-NL"))).isEqualTo(ShortDateFormat(dayFirst = true, separator = '-'))
|
||||
assertThat(ShortDateFormat.of(Locale.JAPAN).dayFirst).isFalse()
|
||||
assertThat(ShortDateFormat.of(Locale.forLanguageTag("ar")).separator).isAnyOf('/', '.', '-')
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `English names nothing twice`() {
|
||||
assertThat(QuickAddKeywords.English.collisions()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a word standing for two things is a collision`() {
|
||||
val clash = QuickAddKeywords.English + QuickAddKeywords.fromTranslations { name ->
|
||||
mapOf(QuickAddKeywords.TODAY to "mon", QuickAddKeywords.WEEKS to "m")[name]
|
||||
}
|
||||
assertThat(clash.collisions()).containsExactly("mon", "m")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
class ScopePresetTest {
|
||||
|
||||
private val zone = ZoneId.of("Europe/Berlin")
|
||||
|
||||
// A Thursday.
|
||||
private val today = LocalDate.of(2026, 11, 26)
|
||||
private fun clockOn(day: LocalDate) = RuleClock(startOfDay(day, zone), startOfDay(day.plusDays(1), zone), zone, DayOfWeek.MONDAY)
|
||||
private val clock = clockOn(today)
|
||||
|
||||
private fun all(vararg rules: Rule) = Rule.AllOf(rules.toList())
|
||||
private fun any(vararg rules: Rule) = Rule.AnyOf(rules.toList())
|
||||
private fun due(window: DueWindow) = Rule.Due(DueSpec.Window(window))
|
||||
|
||||
@Test
|
||||
fun `no scope presets nothing`() {
|
||||
assertThat((null as Rule?).scopePreset(clock)).isEqualTo(ScopePreset())
|
||||
assertThat(Rule.Everything.scopePreset(clock)).isEqualTo(ScopePreset())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `one list the scope keeps tasks to is the list`() {
|
||||
assertThat(Rule.InList(setOf(1L)).scopePreset(clock).listId).isEqualTo(1L)
|
||||
assertThat(Rule.InList(setOf(1L, 2L)).scopePreset(clock).listId).isNull()
|
||||
assertThat(all(Rule.InList(setOf(1L, 2L)), Rule.InList(setOf(2L, 3L))).scopePreset(clock).listId).isEqualTo(2L)
|
||||
assertThat(all(Rule.InList(setOf(1L)), Rule.InList(setOf(2L))).scopePreset(clock).listId).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the conditions at the top give list, tags and priority`() {
|
||||
val scope = all(
|
||||
Rule.InList(setOf(1L)),
|
||||
Rule.HasTag("x"),
|
||||
all(Rule.HasTag("y"), Rule.HasTag("x")),
|
||||
Rule.MinPriority(Priority.LOW),
|
||||
Rule.MinPriority(Priority.MEDIUM),
|
||||
)
|
||||
assertThat(scope.scopePreset(clock)).isEqualTo(
|
||||
ScopePreset(listId = 1L, tags = listOf("x", "y"), priority = Priority.MEDIUM),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `nothing under any-of or not is solved for`() {
|
||||
assertThat(any(Rule.InList(setOf(1L)), Rule.HasTag("x")).scopePreset(clock)).isEqualTo(ScopePreset())
|
||||
assertThat(Rule.Not(Rule.InList(setOf(1L))).scopePreset(clock)).isEqualTo(ScopePreset())
|
||||
assertThat(any(Rule.InList(setOf(1L)), Rule.InList(setOf(2L))).scopePreset(clock)).isEqualTo(ScopePreset())
|
||||
val mixed = all(Rule.InList(setOf(1L)), any(Rule.HasTag("a"), Rule.HasTag("b")), Rule.Not(Rule.HasTag("c")))
|
||||
assertThat(mixed.scopePreset(clock)).isEqualTo(ScopePreset(listId = 1L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the list is the one every task in the scope is in, whatever joins the conditions`() {
|
||||
val either = any(all(Rule.InList(setOf(1L)), Rule.HasTag("x")), all(Rule.InList(setOf(1L)), Rule.MinPriority(Priority.HIGH)))
|
||||
assertThat(either.scopePreset(clock)).isEqualTo(ScopePreset(listId = 1L))
|
||||
assertThat(all(Rule.InList(setOf(1L)), Rule.Not(Rule.InList(setOf(2L)))).scopePreset(clock).listId).isEqualTo(1L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the due date is the first of none, today and tomorrow the scope admits`() {
|
||||
assertThat(due(DueWindow.TODAY).scopePreset(clock).dueDate).isEqualTo(today)
|
||||
assertThat(due(DueWindow.UPCOMING).scopePreset(clock).dueDate).isEqualTo(today.plusDays(1))
|
||||
assertThat(due(DueWindow.NO_DATE).scopePreset(clock).dueDate).isNull()
|
||||
assertThat(due(DueWindow.OVERDUE).scopePreset(clock).dueDate).isNull()
|
||||
assertThat(Rule.Due(DueSpec.ThisWeek).scopePreset(clock).dueDate).isEqualTo(today)
|
||||
assertThat(Rule.Due(DueSpec.NextDays(3)).scopePreset(clock).dueDate).isEqualTo(today)
|
||||
assertThat(Rule.HasTag("x").scopePreset(clock).dueDate).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `due conditions together all have to admit the day`() {
|
||||
val upcomingThisWeek = all(due(DueWindow.UPCOMING), Rule.Due(DueSpec.ThisWeek))
|
||||
assertThat(upcomingThisWeek.scopePreset(clock).dueDate).isEqualTo(today.plusDays(1))
|
||||
// On the week's last day, tomorrow is next week's.
|
||||
assertThat(upcomingThisWeek.scopePreset(clockOn(LocalDate.of(2026, 11, 29))).dueDate).isNull()
|
||||
assertThat(any(due(DueWindow.TODAY), due(DueWindow.UPCOMING)).scopePreset(clock).dueDate).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a form reads as the open task it makes`() {
|
||||
val form = TaskForm(title = "t", listId = 3, tags = listOf("x"), priority = Priority.HIGH, due = allDayInstantOf(today), isAllDay = true)
|
||||
val task = form.asOpenTask()
|
||||
assertThat(task.listId).isEqualTo(3L)
|
||||
assertThat(task.tags).containsExactly("x")
|
||||
assertThat(task.priority).isEqualTo(Priority.HIGH)
|
||||
assertThat(task.isClosed).isFalse()
|
||||
assertThat(due(DueWindow.TODAY).matches(task, clock)).isTrue()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
import kotlin.time.toKotlinInstant
|
||||
|
||||
class ViewLayoutTest {
|
||||
|
||||
private val home = View.home().blocks
|
||||
private val today = BlockSource.Smart(SmartList.TODAY)
|
||||
private val withTaskList = home + Block(8, BlockType.TASK_LIST, BlockSource.Smart(SmartList.ALL))
|
||||
|
||||
@Test
|
||||
fun `an added block goes last with a new id`() {
|
||||
val added = home.withBlock(BlockType.WEEK_STRIP)
|
||||
assertThat(added.last()).isEqualTo(Block(8, BlockType.WEEK_STRIP))
|
||||
assertThat(added.layoutProblems()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an added block goes before the task list, which stays last`() {
|
||||
val added = withTaskList.withBlock(BlockType.COUNT_TILE, today)
|
||||
assertThat(added.map { it.type }.takeLast(2)).containsExactly(BlockType.COUNT_TILE, BlockType.TASK_LIST).inOrder()
|
||||
assertThat(added.first { it.type == BlockType.COUNT_TILE && it.id == 9L }.width).isEqualTo(BlockWidth.HALF)
|
||||
assertThat(added.layoutProblems()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a second task list or a block with the wrong source isn't added`() {
|
||||
assertThat(withTaskList.canAdd(BlockType.TASK_LIST)).isFalse()
|
||||
assertThat(withTaskList.withBlock(BlockType.TASK_LIST, today)).isEqualTo(withTaskList)
|
||||
assertThat(home.withBlock(BlockType.PREVIEW)).isEqualTo(home)
|
||||
assertThat(home.withBlock(BlockType.TAGS, today)).isEqualTo(home)
|
||||
assertThat(home.canAdd(BlockType.TASK_LIST)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a removed block comes back where it was`() {
|
||||
val removed = home.without(4)
|
||||
assertThat(removed.map { it.id }).containsExactly(1L, 2L, 3L, 5L, 6L, 7L).inOrder()
|
||||
val restored = removed.restored(home[3], 3)
|
||||
assertThat(restored).isEqualTo(home)
|
||||
assertThat(restored.restored(home[3], 0)).isEqualTo(home)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a removed task list comes back last whatever its index`() {
|
||||
val taskList = withTaskList.last()
|
||||
val restored = withTaskList.without(taskList.id).restored(taskList, 0)
|
||||
assertThat(restored.last()).isEqualTo(taskList)
|
||||
assertThat(restored.layoutProblems()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blocks move into the given order and the task list stays last`() {
|
||||
val moved = withTaskList.reordered(listOf(8, 7, 6, 5, 4, 3, 2, 1))
|
||||
assertThat(moved.map { it.id }).containsExactly(7L, 6L, 5L, 4L, 3L, 2L, 1L, 8L).inOrder()
|
||||
assertThat(moved.layoutProblems()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blocks the order leaves out keep their place after it`() {
|
||||
val moved = home.reordered(listOf(3, 2))
|
||||
assertThat(moved.map { it.id }).containsExactly(3L, 2L, 1L, 4L, 5L, 6L, 7L).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block resizes only to a width its type allows`() {
|
||||
assertThat(home.resized(2, BlockWidth.FULL).first { it.id == 2L }.width).isEqualTo(BlockWidth.FULL)
|
||||
assertThat(home.resized(1, BlockWidth.HALF).first { it.id == 1L }.width).isEqualTo(BlockWidth.HALF)
|
||||
assertThat(home.resized(4, BlockWidth.HALF)).isEqualTo(home)
|
||||
assertThat(home.resized(4, BlockWidth.HALF).layoutProblems()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block's settings replace it in place`() {
|
||||
val preview = home.first { it.id == 4L }
|
||||
val changed = preview.copy(ignoreScope = true, options = BlockOptions.Preview(count = 10, title = "Soon"))
|
||||
assertThat(home.replaced(changed)[3]).isEqualTo(changed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the week holds today and starts on the week start`() {
|
||||
val thursday = LocalDate.of(2026, 11, 26)
|
||||
assertThat(weekDays(thursday, DayOfWeek.MONDAY).first()).isEqualTo(LocalDate.of(2026, 11, 23))
|
||||
assertThat(weekDays(thursday, DayOfWeek.SUNDAY).first()).isEqualTo(LocalDate.of(2026, 11, 22))
|
||||
assertThat(weekDays(thursday, DayOfWeek.SATURDAY).first()).isEqualTo(LocalDate.of(2026, 11, 21))
|
||||
assertThat(weekDays(thursday, DayOfWeek.THURSDAY).first()).isEqualTo(thursday)
|
||||
assertThat(weekDays(thursday, DayOfWeek.FRIDAY).first()).isEqualTo(LocalDate.of(2026, 11, 20))
|
||||
weekDays(thursday, DayOfWeek.SUNDAY).let { days ->
|
||||
assertThat(days).hasSize(7)
|
||||
assertThat(days).contains(thursday)
|
||||
assertThat(days.zipWithNext().all { (a, b) -> b == a.plusDays(1) }).isTrue()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a week runs across month and year ends`() {
|
||||
val days = weekDays(LocalDate.of(2026, 12, 31), DayOfWeek.MONDAY)
|
||||
assertThat(days.first()).isEqualTo(LocalDate.of(2026, 12, 28))
|
||||
assertThat(days.last()).isEqualTo(LocalDate.of(2027, 1, 3))
|
||||
val leap = weekDays(LocalDate.of(2028, 3, 1), DayOfWeek.SUNDAY)
|
||||
assertThat(leap.first()).isEqualTo(LocalDate.of(2028, 2, 27))
|
||||
assertThat(leap).contains(LocalDate.of(2028, 2, 29))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `due dots count the open top-level tasks due on each day`() {
|
||||
val zone = ZoneId.of("Europe/Berlin")
|
||||
val days = weekDays(LocalDate.of(2026, 11, 26), DayOfWeek.MONDAY)
|
||||
fun at(date: LocalDate) = date.atTime(LocalTime.of(10, 0)).atZone(zone).toInstant().toKotlinInstant()
|
||||
val tasks = listOf(
|
||||
testTask(id = 1, due = at(LocalDate.of(2026, 11, 23))),
|
||||
testTask(id = 2, due = at(LocalDate.of(2026, 11, 23))),
|
||||
testTask(id = 3, due = at(LocalDate.of(2026, 11, 26)), status = TaskStatus.COMPLETED),
|
||||
testTask(id = 4, due = at(LocalDate.of(2026, 11, 29)), parentId = 1),
|
||||
testTask(id = 5, due = at(LocalDate.of(2026, 11, 30))),
|
||||
testTask(id = 6, due = at(LocalDate.of(2026, 11, 29))),
|
||||
testTask(id = 7),
|
||||
)
|
||||
assertThat(dueCounts(tasks, days, zone))
|
||||
.containsExactly(LocalDate.of(2026, 11, 23), 2, LocalDate.of(2026, 11, 29), 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recently completed are the latest completed, newest first`() {
|
||||
fun done(id: Long, at: Long?, parent: Long? = null) = testTask(
|
||||
id = id,
|
||||
status = TaskStatus.COMPLETED,
|
||||
completedAt = at?.let { Instant.fromEpochSeconds(it) },
|
||||
parentId = parent,
|
||||
)
|
||||
val tasks = listOf(done(1, 100), done(2, 300), done(3, null), testTask(id = 4), done(5, 200), done(6, 400, parent = 1))
|
||||
assertThat(recentlyCompleted(tasks, 3).map { it.taskId }).containsExactly(2L, 5L, 1L).inOrder()
|
||||
assertThat(recentlyCompleted(tasks, 10).map { it.taskId }).containsExactly(2L, 5L, 1L, 3L).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `undo still brings a block back when a new one took its id meanwhile`() {
|
||||
val last = home.last()
|
||||
val removed = home.without(last.id)
|
||||
// A block added while the undo is offered keeps clear of the removed block's id.
|
||||
val added = removed.withBlock(BlockType.WEEK_STRIP, reserved = setOf(last.id))
|
||||
assertThat(added.last().id).isEqualTo(last.id + 1)
|
||||
// And one that took it anyway doesn't swallow the undo.
|
||||
val clash = removed + Block(last.id, BlockType.WEEK_STRIP)
|
||||
val restored = clash.restored(last, 6)
|
||||
assertThat(restored).hasSize(8)
|
||||
assertThat(restored[6].type).isEqualTo(last.type)
|
||||
assertThat(restored.layoutProblems()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a removed task list doesn't come back next to a new one`() {
|
||||
val taskList = withTaskList.last()
|
||||
val other = withTaskList.without(taskList.id).withBlock(BlockType.TASK_LIST, BlockSource.Smart(SmartList.TODAY))
|
||||
assertThat(other.restored(taskList, 7)).isEqualTo(other)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
class ViewScopeTest {
|
||||
|
||||
private val zone = ZoneId.of("Europe/Berlin")
|
||||
private val today = LocalDate.of(2026, 11, 26)
|
||||
private val clock = RuleClock(startOfDay(today, zone), startOfDay(today.plusDays(1), zone), zone, DayOfWeek.MONDAY)
|
||||
private val context = SourceContext(clock, upcomingEnd = null, filters = emptyMap())
|
||||
|
||||
private fun view(scope: Rule?) = View(2, "Work", ViewIcon.WORK, scope, emptyList())
|
||||
|
||||
@Test
|
||||
fun `a scope names its lists and the lists a task must be in`() {
|
||||
val rule = Rule.AllOf(
|
||||
listOf(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(1L, 2L)), Rule.InList(setOf(3L)))),
|
||||
Rule.Not(Rule.InList(setOf(4L))),
|
||||
Rule.HasTag("x"),
|
||||
),
|
||||
)
|
||||
assertThat(rule.namedListIds()).containsExactly(1L, 2L, 3L, 4L)
|
||||
assertThat(rule.listUniverse()).containsExactly(1L, 2L, 3L)
|
||||
assertThat(Rule.AllOf(listOf(Rule.InList(setOf(1L, 2L)), Rule.InList(setOf(2L, 3L)))).listUniverse()).containsExactly(2L)
|
||||
assertThat(Rule.AnyOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x"))).listUniverse()).isNull()
|
||||
assertThat(Rule.Not(Rule.InList(setOf(1L))).listUniverse()).isNull()
|
||||
assertThat(Rule.Everything.listUniverse()).isNull()
|
||||
assertThat(Rule.AnyOf(emptyList()).listUniverse()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no scope admits every task`() {
|
||||
val applied = view(null).appliedScope(setOf(1L))
|
||||
assertThat(applied).isEqualTo(AppliedScope.None)
|
||||
assertThat(applied.admits(testTask(listId = 9), clock)).isTrue()
|
||||
assertThat(applied.lists).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a deleted list in the scope matches nothing, never widening`() {
|
||||
val applied = view(Rule.InList(setOf(1L, 2L))).appliedScope(exist = setOf(2L, 3L))
|
||||
assertThat(applied.goneLists).containsExactly(1L)
|
||||
assertThat(applied.admits(testTask(listId = 2), clock)).isTrue()
|
||||
assertThat(applied.admits(testTask(listId = 3), clock)).isFalse()
|
||||
|
||||
val allGone = view(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x")))).appliedScope(exist = setOf(3L))
|
||||
assertThat(allGone.goneLists).containsExactly(1L)
|
||||
assertThat(allGone.admits(testTask(listId = 3, tags = listOf("x")), clock)).isFalse()
|
||||
// A list made later with the deleted one's id doesn't creep back in.
|
||||
assertThat(allGone.admits(testTask(listId = 1, tags = listOf("x")), clock)).isFalse()
|
||||
assertThat(allGone.lists).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a read finding no lists proves none gone`() {
|
||||
val applied = view(Rule.InList(setOf(1L))).appliedScope(exist = emptySet())
|
||||
assertThat(applied.goneLists).isEmpty()
|
||||
assertThat(applied.admits(testTask(listId = 1), clock)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a list named in the scope shows in the smart lists though hidden`() {
|
||||
val applied = view(Rule.InList(setOf(1L))).appliedScope(setOf(1L, 2L))
|
||||
assertThat(applied.hiddenFromSmart(setOf(1L, 2L))).containsExactly(2L)
|
||||
assertThat(AppliedScope.None.hiddenFromSmart(setOf(1L))).containsExactly(1L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block that ignores the scope reads through none`() {
|
||||
val applied = view(Rule.HasTag("x")).appliedScope(setOf(1L))
|
||||
val block = Block(1, BlockType.TAGS)
|
||||
assertThat(applied.forBlock(block)).isEqualTo(applied)
|
||||
assertThat(applied.forBlock(block.copy(ignoreScope = true))).isEqualTo(AppliedScope.None)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a source is gone once its list or filter is`() {
|
||||
assertThat(BlockSource.List(1).isGone(lists = setOf(2L), filters = emptySet())).isTrue()
|
||||
assertThat(BlockSource.List(1).isGone(lists = emptySet(), filters = emptySet())).isFalse()
|
||||
assertThat(BlockSource.Filter(4).isGone(lists = setOf(1L), filters = setOf(5L))).isTrue()
|
||||
assertThat(BlockSource.Filter(4).isGone(lists = setOf(1L), filters = setOf(4L))).isFalse()
|
||||
assertThat(BlockSource.Smart(SmartList.ALL).isGone(emptySet(), emptySet())).isFalse()
|
||||
assertThat(BlockSource.Tag("x").isGone(setOf(1L), emptySet())).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sources hold their tasks, counts the open ones but for Completed`() {
|
||||
val open = testTask(listId = 1, tags = listOf("x"))
|
||||
val done = testTask(id = 2, listId = 1, status = TaskStatus.COMPLETED)
|
||||
val filter = SavedFilter(4, "f", Rule.HasTag("x"))
|
||||
val withFilter = SourceContext(clock, null, mapOf(4L to filter))
|
||||
assertThat(BlockSource.List(1).contains(done, context)).isTrue()
|
||||
assertThat(BlockSource.List(1).counts(done, context)).isFalse()
|
||||
assertThat(BlockSource.List(1).counts(open, context)).isTrue()
|
||||
assertThat(BlockSource.Smart(SmartList.COMPLETED).counts(done, context)).isTrue()
|
||||
assertThat(BlockSource.Smart(SmartList.COMPLETED).counts(open, context)).isFalse()
|
||||
assertThat(BlockSource.Smart(SmartList.ALL).counts(open, context, hidden = setOf(1L))).isFalse()
|
||||
assertThat(BlockSource.Tag("x").counts(open, context)).isTrue()
|
||||
assertThat(BlockSource.Filter(4).counts(open, withFilter)).isTrue()
|
||||
assertThat(BlockSource.Filter(4).counts(open, context)).isFalse()
|
||||
assertThat(BlockSource.ListElsewhere("OWN:1").contains(open, context)).isFalse()
|
||||
assertThat(BlockSource.Rules(Rule.InList(setOf(1L))).counts(open, context)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `pinning a list or filter makes a view of it`() {
|
||||
val list = TaskList(7, "Work", 0, "Local", "local", isSynced = false, isVisible = true, owner = null)
|
||||
val pinned = pinnedViewOf(list, null)!!
|
||||
assertThat(pinned.id).isEqualTo(0L)
|
||||
assertThat(pinned.name).isEqualTo("Work")
|
||||
assertThat(pinned.icon).isEqualTo(ViewIcon.LIST)
|
||||
assertThat(pinned.scope).isEqualTo(Rule.InList(setOf(7L)))
|
||||
assertThat(pinned.quickAdd).isTrue()
|
||||
assertThat(pinned.blocks.map { it.type to it.source })
|
||||
.containsExactly(BlockType.TASK_LIST to BlockSource.Smart(SmartList.ALL))
|
||||
assertThat(pinned.problems).isEmpty()
|
||||
|
||||
val rule = Rule.AnyOf(listOf(Rule.HasTag("next"), Rule.InList(setOf(3L))))
|
||||
val fromFilter = pinnedViewOf(null, SavedFilter(4, "Next", rule))!!
|
||||
assertThat(fromFilter.name).isEqualTo("Next")
|
||||
assertThat(fromFilter.icon).isEqualTo(ViewIcon.FILTER)
|
||||
assertThat(fromFilter.scope).isEqualTo(rule)
|
||||
assertThat(pinnedViewOf(null, null)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new view starts with Home's blocks and no scope`() {
|
||||
val view = newView(0, "Mine")
|
||||
assertThat(view.blocks).isEqualTo(View.home().blocks)
|
||||
assertThat(view.scope).isNull()
|
||||
assertThat(view.icon).isEqualTo(ViewIcon.DASHBOARD)
|
||||
assertThat(view.deletable).isTrue()
|
||||
assertThat(View.home().deletable).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reordering keeps Home first and leaves views not named after the others`() {
|
||||
val views = listOf(View.home(), view(null), view(null).copy(id = 3), view(null).copy(id = 4))
|
||||
assertThat(views.reordered(listOf(4L, View.HOME_ID, 2L)).map { it.id }).containsExactly(1L, 4L, 2L, 3L).inOrder()
|
||||
assertThat(views.reordered(listOf(3L, 2L, 4L)).map { it.id }).containsExactly(1L, 3L, 2L, 4L).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the start destination opens its view, or a list or filter over Home`() {
|
||||
val views = setOf(1L, 2L, 3L)
|
||||
assertThat(StartDestination.LastUsed.plan(views, lastUsed = 3, lists = null, filters = emptySet()))
|
||||
.isEqualTo(StartPlan(3))
|
||||
assertThat(StartDestination.LastUsed.plan(views, lastUsed = 9, lists = null, filters = emptySet()))
|
||||
.isEqualTo(StartPlan(View.HOME_ID))
|
||||
assertThat(StartDestination.View(2).plan(views, lastUsed = 3, lists = null, filters = emptySet()))
|
||||
.isEqualTo(StartPlan(2))
|
||||
assertThat(StartDestination.View(9).plan(views, lastUsed = 3, lists = null, filters = emptySet()))
|
||||
.isEqualTo(StartPlan(View.HOME_ID))
|
||||
assertThat(StartDestination.List(5).plan(views, lastUsed = 3, lists = setOf(5L), filters = emptySet()))
|
||||
.isEqualTo(StartPlan(View.HOME_ID, TaskFilter.OfList(5)))
|
||||
assertThat(StartDestination.List(5).plan(views, lastUsed = 3, lists = setOf(6L), filters = emptySet()))
|
||||
.isEqualTo(StartPlan(View.HOME_ID))
|
||||
assertThat(StartDestination.List(5).plan(views, lastUsed = 3, lists = null, filters = emptySet()))
|
||||
.isEqualTo(StartPlan(View.HOME_ID, TaskFilter.OfList(5)))
|
||||
assertThat(StartDestination.Filter(4).plan(views, lastUsed = 3, lists = null, filters = setOf(4L)))
|
||||
.isEqualTo(StartPlan(View.HOME_ID, TaskFilter.Saved(4)))
|
||||
assertThat(StartDestination.Filter(4).plan(views, lastUsed = 3, lists = null, filters = emptySet()))
|
||||
.isEqualTo(StartPlan(View.HOME_ID))
|
||||
assertThat(DefaultStartDestination).isEqualTo(StartDestination.View(View.HOME_ID))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only a gone list that narrowed the scope raises the notice`() {
|
||||
assertThat(view(Rule.InList(setOf(1L))).appliedScope(setOf(2L)).narrowedByGone).isTrue()
|
||||
val excluded = view(Rule.Not(Rule.InList(setOf(1L)))).appliedScope(setOf(2L))
|
||||
assertThat(excluded.goneLists).containsExactly(1L)
|
||||
assertThat(excluded.narrowedByGone).isFalse()
|
||||
assertThat(excluded.admits(testTask(listId = 2), clock)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a scope's limiting lists leave out those under a not`() {
|
||||
assertThat(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.Not(Rule.InList(setOf(2L))))).limitingListIds()).containsExactly(1L)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,11 @@ import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultDueDate
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
|
||||
@@ -30,6 +35,7 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||
@@ -118,6 +124,42 @@ class TaskEditViewModelTest {
|
||||
assertThat(vm.state.value.start).isEqualTo(allDayInstantOf(day.plusDays(1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new task in a scoped view takes the scope's list, tags and due`() = runTest {
|
||||
repository.lists = listOf(list(1, "Work"), list(2, "Home"))
|
||||
val prefs = settingsPrefs().apply { setDefaultListId(2) }
|
||||
val scope = Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x"), Rule.Due(DueSpec.Window(DueWindow.TODAY))))
|
||||
val viewId = checkNotNull(prefs.saveView(View(0, "Work", ViewIcon.WORK, scope, emptyList())))
|
||||
val vm = TaskEditViewModel(repository, prefs)
|
||||
val today = aroundToday { vm.bindNew(presetTags = listOf("y"), scopeViewId = viewId) }
|
||||
|
||||
// The views are read off the main thread.
|
||||
val state = vm.state.first { !it.loading }
|
||||
assertThat(state.listId).isEqualTo(1L)
|
||||
assertThat(state.tags).containsExactly("y", "x").inOrder()
|
||||
assertThat(state.due).isIn(today.map { allDayInstantOf(it) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a list picked for the task wins over the scope's`() = runTest {
|
||||
repository.lists = listOf(list(1, "Work"), list(2, "Home"))
|
||||
val prefs = settingsPrefs()
|
||||
val viewId = checkNotNull(prefs.saveView(View(0, "Work", ViewIcon.WORK, Rule.InList(setOf(1L)), emptyList())))
|
||||
val vm = TaskEditViewModel(repository, prefs).apply { bindNew(presetListId = 2, scopeViewId = viewId) }
|
||||
|
||||
assertThat(vm.state.first { !it.loading }.listId).isEqualTo(2L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a due time from quick-add makes the task timed`() = runTest {
|
||||
val vm = TaskEditViewModel(repository, settingsPrefs())
|
||||
val day = LocalDate.now().plusDays(2)
|
||||
vm.bindNew(presetDueDate = day, presetDueTime = LocalTime.of(14, 30))
|
||||
|
||||
assertThat(vm.state.value.due).isEqualTo(localToInstant(day, LocalTime.of(14, 30)))
|
||||
assertThat(vm.state.value.isAllDay).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new subtask takes no default due`() = runTest {
|
||||
val prefs = settingsPrefs().apply { setDefaultDueDate(DefaultDueDate.TOMORROW) }
|
||||
@@ -420,6 +462,9 @@ class TaskEditViewModelTest {
|
||||
assertThat(sub.state.value.repeatFromOffered).isFalse()
|
||||
}
|
||||
|
||||
private fun list(id: Long, name: String) =
|
||||
TaskList(id, name, 0, "me", "bitfire.at.davdroid", isSynced = true, isVisible = true, owner = null)
|
||||
|
||||
private fun task(start: Instant?, due: Instant?) = Task(
|
||||
taskId = TASK_ID,
|
||||
listId = LIST_ID,
|
||||
@@ -451,11 +496,12 @@ class TaskEditViewModelTest {
|
||||
var reminders: List<TaskReminder> = emptyList()
|
||||
var saved: TaskForm? = null
|
||||
var untimedEnds = true
|
||||
var lists: List<TaskList> = emptyList()
|
||||
|
||||
override fun supportsUntimedEnds() = untimedEnds
|
||||
|
||||
override fun supportsRepeatFromCompletion() = true
|
||||
override fun taskLists() = flowOf(emptyList<TaskList>())
|
||||
override fun taskLists() = flowOf(lists)
|
||||
override fun tasks(filter: TaskFilter): Flow<List<Task>> = flowOf(emptyList())
|
||||
override fun taskDetail(taskId: Long, occurrenceStart: Instant?) =
|
||||
flowOf(task?.let { TaskDetail(it, emptyList()) })
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class RuleDraftTest {
|
||||
|
||||
private val work = Rule.InList(setOf(1L))
|
||||
private val focus = Rule.HasTag("focus")
|
||||
private val high = Rule.MinPriority(Priority.HIGH)
|
||||
private val nested = Rule.AllOf(listOf(work, Rule.AnyOf(listOf(focus, high)), Rule.Not(Rule.HasTag("someday"))))
|
||||
|
||||
@Test
|
||||
fun `a rule the simple form can show opens there, any other in the advanced editor`() {
|
||||
assertThat(RuleDraft.of(work).simple).isEqualTo(SimpleRule(listIds = setOf(1L)))
|
||||
val advanced = RuleDraft.of(nested)
|
||||
assertThat(advanced.advanced).isTrue()
|
||||
assertThat(advanced.rule).isEqualTo(nested)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the advanced editor gets a group at the root and no double negation`() {
|
||||
assertThat(Rule.Not(Rule.Not(work)).forAdvanced()).isEqualTo(Rule.AllOf(listOf(work)))
|
||||
assertThat(Rule.Not(Rule.AnyOf(listOf(Rule.Not(Rule.Not(focus))))).forAdvanced())
|
||||
.isEqualTo(Rule.Not(Rule.AnyOf(listOf(focus))))
|
||||
assertThat(nested.forAdvanced()).isEqualTo(nested)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `simple to advanced always, back only while the simple form can show the rule`() {
|
||||
val simple = RuleDraft.of(SimpleRule(match = Match.ANY, listIds = setOf(1L), tags = setOf("focus")))
|
||||
val advanced = simple.toAdvanced()
|
||||
assertThat(advanced.advanced).isTrue()
|
||||
assertThat(advanced.rule).isEqualTo(simple.rule)
|
||||
assertThat(advanced.toSimple()).isEqualTo(simple)
|
||||
|
||||
val grown = advanced.editAdvanced { it.addTo(emptyList(), Rule.AllOf(listOf(high, focus))) }
|
||||
assertThat(grown.canSimplify).isFalse()
|
||||
assertThat(grown.toSimple()).isEqualTo(grown)
|
||||
assertThat(grown.editAdvanced { it.removeAt(listOf(2)) }.toSimple().simple).isEqualTo(simple.simple)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `each editor's changes only apply in it`() {
|
||||
val simple = RuleDraft.of(SimpleRule())
|
||||
assertThat(simple.editAdvanced { Rule.Everything.toggleNot() }).isEqualTo(simple)
|
||||
val advanced = simple.toAdvanced()
|
||||
assertThat(advanced.editSimple { it.copy(minPriority = Priority.LOW) }).isEqualTo(advanced)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a look at the advanced editor brings the simple form back as it was left`() {
|
||||
val any = RuleDraft.of(SimpleRule()).editSimple { it.copy(match = Match.ANY) }
|
||||
assertThat(any.toAdvanced().toSimple().simple!!.match).isEqualTo(Match.ANY)
|
||||
val changed = any.toAdvanced().editAdvanced { it.addTo(emptyList(), work) }
|
||||
assertThat(changed.toSimple().simple).isEqualTo(SimpleRule(listIds = setOf(1L)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `is not drops out of a section once nothing in it is picked`() {
|
||||
val draft = RuleDraft.of(SimpleRule(tags = setOf("a"), tagsNegated = true))
|
||||
.editSimple { it.copy(tags = emptySet()) }
|
||||
assertThat(draft.simple!!.tagsNegated).isFalse()
|
||||
assertThat(draft.editSimple { it.copy(tags = setOf("b")) }.rule)
|
||||
.isEqualTo(Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.HasTag("b"))))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the simple form keeps a choice its rule can't hold`() {
|
||||
val any = RuleDraft.of(SimpleRule()).editSimple { it.copy(match = Match.ANY) }
|
||||
assertThat(any.simple!!.match).isEqualTo(Match.ANY)
|
||||
assertThat(any.rule).isEqualTo(Rule.Everything)
|
||||
val picked = any.editSimple { it.copy(listIds = setOf(1L), tags = setOf("a")) }
|
||||
assertThat(picked.rule).isEqualTo(Rule.AnyOf(listOf(work, Rule.AnyOf(listOf(Rule.HasTag("a"))))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `conditions and groups are added, changed and removed by path`() {
|
||||
var rule: Rule = Rule.AllOf(emptyList())
|
||||
rule = rule.addTo(emptyList(), work)
|
||||
rule = rule.addTo(emptyList(), newGroupUnder(rule))
|
||||
assertThat(rule.at(listOf(1))).isEqualTo(Rule.AnyOf(emptyList()))
|
||||
rule = rule.addTo(listOf(1), focus).addTo(listOf(1), high)
|
||||
rule = rule.addTo(emptyList(), Rule.Not(Rule.HasTag("someday")))
|
||||
assertThat(rule).isEqualTo(nested)
|
||||
|
||||
assertThat(rule.updateAt(listOf(1, 0), Rule::toggleNot).at(listOf(1, 0))).isEqualTo(Rule.Not(focus))
|
||||
assertThat(rule.updateAt(listOf(2), Rule::toggleNot).at(listOf(2))).isEqualTo(Rule.HasTag("someday"))
|
||||
assertThat(rule.updateAt(listOf(1)) { it.withGroupMatch(Match.ALL) }.at(listOf(1))).isEqualTo(Rule.AllOf(listOf(focus, high)))
|
||||
assertThat(rule.removeAt(listOf(1, 0)).at(listOf(1))).isEqualTo(Rule.AnyOf(listOf(high)))
|
||||
assertThat(rule.removeAt(emptyList())).isEqualTo(rule)
|
||||
assertThat(rule.removeAt(listOf(9))).isEqualTo(rule)
|
||||
assertThat(rule.updateAt(listOf(0, 3)) { Rule.Everything }).isEqualTo(rule)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a negated group keeps its negation through changes inside it`() {
|
||||
var rule: Rule = Rule.AllOf(listOf(Rule.Not(Rule.AnyOf(listOf(focus)))))
|
||||
rule = rule.addTo(listOf(0), high)
|
||||
assertThat(rule.at(listOf(0))).isEqualTo(Rule.Not(Rule.AnyOf(listOf(focus, high))))
|
||||
assertThat(rule.at(listOf(0, 1))).isEqualTo(high)
|
||||
rule = rule.updateAt(listOf(0)) { it.withGroupMatch(Match.ALL) }
|
||||
assertThat(rule.at(listOf(0))).isEqualTo(Rule.Not(Rule.AllOf(listOf(focus, high))))
|
||||
rule = rule.removeAt(listOf(0, 0))
|
||||
assertThat(rule.at(listOf(0))).isEqualTo(Rule.Not(Rule.AllOf(listOf(high))))
|
||||
assertThat(rule.at(listOf(0))!!.isGroup).isTrue()
|
||||
assertThat(rule.at(listOf(0, 0))!!.field).isEqualTo(RuleField.PRIORITY)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new group is of the other kind than its parent`() {
|
||||
assertThat(newGroupUnder(Rule.AllOf(emptyList()))).isEqualTo(Rule.AnyOf(emptyList()))
|
||||
assertThat(newGroupUnder(Rule.Not(Rule.AnyOf(emptyList())))).isEqualTo(Rule.AllOf(emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `templates fill in the rules they name`() {
|
||||
val tags = listOf("Waiting", "nextaction")
|
||||
fun rule(template: FilterTemplate) = template.form(nextList = 2L, tags = tags).toRule()
|
||||
|
||||
assertThat(rule(FilterTemplate.NEXT_ACTIONS)).isEqualTo(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(2L)), Rule.AnyOf(listOf(Rule.HasTag("nextaction"))))),
|
||||
)
|
||||
assertThat(rule(FilterTemplate.THIS_WEEK)).isEqualTo(
|
||||
Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(DueSpec.Window(DueWindow.OVERDUE)), Rule.Due(DueSpec.ThisWeek))))),
|
||||
)
|
||||
assertThat(rule(FilterTemplate.THIS_MONTH)).isEqualTo(Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(DueSpec.ThisMonth))))))
|
||||
assertThat(rule(FilterTemplate.HIGH_PRIORITY)).isEqualTo(Rule.AllOf(listOf(high)))
|
||||
assertThat(rule(FilterTemplate.WAITING_FOR)).isEqualTo(Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.HasTag("Waiting"))))))
|
||||
assertThat(rule(FilterTemplate.NO_DATE))
|
||||
.isEqualTo(Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(DueSpec.Window(DueWindow.NO_DATE)))))))
|
||||
// Every template opens in the simple editor.
|
||||
for (template in FilterTemplate.entries) assertThat(RuleDraft.of(rule(template)).simple).isNotNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `with the list skipped and no tags in use the GTD template still asks for the tag`() {
|
||||
assertThat(FilterTemplate.NEXT_ACTIONS.form(nextList = null, tags = emptyList()))
|
||||
.isEqualTo(SimpleRule(match = Match.ANY, tags = setOf("nextAction")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a rule that admits every task by its shape is told apart from one that narrows`() {
|
||||
val empty = Rule.AllOf(emptyList())
|
||||
val nothing = Rule.AnyOf(emptyList())
|
||||
assertThat(Rule.AllOf(listOf(empty)).admitsEverything).isTrue()
|
||||
assertThat(Rule.AllOf(listOf(Rule.Not(nothing))).admitsEverything).isTrue()
|
||||
assertThat(Rule.Not(Rule.InList(emptySet())).admitsEverything).isTrue()
|
||||
assertThat(Rule.MinPriority(Priority.NONE).admitsEverything).isTrue()
|
||||
assertThat(Rule.AnyOf(listOf(work, empty)).admitsEverything).isTrue()
|
||||
assertThat(Rule.AllOf(listOf(work, empty)).admitsEverything).isFalse()
|
||||
assertThat(Rule.Not(Rule.InList(emptySet(), setOf("EXTERNAL:1"))).admitsEverything).isFalse()
|
||||
assertThat(nothing.admitsEverything).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a result survives the trip between screens`() {
|
||||
val rule = Rule.AllOf(listOf(Rule.InList(setOf(3L), setOf("EXTERNAL:9")), Rule.Not(Rule.HasTag("a,b(c)")), Rule.Due(DueSpec.NextDays(5))))
|
||||
for (result in listOf(RuleEditResult.Rules(rule), RuleEditResult.Filter(12))) {
|
||||
assertThat(RuleEditResult.decode(result.encode())).isEqualTo(result)
|
||||
}
|
||||
assertThat(RuleEditResult.decode("rules:nope(")).isNull()
|
||||
assertThat(RuleEditResult.decode("other")).isNull()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.Block
|
||||
import de.jeanlucmakiola.agendula.domain.BlockSource
|
||||
import de.jeanlucmakiola.agendula.domain.BlockType
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.newView
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.lang.reflect.Proxy
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class RuleEditViewModelTest {
|
||||
|
||||
private val prefs = SettingsPrefs(MemoryDataStore(), ProviderResolver(NoProviders))
|
||||
private val repository = FakeRepository(listOf(list(1), list(2)))
|
||||
|
||||
@BeforeEach fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
|
||||
|
||||
@AfterEach fun tearDown() = Dispatchers.resetMain()
|
||||
|
||||
/** A view holding a tile on [source] as block 2, as stored. */
|
||||
private fun storedView(source: BlockSource): Long = runBlocking {
|
||||
prefs.setStorageMode(StorageMode.OWN)
|
||||
val view = newView(0, "V").let { v ->
|
||||
v.copy(blocks = v.blocks.map { if (it.id == 2L) it.copy(source = source) else it })
|
||||
}
|
||||
prefs.saveView(view)!!
|
||||
}
|
||||
|
||||
private fun block(viewId: Long): Block = runBlocking { prefs.views.first().first { it.id == viewId }.blocks.first { it.id == 2L } }
|
||||
|
||||
/** An editor bound to [target], once it has loaded; the views are read off the main thread. */
|
||||
private fun editor(target: RuleEditViewModel.Target, purpose: RulePurpose) =
|
||||
RuleEditViewModel(prefs, repository).apply {
|
||||
bind(target, purpose)
|
||||
runBlocking { state.first { it != null } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a scope comes back as rules and offers no templates`() {
|
||||
val scope = Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("work")))
|
||||
val vm = editor(RuleEditViewModel.Target.Result(scope), RulePurpose.SCOPE)
|
||||
assertThat(vm.state.value!!.choosingTemplate).isFalse()
|
||||
assertThat(vm.state.value!!.rules.rule).isEqualTo(scope)
|
||||
|
||||
vm.updateRules { draft -> draft.editSimple { it.copy(minPriority = Priority.HIGH) } }
|
||||
var result: RuleEditResult? = null
|
||||
vm.save { result = it }
|
||||
assertThat(result).isEqualTo(
|
||||
RuleEditResult.Rules(
|
||||
Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.MinPriority(Priority.HIGH), Rule.AnyOf(listOf(Rule.HasTag("work"))))),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a list deleted since drops out, so its condition shows as matching nothing`() {
|
||||
val scope = Rule.InList(setOf(9L))
|
||||
val vm = editor(RuleEditViewModel.Target.Result(scope), RulePurpose.SCOPE)
|
||||
val draft = vm.state.value!!.rules
|
||||
assertThat(draft.advanced).isTrue()
|
||||
assertThat(draft.rule).isEqualTo(Rule.AllOf(listOf(Rule.InList(emptySet()))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `new custom rules start from a template and are written into the block`() {
|
||||
val viewId = storedView(BlockSource.Smart(SmartList.OVERDUE))
|
||||
val vm = editor(RuleEditViewModel.Target.Block(viewId, 2), RulePurpose.SOURCE)
|
||||
assertThat(vm.state.value!!.choosingTemplate).isTrue()
|
||||
|
||||
vm.startFrom(FilterTemplate.HIGH_PRIORITY)
|
||||
assertThat(vm.state.value!!.choosingTemplate).isFalse()
|
||||
var done = false
|
||||
vm.save { done = it == null }
|
||||
assertThat(done).isTrue()
|
||||
assertThat(block(viewId).source).isEqualTo(BlockSource.Rules(Rule.AllOf(listOf(Rule.MinPriority(Priority.HIGH)))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block's custom rules open as stored`() {
|
||||
val rule = Rule.AnyOf(listOf(Rule.InList(setOf(2L)), Rule.HasTag("next")))
|
||||
val viewId = storedView(BlockSource.Rules(rule))
|
||||
val vm = editor(RuleEditViewModel.Target.Block(viewId, 2), RulePurpose.SOURCE)
|
||||
assertThat(vm.state.value!!.choosingTemplate).isFalse()
|
||||
assertThat(vm.state.value!!.rules.rule).isEqualTo(rule)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `saved as a filter, the block shows the new filter`() {
|
||||
val viewId = storedView(BlockSource.Smart(SmartList.ALL))
|
||||
val vm = editor(RuleEditViewModel.Target.Block(viewId, 2), RulePurpose.SOURCE)
|
||||
vm.startFrom(null)
|
||||
vm.setSaveAsFilter(true)
|
||||
assertThat(vm.state.value!!.canSave).isFalse()
|
||||
vm.renameFilter(" Mine ")
|
||||
vm.save { }
|
||||
|
||||
val filter = runBlocking { prefs.savedFilters.first().single() }
|
||||
assertThat(filter.name).isEqualTo("Mine")
|
||||
assertThat(filter.rule).isEqualTo(Rule.Everything)
|
||||
assertThat(block(viewId).source).isEqualTo(BlockSource.Filter(filter.id))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block that is gone gets no filter and says so`() {
|
||||
runBlocking { prefs.setStorageMode(StorageMode.OWN) }
|
||||
val vm = editor(RuleEditViewModel.Target.Block(42, 2), RulePurpose.SOURCE)
|
||||
vm.startFrom(null)
|
||||
vm.setSaveAsFilter(true)
|
||||
vm.renameFilter("Mine")
|
||||
var done = false
|
||||
vm.save { done = true }
|
||||
assertThat(done).isFalse()
|
||||
assertThat(vm.blockGone.value).isTrue()
|
||||
assertThat(vm.saveFailed.value).isFalse()
|
||||
assertThat(runBlocking { prefs.savedFilters.first() }).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block removed from its view meanwhile isn't reported saved`() {
|
||||
val viewId = storedView(BlockSource.Smart(SmartList.ALL))
|
||||
val vm = editor(RuleEditViewModel.Target.Block(viewId, 99), RulePurpose.SOURCE)
|
||||
vm.startFrom(null)
|
||||
var done = false
|
||||
vm.save { done = true }
|
||||
assertThat(done).isFalse()
|
||||
assertThat(vm.blockGone.value).isTrue()
|
||||
assertThat(vm.saveFailed.value).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a second template tap while the first is read is ignored`() {
|
||||
val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE)
|
||||
vm.startFrom(null)
|
||||
vm.startFrom(FilterTemplate.HIGH_PRIORITY)
|
||||
assertThat(vm.state.value!!.rules.rule).isEqualTo(Rule.Everything)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `custom rules opened for a result hand back the filter they were saved as`() {
|
||||
runBlocking { prefs.setStorageMode(StorageMode.OWN) }
|
||||
val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE)
|
||||
assertThat(vm.state.value!!.choosingTemplate).isTrue()
|
||||
vm.startFrom(FilterTemplate.NO_DATE)
|
||||
vm.setSaveAsFilter(true)
|
||||
vm.renameFilter("Undated")
|
||||
var result: RuleEditResult? = null
|
||||
vm.save { result = it }
|
||||
val filter = runBlocking { prefs.savedFilters.first().single() }
|
||||
assertThat(result).isEqualTo(RuleEditResult.Filter(filter.id))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lists deleted while the editor was open don't come back with the rules`() {
|
||||
val vm = editor(RuleEditViewModel.Target.Result(Rule.InList(setOf(1L, 2L))), RulePurpose.SCOPE)
|
||||
repository.lists = listOf(list(1))
|
||||
var result: RuleEditResult? = null
|
||||
vm.save { result = it }
|
||||
assertThat(result).isEqualTo(RuleEditResult.Rules(Rule.InList(setOf(1L))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the GTD template takes the list picked for it, the tag as spelt in use, and names an unnamed filter`() {
|
||||
repository.tasks = listOf(testTask(tags = listOf("NEXTACTION")))
|
||||
val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE)
|
||||
vm.startFrom(FilterTemplate.NEXT_ACTIONS, nextList = 2L, name = "Next actions")
|
||||
assertThat(vm.state.value!!.rules.simple)
|
||||
.isEqualTo(SimpleRule(match = Match.ANY, listIds = setOf(2L), tags = setOf("NEXTACTION")))
|
||||
assertThat(vm.state.value!!.filterName).isEqualTo("Next actions")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a template's name doesn't replace one already typed`() {
|
||||
val vm = editor(RuleEditViewModel.Target.Result(null), RulePurpose.SOURCE)
|
||||
vm.renameFilter("Mine")
|
||||
vm.startFrom(FilterTemplate.NO_DATE, name = "No date")
|
||||
assertThat(vm.state.value!!.filterName).isEqualTo("Mine")
|
||||
}
|
||||
|
||||
private class FakeRepository(var lists: List<TaskList>) : TasksRepository by unsupported() {
|
||||
var tasks: List<Task> = emptyList()
|
||||
override fun taskLists() = flowOf(lists)
|
||||
override fun tasks(filter: TaskFilter): Flow<List<Task>> = flowOf(tasks)
|
||||
}
|
||||
|
||||
private class MemoryDataStore : DataStore<Preferences> {
|
||||
override val data = MutableStateFlow(emptyPreferences())
|
||||
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) =
|
||||
transform(data.value).also { data.value = it }
|
||||
}
|
||||
|
||||
private object NoProviders : ProviderEnvironment {
|
||||
override fun packageDeclaring(authority: String): String? = null
|
||||
override fun isGranted(permission: String) = false
|
||||
override fun appLabel(packageName: String): String? = null
|
||||
}
|
||||
|
||||
private companion object {
|
||||
fun list(id: Long) = TaskList(id, "L$id", 0, "Local", "local", isSynced = false, isVisible = true, owner = null)
|
||||
|
||||
/** Fails any call the test does not expect. */
|
||||
inline fun <reified T> unsupported(): T =
|
||||
Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ ->
|
||||
throw UnsupportedOperationException("Unexpected call: ${method.name}")
|
||||
} as T
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package de.jeanlucmakiola.agendula.ui.filters
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.domain.DueSpec
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.FilterCriteria
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
|
||||
import de.jeanlucmakiola.agendula.domain.matches
|
||||
import de.jeanlucmakiola.agendula.domain.startOfDay
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
class SimpleRuleTest {
|
||||
|
||||
private val today = window(DueWindow.TODAY)
|
||||
private val overdue = window(DueWindow.OVERDUE)
|
||||
private val noDate = window(DueWindow.NO_DATE)
|
||||
|
||||
private val forms = listOf(
|
||||
SimpleRule(listIds = setOf(1L)),
|
||||
SimpleRule(match = Match.ANY, listIds = setOf(1L), tags = setOf("nextAction")),
|
||||
SimpleRule(due = setOf(overdue, DueSpec.ThisWeek), dueNegated = true),
|
||||
SimpleRule(due = setOf(DueSpec.NextDays(7), noDate, today)),
|
||||
SimpleRule(listIds = setOf(1L, 2L), listsElsewhere = setOf("EXTERNAL:3"), listsNegated = true),
|
||||
SimpleRule(listsElsewhere = setOf("EXTERNAL:3")),
|
||||
SimpleRule(tags = setOf("a", "b"), tagMatch = TagMatch.ALL, tagsNegated = true),
|
||||
SimpleRule(tags = setOf("a"), tagMatch = TagMatch.ALL),
|
||||
SimpleRule(tags = setOf("a")),
|
||||
SimpleRule(minPriority = Priority.MEDIUM),
|
||||
SimpleRule(
|
||||
match = Match.ANY,
|
||||
due = setOf(DueSpec.ThisMonth),
|
||||
listIds = setOf(4L),
|
||||
tags = setOf("x", "y"),
|
||||
tagsNegated = true,
|
||||
minPriority = Priority.HIGH,
|
||||
),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `every form that narrows reads back from its rule unchanged`() {
|
||||
for (form in forms) assertThat(SimpleRule.of(form.toRule())).isEqualTo(form)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every rule the form writes is written again unchanged`() {
|
||||
for (rule in forms.map { it.toRule() }) assertThat(SimpleRule.of(rule)!!.toRule()).isEqualTo(rule)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a form that narrows by nothing is every task, whatever its match`() {
|
||||
assertThat(SimpleRule().toRule()).isEqualTo(Rule.Everything)
|
||||
assertThat(SimpleRule(match = Match.ANY).toRule()).isEqualTo(Rule.Everything)
|
||||
assertThat(SimpleRule.of(Rule.Everything)).isEqualTo(SimpleRule())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `filters made by the flat editor keep their rule`() {
|
||||
val criteria = listOf(
|
||||
FilterCriteria(),
|
||||
FilterCriteria(due = setOf(DueWindow.TODAY, DueWindow.OVERDUE)),
|
||||
FilterCriteria(listIds = setOf(1L), listsElsewhere = setOf("EXTERNAL:2"), minPriority = Priority.LOW),
|
||||
FilterCriteria(tags = setOf("b", "a"), tagMatch = TagMatch.ALL),
|
||||
FilterCriteria(due = setOf(DueWindow.NO_DATE), tags = setOf("x"), minPriority = Priority.HIGH, listIds = setOf(5L)),
|
||||
)
|
||||
for (flat in criteria) {
|
||||
val rule = flat.toRule()
|
||||
assertThat(SimpleRule.of(rule)!!.toRule()).isEqualTo(rule)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the GTD case is any of list Next and tag nextAction, also as built in the advanced editor`() {
|
||||
val form = SimpleRule(match = Match.ANY, listIds = setOf(7L), tags = setOf("nextAction"))
|
||||
assertThat(form.toRule()).isEqualTo(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(7L)), Rule.AnyOf(listOf(Rule.HasTag("nextAction"))))),
|
||||
)
|
||||
assertThat(SimpleRule.of(Rule.AnyOf(listOf(Rule.HasTag("nextAction"), Rule.InList(setOf(7L)))))).isEqualTo(form)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a lone criterion reads as all rules`() {
|
||||
assertThat(SimpleRule.of(Rule.InList(setOf(3L)))).isEqualTo(SimpleRule(listIds = setOf(3L)))
|
||||
assertThat(SimpleRule.of(Rule.Not(Rule.HasTag("someday"))))
|
||||
.isEqualTo(SimpleRule(tags = setOf("someday"), tagsNegated = true))
|
||||
assertThat(SimpleRule.of(Rule.Due(DueSpec.ThisWeek))).isEqualTo(SimpleRule(due = setOf(DueSpec.ThisWeek)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `bare tags take the top group's all or any, bare due conditions only an any`() {
|
||||
val tags = listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)), Rule.HasTag("b"))
|
||||
assertThat(SimpleRule.of(Rule.AllOf(tags)))
|
||||
.isEqualTo(SimpleRule(listIds = setOf(1L), tags = setOf("a", "b"), tagMatch = TagMatch.ALL))
|
||||
assertThat(SimpleRule.of(Rule.AnyOf(tags)))
|
||||
.isEqualTo(SimpleRule(match = Match.ANY, listIds = setOf(1L), tags = setOf("a", "b"), tagMatch = TagMatch.ANY))
|
||||
val dues = listOf(Rule.Due(today), Rule.Due(DueSpec.ThisMonth))
|
||||
assertThat(SimpleRule.of(Rule.AnyOf(dues))).isEqualTo(SimpleRule(match = Match.ANY, due = setOf(today, DueSpec.ThisMonth)))
|
||||
assertThat(SimpleRule.of(Rule.AllOf(dues))).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `shapes read differently from how they are written mean the same`() {
|
||||
val zone = ZoneId.of("Europe/Berlin")
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val clock = RuleClock(startOfDay(day, zone), startOfDay(day.plusDays(1), zone), zone, DayOfWeek.MONDAY)
|
||||
val tasks = listOf(
|
||||
testTask(listId = 1, tags = listOf("a")),
|
||||
testTask(listId = 2, tags = listOf("a", "b")),
|
||||
testTask(listId = 1, due = allDayInstantOf(day), isAllDay = true),
|
||||
testTask(listId = 3, tags = listOf("b"), due = allDayInstantOf(day.plusDays(9)), isAllDay = true),
|
||||
testTask(listId = 3, priority = Priority.HIGH),
|
||||
)
|
||||
val rules = listOf(
|
||||
Rule.AllOf(listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)), Rule.HasTag("b"))),
|
||||
Rule.AnyOf(listOf(Rule.HasTag("b"), Rule.Due(today), Rule.MinPriority(Priority.HIGH), Rule.Due(DueSpec.NextDays(3)))),
|
||||
Rule.AllOf(listOf(Rule.Not(Rule.InList(setOf(3L))), Rule.HasTag("a"))),
|
||||
Rule.Not(Rule.AnyOf(listOf(Rule.Due(today)))),
|
||||
)
|
||||
for (rule in rules) {
|
||||
val written = SimpleRule.of(rule)!!.toRule()
|
||||
for (task in tasks) assertThat(written.matches(task, clock)).isEqualTo(rule.matches(task, clock))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `shapes the form can't show need the advanced editor`() {
|
||||
val notSimple = listOf(
|
||||
Rule.AnyOf(emptyList()),
|
||||
Rule.Not(Rule.Not(Rule.HasTag("a"))),
|
||||
Rule.Not(Rule.MinPriority(Priority.HIGH)),
|
||||
Rule.MinPriority(Priority.NONE),
|
||||
Rule.InList(emptySet()),
|
||||
Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.InList(setOf(2L)))),
|
||||
Rule.AllOf(listOf(Rule.HasTag("a"), Rule.AnyOf(listOf(Rule.HasTag("b"))))),
|
||||
Rule.AllOf(listOf(Rule.Not(Rule.HasTag("a")), Rule.HasTag("b"))),
|
||||
Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(today), Rule.HasTag("a"))))),
|
||||
Rule.AllOf(listOf(Rule.AllOf(listOf(Rule.Due(today))))),
|
||||
Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.Due(DueSpec.NextDays(3)), Rule.Due(DueSpec.NextDays(7)))))),
|
||||
Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.HasTag("a"), Rule.HasTag("a"))))),
|
||||
Rule.AllOf(listOf(Rule.AllOf(emptyList()))),
|
||||
Rule.Not(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("a")))),
|
||||
)
|
||||
for (rule in notSimple) assertThat(SimpleRule.of(rule)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a second next N days replaces the first`() {
|
||||
val form = SimpleRule().toggleDue(DueSpec.NextDays(3)).toggleDue(today).toggleDue(DueSpec.NextDays(7))
|
||||
assertThat(form.due).containsExactly(today, DueSpec.NextDays(7))
|
||||
assertThat(form.withNextDays(null).due).containsExactly(today)
|
||||
assertThat(form.toggleDue(today).due).containsExactly(DueSpec.NextDays(7))
|
||||
}
|
||||
|
||||
private fun window(window: DueWindow) = DueSpec.Window(window)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package de.jeanlucmakiola.agendula.ui.lists
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.prefs.RuleCodec
|
||||
import de.jeanlucmakiola.agendula.domain.Block
|
||||
import de.jeanlucmakiola.agendula.domain.BlockSource
|
||||
import de.jeanlucmakiola.agendula.domain.BlockType
|
||||
import de.jeanlucmakiola.agendula.domain.BlockWidth
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFiltering
|
||||
import de.jeanlucmakiola.agendula.domain.TaskGroups
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
import de.jeanlucmakiola.agendula.domain.groupingKey
|
||||
import de.jeanlucmakiola.agendula.domain.startOfDay
|
||||
import de.jeanlucmakiola.agendula.domain.taskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
/** A block's custom rules source works in every block that takes a source. */
|
||||
class CustomRulesBlocksTest {
|
||||
|
||||
private val zone = ZoneId.systemDefault()
|
||||
private val today = LocalDate.of(2026, 11, 26)
|
||||
private val clock = RuleClock(startOfDay(today, zone), startOfDay(today.plusDays(1), zone), zone, DayOfWeek.MONDAY)
|
||||
private fun list(id: Long) = TaskList(id, "L$id", 0, "Local", "local", isSynced = false, isVisible = true, owner = null)
|
||||
|
||||
private val urgent = Rule.AnyOf(listOf(Rule.HasTag("next"), Rule.MinPriority(Priority.HIGH)))
|
||||
private val open = listOf(
|
||||
testTask(id = 1, listId = 1, tags = listOf("next")),
|
||||
testTask(id = 2, listId = 2, priority = Priority.HIGH),
|
||||
testTask(id = 3, listId = 1),
|
||||
)
|
||||
private val done = listOf(
|
||||
testTask(id = 4, listId = 1, tags = listOf("next"), status = TaskStatus.COMPLETED),
|
||||
testTask(id = 5, listId = 2, status = TaskStatus.COMPLETED),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `a rules source opens a task screen that matches by the rule, open and done`() {
|
||||
val filter = BlockSource.Rules(urgent).taskFilter
|
||||
assertThat(filter).isEqualTo(TaskFilter.Matching(urgent))
|
||||
val matched = (open + done).filter {
|
||||
TaskFiltering.matches(it, filter!!, clock.todayStart, clock.todayEnd, ruleClock = clock)
|
||||
}
|
||||
assertThat(matched.map { it.taskId }).containsExactly(1L, 2L, 4L)
|
||||
// Without a clock to read the rule against, nothing matches, as for a saved filter.
|
||||
assertThat(open.none { TaskFiltering.matches(it, filter!!, clock.todayStart, clock.todayEnd) }).isTrue()
|
||||
assertThat(filter!!.groupingKey()).isEqualTo("rules")
|
||||
assertThat(TaskGroups.offeredFor(filter)).isNotEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `progress, counts and previews read a rules source through the view's scope unless ignored`() {
|
||||
val blocks = listOf(
|
||||
Block(1, BlockType.PROGRESS, BlockSource.Rules(urgent)),
|
||||
Block(2, BlockType.PROGRESS, BlockSource.Rules(urgent), BlockWidth.HALF, ignoreScope = true),
|
||||
Block(3, BlockType.COUNT_TILE, BlockSource.Rules(urgent), BlockWidth.HALF),
|
||||
Block(4, BlockType.PREVIEW, BlockSource.Rules(urgent)),
|
||||
Block(5, BlockType.TASK_LIST, BlockSource.Rules(urgent)),
|
||||
)
|
||||
val view = View(2, "Work", ViewIcon.WORK, Rule.InList(setOf(1L)), blocks)
|
||||
val state = homeContent(view, listOf(view), listOf(list(1), list(2)), open, done, emptySet(), emptyList(), clock, null)
|
||||
// Task 4 was completed before today, so it only shows as not open.
|
||||
assertThat(state.progress.getValue(1L)).isEqualTo(BlockProgress(done = 0, total = 1))
|
||||
assertThat(state.progress.getValue(2L)).isEqualTo(BlockProgress(done = 0, total = 2))
|
||||
assertThat(state.counts.getValue(3L)).isEqualTo(1)
|
||||
assertThat(state.previews.getValue(4L).map { it.taskId }).containsExactly(1L)
|
||||
assertThat(state.goneSources).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a rule survives the route to its task screen`() {
|
||||
val rule = Rule.AllOf(listOf(Rule.InList(setOf(3L), setOf("EXTERNAL:7")), Rule.Not(Rule.HasTag("a b&c"))))
|
||||
assertThat(RuleCodec.decode(RuleCodec.encode(rule, "ROUTE"), "ROUTE")).isEqualTo(rule)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `progress counts open tasks and those done today, not everything ever done`() {
|
||||
val doneToday = testTask(id = 6, listId = 1, status = TaskStatus.COMPLETED, completedAt = clock.todayStart)
|
||||
val doneEarlier = testTask(id = 7, listId = 1, status = TaskStatus.COMPLETED, completedAt = startOfDay(today.minusDays(3), zone))
|
||||
val blocks = listOf(
|
||||
Block(1, BlockType.PROGRESS, BlockSource.List(1)),
|
||||
Block(2, BlockType.PROGRESS, BlockSource.Smart(SmartList.ALL)),
|
||||
Block(3, BlockType.PROGRESS, BlockSource.Smart(SmartList.COMPLETED)),
|
||||
)
|
||||
val view = View(2, "Work", ViewIcon.WORK, null, blocks)
|
||||
val state = homeContent(
|
||||
view, listOf(view), listOf(list(1), list(2)), open, listOf(doneToday, doneEarlier),
|
||||
emptySet(), emptyList(), clock, null,
|
||||
)
|
||||
assertThat(state.progress.getValue(1L)).isEqualTo(BlockProgress(done = 1, total = 3))
|
||||
assertThat(state.progress.getValue(2L)).isEqualTo(BlockProgress(done = 1, total = 4))
|
||||
assertThat(state.progress.getValue(3L)).isEqualTo(BlockProgress(done = 1, total = 1))
|
||||
}
|
||||
}
|
||||
@@ -5,31 +5,216 @@ import de.jeanlucmakiola.agendula.domain.Block
|
||||
import de.jeanlucmakiola.agendula.domain.BlockOptions
|
||||
import de.jeanlucmakiola.agendula.domain.BlockSource
|
||||
import de.jeanlucmakiola.agendula.domain.BlockType
|
||||
import de.jeanlucmakiola.agendula.domain.BlockWidth
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
import de.jeanlucmakiola.agendula.domain.ViewIcon
|
||||
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
|
||||
import de.jeanlucmakiola.agendula.domain.startOfDay
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
/** Home as the active view lays it out, through its scope (#59). */
|
||||
class HomePreviewsTest {
|
||||
|
||||
private val upcoming = (1L..12L).map { testTask(id = it) }
|
||||
private val zone = ZoneId.systemDefault()
|
||||
private val today = LocalDate.of(2026, 11, 26)
|
||||
private val clock = RuleClock(startOfDay(today, zone), startOfDay(today.plusDays(1), zone), zone, DayOfWeek.MONDAY)
|
||||
|
||||
private fun list(id: Long, name: String) =
|
||||
TaskList(id, name, 0, "Local", "local", isSynced = false, isVisible = true, owner = null)
|
||||
|
||||
private val work = list(1, "Work")
|
||||
private val home = list(2, "Home")
|
||||
private fun dueOn(day: LocalDate) = allDayInstantOf(day)
|
||||
|
||||
private val upcoming = (1L..12L).map { testTask(id = it, listId = if (it % 2 == 0L) 1 else 2, due = dueOn(today.plusDays(it))) }
|
||||
private val todayWork = testTask(id = 20, listId = 1, due = dueOn(today), isAllDay = true, tags = listOf("x"))
|
||||
private val todayHome = testTask(id = 21, listId = 2, due = dueOn(today), isAllDay = true)
|
||||
private val doneToday = testTask(
|
||||
id = 22,
|
||||
listId = 1,
|
||||
status = TaskStatus.COMPLETED,
|
||||
completedAt = startOfDay(today, zone),
|
||||
)
|
||||
|
||||
private fun content(
|
||||
view: View,
|
||||
open: List<Task> = upcoming.map { it.copy(isAllDay = true) } + todayWork + todayHome,
|
||||
lists: List<TaskList> = listOf(work, home),
|
||||
hidden: Set<Long> = emptySet(),
|
||||
filters: List<SavedFilter> = emptyList(),
|
||||
) = homeContent(view, listOf(view), lists, open, listOf(doneToday), hidden, filters, clock, upcomingEnd = null)
|
||||
|
||||
private fun scoped(scope: Rule?, blocks: List<Block> = View.home().blocks) =
|
||||
View(2, "Work", ViewIcon.WORK, scope, blocks)
|
||||
|
||||
@Test
|
||||
fun `home previews the next three upcoming tasks, as 1_4 did`() {
|
||||
assertThat(View.home().previews(upcoming.asSequence())).containsExactly(4L, upcoming.take(3))
|
||||
val state = content(View.home())
|
||||
val expected = upcoming.take(3).map { it.taskId }
|
||||
assertThat(state.previews.getValue(4L).map { it.taskId }).isEqualTo(expected)
|
||||
assertThat(state.progress.getValue(1L)).isEqualTo(BlockProgress(done = 1, total = 3))
|
||||
assertThat(state.counts.getValue(3L)).isEqualTo(14)
|
||||
assertThat(state.counts.getValue(2L)).isEqualTo(0)
|
||||
assertThat(state.goneSources).isEmpty()
|
||||
assertThat(state.scopedTasks).isSameInstanceAs(state.allTasks)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `each Upcoming preview takes its own count, other sources show nothing yet`() {
|
||||
fun `each preview takes its own count and source`() {
|
||||
val view = View.home().copy(
|
||||
blocks = listOf(
|
||||
Block(1, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(count = 5)),
|
||||
Block(2, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(count = 10)),
|
||||
Block(3, BlockType.PREVIEW, BlockSource.Smart(SmartList.TODAY)),
|
||||
Block(3, BlockType.PREVIEW, BlockSource.Tag("x")),
|
||||
),
|
||||
)
|
||||
assertThat(view.previews(upcoming.asSequence())).containsExactly(1L, upcoming.take(5), 2L, upcoming.take(10))
|
||||
assertThat(view.previews(emptySequence())).containsExactly(1L, emptyList<Task>(), 2L, emptyList<Task>())
|
||||
val state = content(view)
|
||||
assertThat(state.previews.getValue(1L)).hasSize(5)
|
||||
assertThat(state.previews.getValue(2L)).hasSize(10)
|
||||
assertThat(state.previews.getValue(3L).map { it.taskId }).containsExactly(20L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every block reads its source through the scope`() {
|
||||
val state = content(scoped(Rule.InList(setOf(1L))))
|
||||
assertThat(state.progress.getValue(1L)).isEqualTo(BlockProgress(done = 1, total = 2))
|
||||
assertThat(state.counts.getValue(3L)).isEqualTo(7)
|
||||
assertThat(state.previews.getValue(4L).map { it.listId }.toSet()).containsExactly(1L)
|
||||
// The lists block shows the lists the scope keeps tasks to, with scoped counts.
|
||||
assertThat(state.sections.groups.flatMap { g -> g.lists.map { it.list.id to it.openCount } })
|
||||
.containsExactly(1L to 7)
|
||||
assertThat(state.sections.tags.map { it.tag to it.openCount }).containsExactly("x" to 1)
|
||||
assertThat(state.unscopedSections.groups.flatMap { g -> g.lists.map { it.list.id } }).containsExactly(1L, 2L)
|
||||
assertThat(state.scopedTasks.map { it.listId }.toSet()).containsExactly(1L)
|
||||
assertThat(state.allTasks.map { it.listId }.toSet()).containsExactly(1L, 2L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block that ignores the scope counts everything`() {
|
||||
val blocks = View.home().blocks.map { if (it.id == 3L) it.copy(ignoreScope = true) else it }
|
||||
val state = content(scoped(Rule.InList(setOf(1L)), blocks))
|
||||
assertThat(state.counts.getValue(3L)).isEqualTo(14)
|
||||
assertThat(state.sectionsFor(blocks.single { it.id == 3L })).isEqualTo(state.unscopedSections)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a list named in the scope counts in the smart lists though hidden`() {
|
||||
val hidden = setOf(1L)
|
||||
assertThat(content(View.home(), hidden = hidden).counts.getValue(3L)).isEqualTo(7)
|
||||
assertThat(content(scoped(Rule.InList(setOf(1L))), hidden = hidden).counts.getValue(3L)).isEqualTo(7)
|
||||
assertThat(content(scoped(Rule.HasTag("x")), hidden = hidden).counts.getValue(3L)).isEqualTo(0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block whose list or filter is deleted says so, and shows nothing`() {
|
||||
val blocks = listOf(
|
||||
Block(1, BlockType.COUNT_TILE, BlockSource.List(9), BlockWidth.HALF),
|
||||
Block(2, BlockType.PREVIEW, BlockSource.Filter(4)),
|
||||
Block(3, BlockType.COUNT_TILE, BlockSource.List(1), BlockWidth.HALF),
|
||||
Block(4, BlockType.TASK_LIST, BlockSource.Filter(5)),
|
||||
)
|
||||
val state = content(scoped(null, blocks), filters = listOf(SavedFilter(5, "f", Rule.HasTag("x"))))
|
||||
assertThat(state.goneSources).containsExactly(1L, 2L)
|
||||
assertThat(state.counts.keys).containsExactly(3L)
|
||||
assertThat(state.previews).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a scope list since deleted matches nothing and raises the notice`() {
|
||||
val state = content(scoped(Rule.InList(setOf(9L))))
|
||||
assertThat(state.scopeListsGone).isTrue()
|
||||
assertThat(state.counts.getValue(3L)).isEqualTo(0)
|
||||
assertThat(state.progress.getValue(1L)).isEqualTo(BlockProgress(done = 0, total = 0))
|
||||
assertThat(state.sections.groups).isEmpty()
|
||||
assertThat(state.scopedTasks).isEmpty()
|
||||
assertThat(content(scoped(Rule.InList(setOf(1L)))).scopeListsGone).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a tag tile counts a subtask whose parent doesn't carry the tag`() {
|
||||
val parent = testTask(id = 30, listId = 1)
|
||||
val sub = testTask(id = 31, listId = 1, parentId = 30, tags = listOf("y"))
|
||||
val view = scoped(null, listOf(Block(1, BlockType.COUNT_TILE, BlockSource.Tag("y"), BlockWidth.HALF)))
|
||||
val state = content(view, open = listOf(parent, sub))
|
||||
assertThat(state.counts.getValue(1L)).isEqualTo(1)
|
||||
assertThat(state.counts.getValue(1L)).isEqualTo(state.sections.tags.single { it.tag == "y" }.openCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a scoped view hands on its scope as it applies, deleted lists matching nothing`() {
|
||||
val rule = Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x")))
|
||||
assertThat(content(scoped(rule)).scopeRule).isEqualTo(rule)
|
||||
assertThat(content(scoped(Rule.InList(setOf(1L, 99L)))).scopeRule).isEqualTo(Rule.InList(setOf(1L)))
|
||||
assertThat(content(scoped(null)).scopeRule).isNull()
|
||||
assertThat(content(scoped(Rule.Not(Rule.InList(setOf(9L))))).scopeListsGone).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recently completed shows the view's completed tasks, latest first, unless it ignores the scope`() {
|
||||
fun done(id: Long, listId: Long, minutes: Long) = testTask(
|
||||
id = id,
|
||||
listId = listId,
|
||||
status = TaskStatus.COMPLETED,
|
||||
completedAt = startOfDay(today, zone) + kotlin.time.Duration.parse("${minutes}m"),
|
||||
)
|
||||
val completed = listOf(done(30, 1, 10), done(31, 2, 30), done(32, 1, 20), done(33, 1, 5))
|
||||
val blocks = listOf(
|
||||
Block(1, BlockType.RECENTLY_COMPLETED),
|
||||
Block(2, BlockType.RECENTLY_COMPLETED, ignoreScope = true, options = BlockOptions.RecentlyCompleted(count = 5)),
|
||||
)
|
||||
val state = homeContent(
|
||||
scoped(Rule.InList(setOf(1L)), blocks), listOf(View.home()), listOf(work, home),
|
||||
openTasks = emptyList(), completedTasks = completed, hidden = emptySet(),
|
||||
savedFilters = emptyList(), clock = clock, upcomingEnd = null,
|
||||
)
|
||||
assertThat(state.recent.getValue(1L).map { it.taskId }).containsExactly(32L, 30L, 33L).inOrder()
|
||||
assertThat(state.recent.getValue(2L).map { it.taskId }).containsExactly(31L, 32L, 30L, 33L).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the week strip counts the open tasks due on each day of the week, in the scope`() {
|
||||
val view = scoped(Rule.InList(setOf(1L)), listOf(Block(1, BlockType.WEEK_STRIP)))
|
||||
val week = content(view).weeks.getValue(1L)
|
||||
assertThat(week.today).isEqualTo(today)
|
||||
assertThat(week.days.first()).isEqualTo(LocalDate.of(2026, 11, 23))
|
||||
assertThat(week.days.last()).isEqualTo(LocalDate.of(2026, 11, 29))
|
||||
// Today's work task, then the even upcoming ones (list 1) due by Sunday.
|
||||
assertThat(week.due).containsExactly(today, 1, today.plusDays(2), 1)
|
||||
}
|
||||
|
||||
private fun inputs(view: View, open: List<Task> = upcoming.map { it.copy(isAllDay = true) } + todayWork + todayHome) =
|
||||
HomeInputs(view, listOf(work, home), open, listOf(doneToday), emptySet(), emptyList(), clock, upcomingEnd = null)
|
||||
|
||||
@Test
|
||||
fun `a new task shows when the view's task list holds it`() {
|
||||
val view = scoped(null, listOf(Block(1, BlockType.TASK_LIST, BlockSource.List(1))))
|
||||
assertThat(inputs(view).shows(testTask(id = 99, listId = 1))).isTrue()
|
||||
assertThat(inputs(view).shows(testTask(id = 99, listId = 2))).isFalse()
|
||||
val ignoring = scoped(Rule.HasTag("x"), listOf(Block(1, BlockType.TASK_LIST, BlockSource.List(1), ignoreScope = true)))
|
||||
assertThat(inputs(ignoring).shows(testTask(id = 99, listId = 1))).isTrue()
|
||||
val scopedOut = scoped(Rule.HasTag("x"), listOf(Block(1, BlockType.TASK_LIST, BlockSource.List(1))))
|
||||
assertThat(inputs(scopedOut).shows(testTask(id = 99, listId = 1))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new task shows when a preview has it among its first, not when only a count goes up`() {
|
||||
val soon = testTask(id = 99, listId = 1, due = dueOn(today.plusDays(1)), isAllDay = true)
|
||||
val late = testTask(id = 98, listId = 1, due = dueOn(today.plusDays(30)), isAllDay = true)
|
||||
assertThat(inputs(View.home()).shows(soon)).isTrue()
|
||||
assertThat(inputs(View.home()).shows(late)).isFalse()
|
||||
assertThat(inputs(View.home()).shows(testTask(id = 97, listId = 1))).isFalse()
|
||||
// Already read back from the store, it still counts once.
|
||||
assertThat(inputs(View.home(), open = upcoming.map { it.copy(isAllDay = true) } + soon).shows(soon)).isTrue()
|
||||
}
|
||||
}
|
||||
@@ -27,4 +27,20 @@ class DestinationsTest {
|
||||
assertThat(Dest.FilterEdit.build(5)).isEqualTo("filterEdit?filterId=5")
|
||||
assertThat(Dest.TaskEdit.buildNew(filterId = 5)).isEqualTo("taskEdit?filterId=5")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a list opened from a scoped view carries the view`() {
|
||||
assertThat(Dest.TaskList.build(TaskFilter.OfList(3), scopeViewId = 2)).isEqualTo("taskList?listId=3&view=2")
|
||||
assertThat(Dest.TaskList.build(TaskFilter.OfList(3))).isEqualTo("taskList?listId=3")
|
||||
assertThat(Dest.EditView.build(4)).isEqualTo("views/4")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new task's tags come back one by one, and the quick-add mark and time with them`() {
|
||||
assertThat(Dest.TaskEdit.tagsOf("work\nurgent")).containsExactly("work", "urgent").inOrder()
|
||||
assertThat(Dest.TaskEdit.tagsOf(null)).isEmpty()
|
||||
assertThat(Dest.TaskEdit.tagsOf("")).isEmpty()
|
||||
val route = Dest.TaskEdit.buildNew(due = java.time.LocalDate.of(2026, 12, 4), dueTime = java.time.LocalTime.of(14, 30), fromQuickAdd = true)
|
||||
assertThat(route).isEqualTo("taskEdit?due=2026-12-04&dueTime=14:30&fromQuickAdd=true")
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package de.jeanlucmakiola.agendula.ui.quickadd
|
||||
|
||||
import com.google.common.truth.Truth.assertWithMessage
|
||||
import de.jeanlucmakiola.agendula.domain.QuickAddKeywords
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.io.File
|
||||
import javax.xml.parsers.DocumentBuilderFactory
|
||||
|
||||
/** The `@date` words as the string resources give them, in English and in every translation. */
|
||||
class QuickAddKeywordsResourcesTest {
|
||||
|
||||
private val res = File("src/main/res")
|
||||
|
||||
private fun strings(file: File): Map<String, String> {
|
||||
val nodes = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file).getElementsByTagName("string")
|
||||
return (0 until nodes.length).associate { i ->
|
||||
val node = nodes.item(i)
|
||||
node.attributes.getNamedItem("name").nodeValue to node.textContent.replace("\\'", "'").replace("\\\"", "\"")
|
||||
}
|
||||
}
|
||||
|
||||
private val base = strings(File(res, "values/strings.xml"))
|
||||
|
||||
@Test
|
||||
fun `the English resources are the built-in words`() {
|
||||
assertWithMessage("values/strings.xml").that(QuickAddKeywords.RESOURCE_NAMES.filterNot { it in base }).isEmpty()
|
||||
assertWithMessage("values/strings.xml").that(QuickAddKeywords.fromTranslations(base::get)).isEqualTo(QuickAddKeywords.English)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no translation makes a word stand for two things, English ones included`() {
|
||||
val translations = res.listFiles { dir -> dir.isDirectory && dir.name.startsWith("values-") }.orEmpty()
|
||||
.map { File(it, "strings.xml") }
|
||||
.filter { it.exists() }
|
||||
assertWithMessage("translations found").that(translations).isNotEmpty()
|
||||
translations.forEach { file ->
|
||||
val translated = strings(file)
|
||||
if (QuickAddKeywords.RESOURCE_NAMES.none { it in translated }) return@forEach
|
||||
// A word left untranslated is the English one at runtime.
|
||||
val keywords = QuickAddKeywords.English + QuickAddKeywords.fromTranslations { translated[it] ?: base[it] }
|
||||
assertWithMessage("${file.parentFile.name}: words standing for two things").that(keywords.collisions()).isEmpty()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package de.jeanlucmakiola.agendula.ui.tasklist
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskEnd
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFiltering
|
||||
import de.jeanlucmakiola.agendula.domain.TaskGroupKey
|
||||
import de.jeanlucmakiola.agendula.domain.TaskGroups
|
||||
import de.jeanlucmakiola.agendula.domain.TaskGrouping
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
import kotlin.time.toKotlinInstant
|
||||
|
||||
/** The one Completed section Today, All, the lists and the task list block share (#140). */
|
||||
class CompletedSectionTest {
|
||||
|
||||
private val done = TaskStatus.COMPLETED
|
||||
|
||||
@Test
|
||||
fun `clear takes the completed tasks shown that can go`() {
|
||||
val content = TaskListUiState.Content(
|
||||
tasks = listOf(
|
||||
testTask(id = 1),
|
||||
testTask(id = 2, status = done),
|
||||
testTask(id = 3, status = done).copy(isReadOnly = true),
|
||||
testTask(id = 4, status = done).copy(subtaskDone = 1, subtaskTotal = 2),
|
||||
testTask(id = 5, status = done, listId = 2).copy(subtaskDone = 2, subtaskTotal = 2),
|
||||
testTask(id = 6, status = TaskStatus.CANCELLED),
|
||||
),
|
||||
)
|
||||
assertThat(content.clearableCompleted().map { it.taskId }).containsExactly(2L, 5L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `completed tasks close any list in their own section`() {
|
||||
val tasks = listOf(testTask(id = 1, status = done), testTask(id = 2), testTask(id = 3, status = done))
|
||||
TaskGrouping.entries.forEach { grouping ->
|
||||
val groups = TaskGroups.of(tasks, grouping, Instant.DISTANT_PAST, Instant.DISTANT_PAST)
|
||||
assertThat(groups.last().key).isEqualTo(TaskGroupKey.COMPLETED)
|
||||
assertThat(groups.last().tasks.map { it.taskId }).containsExactly(1L, 3L).inOrder()
|
||||
assertThat(groups.dropLast(1).flatMap { it.tasks }.none { it.isCompleted }).isTrue()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a day's list holds what is due that day, open or done`() {
|
||||
val zone = ZoneId.systemDefault()
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
fun on(date: LocalDate) = date.atTime(LocalTime.NOON).atZone(zone).toInstant().toKotlinInstant()
|
||||
val filter = TaskFilter.DueOn(day)
|
||||
val matching = listOf(
|
||||
testTask(id = 1, due = on(day)),
|
||||
testTask(id = 2, due = on(day), status = done),
|
||||
testTask(id = 3, due = on(day.plusDays(1))),
|
||||
testTask(id = 4),
|
||||
).filter { TaskFiltering.matches(it, filter, Instant.DISTANT_PAST, Instant.DISTANT_PAST) }
|
||||
assertThat(matching.map { it.taskId }).containsExactly(1L, 2L)
|
||||
assertThat(matching.all { it.dateOf(TaskEnd.DUE, zone) == day }).isTrue()
|
||||
assertThat(TaskGroups.offeredFor(filter)).doesNotContain(TaskGrouping.DAY)
|
||||
assertThat(TaskGroups.offeredFor(TaskFilter.Smart(SmartList.ALL))).contains(TaskGrouping.DAY)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package de.jeanlucmakiola.agendula.ui.theme
|
||||
import android.app.UiModeManager
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class SystemThemeTest {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package de.jeanlucmakiola.agendula.ui.views
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.newView
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.lang.reflect.Proxy
|
||||
|
||||
/** The scope edited in the rule editor is stored with the view (#59, #172). */
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class EditViewScopeTest {
|
||||
|
||||
private val prefs = SettingsPrefs(MemoryDataStore(), ProviderResolver(NoProviders))
|
||||
private val repository = FakeRepository()
|
||||
|
||||
@BeforeEach fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
|
||||
|
||||
@AfterEach fun tearDown() = Dispatchers.resetMain()
|
||||
|
||||
private fun editing(viewId: Long) = EditViewViewModel(prefs, ViewSession(prefs, repository, CoroutineScope(Dispatchers.Unconfined)), repository)
|
||||
.apply {
|
||||
bind(viewId)
|
||||
runBlocking { draft.first { it != null } }
|
||||
}
|
||||
|
||||
/** Saves, and waits for the write, which reads the views off the main thread. */
|
||||
private fun EditViewViewModel.saveNow() = runBlocking {
|
||||
val saved = CompletableDeferred<Unit>()
|
||||
save { saved.complete(Unit) }
|
||||
withTimeout(5_000) { saved.await() }
|
||||
}
|
||||
|
||||
private fun stored(id: Long) = runBlocking { prefs.views.first().first { it.id == id } }
|
||||
|
||||
@Test
|
||||
fun `a scope set here is saved with the view`() {
|
||||
val id = runBlocking {
|
||||
prefs.setStorageMode(StorageMode.OWN)
|
||||
prefs.saveView(newView(0, "Work"))!!
|
||||
}
|
||||
val scope = Rule.AnyOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("next")))
|
||||
val vm = editing(id)
|
||||
vm.setScope(scope)
|
||||
vm.saveNow()
|
||||
assertThat(stored(id).scope).isEqualTo(scope)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a scope that admits every task is none`() {
|
||||
val id = runBlocking {
|
||||
prefs.setStorageMode(StorageMode.OWN)
|
||||
prefs.saveView(newView(0, "Work").copy(scope = Rule.HasTag("x")))!!
|
||||
}
|
||||
val vm = editing(id)
|
||||
vm.setScope(Rule.AllOf(listOf(Rule.AllOf(emptyList()))))
|
||||
assertThat(vm.draft.value!!.scope).isNull()
|
||||
vm.setScope(Rule.Everything)
|
||||
assertThat(vm.draft.value!!.scope).isNull()
|
||||
vm.saveNow()
|
||||
assertThat(stored(id).scope).isNull()
|
||||
}
|
||||
|
||||
private class FakeRepository : TasksRepository by unsupported() {
|
||||
override fun taskLists() = flowOf(emptyList<TaskList>())
|
||||
}
|
||||
|
||||
private class MemoryDataStore : DataStore<Preferences> {
|
||||
override val data = MutableStateFlow(emptyPreferences())
|
||||
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) =
|
||||
transform(data.value).also { data.value = it }
|
||||
}
|
||||
|
||||
private object NoProviders : ProviderEnvironment {
|
||||
override fun packageDeclaring(authority: String): String? = null
|
||||
override fun isGranted(permission: String) = false
|
||||
override fun appLabel(packageName: String): String? = null
|
||||
}
|
||||
|
||||
private companion object {
|
||||
inline fun <reified T> unsupported(): T =
|
||||
Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ ->
|
||||
throw UnsupportedOperationException("Unexpected call: ${method.name}")
|
||||
} as T
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package de.jeanlucmakiola.agendula.widget
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
||||
@@ -10,6 +9,7 @@ import de.jeanlucmakiola.agendula.domain.allDayInstantOf
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import de.jeanlucmakiola.floret.glance.WidgetBackground
|
||||
import de.jeanlucmakiola.floret.glance.WidgetThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
### الإضافات
|
||||
- الترجمة الإسبانية.
|
||||
|
||||
### التغييرات
|
||||
- الترجمة الجاليكية شبه مكتملة.
|
||||
@@ -0,0 +1,5 @@
|
||||
### Přidáno
|
||||
- Španělský překlad.
|
||||
|
||||
### Změněno
|
||||
- Galicijský překlad je téměř hotový.
|
||||
@@ -0,0 +1,5 @@
|
||||
### Neu
|
||||
- Spanische Übersetzung.
|
||||
|
||||
### Geändert
|
||||
- Galicische Übersetzung fast vollständig.
|
||||
@@ -0,0 +1,5 @@
|
||||
### Added
|
||||
- Spanish translation.
|
||||
|
||||
### Changed
|
||||
- Galician translation nearly complete.
|
||||
@@ -0,0 +1,5 @@
|
||||
### Added
|
||||
- Spanish translation.
|
||||
|
||||
### Changed
|
||||
- Galician translation nearly complete.
|
||||
@@ -0,0 +1,5 @@
|
||||
### Novedades
|
||||
- Traducción al español.
|
||||
|
||||
### Cambios
|
||||
- Traducción al gallego casi completa.
|
||||
@@ -0,0 +1,11 @@
|
||||
Agendula es una app de tareas moderna y de código abierto para Android.
|
||||
|
||||
Sincroniza tus tareas por CalDAV: añade una cuenta de Nextcloud, Radicale, Baïkal o cualquier otra cuenta CalDAV y elige qué listas de tareas quieres traer. O guárdalo todo en el teléfono: Agendula almacena las tareas por sí misma, sin cuenta y sin nada más que instalar.
|
||||
|
||||
¿Ya usas OpenTasks o tasks.org? Haz que Agendula use esa app, para que las tareas sincronizadas por DAVx5 o similares aparezcan tal como están, y cópialas al almacenamiento propio de Agendula cuando quieras, en Ajustes → Almacenamiento.
|
||||
|
||||
Lo que hace: listas que gestionas en la app, fechas de vencimiento y de inicio, tareas de día completo, subtareas, prioridades, progreso, tareas repetitivas que puedes editar una ocurrencia cada vez, varios recordatorios por tarea con posponer, importación y exportación iCalendar, un widget para la pantalla de inicio, accesos directos en el lanzador y un mosaico de Ajustes rápidos.
|
||||
|
||||
El diseño es Material 3 Expressive de verdad en todo, con color dinámico y movimiento y formas expresivos.
|
||||
|
||||
Privacidad: sin telemetría, sin analíticas, sin anuncios. Agendula solo se conecta para sincronizar con las cuentas CalDAV que añadas. Sin ninguna, tus tareas nunca salen del dispositivo, salvo que las exportes.
|
||||
@@ -0,0 +1 @@
|
||||
Una app de tareas Material 3 Expressive con sincronización CalDAV.
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user