Compare commits
123
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 | ||
|
|
080afe7aa3 | ||
|
|
e7b726ee82 | ||
|
|
87a98e2998 | ||
|
|
bb6e027011 | ||
|
|
1fc94757b0 | ||
|
|
355daad87b | ||
|
|
3f97683c6d | ||
|
|
afab067884 | ||
|
|
6dec534528 | ||
|
|
b0bb853854 | ||
|
|
ba9d984a42 | ||
|
|
5390cb8882 | ||
|
|
1ad7ed6fe3 | ||
|
|
f745698b5b | ||
|
|
f9926a80b3 | ||
|
|
bfbe7398d4 | ||
|
|
9dd8660571 | ||
|
|
ceaff3183c | ||
|
|
697e2e8554 | ||
|
|
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)
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.app.Application
|
||||
import androidx.hilt.work.HiltWorkerFactory
|
||||
import androidx.lifecycle.ProcessLifecycleOwner
|
||||
import androidx.work.Configuration
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import dagger.hilt.EntryPoint
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.EntryPointAccessors
|
||||
@@ -97,9 +98,11 @@ class AgendulaApp : Application(), Configuration.Provider {
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
refreshNotificationChannels()
|
||||
// Language or dark mode changed: the widget's strings and list colours follow.
|
||||
// Language or dark mode changed: week starts, the widget's strings and list colours follow.
|
||||
runCatching {
|
||||
EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java).taskWidgetUpdater().requestRefresh()
|
||||
val entryPoint = EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java)
|
||||
entryPoint.settingsPrefs().onLocaleChanged()
|
||||
entryPoint.taskWidgetUpdater().requestRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,5 +131,6 @@ class AgendulaApp : Application(), Configuration.Provider {
|
||||
fun reminderRefresher(): ReminderRefresher
|
||||
fun providerSnapshotSource(): ProviderSnapshotSource
|
||||
fun autoBackupScheduler(): AutoBackupScheduler
|
||||
fun settingsPrefs(): SettingsPrefs
|
||||
}
|
||||
}
|
||||
@@ -3,49 +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 de.jeanlucmakiola.agendula.ui.common.localeFirstDayOfWeek
|
||||
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]).
|
||||
*/
|
||||
@@ -56,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.
|
||||
@@ -64,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)
|
||||
|
||||
@@ -77,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.
|
||||
@@ -89,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)
|
||||
@@ -98,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.weekStart ?: localeFirstDayOfWeek()
|
||||
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,
|
||||
@@ -139,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() {
|
||||
@@ -165,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"
|
||||
@@ -248,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) {
|
||||
@@ -272,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) {
|
||||
@@ -286,3 +367,6 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The longest the first frame waits for the stored appearance. */
|
||||
private const val APPEARANCE_WAIT_MS = 600L
|
||||
@@ -12,6 +12,8 @@ import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SavedFilterMigration
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ViewsMigration
|
||||
import de.jeanlucmakiola.agendula.data.tasks.AndroidProviderEnvironment
|
||||
import de.jeanlucmakiola.agendula.data.tasks.AndroidTasksDataSource
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ModeRoutingTasksDataSource
|
||||
@@ -48,6 +50,7 @@ internal fun replaceCorrupted() = ReplaceFileCorruptionHandler { emptyPreference
|
||||
private val Context.agendulaDataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = "agendula_prefs",
|
||||
corruptionHandler = replaceCorrupted(),
|
||||
produceMigrations = { listOf(SavedFilterMigration, ViewsMigration) },
|
||||
)
|
||||
|
||||
@Module
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
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 java.net.URLDecoder
|
||||
import java.net.URLEncoder
|
||||
|
||||
/**
|
||||
* The stored grammar of a [Rule], shared by saved filters ([SavedFilterCodec])
|
||||
* and views ([ViewCodec]): nested calls `and(…)`, `or(…)`, `not(…)`,
|
||||
* `list(OWN%3A3,…)`, `tag(…)`, `prio(HIGH)`, `due(TODAY)` and
|
||||
* `range(week|month)` or `range(next,7)`. Tags and list refs are URL-encoded,
|
||||
* and list ids are qualified by the store they belong to (`OWN:3`), since each
|
||||
* store numbers its lists on its own.
|
||||
*
|
||||
* Fixed once released, and part of both formats: a change here is a change to
|
||||
* both, with a version bump and a data migration for each.
|
||||
*/
|
||||
internal object RuleCodec {
|
||||
|
||||
/** [rule] as text, [mode]'s list ids qualified by it. */
|
||||
fun encode(rule: Rule, mode: String): String = when (rule) {
|
||||
is Rule.AllOf -> "and(${rule.children.joinToString(",") { encode(it, mode) }})"
|
||||
is Rule.AnyOf -> "or(${rule.children.joinToString(",") { encode(it, mode) }})"
|
||||
is Rule.Not -> "not(${encode(rule.child, mode)})"
|
||||
is Rule.InList -> {
|
||||
val refs = rule.listIds.sorted().map { "$mode:$it" } + rule.elsewhere.sorted()
|
||||
"list(${refs.joinToString(",") { encodeText(it) }})"
|
||||
}
|
||||
is Rule.HasTag -> "tag(${encodeText(rule.tag)})"
|
||||
is Rule.MinPriority -> "prio(${rule.priority.name})"
|
||||
is Rule.Due -> when (val spec = rule.spec) {
|
||||
is DueSpec.Window -> "due(${spec.window.name})"
|
||||
DueSpec.ThisWeek -> "range(week)"
|
||||
DueSpec.ThisMonth -> "range(month)"
|
||||
is DueSpec.NextDays -> "range(next,${spec.days})"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The rule [text] holds, with [mode]'s list ids; throws on text that isn't
|
||||
* the grammar. It prunes nothing: what [encode] wrote reads back equal.
|
||||
*/
|
||||
fun decode(text: String, mode: String): Rule = RuleParser(text, mode).parse()
|
||||
|
||||
/** Reads the grammar [encode] writes. */
|
||||
private class RuleParser(private val text: String, private val mode: String) {
|
||||
private var at = 0
|
||||
|
||||
fun parse(): Rule = rule().also { require(at == text.length) { "Trailing input at $at" } }
|
||||
|
||||
private fun rule(): Rule {
|
||||
val name = atom()
|
||||
expect('(')
|
||||
val rule = when (name) {
|
||||
"and" -> Rule.AllOf(list(::rule))
|
||||
"or" -> Rule.AnyOf(list(::rule))
|
||||
"not" -> Rule.Not(rule())
|
||||
"list" -> listRule(list(::atom).map(::decodeText))
|
||||
"tag" -> Rule.HasTag(decodeText(atom()))
|
||||
"prio" -> Rule.MinPriority(Priority.valueOf(atom()))
|
||||
"due" -> Rule.Due(DueSpec.Window(DueWindow.valueOf(atom())))
|
||||
"range" -> Rule.Due(range(list(::atom)))
|
||||
else -> throw IllegalArgumentException("Unknown rule $name")
|
||||
}
|
||||
expect(')')
|
||||
return rule
|
||||
}
|
||||
|
||||
/** [mode]'s list ids; any other ref, one that names no id included, is kept as it is. */
|
||||
private fun listRule(refs: List<String>): Rule.InList {
|
||||
val here = HashSet<Long>()
|
||||
val elsewhere = HashSet<String>()
|
||||
refs.forEach { ref ->
|
||||
ref.removePrefix("$mode:").takeIf { it != ref }?.toLongOrNull()?.let(here::add) ?: elsewhere.add(ref)
|
||||
}
|
||||
return Rule.InList(here, elsewhere)
|
||||
}
|
||||
|
||||
private fun range(args: List<String>): DueSpec.Range = when {
|
||||
args == listOf("week") -> DueSpec.ThisWeek
|
||||
args == listOf("month") -> DueSpec.ThisMonth
|
||||
args.size == 2 && args[0] == "next" -> DueSpec.NextDays(args[1].toInt())
|
||||
else -> throw IllegalArgumentException("Unknown range $args")
|
||||
}
|
||||
|
||||
/** Comma-separated [item]s up to the closing parenthesis, which stays unread. */
|
||||
private fun <T> list(item: () -> T): List<T> {
|
||||
if (peek() == ')') return emptyList()
|
||||
val items = mutableListOf(item())
|
||||
while (peek() == ',') {
|
||||
at++
|
||||
items += item()
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
private fun atom(): String {
|
||||
val start = at
|
||||
while (at < text.length && text[at] !in "(),") at++
|
||||
return text.substring(start, at)
|
||||
}
|
||||
|
||||
private fun peek(): Char? = text.getOrNull(at)
|
||||
|
||||
private fun expect(c: Char) {
|
||||
require(peek() == c) { "Expected $c at $at" }
|
||||
at++
|
||||
}
|
||||
}
|
||||
|
||||
private fun encodeText(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
|
||||
|
||||
private fun decodeText(value: String): String = URLDecoder.decode(value, Charsets.UTF_8.name())
|
||||
}
|
||||
@@ -1,92 +1,132 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
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.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import de.jeanlucmakiola.agendula.domain.flatten
|
||||
import de.jeanlucmakiola.agendula.domain.mapLists
|
||||
import de.jeanlucmakiola.agendula.domain.withoutLists
|
||||
import java.net.URLDecoder
|
||||
import java.net.URLEncoder
|
||||
|
||||
/**
|
||||
* Stored form of the saved filters: one line per filter,
|
||||
* `id|name|due|lists|tags|match|priority`, with name and tags URL-encoded and
|
||||
* list ids qualified by the store they belong to (`OWN:3`), since each store
|
||||
* numbers its lists on its own. Fixed once released — don't change without a
|
||||
* data migration.
|
||||
* Stored form of the saved filters: one line per filter, `v2|id|name|rule`,
|
||||
* the rule in [RuleCodec]'s grammar and the name URL-encoded. Reading a line
|
||||
* drops a top-level list condition left with no list, so the filter goes back
|
||||
* to any list, as a flat filter did.
|
||||
*
|
||||
* Lines without the `v2|` mark are the flat format of 1.4 and earlier,
|
||||
* `id|name|due|lists|tags|match|priority`. They are still read, and [migrate]
|
||||
* rewrites them once.
|
||||
*
|
||||
* Fixed once released — don't change without a data migration.
|
||||
*/
|
||||
internal object SavedFilterCodec {
|
||||
|
||||
private const val V2 = "v2"
|
||||
|
||||
/** The filters in [raw], with only the list ids of [mode]'s store. */
|
||||
fun decode(raw: String?, mode: String): List<SavedFilter> =
|
||||
lines(raw).mapNotNull { runCatching { decodeLine(it, mode) }.getOrNull() }
|
||||
|
||||
/** [raw] with [filter] replacing the line of the same id, or appended. */
|
||||
/**
|
||||
* [raw] with [filter] replacing the line of the same id, or appended. Other
|
||||
* stores' lists the stored line no longer has, e.g. pruned while the filter
|
||||
* was being edited, stay gone.
|
||||
*/
|
||||
fun upsert(raw: String?, filter: SavedFilter, mode: String): String {
|
||||
val existing = lines(raw)
|
||||
val index = existing.indexOfFirst { idOf(it) == filter.id }
|
||||
// Keep the lists another store contributed, so switching stores and back
|
||||
// doesn't widen a filter that was edited in between, unless "any list"
|
||||
// was chosen here, which drops them on purpose.
|
||||
val foreign = if (filter.anyList) {
|
||||
emptyList()
|
||||
} else {
|
||||
existing.getOrNull(index)?.let(::fields)?.getOrNull(3)
|
||||
?.let(::splitList)?.filterNot { it.startsWith("$mode:") }.orEmpty()
|
||||
val stored = existing.getOrNull(index)?.let { runCatching { decodeLine(it, mode) }.getOrNull() }
|
||||
val kept = stored?.rule?.elsewhereRefs()?.let { refs ->
|
||||
filter.copy(rule = filter.rule.mapLists { it.copy(elsewhere = it.elsewhere intersect refs) }.withoutLists { false })
|
||||
}
|
||||
val line = encodeLine(filter, mode, foreign)
|
||||
val line = encodeLine(kept ?: filter, mode)
|
||||
val updated = if (index >= 0) existing.toMutableList().also { it[index] = line } else existing + line
|
||||
return updated.joinToString("\n")
|
||||
}
|
||||
|
||||
/**
|
||||
* [raw] without the lists of [mode]'s store [gone] names. A filter left
|
||||
* without lists matches any, as a read of it already did with them gone.
|
||||
* [raw] without the lists of [mode]'s store [gone] names (see [Rule.withoutLists]).
|
||||
*/
|
||||
fun withoutLists(raw: String?, mode: String, gone: (Long) -> Boolean): String =
|
||||
lines(raw).joinToString("\n") { line ->
|
||||
val f = fields(line)
|
||||
if (f.size < 7) return@joinToString line
|
||||
val kept = splitList(f[3]).filterNot { it.startsWith("$mode:") && it.removePrefix("$mode:").toLongOrNull()?.let(gone) == true }
|
||||
f.toMutableList().also { it[3] = kept.joinToString(",") }.joinToString("|")
|
||||
// Most filters hold none of this store's lists; only those need reading.
|
||||
if ("$mode:" !in line && encode("$mode:") !in line) return@joinToString line
|
||||
val filter = runCatching { decodeLine(line, mode) }.getOrNull() ?: return@joinToString line
|
||||
val pruned = filter.copy(rule = filter.rule.withoutLists(gone))
|
||||
if (pruned == filter) line else encodeLine(pruned, mode)
|
||||
}
|
||||
|
||||
fun remove(raw: String?, id: Long): String = lines(raw).filterNot { idOf(it) == id }.joinToString("\n")
|
||||
|
||||
/** Whether [raw] still holds lines of the flat format. */
|
||||
fun needsMigration(raw: String?): Boolean = lines(raw).any { !isV2(it) }
|
||||
|
||||
/**
|
||||
* [raw] with every flat line rewritten as a rule, lists of every store kept
|
||||
* as they are. Lines that never read as a filter are dropped.
|
||||
*/
|
||||
fun migrate(raw: String?): String = lines(raw).mapNotNull { line ->
|
||||
if (isV2(line)) return@mapNotNull line
|
||||
// No store owns NO_STORE, so every list stays a qualified ref and comes back out unchanged.
|
||||
runCatching { decodeFlatLine(line, NO_STORE) }.getOrNull()?.let { encodeLine(it, NO_STORE) }
|
||||
}.joinToString("\n")
|
||||
|
||||
private const val NO_STORE = "\u0000"
|
||||
|
||||
private fun lines(raw: String?): List<String> = raw.orEmpty().split('\n').filter { it.isNotBlank() }
|
||||
|
||||
private fun fields(line: String): List<String> = line.split('|')
|
||||
|
||||
private fun idOf(line: String): Long? = fields(line).firstOrNull()?.toLongOrNull()
|
||||
private fun isV2(line: String): Boolean = line.startsWith("$V2|")
|
||||
|
||||
private fun idOf(line: String): Long? = fields(line).getOrNull(if (isV2(line)) 1 else 0)?.toLongOrNull()
|
||||
|
||||
private fun Rule.elsewhereRefs(): Set<String> =
|
||||
flatten().filterIsInstance<Rule.InList>().flatMapTo(HashSet()) { it.elsewhere }
|
||||
|
||||
private fun splitList(value: String): List<String> = value.split(',').filter { it.isNotEmpty() }
|
||||
|
||||
private fun encodeLine(filter: SavedFilter, mode: String, foreignLists: List<String>): String =
|
||||
listOf(
|
||||
filter.id.toString(),
|
||||
encode(filter.name),
|
||||
filter.due.sorted().joinToString(",") { it.name },
|
||||
(filter.listIds.sorted().map { "$mode:$it" } + foreignLists).joinToString(","),
|
||||
filter.tags.sorted().joinToString(",") { encode(it) },
|
||||
filter.tagMatch.name,
|
||||
filter.minPriority.name,
|
||||
).joinToString("|")
|
||||
private fun encodeLine(filter: SavedFilter, mode: String): String =
|
||||
listOf(V2, filter.id.toString(), encode(filter.name), RuleCodec.encode(filter.rule, mode)).joinToString("|")
|
||||
|
||||
private fun decodeLine(line: String, mode: String): SavedFilter? {
|
||||
if (!isV2(line)) return decodeFlatLine(line, mode)
|
||||
val f = fields(line)
|
||||
if (f.size != 4) return null
|
||||
val id = f[1].toLongOrNull() ?: return null
|
||||
// A ref of this store naming no list is dropped, and a top-level list condition with
|
||||
// none of its lists readable drops out, as a flat filter's did.
|
||||
val rule = RuleCodec.decode(f[3], mode)
|
||||
.mapLists { list -> list.copy(elsewhere = list.elsewhere.filterNotTo(HashSet()) { it.startsWith("$mode:") }) }
|
||||
.withoutLists { false }
|
||||
return SavedFilter(id = id, name = decode(f[2]), rule = rule)
|
||||
}
|
||||
|
||||
private fun decodeFlatLine(line: String, mode: String): SavedFilter? {
|
||||
val f = fields(line)
|
||||
if (f.size < 7) return null
|
||||
val id = f[0].toLongOrNull() ?: return null
|
||||
val lists = splitList(f[3])
|
||||
val here = lists.filter { it.startsWith("$mode:") }.mapNotNull { it.removePrefix("$mode:").toLongOrNull() }.toSet()
|
||||
return SavedFilter(
|
||||
id = id,
|
||||
name = decode(f[1]),
|
||||
val (here, elsewhere) = splitRefs(splitList(f[3]), mode)
|
||||
val criteria = FilterCriteria(
|
||||
due = splitList(f[2]).mapNotNull { runCatching { DueWindow.valueOf(it) }.getOrNull() }.toSet(),
|
||||
listIds = here,
|
||||
listsElsewhere = lists.any { !it.startsWith("$mode:") },
|
||||
listsElsewhere = elsewhere,
|
||||
tags = splitList(f[4]).map(::decode).toSet(),
|
||||
tagMatch = runCatching { TagMatch.valueOf(f[5]) }.getOrDefault(TagMatch.ANY),
|
||||
minPriority = runCatching { Priority.valueOf(f[6]) }.getOrDefault(Priority.NONE),
|
||||
)
|
||||
return SavedFilter(id = id, name = decode(f[1]), criteria = criteria)
|
||||
}
|
||||
|
||||
/** [refs] split into [mode]'s list ids and the other stores' refs as they are. */
|
||||
private fun splitRefs(refs: List<String>, mode: String): Pair<Set<Long>, Set<String>> {
|
||||
val (here, elsewhere) = refs.partition { it.startsWith("$mode:") }
|
||||
return here.mapNotNull { it.removePrefix("$mode:").toLongOrNull() }.toSet() to elsewhere.toSet()
|
||||
}
|
||||
|
||||
private fun encode(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataMigration
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
|
||||
/** Rewrites the saved filters of 1.4 and earlier as rules, in place and once (see [SavedFilterCodec.migrate]). */
|
||||
internal object SavedFilterMigration : DataMigration<Preferences> {
|
||||
|
||||
val KEY = stringPreferencesKey("saved_filters")
|
||||
|
||||
override suspend fun shouldMigrate(currentData: Preferences): Boolean =
|
||||
SavedFilterCodec.needsMigration(currentData[KEY])
|
||||
|
||||
override suspend fun migrate(currentData: Preferences): Preferences =
|
||||
currentData.toMutablePreferences().apply { this[KEY] = SavedFilterCodec.migrate(this[KEY]) }
|
||||
|
||||
override suspend fun cleanUp() = Unit
|
||||
}
|
||||
@@ -15,6 +15,24 @@ 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
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
@@ -31,38 +49,40 @@ 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
|
||||
import de.jeanlucmakiola.floret.reminders.applyReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.normalizeReminders
|
||||
import de.jeanlucmakiola.floret.reminders.reminderLeadsFor
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import java.time.DayOfWeek
|
||||
import java.time.ZoneId
|
||||
import java.time.LocalDate
|
||||
import java.util.Locale
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
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 }
|
||||
|
||||
@@ -100,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. */
|
||||
@@ -160,6 +186,9 @@ data class Settings(
|
||||
/** How far ahead the Upcoming smart list reaches. */
|
||||
val upcomingRange: UpcomingRange = UpcomingRange.ALL,
|
||||
) {
|
||||
/** The first day of the week, the locale's when none is set. */
|
||||
val effectiveWeekStart: DayOfWeek get() = weekStart ?: localeWeekStart()
|
||||
|
||||
/** Whether a save rings the reminders it puts in the past (#106). */
|
||||
val ringsPastOnSave: Boolean get() = remindersEnabled && remindPastOnSave
|
||||
|
||||
@@ -184,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 ->
|
||||
@@ -245,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. */
|
||||
@@ -277,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)
|
||||
@@ -310,7 +396,7 @@ class SettingsPrefs @Inject constructor(
|
||||
?: TimeFormatPref.AUTO,
|
||||
autofocusTitle = p[AUTOFOCUS_TITLE] ?: true,
|
||||
syncIntervalMinutes = p[SYNC_INTERVAL]?.takeIf { it == 0 || it >= 15 } ?: DEFAULT_SYNC_INTERVAL_MINUTES,
|
||||
weekStart = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() },
|
||||
weekStart = storedWeekStart(p),
|
||||
pushEnabled = p[PUSH_ENABLED] ?: true,
|
||||
hiddenFromSmartLists = scope.let { mode ->
|
||||
p[SMART_LIST_HIDDEN].orEmpty()
|
||||
@@ -330,6 +416,20 @@ class SettingsPrefs @Inject constructor(
|
||||
)
|
||||
}.distinctUntilChanged() // Other stores write this DataStore too.
|
||||
|
||||
private val locale = MutableStateFlow(Locale.getDefault())
|
||||
|
||||
private fun storedWeekStart(p: Preferences): DayOfWeek? = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() }
|
||||
|
||||
/** Call when the device language changes: a week start left on automatic follows it. */
|
||||
fun onLocaleChanged() {
|
||||
locale.value = Locale.getDefault()
|
||||
}
|
||||
|
||||
/** The first day of the week: the setting, or the current locale's when none is set. */
|
||||
val firstDayOfWeek: Flow<DayOfWeek> =
|
||||
combine(dataStore.data.map { storedWeekStart(it) }.distinctUntilChanged(), locale) { set, locale -> set ?: localeWeekStart(locale) }
|
||||
.distinctUntilChanged()
|
||||
|
||||
/** Folds or unfolds the group with [id]; day groups that have passed are dropped on the way. */
|
||||
suspend fun setGroupCollapsed(id: String, collapsed: Boolean) = dataStore.edit { p ->
|
||||
val stored = scopeListKey(id, claimedScope(p))
|
||||
@@ -440,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
|
||||
}
|
||||
@@ -597,13 +700,116 @@ class SettingsPrefs @Inject constructor(
|
||||
p[GROUPINGS] = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key }
|
||||
}
|
||||
|
||||
/**
|
||||
* The views in order, with the list ids of the current store, Home first (see
|
||||
* [withHomeFirst]). Lists are qualified by the store alone, as the saved
|
||||
* filters' are, since both share one rule grammar.
|
||||
*/
|
||||
val views: Flow<List<View>> =
|
||||
dataStore.data.map { p -> p[VIEWS] to p[STORAGE_MODE] }
|
||||
.distinctUntilChanged()
|
||||
.map { (raw, mode) -> ViewCodec.decode(raw, (storedMode(mode) ?: resolver.autoMode()).name).withHomeFirst() }
|
||||
.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")
|
||||
@@ -638,8 +844,12 @@ class SettingsPrefs @Inject constructor(
|
||||
val COLLAPSED_SECTIONS = stringSetPreferencesKey("collapsed_sections")
|
||||
val UPCOMING_RANGE = stringPreferencesKey("upcoming_range")
|
||||
val GROUPINGS = stringSetPreferencesKey("task_groupings")
|
||||
val SAVED_FILTERS = stringPreferencesKey("saved_filters")
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -650,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. */
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
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.SmartList
|
||||
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.normalized
|
||||
import java.net.URLDecoder
|
||||
import java.net.URLEncoder
|
||||
|
||||
/**
|
||||
* Stored form of the views, in order. A `v1` line comes first, then each view
|
||||
* as a `view|id|name|icon|quickAdd|scope` line followed by its blocks as
|
||||
* `block|id|type|width|ignoreScope|source|options` lines.
|
||||
*
|
||||
* Rules (a scope, a `rules:` source) are written by [RuleCodec], so list
|
||||
* ids are qualified by their store (`OWN:3`) here too. Sources read `smart:TODAY`,
|
||||
* `list:OWN%3A3`, `tag:…`, `filter:4` or `rules:…`; options are `key=value`
|
||||
* pairs joined by `;`. Text is URL-encoded and booleans are `1` / `0`.
|
||||
*
|
||||
* A later version that adds an option key or an enum value bumps [VERSION], so an
|
||||
* older one reads none of its layout rather than a part of it. A writer has to
|
||||
* keep the lines [decode] skips rather than encode only what it read, or a view
|
||||
* from a newer version, or with a scope that doesn't parse, is lost.
|
||||
*
|
||||
* Fixed once released — don't change without a data migration.
|
||||
*/
|
||||
internal object ViewCodec {
|
||||
|
||||
const val VERSION = "v1"
|
||||
|
||||
/**
|
||||
* The views in [raw], with only the list ids of [mode]'s store. Lines that
|
||||
* don't read are skipped, and a stored layout of another version reads as none.
|
||||
*/
|
||||
fun decode(raw: String?, mode: String): List<View> {
|
||||
val lines = raw.orEmpty().split('\n').filter { it.isNotBlank() }
|
||||
if (lines.firstOrNull() != VERSION) return emptyList()
|
||||
val views = mutableListOf<View>()
|
||||
// A block line belongs to the view above it; those under an unreadable view go with it.
|
||||
var current: View? = null
|
||||
fun close() {
|
||||
current?.let { views += it.copy(blocks = it.blocks.normalized()) }
|
||||
current = null
|
||||
}
|
||||
lines.drop(1).forEach { line ->
|
||||
val f = line.split('|')
|
||||
when (f.firstOrNull()) {
|
||||
"view" -> {
|
||||
close()
|
||||
current = runCatching { decodeView(f, mode) }.getOrNull()
|
||||
}
|
||||
"block" -> current?.let { view ->
|
||||
runCatching { decodeBlock(f, mode) }.getOrNull()?.let { current = view.copy(blocks = view.blocks + it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
close()
|
||||
return views.distinctBy { it.id }
|
||||
}
|
||||
|
||||
fun encode(views: List<View>, mode: String): String = buildList {
|
||||
add(VERSION)
|
||||
views.forEach { view ->
|
||||
add(
|
||||
listOf(
|
||||
"view",
|
||||
view.id.toString(),
|
||||
encode(view.name),
|
||||
view.icon.name,
|
||||
flag(view.quickAdd),
|
||||
view.scope?.let { RuleCodec.encode(it, mode) }.orEmpty(),
|
||||
).joinToString("|"),
|
||||
)
|
||||
view.blocks.forEach { add(encodeBlock(it, mode)) }
|
||||
}
|
||||
}.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(
|
||||
id = f[1].toLongOrNull() ?: return null,
|
||||
name = decode(f[2]),
|
||||
icon = enumOr(f[3], ViewIcon.HOME),
|
||||
quickAdd = f[4] != "0",
|
||||
scope = f[5].takeIf { it.isNotEmpty() }?.let { RuleCodec.decode(it, mode) },
|
||||
blocks = emptyList(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun encodeBlock(block: Block, mode: String): String = listOf(
|
||||
"block",
|
||||
block.id.toString(),
|
||||
block.type.name,
|
||||
block.width.name,
|
||||
flag(block.ignoreScope),
|
||||
block.source?.let { encodeSource(it, mode) }.orEmpty(),
|
||||
encodeOptions(block.options),
|
||||
).joinToString("|")
|
||||
|
||||
private fun decodeBlock(f: List<String>, mode: String): Block? {
|
||||
if (f.size != 7) return null
|
||||
val type = BlockType.valueOf(f[2])
|
||||
return Block(
|
||||
id = f[1].toLongOrNull() ?: return null,
|
||||
type = type,
|
||||
width = enumOr(f[3], type.widths.first()),
|
||||
ignoreScope = f[4] == "1",
|
||||
source = f[5].takeIf { it.isNotEmpty() }?.let { decodeSource(it, mode) },
|
||||
options = decodeOptions(type, pairs(f[6])),
|
||||
)
|
||||
}
|
||||
|
||||
private fun encodeSource(source: BlockSource, mode: String): String = when (source) {
|
||||
is BlockSource.Smart -> "smart:${source.smart.name}"
|
||||
is BlockSource.List -> "list:${encode("$mode:${source.listId}")}"
|
||||
is BlockSource.ListElsewhere -> "list:${encode(source.ref)}"
|
||||
is BlockSource.Tag -> "tag:${encode(source.tag)}"
|
||||
is BlockSource.Filter -> "filter:${source.filterId}"
|
||||
is BlockSource.Rules -> "rules:${RuleCodec.encode(source.rule, mode)}"
|
||||
}
|
||||
|
||||
/** The source [text] names; a list of another store stays as its stored ref. */
|
||||
private fun decodeSource(text: String, mode: String): BlockSource {
|
||||
val kind = text.substringBefore(':')
|
||||
val value = text.substringAfter(':')
|
||||
return when (kind) {
|
||||
"smart" -> BlockSource.Smart(SmartList.valueOf(value))
|
||||
"list" -> decode(value).let { ref ->
|
||||
ref.removePrefix("$mode:").takeIf { it != ref }?.toLongOrNull()?.let(BlockSource::List)
|
||||
?: BlockSource.ListElsewhere(ref)
|
||||
}
|
||||
"tag" -> BlockSource.Tag(decode(value))
|
||||
"filter" -> BlockSource.Filter(value.toLong())
|
||||
"rules" -> BlockSource.Rules(RuleCodec.decode(value, mode))
|
||||
else -> throw IllegalArgumentException("Unknown source $kind")
|
||||
}
|
||||
}
|
||||
|
||||
private fun encodeOptions(options: BlockOptions): String = when (options) {
|
||||
is BlockOptions.Progress -> listOf("wave" to flag(options.wave), "title" to options.title?.let(::encode))
|
||||
is BlockOptions.CountTile -> listOf(
|
||||
"title" to options.title?.let(::encode),
|
||||
"color" to options.color?.name,
|
||||
"icon" to options.icon?.name,
|
||||
)
|
||||
is BlockOptions.Preview -> listOf(
|
||||
"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,
|
||||
"completed" to flag(options.showCompleted),
|
||||
"inlineDone" to flag(options.inlineDone),
|
||||
)
|
||||
is BlockOptions.Lists -> listOf(
|
||||
"accounts" to options.accounts?.sorted()?.joinToString(",") { encode(it) },
|
||||
"counts" to flag(options.counts),
|
||||
)
|
||||
is BlockOptions.SectionHeading -> listOf("text" to encode(options.text))
|
||||
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. */
|
||||
private fun decodeOptions(type: BlockType, p: Map<String, String>): BlockOptions = when (type) {
|
||||
BlockType.PROGRESS -> BlockOptions.Progress(
|
||||
wave = p["wave"] != "0",
|
||||
title = text(p["title"]),
|
||||
)
|
||||
BlockType.COUNT_TILE -> BlockOptions.CountTile(
|
||||
title = text(p["title"]),
|
||||
color = p["color"]?.let { enumOrNull<TileColor>(it) },
|
||||
icon = p["icon"]?.let { enumOrNull<ViewIcon>(it) },
|
||||
)
|
||||
BlockType.PREVIEW -> BlockOptions.Preview(
|
||||
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) },
|
||||
showCompleted = p["completed"] != "0",
|
||||
inlineDone = p["inlineDone"] != "0",
|
||||
)
|
||||
BlockType.LISTS -> BlockOptions.Lists(
|
||||
accounts = p["accounts"]?.split(',')?.mapTo(HashSet(), ::decode),
|
||||
counts = p["counts"] != "0",
|
||||
)
|
||||
BlockType.TAGS -> BlockOptions.Tags
|
||||
BlockType.FILTERS -> BlockOptions.Filters
|
||||
BlockType.SECTION_HEADING -> BlockOptions.SectionHeading(p["text"]?.let(::decode).orEmpty())
|
||||
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. */
|
||||
private fun text(value: String?): String? = value?.let(::decode)?.takeIf { it.isNotBlank() }
|
||||
|
||||
private fun previewCount(value: String?): Int =
|
||||
value?.toIntOrNull()?.takeIf { it in BlockOptions.PREVIEW_COUNTS } ?: BlockOptions.PREVIEW_COUNTS.first()
|
||||
|
||||
private fun pairs(text: String): Map<String, String> = text.split(';').filter { '=' in it }
|
||||
.associate { it.substringBefore('=') to it.substringAfter('=') }
|
||||
|
||||
private fun flag(value: Boolean): String = if (value) "1" else "0"
|
||||
|
||||
private inline fun <reified E : Enum<E>> enumOrNull(name: String): E? =
|
||||
enumValues<E>().firstOrNull { it.name == name }
|
||||
|
||||
private inline fun <reified E : Enum<E>> enumOr(name: String, default: E): E = enumOrNull<E>(name) ?: default
|
||||
|
||||
private fun encode(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
|
||||
|
||||
private fun decode(value: String): String = URLDecoder.decode(value, Charsets.UTF_8.name())
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataMigration
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import de.jeanlucmakiola.agendula.domain.View
|
||||
|
||||
/**
|
||||
* Stores the [View.home] layout once, when there are no views yet: on the
|
||||
* upgrade from 1.4 and on a fresh install alike.
|
||||
*/
|
||||
internal object ViewsMigration : DataMigration<Preferences> {
|
||||
|
||||
val KEY = stringPreferencesKey("views")
|
||||
|
||||
// Home names no list, so the store its ids would be qualified by doesn't matter.
|
||||
private const val ANY_STORE = "OWN"
|
||||
|
||||
override suspend fun shouldMigrate(currentData: Preferences): Boolean = currentData[KEY] == null
|
||||
|
||||
override suspend fun migrate(currentData: Preferences): Preferences =
|
||||
currentData.toMutablePreferences().apply { this[KEY] = ViewCodec.encode(listOf(View.home()), ANY_STORE) }
|
||||
|
||||
override suspend fun cleanUp() = Unit
|
||||
}
|
||||
@@ -21,6 +21,8 @@ import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.readsWeekStart
|
||||
import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
@@ -37,6 +39,7 @@ import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.time.DayOfWeek
|
||||
import java.time.ZoneId
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
import javax.inject.Inject
|
||||
@@ -85,13 +88,20 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
// A deleted filter shows nothing rather than failing the screen or widget on it.
|
||||
is TaskFilter.Saved -> settingsPrefs.savedFilter(filter.id)
|
||||
.flatMapLatest { saved ->
|
||||
if (saved == null) flowOf(FilteredTasks(emptyList()))
|
||||
else observing {
|
||||
// A deleted list's id would otherwise leave the filter quietly empty.
|
||||
val current = saved.withListsIn(dataSource.taskLists().mapTo(HashSet()) { it.id })
|
||||
FilteredTasks(loadTasks(filter, current), current)
|
||||
if (saved == null) return@flatMapLatest flowOf(FilteredTasks(emptyList()))
|
||||
// Only a rule with weeks in it reloads when the week start moves; others never read it.
|
||||
val weekStarts = if (saved.rule.readsWeekStart) settingsPrefs.firstDayOfWeek else flowOf(DayOfWeek.MONDAY)
|
||||
weekStarts.flatMapLatest { weekStart ->
|
||||
observing {
|
||||
// A deleted list's id would otherwise leave the filter quietly empty.
|
||||
val current = saved.withListsIn(dataSource.taskLists().mapTo(HashSet()) { it.id })
|
||||
FilteredTasks(loadTasks(filter, current, weekStart), current)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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)) }
|
||||
}
|
||||
|
||||
@@ -113,7 +123,8 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadTasks(filter: TaskFilter, saved: SavedFilter? = null): List<Task> {
|
||||
/** [weekStart] is where [saved]'s weeks begin. */
|
||||
private fun loadTasks(filter: TaskFilter, saved: SavedFilter? = null, weekStart: DayOfWeek = DayOfWeek.MONDAY): List<Task> {
|
||||
val query = when (filter) {
|
||||
is TaskFilter.OfList -> TaskQuery(listId = filter.listId, includeCompleted = true)
|
||||
// Read completed tasks too, then let [TaskFiltering.matches] enforce each
|
||||
@@ -126,8 +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 (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), zone)
|
||||
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
|
||||
@@ -137,7 +152,7 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
(if (t.isCompleted) done + 1 else done) to (total + 1)
|
||||
}
|
||||
return all
|
||||
.filter { TaskFiltering.matches(it, filter, todayStart, todayEnd, saved) }
|
||||
.filter { TaskFiltering.matches(it, filter, todayStart, todayEnd, saved, ruleClock = clock) }
|
||||
.map { task ->
|
||||
progress[task.taskId]?.let { (done, total) ->
|
||||
task.copy(subtaskDone = done, subtaskTotal = total)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
/**
|
||||
* The flat form of a filter, as the filter editor shows it: every criterion
|
||||
* must hold, and an empty one doesn't narrow. No [due] windows means any due
|
||||
* date, no lists any list, no [tags] any tag, [Priority.NONE] any priority.
|
||||
*
|
||||
* [listsElsewhere] are the filter's lists in other task stores, as stored (see
|
||||
* [Rule.InList.elsewhere]). With some of them but no [listIds] the filter
|
||||
* matches nothing here rather than every list.
|
||||
*/
|
||||
data class FilterCriteria(
|
||||
val due: Set<DueWindow> = emptySet(),
|
||||
val listIds: Set<Long> = emptySet(),
|
||||
val listsElsewhere: Set<String> = emptySet(),
|
||||
val tags: Set<String> = emptySet(),
|
||||
val tagMatch: TagMatch = TagMatch.ANY,
|
||||
val minPriority: Priority = Priority.NONE,
|
||||
) {
|
||||
/** Whether the filter narrows by list at all. */
|
||||
val anyList: Boolean get() = listIds.isEmpty() && listsElsewhere.isEmpty()
|
||||
|
||||
/** These criteria as a rule: an [Rule.AllOf] of the criteria that narrow. */
|
||||
fun toRule(): Rule = Rule.AllOf(
|
||||
buildList {
|
||||
if (due.isNotEmpty()) add(Rule.AnyOf(DueWindow.entries.filter { it in due }.map { Rule.Due(DueSpec.Window(it)) }))
|
||||
if (!anyList) add(Rule.InList(listIds, listsElsewhere))
|
||||
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))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* [rule] in flat form, or `null` when it has none: a [Rule.Not], a
|
||||
* relative due range, a group that mixes kinds of criteria, or one kind
|
||||
* given twice.
|
||||
*/
|
||||
fun of(rule: Rule): FilterCriteria? {
|
||||
val parts = if (rule is Rule.AllOf) rule.children else listOf(rule)
|
||||
var criteria = FilterCriteria()
|
||||
val seen = mutableSetOf<Kind>()
|
||||
fun claim(kind: Kind): Boolean = seen.add(kind)
|
||||
for (part in parts) {
|
||||
criteria = when {
|
||||
part is Rule.Due && part.spec is DueSpec.Window -> {
|
||||
if (!claim(Kind.DUE)) return null
|
||||
criteria.copy(due = setOf(part.spec.window))
|
||||
}
|
||||
part is Rule.InList -> {
|
||||
if (!claim(Kind.LISTS) || part.listIds.isEmpty() && part.elsewhere.isEmpty()) return null
|
||||
criteria.copy(listIds = part.listIds, listsElsewhere = part.elsewhere)
|
||||
}
|
||||
part is Rule.MinPriority -> {
|
||||
if (!claim(Kind.PRIORITY)) return null
|
||||
criteria.copy(minPriority = part.priority)
|
||||
}
|
||||
// Tags straight under the top read as all of them.
|
||||
part is Rule.HasTag -> {
|
||||
if (Kind.TAG_GROUP in seen) return null
|
||||
seen += Kind.TAGS
|
||||
criteria.copy(tags = criteria.tags + part.tag, tagMatch = TagMatch.ALL)
|
||||
}
|
||||
else -> {
|
||||
val group = groupOf(part) ?: return null
|
||||
val windows = group.mapNotNull { ((it as? Rule.Due)?.spec as? DueSpec.Window)?.window }
|
||||
val tags = group.mapNotNull { (it as? Rule.HasTag)?.tag }
|
||||
when {
|
||||
part is Rule.AnyOf && windows.size == group.size -> {
|
||||
if (!claim(Kind.DUE)) return null
|
||||
criteria.copy(due = windows.toSet())
|
||||
}
|
||||
tags.size == group.size -> {
|
||||
if (!claim(Kind.TAGS) || !claim(Kind.TAG_GROUP)) return null
|
||||
criteria.copy(tags = tags.toSet(), tagMatch = if (part is Rule.AllOf) TagMatch.ALL else TagMatch.ANY)
|
||||
}
|
||||
else -> return null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return criteria
|
||||
}
|
||||
|
||||
private enum class Kind { DUE, LISTS, PRIORITY, TAGS, TAG_GROUP }
|
||||
|
||||
/** The children of a non-empty [Rule.AllOf] or [Rule.AnyOf]; `null` for anything else. */
|
||||
private fun groupOf(rule: Rule): List<Rule>? = when (rule) {
|
||||
is Rule.AllOf -> rule.children
|
||||
is Rule.AnyOf -> rule.children
|
||||
else -> null
|
||||
}?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -70,8 +97,8 @@ fun newTaskDates(
|
||||
|
||||
/**
|
||||
* Whether an open task with these dates shows in [smartList], Upcoming reaching
|
||||
* up to [upcomingEnd], or passes [savedFilter]'s due windows; with neither it
|
||||
* shows anywhere.
|
||||
* up to [upcomingEnd], or passes [savedFilter]'s due conditions read with
|
||||
* [ruleClock]; with neither it shows anywhere, as does a saved filter without a clock.
|
||||
*/
|
||||
fun NewTaskDates.showsIn(
|
||||
smartList: SmartList?,
|
||||
@@ -79,11 +106,38 @@ fun NewTaskDates.showsIn(
|
||||
todayStart: Instant,
|
||||
todayEnd: Instant,
|
||||
upcomingEnd: Instant? = null,
|
||||
ruleClock: RuleClock? = null,
|
||||
): Boolean {
|
||||
val probe = openTaskDated(start, due, isAllDay)
|
||||
return when {
|
||||
savedFilter != null -> savedFilter.due.isEmpty() || dueWindowOf(probe, todayStart, todayEnd) in savedFilter.due
|
||||
savedFilter != null -> ruleClock == null || savedFilter.admitsDueOf(probe, ruleClock)
|
||||
smartList != null -> TaskFiltering.matches(probe, TaskFilter.Smart(smartList), todayStart, todayEnd, upcomingEnd = upcomingEnd)
|
||||
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(" ")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.temporal.TemporalAdjusters
|
||||
import java.time.temporal.WeekFields
|
||||
import java.util.Locale
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* A condition on a task, nestable with [AllOf], [AnyOf] and [Not]. An empty [AllOf]
|
||||
* passes every task, an empty [AnyOf] none. Whether a task is open or done is not
|
||||
* a rule: the view a rule is used in decides that.
|
||||
*/
|
||||
sealed interface Rule {
|
||||
data class AllOf(val children: List<Rule>) : Rule
|
||||
data class AnyOf(val children: List<Rule>) : Rule
|
||||
data class Not(val child: Rule) : Rule
|
||||
|
||||
/**
|
||||
* In one of [listIds], this store's lists. [elsewhere] holds the lists of
|
||||
* other task stores as stored, so saving here keeps them; they never match
|
||||
* a task here, so with no [listIds] this matches nothing.
|
||||
*/
|
||||
data class InList(val listIds: Set<Long>, val elsewhere: Set<String> = emptySet()) : Rule
|
||||
|
||||
/** Carries [tag], compared exactly. */
|
||||
data class HasTag(val tag: String) : Rule
|
||||
|
||||
/** At [priority] or higher. */
|
||||
data class MinPriority(val priority: Priority) : Rule
|
||||
|
||||
data class Due(val spec: DueSpec) : Rule
|
||||
|
||||
companion object {
|
||||
/** The rule every task passes. */
|
||||
val Everything: Rule = AllOf(emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When a task is due: one of the [DueWindow]s, or a range of days around today.
|
||||
* Due today is [DueWindow.TODAY]; there is no range for it.
|
||||
*/
|
||||
sealed interface DueSpec {
|
||||
data class Window(val window: DueWindow) : DueSpec
|
||||
|
||||
/** Due on a day in a range relative to today; an undated task is in none. */
|
||||
sealed interface Range : DueSpec {
|
||||
/** The first day of the range and the day after its last, when today is [today]. */
|
||||
fun days(today: LocalDate, weekStart: DayOfWeek): Pair<LocalDate, LocalDate>
|
||||
}
|
||||
|
||||
/** The calendar week holding today, starting on [weekStart]. */
|
||||
data object ThisWeek : Range {
|
||||
override fun days(today: LocalDate, weekStart: DayOfWeek): Pair<LocalDate, LocalDate> {
|
||||
val first = today.with(TemporalAdjusters.previousOrSame(weekStart))
|
||||
return first to first.plusWeeks(1)
|
||||
}
|
||||
}
|
||||
|
||||
/** The calendar month holding today. */
|
||||
data object ThisMonth : Range {
|
||||
override fun days(today: LocalDate, weekStart: DayOfWeek): Pair<LocalDate, LocalDate> {
|
||||
val first = today.withDayOfMonth(1)
|
||||
return first to first.plusMonths(1)
|
||||
}
|
||||
}
|
||||
|
||||
/** Today and the [days] after it, the way [UpcomingRange] reaches ahead. */
|
||||
data class NextDays(val days: Int) : Range {
|
||||
init {
|
||||
require(days >= 0) { "days must not be negative: $days" }
|
||||
}
|
||||
|
||||
override fun days(today: LocalDate, weekStart: DayOfWeek) = today to today.plusDays(days + 1L)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The day rules are read against: local today from [todayStart] to [todayEnd]
|
||||
* (see [DayWindow]) in [zone], with weeks starting on [weekStart].
|
||||
*/
|
||||
data class RuleClock(
|
||||
val todayStart: Instant,
|
||||
val todayEnd: Instant,
|
||||
val zone: ZoneId,
|
||||
val weekStart: DayOfWeek,
|
||||
) {
|
||||
val today: LocalDate by lazy(LazyThreadSafetyMode.PUBLICATION) { todayStart.calendarDate(allDay = false, zone = zone) }
|
||||
}
|
||||
|
||||
/** The first day of the week in [locale]; what an unset week start means. */
|
||||
fun localeWeekStart(locale: Locale = Locale.getDefault()): DayOfWeek = WeekFields.of(locale).firstDayOfWeek
|
||||
|
||||
/** Whether [task] passes this rule, whatever its status. */
|
||||
fun Rule.matches(task: Task, clock: RuleClock): Boolean = when (this) {
|
||||
is Rule.AllOf -> children.all { it.matches(task, clock) }
|
||||
is Rule.AnyOf -> children.any { it.matches(task, clock) }
|
||||
is Rule.Not -> !child.matches(task, clock)
|
||||
is Rule.InList -> task.listId in listIds
|
||||
is Rule.HasTag -> tag in task.tags
|
||||
is Rule.MinPriority -> task.priority >= priority
|
||||
is Rule.Due -> spec.matches(task, clock)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [task]'s due date alone settles this rule: `true` or `false` when it
|
||||
* does, `null` when the rule's other conditions decide.
|
||||
*/
|
||||
fun Rule.dueVerdict(task: Task, clock: RuleClock): Boolean? = when (this) {
|
||||
is Rule.Due -> spec.matches(task, clock)
|
||||
is Rule.Not -> child.dueVerdict(task, clock)?.not()
|
||||
is Rule.AllOf -> children.map { it.dueVerdict(task, clock) }.let { v ->
|
||||
if (false in v) false else if (null in v) null else true
|
||||
}
|
||||
is Rule.AnyOf -> children.map { it.dueVerdict(task, clock) }.let { v ->
|
||||
if (true in v) true else if (null in v) null else false
|
||||
}
|
||||
is Rule.InList, is Rule.HasTag, is Rule.MinPriority -> null
|
||||
}
|
||||
|
||||
/** Whether [task]'s due falls in this spec. */
|
||||
fun DueSpec.matches(task: Task, clock: RuleClock): Boolean = when (this) {
|
||||
is DueSpec.Window -> dueWindowOf(task, clock.todayStart, clock.todayEnd, clock.zone) == window
|
||||
is DueSpec.Range -> {
|
||||
val (first, afterLast) = days(clock.today, clock.weekStart)
|
||||
val due = task.wallClock(TaskEnd.DUE, clock.zone)
|
||||
due != null && due >= startOfDay(first, clock.zone) && due < startOfDay(afterLast, clock.zone)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This rule without the lists [gone] names, e.g. lists since deleted. A list
|
||||
* condition left without lists matches nothing, as it did with them gone, so a
|
||||
* nested rule reads the same. Only at the top, where a flat filter keeps its
|
||||
* criteria, does it drop out instead, so the filter goes back to any list.
|
||||
*
|
||||
* That widening is a saved filter's; a view's scope uses [withoutListIds],
|
||||
* where a list condition left without lists matches nothing at every level.
|
||||
*/
|
||||
fun Rule.withoutLists(gone: (Long) -> Boolean): Rule {
|
||||
val pruned = withoutListIds(gone)
|
||||
return when {
|
||||
pruned.isEmptyList() -> Rule.Everything
|
||||
pruned is Rule.AllOf -> pruned.children.filterNot { it.isEmptyList() }
|
||||
.let { if (it.size == pruned.children.size) pruned else Rule.AllOf(it) }
|
||||
else -> pruned
|
||||
}
|
||||
}
|
||||
|
||||
private fun Rule.isEmptyList(): Boolean = this is Rule.InList && listIds.isEmpty() && elsewhere.isEmpty()
|
||||
|
||||
/** This rule without the lists [gone] names; a list condition left without lists matches nothing. */
|
||||
fun Rule.withoutListIds(gone: (Long) -> Boolean): Rule = mapLists { list ->
|
||||
list.listIds.filterNotTo(HashSet(), gone).let { if (it.size == list.listIds.size) list else list.copy(listIds = it) }
|
||||
}
|
||||
|
||||
/** This rule with each list condition replaced by [transform]; the same instance when nothing changed. */
|
||||
fun Rule.mapLists(transform: (Rule.InList) -> Rule.InList): Rule = when (this) {
|
||||
is Rule.InList -> transform(this)
|
||||
is Rule.AllOf -> children.map { it.mapLists(transform) }.let { if (it == children) this else Rule.AllOf(it) }
|
||||
is Rule.AnyOf -> children.map { it.mapLists(transform) }.let { if (it == children) this else Rule.AnyOf(it) }
|
||||
is Rule.Not -> child.mapLists(transform).let { if (it == child) this else Rule.Not(it) }
|
||||
is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> this
|
||||
}
|
||||
|
||||
/** Every condition in this rule, itself included. */
|
||||
fun Rule.flatten(): Sequence<Rule> = sequence {
|
||||
yield(this@flatten)
|
||||
when (this@flatten) {
|
||||
is Rule.AllOf -> children.forEach { yieldAll(it.flatten()) }
|
||||
is Rule.AnyOf -> children.forEach { yieldAll(it.flatten()) }
|
||||
is Rule.Not -> yieldAll(child.flatten())
|
||||
is Rule.InList, is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this rule depends on where the week starts. */
|
||||
val Rule.readsWeekStart: Boolean get() = flatten().any { it is Rule.Due && it.spec is DueSpec.ThisWeek }
|
||||
@@ -10,42 +10,28 @@ enum class DueWindow { OVERDUE, TODAY, UPCOMING, NO_DATE }
|
||||
/** How a [SavedFilter] with several tags reads them. */
|
||||
enum class TagMatch { ANY, ALL }
|
||||
|
||||
/**
|
||||
* A user-made view over the open tasks. An empty criterion doesn't narrow:
|
||||
* no [due] windows means any due date, no [listIds] any list, no [tags] any tag.
|
||||
* [minPriority] [Priority.NONE] lets every priority through.
|
||||
*
|
||||
* [listsElsewhere] is set when the filter also has lists in another task store.
|
||||
* With none of its lists here it then matches nothing rather than every list.
|
||||
*/
|
||||
/** A user-made view over the open tasks: the ones that pass [rule]. */
|
||||
data class SavedFilter(
|
||||
val id: Long,
|
||||
val name: String,
|
||||
val due: Set<DueWindow> = emptySet(),
|
||||
val listIds: Set<Long> = emptySet(),
|
||||
val tags: Set<String> = emptySet(),
|
||||
val tagMatch: TagMatch = TagMatch.ANY,
|
||||
val minPriority: Priority = Priority.NONE,
|
||||
val listsElsewhere: Boolean = false,
|
||||
val rule: Rule = Rule.Everything,
|
||||
) {
|
||||
/** Whether the filter narrows by list at all. */
|
||||
val anyList: Boolean get() = listIds.isEmpty() && !listsElsewhere
|
||||
constructor(id: Long, name: String, criteria: FilterCriteria) : this(id, name, criteria.toRule())
|
||||
|
||||
/** This filter without the list ids missing from [existing], e.g. lists since deleted. */
|
||||
fun withListsIn(existing: Set<Long>): SavedFilter = copy(listIds = listIds intersect existing)
|
||||
/** [rule] in the flat form the filter editor shows; `null` when it has none. */
|
||||
val criteria: FilterCriteria? by lazy(LazyThreadSafetyMode.PUBLICATION) { FilterCriteria.of(rule) }
|
||||
|
||||
fun matches(task: Task, todayStart: Instant, todayEnd: Instant): Boolean {
|
||||
if (task.isClosed) return false
|
||||
if (listsElsewhere && listIds.isEmpty()) return false
|
||||
if (listIds.isNotEmpty() && task.listId !in listIds) return false
|
||||
if (task.priority < minPriority) return false
|
||||
if (due.isNotEmpty() && dueWindowOf(task, todayStart, todayEnd) !in due) return false
|
||||
return when {
|
||||
tags.isEmpty() -> true
|
||||
tagMatch == TagMatch.ALL -> task.tags.containsAll(tags)
|
||||
else -> task.tags.any { it in tags }
|
||||
}
|
||||
}
|
||||
/**
|
||||
* This filter without the list ids missing from [existing], e.g. lists since
|
||||
* deleted. A read finding no list at all proves nothing, so it keeps them.
|
||||
*/
|
||||
fun withListsIn(existing: Set<Long>): SavedFilter =
|
||||
if (existing.isEmpty()) this else copy(rule = rule.withoutLists { it !in existing })
|
||||
|
||||
fun matches(task: Task, clock: RuleClock): Boolean = !task.isClosed && rule.matches(task, clock)
|
||||
|
||||
/** Whether an open task dated like [probe] can pass this filter, going by its due conditions only. */
|
||||
fun admitsDueOf(probe: Task, clock: RuleClock): Boolean = rule.dueVerdict(probe, clock) != false
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,8 +78,7 @@ val SmartList.dueWindows: Set<DueWindow>
|
||||
/** [end] as a local instant: a date without a time is read as the start of its day. */
|
||||
fun Task.wallClock(end: TaskEnd, zone: ZoneId = ZoneId.systemDefault()): Instant? {
|
||||
if (hasTime(end)) return valueOf(end)
|
||||
val date = dateOf(end, zone) ?: return null
|
||||
return Instant.fromEpochMilliseconds(date.atStartOfDay(zone).toInstant().toEpochMilli())
|
||||
return dateOf(end, zone)?.let { startOfDay(it, zone) }
|
||||
}
|
||||
|
||||
/** What a task created from a [SavedFilter] starts with, so it lands in that filter. */
|
||||
@@ -104,13 +89,19 @@ data class NewTaskPreset(
|
||||
val priority: Priority = Priority.NONE,
|
||||
)
|
||||
|
||||
/** The preset for a new task in this filter; its due is [presetDue]. */
|
||||
fun SavedFilter.newTaskPreset(today: LocalDate): NewTaskPreset = NewTaskPreset(
|
||||
listIds = listIds,
|
||||
tags = when {
|
||||
tagMatch == TagMatch.ALL -> tags.sorted()
|
||||
else -> listOfNotNull(tags.minOrNull())
|
||||
},
|
||||
dueDate = due.presetDue(today),
|
||||
priority = minPriority,
|
||||
)
|
||||
/**
|
||||
* The preset for a new task in this filter; its due is [presetDue]. A filter
|
||||
* without a flat form presets nothing.
|
||||
*/
|
||||
fun SavedFilter.newTaskPreset(today: LocalDate): NewTaskPreset {
|
||||
val criteria = criteria ?: return NewTaskPreset()
|
||||
return NewTaskPreset(
|
||||
listIds = criteria.listIds,
|
||||
tags = when {
|
||||
criteria.tagMatch == TagMatch.ALL -> criteria.tags.sorted()
|
||||
else -> listOfNotNull(criteria.tags.minOrNull())
|
||||
},
|
||||
dueDate = criteria.due.presetDue(today),
|
||||
priority = criteria.minPriority,
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -35,6 +45,7 @@ object TaskFiltering {
|
||||
/**
|
||||
* [saved] is the definition behind a [TaskFilter.Saved]; without one it matches nothing.
|
||||
* [upcomingEnd] caps Upcoming to dues before it (see [UpcomingRange.end]); `null` = no cap.
|
||||
* [ruleClock] reads [saved]'s rule; a saved filter without either matches nothing.
|
||||
*/
|
||||
fun matches(
|
||||
task: Task,
|
||||
@@ -43,13 +54,17 @@ object TaskFiltering {
|
||||
todayEnd: Instant,
|
||||
saved: SavedFilter? = null,
|
||||
upcomingEnd: Instant? = null,
|
||||
ruleClock: RuleClock? = null,
|
||||
): Boolean =
|
||||
when (filter) {
|
||||
is TaskFilter.OfList -> task.listId == filter.listId
|
||||
is TaskFilter.OfLists -> task.listId in filter.listIds
|
||||
is TaskFilter.Smart -> matchesSmart(task, filter.list, todayStart, todayEnd, upcomingEnd)
|
||||
is TaskFilter.Tagged -> filter.tag in task.tags
|
||||
is TaskFilter.Saved -> saved?.takeIf { it.id == filter.id }?.matches(task, todayStart, todayEnd) ?: false
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -95,12 +95,16 @@ object TaskGroups {
|
||||
// No task-list screen, so nowhere to remember a grouping.
|
||||
is TaskFilter.OfLists -> return emptyList()
|
||||
is TaskFilter.Saved -> buildSet {
|
||||
if (savedFilter?.listIds?.size == 1) add(TaskGrouping.LIST)
|
||||
val criteria = savedFilter?.criteria
|
||||
if (criteria?.listIds?.size == 1) add(TaskGrouping.LIST)
|
||||
// Due windows without Upcoming leave no later days to split.
|
||||
val due = savedFilter?.due.orEmpty()
|
||||
val due = criteria?.due.orEmpty()
|
||||
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
|
||||
}
|
||||
@@ -136,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"
|
||||
}
|
||||
@@ -22,10 +22,14 @@ enum class UpcomingRange {
|
||||
fun end(now: Instant, zone: ZoneId = ZoneId.systemDefault()): Instant? {
|
||||
val today = now.calendarDate(allDay = false, zone = zone)
|
||||
val last = lastDay(today) ?: return null
|
||||
return Instant.fromEpochMilliseconds(last.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli())
|
||||
return startOfDay(last.plusDays(1), zone)
|
||||
}
|
||||
}
|
||||
|
||||
/** Local midnight starting [date] in [zone]. */
|
||||
fun startOfDay(date: LocalDate, zone: ZoneId = ZoneId.systemDefault()): Instant =
|
||||
Instant.fromEpochMilliseconds(date.atStartOfDay(zone).toInstant().toEpochMilli())
|
||||
|
||||
/** Whether [task] is due before [end]; an undated task never is. */
|
||||
fun dueBefore(task: Task, end: Instant, zone: ZoneId = ZoneId.systemDefault()): Boolean =
|
||||
task.wallClock(TaskEnd.DUE, zone)?.let { it < end } ?: false
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
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.
|
||||
*/
|
||||
data class View(
|
||||
val id: Long,
|
||||
val name: String,
|
||||
val icon: ViewIcon,
|
||||
val scope: Rule?,
|
||||
val blocks: List<Block>,
|
||||
val quickAdd: Boolean = true,
|
||||
) {
|
||||
/** What is wrong with this view's blocks; empty when nothing is. */
|
||||
val problems: List<LayoutProblem> get() = blocks.layoutProblems()
|
||||
|
||||
companion object {
|
||||
const val HOME_ID = 1L
|
||||
|
||||
/**
|
||||
* The Home view every install starts with: the blocks of the fixed home
|
||||
* of 1.4, in its order. The name is empty so the UI shows its own,
|
||||
* translated one until the user renames it.
|
||||
*/
|
||||
fun home(): View = View(
|
||||
id = HOME_ID,
|
||||
name = "",
|
||||
icon = ViewIcon.HOME,
|
||||
scope = null,
|
||||
blocks = listOf(
|
||||
Block(1, BlockType.PROGRESS, BlockSource.Smart(SmartList.TODAY)),
|
||||
Block(2, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.OVERDUE), BlockWidth.HALF),
|
||||
Block(3, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL), BlockWidth.HALF),
|
||||
Block(4, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING)),
|
||||
Block(5, BlockType.LISTS),
|
||||
Block(6, BlockType.TAGS),
|
||||
Block(7, BlockType.FILTERS),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** One block of a [View]. [source] is set exactly when [type] takes one. */
|
||||
data class Block(
|
||||
val id: Long,
|
||||
val type: BlockType,
|
||||
val source: BlockSource? = null,
|
||||
val width: BlockWidth = type.widths.first(),
|
||||
val ignoreScope: Boolean = false,
|
||||
val options: BlockOptions = BlockOptions.defaultFor(type),
|
||||
) {
|
||||
init {
|
||||
require(options.type == type) { "Options ${options.type} on a $type block" }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* These views with Home first: the stored one, or the default when it is missing,
|
||||
* e.g. because its line didn't read.
|
||||
*/
|
||||
fun List<View>.withHomeFirst(): List<View> =
|
||||
listOf(firstOrNull { it.id == View.HOME_ID } ?: View.home()) + filter { it.id != View.HOME_ID }
|
||||
|
||||
/** How much of a row a block takes: half-width blocks pack two to a row. */
|
||||
enum class BlockWidth { HALF, FULL }
|
||||
|
||||
/** The kinds of block a view can hold. */
|
||||
enum class BlockType(val widths: Set<BlockWidth>, val takesSource: Boolean) {
|
||||
PROGRESS(setOf(BlockWidth.FULL, BlockWidth.HALF), takesSource = true),
|
||||
COUNT_TILE(setOf(BlockWidth.HALF, BlockWidth.FULL), takesSource = true),
|
||||
PREVIEW(setOf(BlockWidth.FULL), takesSource = true),
|
||||
TASK_LIST(setOf(BlockWidth.FULL), takesSource = true),
|
||||
LISTS(setOf(BlockWidth.FULL), takesSource = false),
|
||||
TAGS(setOf(BlockWidth.FULL), takesSource = false),
|
||||
FILTERS(setOf(BlockWidth.FULL), takesSource = false),
|
||||
SECTION_HEADING(setOf(BlockWidth.FULL), takesSource = false),
|
||||
WEEK_STRIP(setOf(BlockWidth.FULL), takesSource = false),
|
||||
|
||||
/** A preview of the completed tasks, latest first. */
|
||||
RECENTLY_COMPLETED(setOf(BlockWidth.FULL), takesSource = false),
|
||||
}
|
||||
|
||||
/** The tasks a block shows. */
|
||||
sealed interface BlockSource {
|
||||
data class Smart(val smart: SmartList) : BlockSource
|
||||
data class List(val listId: Long) : BlockSource
|
||||
|
||||
/** A list of another task store, kept as stored ([ref], e.g. `OWN:3`) so it survives a switch; it shows nothing here. */
|
||||
data class ListElsewhere(val ref: String) : BlockSource
|
||||
data class Tag(val tag: String) : BlockSource
|
||||
data class Filter(val filterId: Long) : BlockSource
|
||||
data class Rules(val rule: Rule) : BlockSource
|
||||
}
|
||||
|
||||
/** The settings of a block, one shape per [BlockType]. */
|
||||
sealed interface BlockOptions {
|
||||
val type: BlockType
|
||||
|
||||
/** [title] replaces the source's name when set. */
|
||||
data class Progress(val wave: Boolean = true, val title: String? = null) : BlockOptions {
|
||||
override val type get() = BlockType.PROGRESS
|
||||
}
|
||||
|
||||
/** [color] and [icon] replace the source's own when set. */
|
||||
data class CountTile(
|
||||
val title: String? = null,
|
||||
val color: TileColor? = null,
|
||||
val icon: ViewIcon? = null,
|
||||
) : 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" }
|
||||
}
|
||||
|
||||
override val type get() = BlockType.PREVIEW
|
||||
}
|
||||
|
||||
/** [sort] is the app's sort order when `null`. */
|
||||
data class TaskList(
|
||||
val sort: TaskSortOrder? = null,
|
||||
val showCompleted: Boolean = true,
|
||||
val inlineDone: Boolean = true,
|
||||
) : BlockOptions {
|
||||
override val type get() = BlockType.TASK_LIST
|
||||
}
|
||||
|
||||
/** [accounts] limits the lists to those accounts; every account when `null`. */
|
||||
data class Lists(val accounts: Set<String>? = null, val counts: Boolean = true) : BlockOptions {
|
||||
init {
|
||||
require(accounts == null || accounts.isNotEmpty()) { "No accounts; null means every one" }
|
||||
}
|
||||
|
||||
override val type get() = BlockType.LISTS
|
||||
}
|
||||
|
||||
data object Tags : BlockOptions {
|
||||
override val type get() = BlockType.TAGS
|
||||
}
|
||||
|
||||
data object Filters : BlockOptions {
|
||||
override val type get() = BlockType.FILTERS
|
||||
}
|
||||
|
||||
data class SectionHeading(val text: String = "") : BlockOptions {
|
||||
override val type get() = BlockType.SECTION_HEADING
|
||||
}
|
||||
|
||||
/** [title] heads the strip when set. */
|
||||
data class WeekStrip(val title: String? = null) : BlockOptions {
|
||||
override val type get() = BlockType.WEEK_STRIP
|
||||
}
|
||||
|
||||
/** [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" }
|
||||
}
|
||||
|
||||
override val type get() = BlockType.RECENTLY_COMPLETED
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** How many tasks a preview may show. */
|
||||
val PREVIEW_COUNTS = listOf(3, 5, 10)
|
||||
|
||||
fun defaultFor(type: BlockType): BlockOptions = when (type) {
|
||||
BlockType.PROGRESS -> Progress()
|
||||
BlockType.COUNT_TILE -> CountTile()
|
||||
BlockType.PREVIEW -> Preview()
|
||||
BlockType.TASK_LIST -> TaskList()
|
||||
BlockType.LISTS -> Lists()
|
||||
BlockType.TAGS -> Tags
|
||||
BlockType.FILTERS -> Filters
|
||||
BlockType.SECTION_HEADING -> SectionHeading()
|
||||
BlockType.WEEK_STRIP -> WeekStrip()
|
||||
BlockType.RECENTLY_COMPLETED -> RecentlyCompleted()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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, 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 {
|
||||
data object LastUsed : StartDestination
|
||||
data class View(val id: Long) : StartDestination
|
||||
data class List(val id: Long) : StartDestination
|
||||
data class Filter(val id: Long) : StartDestination
|
||||
}
|
||||
|
||||
/** Something [layoutProblems] found wrong with a list of blocks. */
|
||||
sealed interface LayoutProblem {
|
||||
data class DuplicateId(val id: Long) : LayoutProblem
|
||||
data class WidthNotAllowed(val blockId: Long) : LayoutProblem
|
||||
data class SourceMismatch(val blockId: Long) : LayoutProblem
|
||||
data object SeveralTaskLists : LayoutProblem
|
||||
data object TaskListNotLast : LayoutProblem
|
||||
}
|
||||
|
||||
/**
|
||||
* What breaks the layout rules: ids repeat, a width the type doesn't allow, a
|
||||
* source on a type that takes none or none where one is needed, and more than
|
||||
* one task list or one that isn't the last block.
|
||||
*/
|
||||
fun List<Block>.layoutProblems(): List<LayoutProblem> {
|
||||
val blocks = this
|
||||
val taskLists = blocks.count { it.type == BlockType.TASK_LIST }
|
||||
return buildList {
|
||||
blocks.groupingBy { it.id }.eachCount().filterValues { it > 1 }.keys
|
||||
.forEach { add(LayoutProblem.DuplicateId(it)) }
|
||||
blocks.forEach { block ->
|
||||
if (block.width !in block.type.widths) add(LayoutProblem.WidthNotAllowed(block.id))
|
||||
if ((block.source != null) != block.type.takesSource) add(LayoutProblem.SourceMismatch(block.id))
|
||||
}
|
||||
if (taskLists > 1) add(LayoutProblem.SeveralTaskLists)
|
||||
if (taskLists > 0 && blocks.last().type != BlockType.TASK_LIST) add(LayoutProblem.TaskListNotLast)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* These blocks made to follow the layout rules: blocks with a wrong source and
|
||||
* later blocks repeating an id dropped, widths a type doesn't allow made full, and only the
|
||||
* first task list kept, moved to the end.
|
||||
*/
|
||||
fun List<Block>.normalized(): List<Block> {
|
||||
val seen = HashSet<Long>()
|
||||
val kept = filter { (it.source != null) == it.type.takesSource && seen.add(it.id) }
|
||||
.map { if (it.width in it.type.widths) it else it.copy(width = BlockWidth.FULL) }
|
||||
val taskList = kept.firstOrNull { it.type == BlockType.TASK_LIST }
|
||||
return kept.filterNot { it.type == BlockType.TASK_LIST } + listOfNotNull(taskList)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. Packed by
|
||||
* floret-kit's [gridRows], as the edit grid packs them.
|
||||
*/
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import de.jeanlucmakiola.agendula.domain.localeWeekStart
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.WeekFields
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
@@ -14,12 +14,9 @@ import java.util.Locale
|
||||
val LocalUse24HourFormat = staticCompositionLocalOf { true }
|
||||
|
||||
/** The resolved first day of the week, provided at the app root from the week-start setting. */
|
||||
val LocalFirstDayOfWeek = staticCompositionLocalOf { WeekFields.of(Locale.getDefault()).firstDayOfWeek }
|
||||
val LocalFirstDayOfWeek = staticCompositionLocalOf { localeWeekStart() }
|
||||
|
||||
/** A minute-of-day as a clock time: "14:00" or "2:00 PM". */
|
||||
fun formatMinuteOfDay(minuteOfDay: Int, is24Hour: Boolean, locale: Locale = Locale.getDefault()): String =
|
||||
LocalTime.of(minuteOfDay / 60 % 24, minuteOfDay % 60)
|
||||
.format(DateTimeFormatter.ofPattern(if (is24Hour) "HH:mm" else "h:mm a", locale))
|
||||
|
||||
/** The locale's first day of the week, for a week start left on automatic. */
|
||||
fun localeFirstDayOfWeek(locale: Locale = Locale.getDefault()): DayOfWeek = WeekFields.of(locale).firstDayOfWeek
|
||||
@@ -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
|
||||
@@ -32,10 +34,18 @@ import de.jeanlucmakiola.agendula.domain.populatedFields
|
||||
import de.jeanlucmakiola.agendula.domain.htmlToPlainText
|
||||
import de.jeanlucmakiola.agendula.domain.looksLikeHtml
|
||||
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
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
|
||||
@@ -218,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
|
||||
@@ -238,27 +254,40 @@ 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)
|
||||
val zone = ZoneId.systemDefault()
|
||||
val (todayStart, todayEnd) = DayWindow.today(now, zone)
|
||||
val upcomingEnd = settings.upcomingRange.end(now, zone)
|
||||
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)
|
||||
val ruleClock = RuleClock(todayStart, todayEnd, zone, settingsPrefs.firstDayOfWeek.first())
|
||||
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,
|
||||
@@ -278,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,24 +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.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
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.
|
||||
* 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(
|
||||
@@ -54,8 +43,7 @@ fun FilterEditScreen(
|
||||
val draft by viewModel.draft.collectAsStateWithLifecycle()
|
||||
val lists by viewModel.lists.collectAsStateWithLifecycle()
|
||||
val tagsInUse by viewModel.tags.collectAsStateWithLifecycle()
|
||||
val filter = draft
|
||||
var choosingPriority by rememberSaveable { mutableStateOf(false) }
|
||||
val filter = draft?.filter
|
||||
var confirmDelete by rememberSaveable { mutableStateOf(false) }
|
||||
val save = { viewModel.save(onSaved) }
|
||||
|
||||
@@ -71,105 +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,
|
||||
onNameChange = { name -> viewModel.update { it.copy(name = name) } },
|
||||
autoFocus = isNew && !current.choosingTemplate && filter.name.isEmpty(),
|
||||
onNameChange = viewModel::rename,
|
||||
onImeAction = save,
|
||||
)
|
||||
|
||||
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 = filter.due.isEmpty(),
|
||||
onClick = { viewModel.update { it.copy(due = emptySet()) } },
|
||||
)
|
||||
windows.forEachIndexed { index, window ->
|
||||
ChoiceRow(
|
||||
title = dueWindowLabel(window),
|
||||
position = positionOf(index + 1, windows.size + 1),
|
||||
selected = window in filter.due,
|
||||
onClick = { viewModel.update { it.copy(due = it.due.toggle(window)) } },
|
||||
)
|
||||
}
|
||||
|
||||
GroupedSectionHeader(stringResource(R.string.filter_section_priority))
|
||||
GroupedRow(
|
||||
title = minPriorityLabel(filter.minPriority),
|
||||
position = Position.Alone,
|
||||
trailing = { Icon(Icons.Rounded.ChevronRight, contentDescription = null) },
|
||||
onClick = { choosingPriority = true },
|
||||
)
|
||||
|
||||
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 = filter.anyList,
|
||||
onClick = { viewModel.update { it.copy(listIds = emptySet(), listsElsewhere = 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 filter.listIds,
|
||||
leading = { ListColorChip(list.color) },
|
||||
onClick = { viewModel.update { 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, filter.tags) {
|
||||
(tagsInUse + filter.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 = filter.tags.isEmpty(),
|
||||
onClick = { viewModel.update { it.copy(tags = emptySet()) } },
|
||||
)
|
||||
tags.forEachIndexed { index, tag ->
|
||||
ChoiceRow(
|
||||
title = tag,
|
||||
position = positionOf(index + 1, tags.size + 1),
|
||||
selected = tag in filter.tags,
|
||||
onClick = { viewModel.update { it.copy(tags = it.tags.toggle(tag)) } },
|
||||
)
|
||||
}
|
||||
if (filter.tags.size > 1) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.filter_match_all_tags),
|
||||
summary = stringResource(
|
||||
if (filter.tagMatch == TagMatch.ALL) R.string.filter_match_all_on else R.string.filter_match_all_off,
|
||||
),
|
||||
position = Position.Alone,
|
||||
trailing = {
|
||||
Switch(
|
||||
checked = filter.tagMatch == TagMatch.ALL,
|
||||
onCheckedChange = { all ->
|
||||
viewModel.update { it.copy(tagMatch = if (all) TagMatch.ALL else TagMatch.ANY) }
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.update { it.copy(tagMatch = if (it.tagMatch == TagMatch.ALL) TagMatch.ANY else TagMatch.ALL) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
RuleEditorSections(current.rules, lists, tagsInUse, onChange = viewModel::updateRules)
|
||||
|
||||
if (filter.id > 0) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
@@ -184,14 +85,12 @@ fun FilterEditScreen(
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
|
||||
if (choosingPriority && filter != null) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.filter_section_priority),
|
||||
options = Priority.entries,
|
||||
selected = filter.minPriority,
|
||||
label = { minPriorityLabel(it) },
|
||||
onSelect = { priority -> viewModel.update { 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,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -211,49 +110,3 @@ fun FilterEditScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@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,6 +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.Rule
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
@@ -19,6 +20,7 @@ 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
|
||||
|
||||
@@ -30,10 +32,16 @@ class FilterEditViewModel @Inject constructor(
|
||||
private val repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _draft = MutableStateFlow<SavedFilter?>(null)
|
||||
/**
|
||||
* 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 rules: RuleDraft, val choosingTemplate: Boolean = false)
|
||||
|
||||
private val _draft = MutableStateFlow<Draft?>(null)
|
||||
|
||||
/** `null` until [bind] has loaded the filter. An id of 0 is a new one. */
|
||||
val draft: StateFlow<SavedFilter?> = _draft.asStateFlow()
|
||||
val draft: StateFlow<Draft?> = _draft.asStateFlow()
|
||||
|
||||
val lists: StateFlow<List<TaskList>> = repository.taskLists()
|
||||
.catch { emit(emptyList()) }
|
||||
@@ -52,28 +60,61 @@ class FilterEditViewModel @Inject constructor(
|
||||
if (bound) return
|
||||
bound = true
|
||||
if (filterId == null) {
|
||||
_draft.value = SavedFilter(id = 0, name = "")
|
||||
_draft.value = Draft(SavedFilter(id = 0, name = ""), RuleDraft.of(Rule.Everything), choosingTemplate = true)
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val saved = settingsPrefs.savedFilter(filterId).first()
|
||||
// Show it as it matches: lists deleted since drop out, as they do in the repository.
|
||||
val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull()
|
||||
_draft.value = saved?.let { if (existing == null) it else it.withListsIn(existing) }
|
||||
?: SavedFilter(id = 0, name = "")
|
||||
load(saved?.let { if (existing == null) it else it.withListsIn(existing) } ?: SavedFilter(id = 0, name = ""))
|
||||
}
|
||||
}
|
||||
|
||||
fun update(transform: (SavedFilter) -> SavedFilter) {
|
||||
_draft.value = _draft.value?.let(transform)
|
||||
fun rename(name: String) {
|
||||
_draft.update { it?.copy(filter = it.filter.copy(name = name)) }
|
||||
}
|
||||
|
||||
/** 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, RuleDraft.of(filter.rule))
|
||||
}
|
||||
|
||||
fun save(onSaved: (Long) -> Unit) {
|
||||
val filter = _draft.value ?: return
|
||||
val filter = _draft.value?.let { it.filter.copy(rule = it.rules.rule) } ?: return
|
||||
if (filter.name.isBlank() || saving) return
|
||||
saving = true
|
||||
viewModelScope.launch {
|
||||
val id = settingsPrefs.saveFilter(filter.copy(name = filter.name.trim()))
|
||||
// Lists deleted while this was open don't come back with it.
|
||||
val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull()
|
||||
val current = if (existing == null) filter else filter.withListsIn(existing)
|
||||
val id = settingsPrefs.saveFilter(current.copy(name = filter.name.trim()))
|
||||
// A widget showing this filter doesn't watch the prefs.
|
||||
widgetUpdater.requestRefresh()
|
||||
onSaved(id)
|
||||
@@ -81,7 +122,7 @@ class FilterEditViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
fun delete(onDeleted: () -> Unit) {
|
||||
val id = _draft.value?.id?.takeIf { it > 0 } ?: return
|
||||
val id = _draft.value?.filter?.id?.takeIf { it > 0 } ?: return
|
||||
viewModelScope.launch {
|
||||
settingsPrefs.deleteFilter(id)
|
||||
widgetUpdater.requestRefresh()
|
||||
|
||||
@@ -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,26 +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.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
|
||||
@@ -80,39 +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,
|
||||
/** The next few open tasks (due tomorrow onward) for the inline preview. */
|
||||
val upcoming: List<Task>,
|
||||
/** The view these are laid out by. */
|
||||
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>,
|
||||
/** Each tag on an open task, alphabetically. */
|
||||
val tags: List<TagOverview> = emptyList(),
|
||||
/** The saved filters, oldest first. */
|
||||
val filters: List<FilterOverview> = emptyList(),
|
||||
) : ListsUiState
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
private const val UPCOMING_PREVIEW = 3
|
||||
/**
|
||||
* 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 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
|
||||
|
||||
/** The home overview: smart lists with live counts, then user lists by account. */
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
@@ -139,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(),
|
||||
@@ -146,88 +431,251 @@ class ListsViewModel @Inject constructor(
|
||||
// Open smart lists drop completed tasks, but the Today ring needs the
|
||||
// ones already ticked off to show "x of y done", so read them too.
|
||||
repository.tasks(TaskFilter.Smart(SmartList.COMPLETED)),
|
||||
settingsPrefs.settings.map { it.hiddenFromSmartLists to it.upcomingRange }.distinctUntilChanged(),
|
||||
settingsPrefs.savedFilters,
|
||||
) { lists, openTasks, completedTasks, (hidden, upcomingRange), filters ->
|
||||
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters) as ListsUiState
|
||||
combine(
|
||||
settingsPrefs.settings.map { it.hiddenFromSmartLists to it.upcomingRange }.distinctUntilChanged(),
|
||||
settingsPrefs.firstDayOfWeek,
|
||||
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>,
|
||||
): 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
|
||||
.filter { inSmart(it, SmartList.UPCOMING) }
|
||||
.take(UPCOMING_PREVIEW)
|
||||
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) })
|
||||
}
|
||||
// Same folding as the tags: a subtask counts only when its parent isn't in the filter too.
|
||||
val filters = savedFilters.map { filter ->
|
||||
val matching = openTasks.filter { filter.matches(it, todayStart, todayEnd) }
|
||||
val ids = matching.mapTo(HashSet()) { it.taskId }
|
||||
FilterOverview(filter, 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(
|
||||
smartCounts = smartCounts,
|
||||
filters = filters,
|
||||
groups = groups,
|
||||
todayDone = completedToday,
|
||||
todayTotal = todayTotal,
|
||||
upcoming = 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)
|
||||
@@ -262,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.ui.common.localeFirstDayOfWeek
|
||||
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 },
|
||||
)
|
||||
}
|
||||
@@ -162,7 +217,7 @@ internal fun AppearanceScreen(
|
||||
if (day == null) {
|
||||
stringResource(
|
||||
R.string.settings_week_start_auto_summary,
|
||||
localeFirstDayOfWeek(locale).getDisplayName(TextStyle.FULL, locale),
|
||||
localeWeekStart(locale).getDisplayName(TextStyle.FULL, locale),
|
||||
)
|
||||
} else {
|
||||
null
|
||||
@@ -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,8 +27,12 @@ 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
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
@@ -97,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(
|
||||
@@ -111,12 +114,13 @@ class SettingsViewModel @Inject constructor(
|
||||
private val taskNotifier: TaskNotifier,
|
||||
private val launcherNameManager: LauncherNameManager,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val widgetUpdater: TaskWidgetUpdater,
|
||||
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,
|
||||
@@ -242,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)
|
||||
@@ -265,7 +272,11 @@ class SettingsViewModel @Inject constructor(
|
||||
prefs.setTimeFormat(pref)
|
||||
refreshShownReminders()
|
||||
}
|
||||
fun setWeekStart(day: DayOfWeek?) = viewModelScope.launch { prefs.setWeekStart(day) }
|
||||
fun setWeekStart(day: DayOfWeek?) = viewModelScope.launch {
|
||||
prefs.setWeekStart(day)
|
||||
// A widget on a saved filter reads weeks from it, and doesn't watch the prefs.
|
||||
widgetUpdater.requestRefresh()
|
||||
}
|
||||
fun setSnoozeMinutes(minutes: Int) = viewModelScope.launch {
|
||||
prefs.setSnoozeMinutes(minutes)
|
||||
refreshShownReminders()
|
||||
|
||||
@@ -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,6 +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_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>
|
||||
@@ -525,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>
|
||||
@@ -1073,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")
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ 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.FilterCriteria
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
@@ -55,22 +56,22 @@ class ForgetDeletedListsTest {
|
||||
@Test
|
||||
fun `a saved filter drops a deleted list, so a list given its id later is not in it`() = runBlocking<Unit> {
|
||||
prefs.setStorageMode(StorageMode.OWN)
|
||||
prefs.saveFilter(SavedFilter(id = 0, name = "Both", listIds = setOf(1L, 2L)))
|
||||
prefs.saveFilter(SavedFilter(id = 0, name = "Gone", listIds = setOf(1L)))
|
||||
prefs.saveFilter(SavedFilter(id = 0, name = "Both", criteria = FilterCriteria(listIds = setOf(1L, 2L))))
|
||||
prefs.saveFilter(SavedFilter(id = 0, name = "Gone", criteria = FilterCriteria(listIds = setOf(1L))))
|
||||
|
||||
prefs.forgetDeletedLists(listOf(1L), StorageMode.OWN)
|
||||
|
||||
val filters = prefs.savedFilters.first().associate { it.name to it.listIds }
|
||||
val filters = prefs.savedFilters.first().associate { it.name to it.criteria!!.listIds }
|
||||
assertThat(filters).containsExactly("Both", setOf(2L), "Gone", emptySet<Long>())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a read of the lists drops the gone ones from the saved filters`() = runBlocking<Unit> {
|
||||
prefs.setStorageMode(StorageMode.OWN)
|
||||
prefs.saveFilter(SavedFilter(id = 0, name = "Both", listIds = setOf(1L, 2L)))
|
||||
prefs.saveFilter(SavedFilter(id = 0, name = "Both", criteria = FilterCriteria(listIds = setOf(1L, 2L))))
|
||||
|
||||
prefs.forgetListsExcept(StorageMode.OWN, null, setOf(2L, 3L))
|
||||
|
||||
assertThat(prefs.savedFilters.first().single().listIds).containsExactly(2L)
|
||||
assertThat(prefs.savedFilters.first().single().criteria!!.listIds).containsExactly(2L)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,90 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import androidx.datastore.preferences.core.preferencesOf
|
||||
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.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class SavedFilterCodecTest {
|
||||
|
||||
private val filter = SavedFilter(
|
||||
id = 3,
|
||||
name = "Work | today, 100%",
|
||||
@Test
|
||||
fun `the stored line stays byte for byte, and its rule reads back through the rule codec`() {
|
||||
val rule = Rule.AllOf(
|
||||
listOf(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(4L, 2L), setOf("EXTERNAL:7")), Rule.HasTag("a b,c"))),
|
||||
Rule.Not(Rule.Due(DueSpec.Window(DueWindow.NO_DATE))),
|
||||
Rule.MinPriority(Priority.HIGH),
|
||||
Rule.Due(DueSpec.ThisWeek),
|
||||
Rule.Due(DueSpec.NextDays(7)),
|
||||
),
|
||||
)
|
||||
val text = "and(or(list(OWN%3A2,OWN%3A4,EXTERNAL%3A7),tag(a+b%2Cc)),not(due(NO_DATE)),prio(HIGH),range(week),range(next,7))"
|
||||
assertThat(SavedFilterCodec.upsert(null, SavedFilter(3, "Work | x", rule), "OWN")).isEqualTo("v2|3|Work+%7C+x|$text")
|
||||
assertThat(RuleCodec.encode(rule, "OWN")).isEqualTo(text)
|
||||
assertThat(RuleCodec.decode(text, "OWN")).isEqualTo(rule)
|
||||
// The rule codec prunes nothing; the saved filter drops an empty top-level list condition itself.
|
||||
assertThat(RuleCodec.decode("list()", "OWN")).isEqualTo(Rule.InList(emptySet()))
|
||||
assertThat(SavedFilterCodec.decode("v2|1|x|list()", "OWN").single().rule).isEqualTo(Rule.Everything)
|
||||
// A ref of this store that names no id is kept as it is.
|
||||
assertThat(RuleCodec.decode("list(OWN%3Aabc,OWN%3A3)", "OWN")).isEqualTo(Rule.InList(setOf(3L), setOf("OWN:abc")))
|
||||
}
|
||||
|
||||
private val criteria = FilterCriteria(
|
||||
due = setOf(DueWindow.TODAY, DueWindow.OVERDUE),
|
||||
listIds = setOf(4L, 9L),
|
||||
tags = setOf("a,b", "größe", "x|y"),
|
||||
tags = setOf("a,b", "größe", "x|y", "f(x)"),
|
||||
tagMatch = TagMatch.ALL,
|
||||
minPriority = Priority.MEDIUM,
|
||||
)
|
||||
private val filter = SavedFilter(id = 3, name = "Work | today, 100% (v2|x)", criteria = criteria)
|
||||
|
||||
private fun SavedFilter.flat(): FilterCriteria = criteria!!
|
||||
|
||||
@Test
|
||||
fun `a filter round-trips, separators and all`() {
|
||||
val raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
assertThat(raw).startsWith("v2|3|")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN")).containsExactly(filter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a nested rule round-trips`() {
|
||||
val rule = Rule.AllOf(
|
||||
listOf(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(2L), setOf("EXTERNAL:7")), Rule.HasTag("next action"))),
|
||||
Rule.Not(Rule.AnyOf(listOf(Rule.HasTag("someday"), Rule.Due(DueSpec.Window(DueWindow.NO_DATE))))),
|
||||
Rule.Not(Rule.Not(Rule.MinPriority(Priority.LOW))),
|
||||
Rule.AnyOf(
|
||||
listOf(
|
||||
Rule.Due(DueSpec.ThisWeek),
|
||||
Rule.Due(DueSpec.ThisMonth),
|
||||
Rule.Due(DueSpec.NextDays(0)),
|
||||
Rule.Due(DueSpec.NextDays(14)),
|
||||
),
|
||||
),
|
||||
Rule.AnyOf(emptyList()),
|
||||
Rule.AllOf(emptyList()),
|
||||
),
|
||||
)
|
||||
val nested = SavedFilter(id = 5, name = "GTD", rule = rule)
|
||||
val raw = SavedFilterCodec.upsert(null, nested, "OWN")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN")).containsExactly(nested)
|
||||
assertThat(nested.criteria).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a filter of everything round-trips`() {
|
||||
val all = SavedFilter(id = 1, name = "All")
|
||||
assertThat(SavedFilterCodec.decode(SavedFilterCodec.upsert(null, all, "OWN"), "OWN")).containsExactly(all)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `upsert replaces by id and keeps the order`() {
|
||||
val first = filter.copy(id = 1, name = "one")
|
||||
@@ -37,28 +97,30 @@ class SavedFilterCodecTest {
|
||||
@Test
|
||||
fun `list ids belong to their store`() {
|
||||
val raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
val elsewhere = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
val elsewhere = SavedFilterCodec.decode(raw, "EXTERNAL").single().flat()
|
||||
assertThat(elsewhere.listIds).isEmpty()
|
||||
assertThat(elsewhere.listsElsewhere).isTrue()
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listsElsewhere).isFalse()
|
||||
assertThat(elsewhere.listsElsewhere).containsExactly("OWN:4", "OWN:9")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().listsElsewhere).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `choosing any list in one store drops the other store's lists`() {
|
||||
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = emptySet(), listsElsewhere = false), "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().anyList).isTrue()
|
||||
val external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
raw = SavedFilterCodec.upsert(raw, external.edit { it.copy(listIds = emptySet(), listsElsewhere = emptySet()) }, "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().anyList).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unticking the last list here keeps the other store's lists`() {
|
||||
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = setOf(1L)), "EXTERNAL")
|
||||
val external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
assertThat(external.listsElsewhere).isTrue()
|
||||
raw = SavedFilterCodec.upsert(raw, external.copy(listIds = emptySet()), "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
|
||||
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().anyList).isFalse()
|
||||
var external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
raw = SavedFilterCodec.upsert(raw, external.edit { it.copy(listIds = setOf(1L)) }, "EXTERNAL")
|
||||
external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
assertThat(external.flat().listsElsewhere).isNotEmpty()
|
||||
raw = SavedFilterCodec.upsert(raw, external.edit { it.copy(listIds = emptySet()) }, "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().listIds).containsExactly(4L, 9L)
|
||||
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().flat().anyList).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -66,15 +128,16 @@ class SavedFilterCodecTest {
|
||||
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
val elsewhere = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
raw = SavedFilterCodec.upsert(raw, elsewhere.copy(name = "renamed"), "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().listIds).containsExactly(4L, 9L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `editing in one store keeps the other store's lists`() {
|
||||
var raw = SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
raw = SavedFilterCodec.upsert(raw, filter.copy(listIds = setOf(1L)), "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().listIds).containsExactly(4L, 9L)
|
||||
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().listIds).containsExactly(1L)
|
||||
val external = SavedFilterCodec.decode(raw, "EXTERNAL").single()
|
||||
raw = SavedFilterCodec.upsert(raw, external.edit { it.copy(listIds = setOf(1L)) }, "EXTERNAL")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().flat().listIds).containsExactly(4L, 9L)
|
||||
assertThat(SavedFilterCodec.decode(raw, "EXTERNAL").single().flat().listIds).containsExactly(1L)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -84,9 +147,133 @@ class SavedFilterCodecTest {
|
||||
assertThat(SavedFilterCodec.decode(SavedFilterCodec.remove(raw, 1), "OWN").map { it.id }).containsExactly(3L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `saving keeps no other store's list pruned meanwhile`() {
|
||||
val both = SavedFilter(1, "f", FilterCriteria(listIds = setOf(1L), listsElsewhere = setOf("EXTERNAL:5", "EXTERNAL:6")))
|
||||
var raw = SavedFilterCodec.upsert(null, both, "OWN")
|
||||
val loaded = SavedFilterCodec.decode(raw, "OWN").single()
|
||||
raw = SavedFilterCodec.withoutLists(raw, "EXTERNAL") { it == 5L }
|
||||
raw = SavedFilterCodec.upsert(raw, loaded.copy(name = "renamed"), "OWN")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").single().criteria!!.listsElsewhere).containsExactly("EXTERNAL:6")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flat and v2 lines are told apart per line`() {
|
||||
val raw = legacyLine(id = 7, refs = listOf("OWN:2")) + "\n" + SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").map { it.id }).containsExactly(7L, 3L).inOrder()
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN").first().criteria!!.listIds).containsExactly(2L)
|
||||
assertThat(SavedFilterCodec.decode(SavedFilterCodec.remove(raw, 7), "OWN").map { it.id }).containsExactly(3L)
|
||||
val renamed = SavedFilterCodec.upsert(raw, SavedFilter(7, "renamed", FilterCriteria(listIds = setOf(2L))), "OWN")
|
||||
assertThat(renamed.lines().first()).startsWith("v2|7|renamed|")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `broken lines are skipped`() {
|
||||
val raw = "nonsense\n" + SavedFilterCodec.upsert(null, filter, "OWN") + "\n7|short\n8|bad%zz||||ANY|NONE"
|
||||
val raw = "nonsense\n" + SavedFilterCodec.upsert(null, filter, "OWN") +
|
||||
"\n7|short\n8|bad%zz||||ANY|NONE\nv2|9|x|and(\nv2|10|x|what(1)\nv2|11|x|and()trailing\nv2|12|x|range(next,-1)"
|
||||
assertThat(SavedFilterCodec.decode(raw, "OWN")).containsExactly(filter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a flat line reads as the same filter`() {
|
||||
val raw = legacyLine(
|
||||
id = 3,
|
||||
name = "Work+%7C+today",
|
||||
due = "OVERDUE,TODAY",
|
||||
refs = listOf("OWN:4", "OWN:9", "EXTERNAL:2"),
|
||||
tags = "a%2Cb,gr%C3%B6%C3%9Fe",
|
||||
match = "ALL",
|
||||
priority = "MEDIUM",
|
||||
)
|
||||
val migrated = SavedFilterCodec.migrate(raw)
|
||||
val own = SavedFilterCodec.decode(migrated, "OWN").single()
|
||||
assertThat(own.name).isEqualTo("Work | today")
|
||||
assertThat(own.flat()).isEqualTo(
|
||||
FilterCriteria(
|
||||
due = setOf(DueWindow.OVERDUE, DueWindow.TODAY),
|
||||
listIds = setOf(4L, 9L),
|
||||
listsElsewhere = setOf("EXTERNAL:2"),
|
||||
tags = setOf("a,b", "größe"),
|
||||
tagMatch = TagMatch.ALL,
|
||||
minPriority = Priority.MEDIUM,
|
||||
),
|
||||
)
|
||||
assertThat(SavedFilterCodec.decode(migrated, "EXTERNAL").single().flat().listIds).containsExactly(2L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `migration rewrites flat lines once and reads the same`() {
|
||||
val raw = listOf(
|
||||
legacyLine(id = 1, due = "UPCOMING", refs = listOf("OWN:1", "EXTERNAL:5"), tags = "x", match = "ANY"),
|
||||
SavedFilterCodec.upsert(null, filter, "OWN"),
|
||||
"garbage",
|
||||
legacyLine(id = 2, refs = listOf("OWN:nope")),
|
||||
).joinToString("\n")
|
||||
assertThat(SavedFilterCodec.needsMigration(raw)).isTrue()
|
||||
val migrated = SavedFilterCodec.migrate(raw)
|
||||
assertThat(SavedFilterCodec.needsMigration(migrated)).isFalse()
|
||||
for (mode in listOf("OWN", "EXTERNAL")) {
|
||||
assertThat(SavedFilterCodec.decode(migrated, mode)).isEqualTo(SavedFilterCodec.decode(raw, mode))
|
||||
}
|
||||
assertThat(migrated.lines()).hasSize(3)
|
||||
assertThat(migrated.lines().all { it.startsWith("v2|") }).isTrue()
|
||||
assertThat(SavedFilterCodec.migrate(migrated)).isEqualTo(migrated)
|
||||
val upcomingX = FilterCriteria(due = setOf(DueWindow.UPCOMING), tags = setOf("x"))
|
||||
assertThat(SavedFilterCodec.decode(migrated, "OWN").map { it.criteria }).containsExactly(
|
||||
upcomingX.copy(listIds = setOf(1L), listsElsewhere = setOf("EXTERNAL:5")),
|
||||
criteria,
|
||||
FilterCriteria(),
|
||||
).inOrder()
|
||||
assertThat(SavedFilterCodec.decode(migrated, "EXTERNAL").map { it.criteria }).containsExactly(
|
||||
upcomingX.copy(listIds = setOf(5L), listsElsewhere = setOf("OWN:1")),
|
||||
criteria.copy(listIds = emptySet(), listsElsewhere = setOf("OWN:4", "OWN:9")),
|
||||
FilterCriteria(listsElsewhere = setOf("OWN:nope")),
|
||||
).inOrder()
|
||||
// An unreadable list of this store reads as no list condition, as it did before.
|
||||
assertThat(SavedFilterCodec.decode(migrated, "OWN").single { it.id == 2L }.rule).isEqualTo(Rule.Everything)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the datastore migration rewrites the key in place and is idempotent`() = runBlocking<Unit> {
|
||||
val raw = legacyLine(id = 1, refs = listOf("OWN:1")) + "\n" + SavedFilterCodec.upsert(null, filter, "OWN")
|
||||
val prefs = preferencesOf(SavedFilterMigration.KEY to raw)
|
||||
assertThat(SavedFilterMigration.shouldMigrate(prefs)).isTrue()
|
||||
val once = SavedFilterMigration.migrate(prefs)
|
||||
assertThat(once[SavedFilterMigration.KEY]!!.lines().all { it.startsWith("v2|") }).isTrue()
|
||||
assertThat(once.asMap().keys).containsExactly(SavedFilterMigration.KEY)
|
||||
assertThat(SavedFilterMigration.shouldMigrate(once)).isFalse()
|
||||
val twice = SavedFilterMigration.migrate(once)
|
||||
assertThat(twice).isEqualTo(once)
|
||||
assertThat(SavedFilterCodec.decode(twice[SavedFilterMigration.KEY], "OWN"))
|
||||
.isEqualTo(SavedFilterCodec.decode(raw, "OWN"))
|
||||
assertThat(SavedFilterMigration.shouldMigrate(preferencesOf())).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dropping lists prunes them from every filter`() {
|
||||
val nested = SavedFilter(
|
||||
id = 5,
|
||||
name = "n",
|
||||
rule = Rule.AnyOf(listOf(Rule.InList(setOf(1L)), Rule.Not(Rule.InList(setOf(1L, 2L))))),
|
||||
)
|
||||
val raw = SavedFilterCodec.upsert(null, nested, "OWN") + "\n" + SavedFilterCodec.migrate(legacyLine(id = 6, refs = listOf("OWN:1", "OWN:3")))
|
||||
val pruned = SavedFilterCodec.decode(SavedFilterCodec.withoutLists(raw, "OWN") { it == 1L }, "OWN")
|
||||
assertThat(pruned[0].rule).isEqualTo(Rule.AnyOf(listOf(Rule.InList(emptySet()), Rule.Not(Rule.InList(setOf(2L))))))
|
||||
assertThat(pruned[1].flat().listIds).containsExactly(3L)
|
||||
assertThat(SavedFilterCodec.withoutLists(raw, "OWN") { it == 99L }).isEqualTo(raw)
|
||||
}
|
||||
|
||||
private fun SavedFilter.edit(transform: (FilterCriteria) -> FilterCriteria) =
|
||||
SavedFilter(id, name, transform(criteria!!))
|
||||
}
|
||||
|
||||
/** A line as 1.4 and earlier wrote it. */
|
||||
internal fun legacyLine(
|
||||
id: Long,
|
||||
name: String = "f",
|
||||
due: String = "",
|
||||
refs: List<String> = emptyList(),
|
||||
tags: String = "",
|
||||
match: String = "ANY",
|
||||
priority: String = "NONE",
|
||||
): String = listOf(id.toString(), name, due, refs.joinToString(","), tags, match, priority).joinToString("|")
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import com.google.common.truth.Truth.assertWithMessage
|
||||
import de.jeanlucmakiola.agendula.domain.DueWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.RuleClock
|
||||
import de.jeanlucmakiola.agendula.domain.TagMatch
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.dueWindowOf
|
||||
import de.jeanlucmakiola.agendula.domain.testTask
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.DayOfWeek
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** Every flat filter, migrated to a rule, keeps the tasks the 1.4 filter kept, in every store. */
|
||||
class SavedFilterMigrationEquivalenceTest {
|
||||
|
||||
private val dayMs = 86_400_000L
|
||||
private val todayStart = Instant.fromEpochMilliseconds(1000 * dayMs)
|
||||
private val todayEnd = Instant.fromEpochMilliseconds(1001 * dayMs)
|
||||
private val clock = RuleClock(todayStart, todayEnd, ZoneId.systemDefault(), DayOfWeek.MONDAY)
|
||||
|
||||
/** The 1.4 filter as its codec read it for one store, and its `matches`. */
|
||||
private data class Legacy(
|
||||
val due: Set<DueWindow>,
|
||||
val listIds: Set<Long>,
|
||||
val listsElsewhere: Boolean,
|
||||
val tags: Set<String>,
|
||||
val tagMatch: TagMatch,
|
||||
val minPriority: Priority,
|
||||
) {
|
||||
fun matches(task: Task, todayStart: Instant, todayEnd: Instant): Boolean {
|
||||
if (task.isClosed) return false
|
||||
if (listsElsewhere && listIds.isEmpty()) return false
|
||||
if (listIds.isNotEmpty() && task.listId !in listIds) return false
|
||||
if (task.priority < minPriority) return false
|
||||
if (due.isNotEmpty() && dueWindowOf(task, todayStart, todayEnd) !in due) return false
|
||||
return when {
|
||||
tags.isEmpty() -> true
|
||||
tagMatch == TagMatch.ALL -> task.tags.containsAll(tags)
|
||||
else -> task.tags.any { it in tags }
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun read(refs: List<String>, mode: String, due: Set<DueWindow>, tags: Set<String>, match: TagMatch, priority: Priority) =
|
||||
Legacy(
|
||||
due = due,
|
||||
listIds = refs.filter { it.startsWith("$mode:") }.mapNotNull { it.removePrefix("$mode:").toLongOrNull() }.toSet(),
|
||||
listsElsewhere = refs.any { !it.startsWith("$mode:") },
|
||||
tags = tags,
|
||||
tagMatch = match,
|
||||
minPriority = priority,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private val tasks: List<Task> = buildList {
|
||||
val dues = listOf(
|
||||
null,
|
||||
Instant.fromEpochMilliseconds(999 * dayMs),
|
||||
Instant.fromEpochMilliseconds(1000 * dayMs + 1),
|
||||
Instant.fromEpochMilliseconds(1003 * dayMs),
|
||||
)
|
||||
val tagSets = listOf(emptyList(), listOf("a"), listOf("b"), listOf("a", "b"), listOf("A"), listOf("c"))
|
||||
for (listId in 1L..3L) for (due in dues) for (tags in tagSets) for (priority in Priority.entries) {
|
||||
for (status in listOf(TaskStatus.NEEDS_ACTION, TaskStatus.COMPLETED)) {
|
||||
add(testTask(listId = listId, due = due, tags = tags, priority = priority, status = status))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every flat filter matches the same tasks after migration`() {
|
||||
val dueSets = (0 until 16).map { bits -> DueWindow.entries.filterIndexed { i, _ -> bits and (1 shl i) != 0 }.toSet() }
|
||||
val refSets = listOf(
|
||||
emptyList(),
|
||||
listOf("OWN:1"),
|
||||
listOf("OWN:1", "OWN:2"),
|
||||
listOf("EXTERNAL:3"),
|
||||
listOf("OWN:2", "EXTERNAL:1"),
|
||||
listOf("OWN:x"),
|
||||
)
|
||||
val tagChoices = listOf(
|
||||
emptySet<String>() to TagMatch.ANY,
|
||||
emptySet<String>() to TagMatch.ALL,
|
||||
setOf("a") to TagMatch.ANY,
|
||||
setOf("a") to TagMatch.ALL,
|
||||
setOf("a", "b") to TagMatch.ANY,
|
||||
setOf("a", "b") to TagMatch.ALL,
|
||||
)
|
||||
var id = 0L
|
||||
var checked = 0
|
||||
val mismatches = mutableListOf<String>()
|
||||
for (due in dueSets) for (refs in refSets) for ((tags, match) in tagChoices) for (priority in Priority.entries) {
|
||||
id++
|
||||
val line = legacyLine(
|
||||
id = id,
|
||||
due = due.joinToString(",") { it.name },
|
||||
refs = refs,
|
||||
tags = tags.joinToString(","),
|
||||
match = match.name,
|
||||
priority = priority.name,
|
||||
)
|
||||
val migrated = SavedFilterCodec.migrate(line)
|
||||
for (mode in listOf("OWN", "EXTERNAL")) {
|
||||
val legacy = Legacy.read(refs, mode, due, tags, match, priority)
|
||||
val now = SavedFilterCodec.decode(migrated, mode).single()
|
||||
for (task in tasks) {
|
||||
if (now.matches(task, clock) != legacy.matches(task, todayStart, todayEnd)) {
|
||||
mismatches += "$line in $mode: $task"
|
||||
}
|
||||
checked++
|
||||
}
|
||||
}
|
||||
}
|
||||
assertWithMessage("mismatches").that(mismatches.take(5)).isEmpty()
|
||||
assertWithMessage("checked").that(checked).isGreaterThan(1_000_000)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package de.jeanlucmakiola.agendula.data.prefs
|
||||
|
||||
import androidx.datastore.preferences.core.preferencesOf
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
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.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.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
|
||||
|
||||
class ViewCodecTest {
|
||||
|
||||
private val rule = Rule.AllOf(
|
||||
listOf(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(2L), setOf("EXTERNAL:7")), Rule.HasTag("next, action|(x)"))),
|
||||
Rule.Not(Rule.Due(DueSpec.Window(DueWindow.NO_DATE))),
|
||||
Rule.MinPriority(Priority.HIGH),
|
||||
Rule.Due(DueSpec.NextDays(7)),
|
||||
),
|
||||
)
|
||||
|
||||
private val everyBlock = listOf(
|
||||
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, 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, 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)),
|
||||
)
|
||||
|
||||
private val views = listOf(
|
||||
View.home(),
|
||||
View(id = 2, name = "Work | stuff\nmore", icon = ViewIcon.WORK, scope = rule, blocks = everyBlock, quickAdd = false),
|
||||
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")
|
||||
assertThat(raw.lines().first()).isEqualTo("v1")
|
||||
assertThat(ViewCodec.decode(raw, "OWN")).isEqualTo(views)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `default options round-trip for every type`() {
|
||||
val blocks = BlockType.entries.mapIndexed { i, type ->
|
||||
Block(i + 1L, type, if (type.takesSource) BlockSource.Smart(SmartList.ALL) else null, type.widths.first())
|
||||
}.let { it.filterNot { b -> b.type == BlockType.TASK_LIST } + it.single { b -> b.type == BlockType.TASK_LIST } }
|
||||
val view = View(1, "x", ViewIcon.HOME, null, blocks)
|
||||
assertThat(ViewCodec.decode(ViewCodec.encode(listOf(view), "OWN"), "OWN")).containsExactly(view)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `another store's lists read as theirs only, and survive a rewrite there`() {
|
||||
val raw = ViewCodec.encode(views, "OWN")
|
||||
val external = ViewCodec.decode(raw, "EXTERNAL")
|
||||
assertThat(external[1].blocks.single { it.id == 2L }.source).isEqualTo(BlockSource.ListElsewhere("OWN:9"))
|
||||
val scope = external[1].scope as Rule.AllOf
|
||||
assertThat((scope.children[0] as Rule.AnyOf).children[0]).isEqualTo(Rule.InList(setOf(7L), setOf("OWN:2")))
|
||||
assertThat(ViewCodec.decode(ViewCodec.encode(external, "EXTERNAL"), "OWN")).isEqualTo(views)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an empty title reads as none`() {
|
||||
val raw = "v1\nview|1|x|HOME|1|\nblock|1|PROGRESS|FULL|0|smart:TODAY|wave=1;title=\nblock|2|COUNT_TILE|HALF|0|smart:ALL|title=+"
|
||||
val blocks = ViewCodec.decode(raw, "OWN").single().blocks
|
||||
assertThat(blocks.map { it.options }).containsExactly(BlockOptions.Progress(), BlockOptions.CountTile()).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rules are stored in the saved filters' grammar`() {
|
||||
val view = View(5, "x", ViewIcon.HOME, Rule.AllOf(listOf(Rule.HasTag("a b"), Rule.InList(setOf(3L)))), emptyList())
|
||||
assertThat(ViewCodec.encode(listOf(view), "OWN").lines()[1]).isEqualTo("view|5|x|HOME|1|and(tag(a+b),list(OWN%3A3))")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an account without a name and a list id that isn't one survive`() {
|
||||
val view = View(1, "x", ViewIcon.HOME, null, listOf(Block(1, BlockType.LISTS, options = BlockOptions.Lists(accounts = setOf("")))))
|
||||
assertThat(ViewCodec.decode(ViewCodec.encode(listOf(view), "OWN"), "OWN")).containsExactly(view)
|
||||
val odd = ViewCodec.decode("v1\nview|1|x|HOME|1|\nblock|4|COUNT_TILE|HALF|0|list:OWN%3Aabc|", "OWN").single()
|
||||
assertThat(odd.blocks.single().source).isEqualTo(BlockSource.ListElsewhere("OWN:abc"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a rule reads back exactly as written, with no saved-filter pruning`() {
|
||||
val scopes = listOf(
|
||||
Rule.InList(emptySet()),
|
||||
Rule.AllOf(listOf(Rule.InList(emptySet()), Rule.HasTag("x"))),
|
||||
Rule.AllOf(listOf(Rule.InList(emptySet()), Rule.InList(emptySet(), setOf("EXTERNAL:7")))),
|
||||
Rule.InList(setOf(3L), setOf("OWN:abc")),
|
||||
)
|
||||
scopes.forEachIndexed { i, scope ->
|
||||
val view = View(i + 1L, "x", ViewIcon.HOME, scope, listOf(Block(1, BlockType.TASK_LIST, BlockSource.Rules(scope))))
|
||||
assertThat(ViewCodec.decode(ViewCodec.encode(listOf(view), "OWN"), "OWN")).containsExactly(view)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `nothing stored, or another version, reads as no views`() {
|
||||
assertThat(ViewCodec.decode(null, "OWN")).isEmpty()
|
||||
assertThat(ViewCodec.decode("", "OWN")).isEmpty()
|
||||
assertThat(ViewCodec.decode("v2\nview|1|x|HOME|1|", "OWN")).isEmpty()
|
||||
assertThat(ViewCodec.decode("view|1|x|HOME|1|", "OWN")).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lines that don't read are skipped, with their blocks`() {
|
||||
val raw = listOf(
|
||||
"v1",
|
||||
"view|1|Home|HOME|1|",
|
||||
"block|1|TAGS|FULL|0||",
|
||||
"block|2|NOPE|FULL|0||",
|
||||
"block|3|PREVIEW|FULL|0|smart:NOPE|",
|
||||
"block|4|PREVIEW|FULL|0|rules:and(|",
|
||||
"block|x|FILTERS|FULL|0||",
|
||||
"garbage",
|
||||
"block|5|FILTERS|FULL|0||",
|
||||
"view|x|Broken|HOME|1|",
|
||||
"block|6|TAGS|FULL|0||",
|
||||
"view|2|Odd|NOPE|0|and(",
|
||||
"view|3|Fine|NOPE|0|",
|
||||
"block|7|COUNT_TILE|WIDE|0|smart:ALL|count=x;color=PINK",
|
||||
"block|8|PREVIEW|HALF|0|smart:UPCOMING|count=4;showAll=0",
|
||||
"block|9|LISTS|FULL|0|smart:ALL|",
|
||||
"view|1|Again|HOME|1|",
|
||||
).joinToString("\n")
|
||||
val decoded = ViewCodec.decode(raw, "OWN")
|
||||
assertThat(decoded.map { it.id }).containsExactly(1L, 3L).inOrder()
|
||||
assertThat(decoded[0].blocks.map { it.id }).containsExactly(1L, 5L).inOrder()
|
||||
val fine = decoded[1]
|
||||
assertThat(fine.icon).isEqualTo(ViewIcon.HOME)
|
||||
assertThat(fine.quickAdd).isFalse()
|
||||
// An unknown width or value falls back; a block with a source its type doesn't take drops out.
|
||||
assertThat(fine.blocks).containsExactly(
|
||||
Block(7, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL), BlockWidth.HALF),
|
||||
Block(8, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(showAll = false)),
|
||||
).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the migration stores Home once, and only when there are no views`() = runBlocking {
|
||||
assertThat(ViewsMigration.shouldMigrate(preferencesOf())).isTrue()
|
||||
val migrated = ViewsMigration.migrate(preferencesOf())
|
||||
assertThat(ViewCodec.decode(migrated[ViewsMigration.KEY], "OWN")).containsExactly(View.home())
|
||||
assertThat(ViewsMigration.shouldMigrate(migrated)).isFalse()
|
||||
assertThat(ViewsMigration.migrate(preferencesOf())).isEqualTo(migrated)
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ 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 de.jeanlucmakiola.floret.time.DayWindow
|
||||
import java.time.ZoneId
|
||||
@@ -102,11 +103,12 @@ class NewTaskDefaultsTest {
|
||||
@Test
|
||||
fun `a saved filter checks only its due windows`() {
|
||||
val (start, end) = DayWindow.today(now, zone)
|
||||
val filter = SavedFilter(id = 1L, name = "Soon", due = setOf(DueWindow.TODAY), listIds = setOf(9L))
|
||||
val clock = RuleClock(start, end, zone, DayOfWeek.MONDAY)
|
||||
val filter = SavedFilter(id = 1L, name = "Soon", criteria = FilterCriteria(due = setOf(DueWindow.TODAY), listIds = setOf(9L)))
|
||||
val dates = newTaskDates(DefaultDueDate.TODAY, DefaultStartDate.NONE, localToday, localToday, now)
|
||||
assertThat(dates.showsIn(null, filter, start, end)).isTrue()
|
||||
assertThat(dates.showsIn(null, filter, start, end, ruleClock = clock)).isTrue()
|
||||
val later = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, localToday, localToday, now)
|
||||
assertThat(later.showsIn(null, filter, start, end)).isFalse()
|
||||
assertThat(later.showsIn(null, filter, start, end, ruleClock = clock)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -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,280 @@
|
||||
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
|
||||
|
||||
class RuleTest {
|
||||
|
||||
private val zone = ZoneId.of("Europe/Berlin")
|
||||
|
||||
private fun clockOn(day: LocalDate, weekStart: DayOfWeek = DayOfWeek.MONDAY, zone: ZoneId = this.zone) =
|
||||
RuleClock(startOfDay(day, zone), startOfDay(day.plusDays(1), zone), zone, weekStart)
|
||||
|
||||
private fun dueOn(day: LocalDate) = testTask(due = allDayInstantOf(day), isAllDay = true)
|
||||
|
||||
private fun dueAt(day: LocalDate, time: LocalTime, zone: ZoneId = this.zone) =
|
||||
testTask(due = Instant.fromEpochMilliseconds(day.atTime(time).atZone(zone).toInstant().toEpochMilli()))
|
||||
|
||||
private fun Rule.matches(task: Task, day: LocalDate, weekStart: DayOfWeek = DayOfWeek.MONDAY) =
|
||||
matches(task, clockOn(day, weekStart))
|
||||
|
||||
private fun DueSpec.Range.daysIn(today: LocalDate, weekStart: DayOfWeek = DayOfWeek.MONDAY): List<LocalDate> =
|
||||
(-40L..40L).map { today.plusDays(it) }.filter { Rule.Due(this).matches(dueOn(it), today, weekStart) }
|
||||
|
||||
@Test
|
||||
fun `groups combine their children`() {
|
||||
val work = Rule.HasTag("work")
|
||||
val high = Rule.MinPriority(Priority.HIGH)
|
||||
val task = testTask(tags = listOf("work"), priority = Priority.LOW)
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
assertThat(Rule.AllOf(listOf(work, high)).matches(task, day)).isFalse()
|
||||
assertThat(Rule.AnyOf(listOf(work, high)).matches(task, day)).isTrue()
|
||||
assertThat(Rule.Not(work).matches(task, day)).isFalse()
|
||||
assertThat(Rule.Not(high).matches(task, day)).isTrue()
|
||||
assertThat(Rule.AllOf(emptyList()).matches(task, day)).isTrue()
|
||||
assertThat(Rule.AnyOf(emptyList()).matches(task, day)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `next actions are a list or a tag`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val rule = Rule.AllOf(
|
||||
listOf(
|
||||
Rule.AnyOf(listOf(Rule.InList(setOf(7L)), Rule.HasTag("next"))),
|
||||
Rule.Not(Rule.AnyOf(listOf(Rule.HasTag("someday"), Rule.InList(setOf(9L))))),
|
||||
),
|
||||
)
|
||||
assertThat(rule.matches(testTask(listId = 7), day)).isTrue()
|
||||
assertThat(rule.matches(testTask(listId = 1, tags = listOf("next")), day)).isTrue()
|
||||
assertThat(rule.matches(testTask(listId = 1), day)).isFalse()
|
||||
assertThat(rule.matches(testTask(listId = 7, tags = listOf("someday")), day)).isFalse()
|
||||
assertThat(rule.matches(testTask(listId = 9, tags = listOf("next")), day)).isFalse()
|
||||
assertThat(Rule.Not(Rule.Not(Rule.InList(setOf(7L)))).matches(testTask(listId = 7), day)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tags compare exactly and other stores' lists never match here`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
assertThat(Rule.HasTag("work").matches(testTask(tags = listOf("Work")), day)).isFalse()
|
||||
assertThat(Rule.InList(emptySet(), setOf("EXTERNAL:1")).matches(testTask(listId = 1), day)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a rule doesn't look at status, a saved filter keeps to open tasks`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val done = testTask(status = TaskStatus.COMPLETED)
|
||||
assertThat(Rule.Everything.matches(done, day)).isTrue()
|
||||
assertThat(SavedFilter(1, "f").matches(done, clockOn(day))).isFalse()
|
||||
assertThat(SavedFilter(1, "f", Rule.Not(Rule.Everything)).matches(testTask(), clockOn(day))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `due windows read as before`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
fun window(w: DueWindow) = Rule.Due(DueSpec.Window(w))
|
||||
assertThat(window(DueWindow.TODAY).matches(dueAt(day, LocalTime.of(23, 59)), day)).isTrue()
|
||||
assertThat(window(DueWindow.OVERDUE).matches(dueOn(day.minusDays(1)), day)).isTrue()
|
||||
assertThat(window(DueWindow.UPCOMING).matches(dueOn(day.plusDays(1)), day)).isTrue()
|
||||
assertThat(window(DueWindow.NO_DATE).matches(testTask(), day)).isTrue()
|
||||
assertThat(window(DueWindow.NO_DATE).matches(dueOn(day), day)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the next zero days are today, timed or not`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val today = Rule.Due(DueSpec.NextDays(0))
|
||||
assertThat(DueSpec.NextDays(0).daysIn(day)).containsExactly(day)
|
||||
assertThat(today.matches(dueAt(day, LocalTime.MIDNIGHT), day)).isTrue()
|
||||
assertThat(today.matches(dueAt(day, LocalTime.of(23, 59)), day)).isTrue()
|
||||
assertThat(today.matches(dueAt(day.plusDays(1), LocalTime.MIDNIGHT), day)).isFalse()
|
||||
assertThat(today.matches(testTask(), day)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `this week starts on the week start`() {
|
||||
// A Thursday.
|
||||
val thursday = LocalDate.of(2026, 11, 26)
|
||||
val monday = LocalDate.of(2026, 11, 23)
|
||||
val sunday = LocalDate.of(2026, 11, 22)
|
||||
val saturday = LocalDate.of(2026, 11, 21)
|
||||
assertThat(DueSpec.ThisWeek.daysIn(thursday, DayOfWeek.MONDAY)).isEqualTo((0L..6L).map { monday.plusDays(it) })
|
||||
assertThat(DueSpec.ThisWeek.daysIn(thursday, DayOfWeek.SUNDAY)).isEqualTo((0L..6L).map { sunday.plusDays(it) })
|
||||
assertThat(DueSpec.ThisWeek.daysIn(thursday, DayOfWeek.SATURDAY)).isEqualTo((0L..6L).map { saturday.plusDays(it) })
|
||||
// On the week start itself, and on the last day of the week.
|
||||
assertThat(DueSpec.ThisWeek.daysIn(monday, DayOfWeek.MONDAY).first()).isEqualTo(monday)
|
||||
assertThat(DueSpec.ThisWeek.daysIn(sunday, DayOfWeek.MONDAY).first()).isEqualTo(LocalDate.of(2026, 11, 16))
|
||||
assertThat(DueSpec.ThisWeek.daysIn(sunday, DayOfWeek.SUNDAY).first()).isEqualTo(sunday)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `this week crosses the year`() {
|
||||
val newYear = LocalDate.of(2027, 1, 1)
|
||||
assertThat(DueSpec.ThisWeek.daysIn(newYear, DayOfWeek.MONDAY))
|
||||
.isEqualTo((0L..6L).map { LocalDate.of(2026, 12, 28).plusDays(it) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `this month is the calendar month`() {
|
||||
assertThat(DueSpec.ThisMonth.daysIn(LocalDate.of(2026, 12, 31)))
|
||||
.isEqualTo((1..31).map { LocalDate.of(2026, 12, it) })
|
||||
assertThat(DueSpec.ThisMonth.daysIn(LocalDate.of(2027, 1, 1)))
|
||||
.isEqualTo((1..31).map { LocalDate.of(2027, 1, it) })
|
||||
assertThat(DueSpec.ThisMonth.daysIn(LocalDate.of(2028, 2, 29)))
|
||||
.isEqualTo((1..29).map { LocalDate.of(2028, 2, it) })
|
||||
assertThat(DueSpec.ThisMonth.daysIn(LocalDate.of(2027, 2, 15)))
|
||||
.isEqualTo((1..28).map { LocalDate.of(2027, 2, it) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `next days run from today and reach as far as upcoming does`() {
|
||||
val day = LocalDate.of(2026, 12, 29)
|
||||
assertThat(DueSpec.NextDays(0).daysIn(day)).containsExactly(day)
|
||||
assertThat(DueSpec.NextDays(7).daysIn(day)).isEqualTo((0L..7L).map { day.plusDays(it) })
|
||||
val now = Instant.fromEpochMilliseconds(day.atTime(12, 0).atZone(zone).toInstant().toEpochMilli())
|
||||
assertThat(DueSpec.NextDays(7).days(day, DayOfWeek.MONDAY).second)
|
||||
.isEqualTo(UpcomingRange.WEEK.lastDay(day)!!.plusDays(1))
|
||||
assertThat(startOfDay(DueSpec.NextDays(7).days(day, DayOfWeek.MONDAY).second, zone))
|
||||
.isEqualTo(UpcomingRange.WEEK.end(now, zone))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an all-day due is read as its date west of utc`() {
|
||||
val west = ZoneId.of("America/New_York")
|
||||
val day = LocalDate.of(2026, 11, 30)
|
||||
val clock = clockOn(day, zone = west)
|
||||
assertThat(Rule.Due(DueSpec.NextDays(0)).matches(dueOn(day), clock)).isTrue()
|
||||
assertThat(Rule.Due(DueSpec.ThisMonth).matches(dueOn(LocalDate.of(2026, 12, 1)), clock)).isFalse()
|
||||
assertThat(Rule.Due(DueSpec.ThisMonth).matches(dueAt(day, LocalTime.of(23, 30), west), clock)).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a top-level list condition losing its lists drops out`() {
|
||||
val gone: (Long) -> Boolean = { it == 1L }
|
||||
assertThat(Rule.InList(setOf(1L, 2L)).withoutLists(gone)).isEqualTo(Rule.InList(setOf(2L)))
|
||||
assertThat(Rule.InList(setOf(1L)).withoutLists(gone)).isEqualTo(Rule.Everything)
|
||||
assertThat(Rule.InList(setOf(1L), setOf("EXTERNAL:1")).withoutLists(gone))
|
||||
.isEqualTo(Rule.InList(emptySet(), setOf("EXTERNAL:1")))
|
||||
assertThat(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("a"))).withoutLists(gone))
|
||||
.isEqualTo(Rule.AllOf(listOf(Rule.HasTag("a"))))
|
||||
assertThat(Rule.Everything.withoutLists(gone)).isEqualTo(Rule.Everything)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a nested list condition losing its lists still matches the same tasks`() {
|
||||
val gone: (Long) -> Boolean = { it == 1L }
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val rules = listOf(
|
||||
Rule.Not(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x")))),
|
||||
Rule.AnyOf(listOf(Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.HasTag("a"))), Rule.HasTag("b"))),
|
||||
Rule.AnyOf(listOf(Rule.Not(Rule.InList(setOf(1L))), Rule.HasTag("x"))),
|
||||
Rule.AllOf(listOf(Rule.HasTag("a"), Rule.Not(Rule.InList(setOf(1L, 2L))))),
|
||||
)
|
||||
val tasks = listOf(2L, 3L).flatMap { list ->
|
||||
listOf(emptyList(), listOf("a"), listOf("b"), listOf("x")).map { testTask(listId = list, tags = it) }
|
||||
}
|
||||
for (rule in rules) {
|
||||
val pruned = rule.withoutLists(gone)
|
||||
assertThat(pruned).isNotEqualTo(rule)
|
||||
for (task in tasks) assertThat(pruned.matches(task, day)).isEqualTo(rule.matches(task, day))
|
||||
}
|
||||
assertThat(rules[0].withoutLists(gone))
|
||||
.isEqualTo(Rule.Not(Rule.AllOf(listOf(Rule.InList(emptySet()), Rule.HasTag("x")))))
|
||||
assertThat(rules[0].withoutLists { false }).isEqualTo(rules[0])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only a week range reads the week start`() {
|
||||
assertThat(Rule.AllOf(listOf(Rule.Not(Rule.Due(DueSpec.ThisWeek)))).readsWeekStart).isTrue()
|
||||
assertThat(Rule.AllOf(listOf(Rule.Due(DueSpec.ThisMonth), Rule.Due(DueSpec.NextDays(7)))).readsWeekStart).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a saved filter is read with its clock`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val filter = SavedFilter(1, "f", Rule.Due(DueSpec.ThisWeek))
|
||||
val clock = clockOn(day)
|
||||
fun matches(task: Task, ruleClock: RuleClock?) =
|
||||
TaskFiltering.matches(task, TaskFilter.Saved(1), clock.todayStart, clock.todayEnd, filter, ruleClock = ruleClock)
|
||||
assertThat(matches(dueOn(day), clock)).isTrue()
|
||||
assertThat(matches(dueOn(day.plusDays(7)), clock)).isFalse()
|
||||
assertThat(matches(dueOn(day), null)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the due date settles a rule only where nothing else decides`() {
|
||||
val day = LocalDate.of(2026, 11, 26)
|
||||
val clock = clockOn(day)
|
||||
val thisWeek = Rule.Due(DueSpec.ThisWeek)
|
||||
val inWeek = dueOn(day)
|
||||
val later = dueOn(day.plusDays(30))
|
||||
val rule = Rule.AllOf(listOf(thisWeek, Rule.Not(Rule.MinPriority(Priority.HIGH))))
|
||||
assertThat(rule.dueVerdict(inWeek, clock)).isNull()
|
||||
assertThat(rule.dueVerdict(later, clock)).isFalse()
|
||||
assertThat(Rule.AnyOf(listOf(thisWeek, Rule.HasTag("a"))).dueVerdict(inWeek, clock)).isTrue()
|
||||
assertThat(Rule.AnyOf(listOf(thisWeek, Rule.HasTag("a"))).dueVerdict(later, clock)).isNull()
|
||||
assertThat(Rule.Not(thisWeek).dueVerdict(later, clock)).isTrue()
|
||||
assertThat(Rule.Everything.dueVerdict(later, clock)).isTrue()
|
||||
val filter = SavedFilter(1, "f", rule)
|
||||
assertThat(filter.admitsDueOf(inWeek, clock)).isTrue()
|
||||
assertThat(filter.admitsDueOf(later, clock)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flat criteria round-trip through a rule`() {
|
||||
val all = FilterCriteria(
|
||||
due = setOf(DueWindow.TODAY, DueWindow.NO_DATE),
|
||||
listIds = setOf(1L),
|
||||
listsElsewhere = setOf("EXTERNAL:2"),
|
||||
tags = setOf("x"),
|
||||
tagMatch = TagMatch.ALL,
|
||||
minPriority = Priority.LOW,
|
||||
)
|
||||
val samples = listOf(
|
||||
FilterCriteria(),
|
||||
all,
|
||||
all.copy(tagMatch = TagMatch.ANY),
|
||||
all.copy(tags = setOf("a", "b")),
|
||||
all.copy(listIds = emptySet()),
|
||||
all.copy(listsElsewhere = emptySet(), due = setOf(DueWindow.OVERDUE)),
|
||||
)
|
||||
for (criteria in samples) assertThat(FilterCriteria.of(criteria.toRule())).isEqualTo(criteria)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a single criterion reads as flat too`() {
|
||||
assertThat(FilterCriteria.of(Rule.InList(setOf(1L)))).isEqualTo(FilterCriteria(listIds = setOf(1L)))
|
||||
assertThat(FilterCriteria.of(Rule.Due(DueSpec.Window(DueWindow.TODAY)))).isEqualTo(FilterCriteria(due = setOf(DueWindow.TODAY)))
|
||||
assertThat(FilterCriteria.of(Rule.AnyOf(listOf(Rule.HasTag("a"), Rule.HasTag("b")))))
|
||||
.isEqualTo(FilterCriteria(tags = setOf("a", "b")))
|
||||
assertThat(FilterCriteria.of(Rule.AllOf(listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)), Rule.HasTag("b")))))
|
||||
.isEqualTo(FilterCriteria(listIds = setOf(1L), tags = setOf("a", "b"), tagMatch = TagMatch.ALL))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rules beyond the flat form have none`() {
|
||||
val notFlat = listOf(
|
||||
Rule.Not(Rule.HasTag("a")),
|
||||
Rule.Due(DueSpec.ThisWeek),
|
||||
Rule.AnyOf(listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)))),
|
||||
Rule.AllOf(listOf(Rule.InList(setOf(1L)), Rule.InList(setOf(2L)))),
|
||||
Rule.AllOf(listOf(Rule.AnyOf(listOf(Rule.HasTag("a"))), Rule.AllOf(listOf(Rule.HasTag("b"))))),
|
||||
Rule.AllOf(listOf(Rule.AnyOf(emptyList()))),
|
||||
Rule.InList(emptySet()),
|
||||
Rule.AllOf(listOf(Rule.AllOf(listOf(Rule.Due(DueSpec.Window(DueWindow.TODAY)))))),
|
||||
Rule.AllOf(listOf(Rule.HasTag("a"), Rule.AnyOf(listOf(Rule.HasTag("b"))))),
|
||||
)
|
||||
for (rule in notFlat) assertThat(FilterCriteria.of(rule)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a filter without a flat form presets nothing`() {
|
||||
val filter = SavedFilter(1, "f", Rule.Not(Rule.InList(setOf(1L))))
|
||||
assertThat(filter.newTaskPreset(LocalDate.of(2026, 11, 26))).isEqualTo(NewTaskPreset())
|
||||
assertThat(filter.withListsIn(setOf(2L)).rule).isEqualTo(Rule.Not(Rule.InList(emptySet())))
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ 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
|
||||
import kotlin.time.Instant
|
||||
@@ -15,10 +16,19 @@ class SavedFilterTest {
|
||||
private val today = Instant.fromEpochMilliseconds(1000 * dayMs + 1)
|
||||
private val upcoming = Instant.fromEpochMilliseconds(1002 * dayMs)
|
||||
|
||||
private fun SavedFilter.matches(task: Task) = matches(task, todayStart, todayEnd)
|
||||
private fun SavedFilter.matches(task: Task) = matches(task, RuleClock(todayStart, todayEnd, ZoneId.systemDefault(), DayOfWeek.MONDAY))
|
||||
|
||||
private val empty = SavedFilter(id = 1, name = "f")
|
||||
|
||||
private fun filterOf(
|
||||
due: Set<DueWindow> = emptySet(),
|
||||
listIds: Set<Long> = emptySet(),
|
||||
listsElsewhere: Set<String> = emptySet(),
|
||||
tags: Set<String> = emptySet(),
|
||||
tagMatch: TagMatch = TagMatch.ANY,
|
||||
minPriority: Priority = Priority.NONE,
|
||||
) = SavedFilter(1, "f", FilterCriteria(due, listIds, listsElsewhere, tags, tagMatch, minPriority))
|
||||
|
||||
@Test
|
||||
fun `an empty filter is every open task`() {
|
||||
assertThat(empty.matches(testTask(due = null))).isTrue()
|
||||
@@ -29,7 +39,7 @@ class SavedFilterTest {
|
||||
|
||||
@Test
|
||||
fun `today and overdue together`() {
|
||||
val filter = empty.copy(due = setOf(DueWindow.TODAY, DueWindow.OVERDUE))
|
||||
val filter = filterOf(due = setOf(DueWindow.TODAY, DueWindow.OVERDUE))
|
||||
assertThat(filter.matches(testTask(due = overdue))).isTrue()
|
||||
assertThat(filter.matches(testTask(due = today))).isTrue()
|
||||
assertThat(filter.matches(testTask(due = upcoming))).isFalse()
|
||||
@@ -38,21 +48,21 @@ class SavedFilterTest {
|
||||
|
||||
@Test
|
||||
fun `lists narrow by membership`() {
|
||||
val filter = empty.copy(listIds = setOf(2L, 3L))
|
||||
val filter = filterOf(listIds = setOf(2L, 3L))
|
||||
assertThat(filter.matches(testTask(listId = 2))).isTrue()
|
||||
assertThat(filter.matches(testTask(listId = 1))).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lists from another store match nothing here`() {
|
||||
val filter = empty.copy(listsElsewhere = true)
|
||||
val filter = filterOf(listsElsewhere = setOf("EXTERNAL:1"))
|
||||
assertThat(filter.matches(testTask(listId = 1))).isFalse()
|
||||
assertThat(filter.copy(listIds = setOf(1L)).matches(testTask(listId = 1))).isTrue()
|
||||
assertThat(filterOf(listIds = setOf(1L), listsElsewhere = setOf("EXTERNAL:1")).matches(testTask(listId = 1))).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `priority is a floor`() {
|
||||
val filter = empty.copy(minPriority = Priority.MEDIUM)
|
||||
val filter = filterOf(minPriority = Priority.MEDIUM)
|
||||
assertThat(filter.matches(testTask(priority = Priority.HIGH))).isTrue()
|
||||
assertThat(filter.matches(testTask(priority = Priority.MEDIUM))).isTrue()
|
||||
assertThat(filter.matches(testTask(priority = Priority.LOW))).isFalse()
|
||||
@@ -61,8 +71,8 @@ class SavedFilterTest {
|
||||
|
||||
@Test
|
||||
fun `tags match any or all`() {
|
||||
val any = empty.copy(tags = setOf("work", "home"))
|
||||
val all = any.copy(tagMatch = TagMatch.ALL)
|
||||
val any = filterOf(tags = setOf("work", "home"))
|
||||
val all = filterOf(tags = setOf("work", "home"), tagMatch = TagMatch.ALL)
|
||||
val one = testTask(tags = listOf("work"))
|
||||
val both = testTask(tags = listOf("home", "work", "x"))
|
||||
assertThat(any.matches(one)).isTrue()
|
||||
@@ -73,7 +83,7 @@ class SavedFilterTest {
|
||||
|
||||
@Test
|
||||
fun `criteria combine with and`() {
|
||||
val filter = empty.copy(due = setOf(DueWindow.TODAY), listIds = setOf(1L), tags = setOf("work"))
|
||||
val filter = filterOf(due = setOf(DueWindow.TODAY), listIds = setOf(1L), tags = setOf("work"))
|
||||
assertThat(filter.matches(testTask(listId = 1, due = today, tags = listOf("work")))).isTrue()
|
||||
assertThat(filter.matches(testTask(listId = 2, due = today, tags = listOf("work")))).isFalse()
|
||||
assertThat(filter.matches(testTask(listId = 1, due = today))).isFalse()
|
||||
@@ -94,7 +104,7 @@ class SavedFilterTest {
|
||||
@Test
|
||||
fun `a new task preset lands in its filter`() {
|
||||
val day = LocalDate.of(2026, 10, 10)
|
||||
val filter = empty.copy(
|
||||
val filter = filterOf(
|
||||
due = setOf(DueWindow.UPCOMING),
|
||||
tags = setOf("work", "home"),
|
||||
tagMatch = TagMatch.ALL,
|
||||
@@ -104,16 +114,17 @@ class SavedFilterTest {
|
||||
assertThat(preset.dueDate).isEqualTo(day.plusDays(1))
|
||||
assertThat(preset.tags).containsExactly("home", "work")
|
||||
assertThat(preset.priority).isEqualTo(Priority.HIGH)
|
||||
assertThat(empty.copy(due = setOf(DueWindow.TODAY, DueWindow.UPCOMING)).newTaskPreset(day).dueDate).isEqualTo(day)
|
||||
assertThat(empty.copy(due = setOf(DueWindow.TODAY, DueWindow.NO_DATE)).newTaskPreset(day).dueDate).isNull()
|
||||
assertThat(empty.copy(tags = setOf("b", "a")).newTaskPreset(day).tags).containsExactly("a")
|
||||
assertThat(filterOf(due = setOf(DueWindow.TODAY, DueWindow.UPCOMING)).newTaskPreset(day).dueDate).isEqualTo(day)
|
||||
assertThat(filterOf(due = setOf(DueWindow.TODAY, DueWindow.NO_DATE)).newTaskPreset(day).dueDate).isNull()
|
||||
assertThat(filterOf(tags = setOf("b", "a")).newTaskPreset(day).tags).containsExactly("a")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lists since deleted drop out`() {
|
||||
val filter = empty.copy(listIds = setOf(1L, 5L))
|
||||
assertThat(filter.withListsIn(setOf(1L, 2L)).listIds).containsExactly(1L)
|
||||
assertThat(filter.withListsIn(setOf(2L)).anyList).isTrue()
|
||||
assertThat(filter.copy(listsElsewhere = true).withListsIn(setOf(2L)).anyList).isFalse()
|
||||
val filter = filterOf(listIds = setOf(1L, 5L))
|
||||
assertThat(filter.withListsIn(setOf(1L, 2L)).criteria!!.listIds).containsExactly(1L)
|
||||
assertThat(filter.withListsIn(setOf(2L)).criteria!!.anyList).isTrue()
|
||||
val elsewhere = filterOf(listIds = setOf(1L, 5L), listsElsewhere = setOf("EXTERNAL:1"))
|
||||
assertThat(elsewhere.withListsIn(setOf(2L)).criteria!!.anyList).isFalse()
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -118,9 +118,9 @@ class TaskGroupsTest {
|
||||
assertThat(TaskGroups.offeredFor(TaskFilter.Smart(SmartList.TODAY))).doesNotContain(TaskGrouping.DAY)
|
||||
assertThat(TaskGroups.offeredFor(TaskFilter.OfList(1))).doesNotContain(TaskGrouping.LIST)
|
||||
assertThat(TaskGroups.offeredFor(TaskFilter.Tagged("x"))).isEqualTo(all)
|
||||
val oneList = SavedFilter(id = 1, name = "f", listIds = setOf(3L))
|
||||
val oneList = SavedFilter(id = 1, name = "f", criteria = FilterCriteria(listIds = setOf(3L)))
|
||||
assertThat(TaskGroups.offeredFor(TaskFilter.Saved(1), oneList)).doesNotContain(TaskGrouping.LIST)
|
||||
val overdueOnly = SavedFilter(id = 2, name = "g", due = setOf(DueWindow.OVERDUE))
|
||||
val overdueOnly = SavedFilter(id = 2, name = "g", criteria = FilterCriteria(due = setOf(DueWindow.OVERDUE)))
|
||||
assertThat(TaskGroups.offeredFor(TaskFilter.Saved(2), overdueOnly)).doesNotContain(TaskGrouping.DAY)
|
||||
assertThat(TaskGroups.offeredFor(TaskFilter.OfLists(setOf(1, 2)))).isEmpty()
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.assertThrows
|
||||
|
||||
class ViewTest {
|
||||
|
||||
private fun half(id: Long) = Block(id, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL), BlockWidth.HALF)
|
||||
private fun full(id: Long) = Block(id, BlockType.TAGS)
|
||||
private fun taskList(id: Long) = Block(id, BlockType.TASK_LIST, BlockSource.Smart(SmartList.TODAY))
|
||||
|
||||
@Test
|
||||
fun `home is the 1_4 home in its order`() {
|
||||
val home = View.home()
|
||||
assertThat(home.scope).isNull()
|
||||
assertThat(home.quickAdd).isTrue()
|
||||
assertThat(home.problems).isEmpty()
|
||||
assertThat(home.blocks.rows().map { row -> row.map { it.type to it.source } }).containsExactly(
|
||||
listOf(BlockType.PROGRESS to BlockSource.Smart(SmartList.TODAY)),
|
||||
listOf(
|
||||
BlockType.COUNT_TILE to BlockSource.Smart(SmartList.OVERDUE),
|
||||
BlockType.COUNT_TILE to BlockSource.Smart(SmartList.ALL),
|
||||
),
|
||||
listOf(BlockType.PREVIEW to BlockSource.Smart(SmartList.UPCOMING)),
|
||||
listOf(BlockType.LISTS to null),
|
||||
listOf(BlockType.TAGS to null),
|
||||
listOf(BlockType.FILTERS to null),
|
||||
).inOrder()
|
||||
assertThat((home.blocks[3].options as BlockOptions.Preview)).isEqualTo(BlockOptions.Preview(count = 3, showAll = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `half blocks pack two to a row, a lone one sits alone`() {
|
||||
val blocks = listOf(half(1), half(2), half(3), full(4), half(5), half(6), half(7))
|
||||
assertThat(blocks.rows().map { row -> row.map { it.id } }).containsExactly(
|
||||
listOf(1L, 2L),
|
||||
listOf(3L),
|
||||
listOf(4L),
|
||||
listOf(5L, 6L),
|
||||
listOf(7L),
|
||||
).inOrder()
|
||||
assertThat(emptyList<Block>().rows()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `options must match the type`() {
|
||||
assertThrows<IllegalArgumentException> { Block(1, BlockType.TAGS, options = BlockOptions.Filters) }
|
||||
assertThrows<IllegalArgumentException> { BlockOptions.Preview(count = 4) }
|
||||
BlockType.entries.forEach { assertThat(BlockOptions.defaultFor(it).type).isEqualTo(it) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `layout problems name what breaks the rules`() {
|
||||
val blocks = listOf(
|
||||
taskList(1),
|
||||
Block(2, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), BlockWidth.HALF),
|
||||
Block(2, BlockType.LISTS, BlockSource.Smart(SmartList.ALL)),
|
||||
Block(4, BlockType.PROGRESS),
|
||||
taskList(5),
|
||||
full(6),
|
||||
)
|
||||
assertThat(blocks.layoutProblems()).containsExactly(
|
||||
LayoutProblem.DuplicateId(2),
|
||||
LayoutProblem.WidthNotAllowed(2),
|
||||
LayoutProblem.SourceMismatch(2),
|
||||
LayoutProblem.SourceMismatch(4),
|
||||
LayoutProblem.SeveralTaskLists,
|
||||
LayoutProblem.TaskListNotLast,
|
||||
)
|
||||
assertThat(listOf(half(1), half(2), taskList(3)).layoutProblems()).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `normalising fixes what layout problems find`() {
|
||||
val blocks = listOf(
|
||||
taskList(1),
|
||||
Block(2, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), BlockWidth.HALF),
|
||||
Block(2, BlockType.TAGS),
|
||||
Block(4, BlockType.PROGRESS),
|
||||
taskList(5),
|
||||
full(6),
|
||||
)
|
||||
val normalized = blocks.normalized()
|
||||
assertThat(normalized.map { it.id }).containsExactly(2L, 6L, 1L).inOrder()
|
||||
assertThat(normalized[0].width).isEqualTo(BlockWidth.FULL)
|
||||
assertThat(normalized.layoutProblems()).isEmpty()
|
||||
assertThat(View.home().blocks.normalized()).isEqualTo(View.home().blocks)
|
||||
// A block dropped for its source doesn't take its id with it.
|
||||
assertThat(listOf(Block(5, BlockType.LISTS, BlockSource.Smart(SmartList.ALL)), full(5)).normalized())
|
||||
.containsExactly(full(5))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a block takes its type's first width unless told`() {
|
||||
assertThat(Block(1, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL)).width).isEqualTo(BlockWidth.HALF)
|
||||
assertThat(Block(1, BlockType.PROGRESS, BlockSource.Smart(SmartList.TODAY)).width).isEqualTo(BlockWidth.FULL)
|
||||
assertThrows<IllegalArgumentException> { BlockOptions.Lists(accounts = emptySet()) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `home comes first, the default standing in when it is missing`() {
|
||||
val work = View(2, "Work", ViewIcon.WORK, null, emptyList())
|
||||
val mine = View.home().copy(name = "Mine")
|
||||
assertThat(listOf(work, mine).withHomeFirst()).containsExactly(mine, work).inOrder()
|
||||
assertThat(listOf(work).withHomeFirst()).containsExactly(View.home(), work).inOrder()
|
||||
assertThat(emptyList<View>().withHomeFirst()).containsExactly(View.home())
|
||||
}
|
||||
}
|
||||
@@ -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()) })
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user