Compare commits
52 Commits
v0.2.0
...
fix/provid
| Author | SHA1 | Date | |
|---|---|---|---|
| 47cf99af32 | |||
| 26628dc0bb | |||
| d2e3832ef2 | |||
| 93857135b3 | |||
| 36beb2d0ad | |||
| bc70ed3a9f | |||
| 3f166ef5f0 | |||
| 41bd49826a | |||
| 05c75bafa7 | |||
| cfa25b9730 | |||
| 9d7fc64b0b | |||
| 4aa65edb45 | |||
| a9843e25b7 | |||
| 5f4711dabe | |||
| 6d3fbc05c1 | |||
| 721b411579 | |||
| 046b8f7e9e | |||
| 06cc9b1c8b | |||
| 2d366a7be3 | |||
| 52aeebcb53 | |||
| 8f6b85008c | |||
| eb1e530ce7 | |||
| 7516972e9f | |||
| 7f58f81fe1 | |||
| 976d496d21 | |||
| 245f1db536 | |||
| 623e533547 | |||
| 2e50356f81 | |||
| e6f503c02a | |||
| c53511196d | |||
| a8595e26b4 | |||
| 411e27659f | |||
| b266653e4e | |||
| 2f5012dc34 | |||
| ccc07e86c7 | |||
| 211450bc46 | |||
| 9d134be621 | |||
| 37e3c4e659 | |||
| 78632865f9 | |||
| e7a62e71df | |||
| 4c05c86e95 | |||
| 37662e83bb | |||
| 63c6191676 | |||
| 4994f5ec2c | |||
| e4c8dbf2c1 | |||
| 069ae38b2c | |||
| a5ddf16537 | |||
| 18e03e27b6 | |||
| 152226c1b2 | |||
| ec7b696eb9 | |||
| 76a0139fda | |||
| d84ac60757 |
23
.gitea/ISSUE_TEMPLATE/bug_report.md
Normal file
23
.gitea/ISSUE_TEMPLATE/bug_report.md
Normal file
@@ -0,0 +1,23 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Something doesn't work the way it should
|
||||
title: ""
|
||||
labels:
|
||||
- bug
|
||||
---
|
||||
|
||||
### What happened
|
||||
|
||||
|
||||
### What you expected
|
||||
|
||||
|
||||
### Steps to reproduce
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
### Environment
|
||||
- Agendula version: <!-- Settings → bottom of the screen -->
|
||||
- Android version:
|
||||
- Device:
|
||||
27
.gitea/ISSUE_TEMPLATE/crash_report.md
Normal file
27
.gitea/ISSUE_TEMPLATE/crash_report.md
Normal file
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: Crash report
|
||||
about: Report a crash. Agendula can capture this for you (Settings → Report a problem, or the prompt after a crash) — it copies the report to your clipboard and prefills this form.
|
||||
title: "Crash: "
|
||||
labels:
|
||||
- bug
|
||||
- crash
|
||||
- priority:high
|
||||
---
|
||||
|
||||
<!--
|
||||
Thanks for reporting a crash in Agendula!
|
||||
|
||||
If the app prefilled this for you, the crash report is already below — just add
|
||||
what you were doing and submit. Otherwise, paste the report from your clipboard
|
||||
into the code block. The report contains only app/Android/device versions and the
|
||||
stack trace — no personal data or calendar content.
|
||||
-->
|
||||
|
||||
### What happened
|
||||
|
||||
|
||||
### Crash report
|
||||
|
||||
```
|
||||
(paste the crash report here)
|
||||
```
|
||||
16
.gitea/ISSUE_TEMPLATE/feature_request.md
Normal file
16
.gitea/ISSUE_TEMPLATE/feature_request.md
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea or improvement
|
||||
title: ""
|
||||
labels:
|
||||
- feat
|
||||
---
|
||||
|
||||
### What would you like Agendula to do?
|
||||
|
||||
|
||||
### Why — what problem does it solve?
|
||||
|
||||
|
||||
### Anything else
|
||||
<!-- mockups, examples from other apps, alternatives you considered -->
|
||||
19
.gitea/ISSUE_TEMPLATE/question.md
Normal file
19
.gitea/ISSUE_TEMPLATE/question.md
Normal file
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: Question
|
||||
about: Ask how something works or get help using Agendula
|
||||
title: ""
|
||||
labels:
|
||||
- question
|
||||
---
|
||||
|
||||
### Your question
|
||||
|
||||
|
||||
### What you've tried
|
||||
<!-- so far, if anything -->
|
||||
|
||||
|
||||
### Context
|
||||
- Agendula version: <!-- Settings → bottom of the screen -->
|
||||
- Android version:
|
||||
- Device:
|
||||
@@ -1,18 +1,23 @@
|
||||
name: CI
|
||||
|
||||
# One gate per pull request. Branch pushes no longer trigger CI on their own,
|
||||
# so a change is built once on its PR (covering feature -> release/* and
|
||||
# release/* -> main) instead of once per push and again on the merge to main.
|
||||
# The merge itself is handled by release.yaml, which only does heavy work when
|
||||
# the merge actually cuts a release.
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
tags-ignore:
|
||||
- '**'
|
||||
pull_request:
|
||||
|
||||
# Cancel superseded runs on the same branch.
|
||||
# Cancel superseded runs for the same PR.
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# Single job named `ci` so the required "CI" status check is always reported,
|
||||
# even for docs-only PRs: those just skip the Android build and the job still
|
||||
# succeeds (fast green check) instead of being filtered out and leaving the
|
||||
# required check pending forever.
|
||||
ci:
|
||||
runs-on: docker
|
||||
env:
|
||||
@@ -21,14 +26,54 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# Full history so the base..HEAD diff below has a merge-base.
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
|
||||
# Cheap, always-on guard: the release build must stay reproducible for the
|
||||
# official F-Droid repo (no AGP VCS-info embedding). Runs regardless of
|
||||
# change scope so a regression can't slip through on a "docs-only" PR.
|
||||
- name: Reproducible-release invariant
|
||||
run: bash scripts/check_reproducible_release.sh
|
||||
|
||||
# Decide whether anything that affects the app build changed. Docs,
|
||||
# F-Droid metadata and the licence don't, so those PRs skip the SDK +
|
||||
# Gradle work below but still report a green `ci`.
|
||||
- name: Classify change scope
|
||||
id: scope
|
||||
run: |
|
||||
set -e
|
||||
BASE="${{ github.base_ref }}"
|
||||
# Full (not --depth=1) base fetch so the merge-base is present even when
|
||||
# the PR branch forked several commits back; a shallow tip has no merge
|
||||
# base with a divergent branch and `git diff base...HEAD` aborts.
|
||||
git fetch --no-tags origin "$BASE"
|
||||
MB=$(git merge-base "origin/$BASE" HEAD 2>/dev/null || true)
|
||||
if [ -z "$MB" ]; then
|
||||
# No common ancestor available — don't risk skipping the build.
|
||||
echo "No merge base with origin/$BASE — running the full build to be safe."
|
||||
echo "code=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
CHANGED=$(git diff --name-only "$MB" HEAD)
|
||||
echo "Changed files:"; echo "$CHANGED"
|
||||
if echo "$CHANGED" | grep -vE '(\.md$|^docs/|^fdroid-metadata/|^fastlane/|^LICENSE$)' | grep -q .; then
|
||||
echo "code=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "code=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Docs/metadata-only change — skipping the Android build."
|
||||
fi
|
||||
|
||||
- name: Setup Java
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '17'
|
||||
|
||||
- name: Setup Android SDK
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
# Default ("tools platform-tools") drags in the Android Emulator
|
||||
@@ -36,12 +81,14 @@ jobs:
|
||||
packages: ''
|
||||
|
||||
- name: Setup Android SDK cache
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: /opt/android-sdk
|
||||
key: ${{ runner.os }}-android-sdk-37-36.0.0
|
||||
|
||||
- name: Install Android SDK packages
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
run: |
|
||||
yes | sdkmanager --licenses >/dev/null || true
|
||||
sdkmanager \
|
||||
@@ -50,6 +97,7 @@ jobs:
|
||||
"build-tools;36.0.0"
|
||||
|
||||
- name: Setup Gradle cache
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
@@ -60,21 +108,25 @@ jobs:
|
||||
${{ runner.os }}-gradle-
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
run: chmod +x ./gradlew
|
||||
|
||||
# No --no-daemon: the daemon lives only as long as this job container
|
||||
# and lets the following steps skip JVM startup + reconfiguration.
|
||||
- name: Lint (debug variant only)
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
run: ./gradlew lintDebug
|
||||
|
||||
- name: Unit tests
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
run: ./gradlew testDebugUnitTest
|
||||
|
||||
- name: Assemble debug APK
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Trivy filesystem scan
|
||||
if: github.ref == 'refs/heads/main'
|
||||
if: steps.scope.outputs.code == 'true'
|
||||
run: |
|
||||
set -e
|
||||
SUDO=""
|
||||
|
||||
@@ -1,78 +1,99 @@
|
||||
name: Release — F-Droid repo + Gitea release
|
||||
name: Release — F-Droid repo + Gitea/Codeberg release
|
||||
|
||||
# A release is cut by merging a release branch into main with a bumped
|
||||
# versionName (see docs/RELEASING.md). This workflow reads that versionName and,
|
||||
# if no matching tag exists yet, runs tests, builds + signs the APK, publishes
|
||||
# it to the F-Droid repo, creates the vX.Y.Z tag + Gitea release, and mirrors
|
||||
# that release to Codeberg with the signed APK + a SHA-256 checksum as a
|
||||
# direct-download channel — the tag is an output of the pipeline, not its
|
||||
# trigger. Ordinary merges (no version bump) fall through `detect` and do
|
||||
# nothing.
|
||||
#
|
||||
# A manual workflow_dispatch (from a branch) runs the re-sign-only recovery
|
||||
# path: it re-signs the existing F-Droid index with the repo key and re-uploads,
|
||||
# without building an APK or creating a release. Used for key rotation / repo
|
||||
# recovery.
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
# Cheap gate: resolve the version from the committed build.gradle and decide
|
||||
# whether this push actually cuts a new release (no tag for it yet). Keeps the
|
||||
# heavy job from running on every merge to main.
|
||||
detect:
|
||||
runs-on: docker
|
||||
env:
|
||||
ANDROID_HOME: /opt/android-sdk
|
||||
ANDROID_SDK_ROOT: /opt/android-sdk
|
||||
outputs:
|
||||
is_release: ${{ steps.v.outputs.is_release }}
|
||||
version: ${{ steps.v.outputs.version }}
|
||||
version_code: ${{ steps.v.outputs.version_code }}
|
||||
prerelease: ${{ steps.v.outputs.prerelease }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '17'
|
||||
submodules: recursive
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: ''
|
||||
|
||||
- name: Setup Android SDK cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: /opt/android-sdk
|
||||
key: ${{ runner.os }}-android-sdk-37-36.0.0
|
||||
|
||||
- name: Install Android SDK packages
|
||||
- name: Resolve version and whether it is a new release
|
||||
id: v
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
run: |
|
||||
yes | sdkmanager --licenses >/dev/null || true
|
||||
sdkmanager \
|
||||
"platform-tools" \
|
||||
"platforms;android-37.0" \
|
||||
"build-tools;36.0.0"
|
||||
set -e
|
||||
VERSION=$(grep -oP 'versionName\s*=\s*"\K[^"]+' app/build.gradle.kts)
|
||||
if [ -z "$VERSION" ]; then echo "No versionName in app/build.gradle.kts" >&2; exit 1; fi
|
||||
MAJOR=$(echo "$VERSION" | cut -d. -f1); MINOR=$(echo "$VERSION" | cut -d. -f2); PATCH=$(echo "$VERSION" | cut -d. -f3)
|
||||
MAJOR=${MAJOR:-0}; MINOR=${MINOR:-0}; PATCH=${PATCH:-0}
|
||||
VERSION_CODE=$(( MAJOR * 10000 + MINOR * 100 + PATCH ))
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
|
||||
# Pre-1.0 is not stable yet: mark the Gitea release as a pre-release
|
||||
# while MAJOR is 0. Graduates to a stable release automatically at 1.0.0.
|
||||
if [ "$MAJOR" = "0" ]; then PRERELEASE=true; else PRERELEASE=false; fi
|
||||
echo "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"
|
||||
echo "Resolved version $VERSION (code $VERSION_CODE, prerelease=$PRERELEASE)"
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
echo "Manual dispatch — re-sign path, not a release."
|
||||
echo "is_release=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
# A tag for this version already existing means the release shipped on
|
||||
# an earlier push; do nothing. Absent => this merge cuts the release.
|
||||
STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
|
||||
-H "Authorization: token $TOKEN" "$API/git/refs/tags/v$VERSION")
|
||||
if [ "$STATUS" = "200" ]; then
|
||||
echo "Tag v$VERSION already exists — nothing to release."
|
||||
echo "is_release=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "No tag for v$VERSION yet — cutting the release."
|
||||
echo "is_release=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Gradle cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-gradle-
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x ./gradlew
|
||||
|
||||
# Lint already enforced on every push to main via ci.yaml.
|
||||
# Release sanity only re-runs tests + a debug build to catch
|
||||
# any tag-resolved drift (e.g. version code substitution issues).
|
||||
|
||||
- name: Unit tests
|
||||
run: ./gradlew testDebugUnitTest
|
||||
|
||||
- name: Assemble debug APK (sanity)
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
build-and-deploy:
|
||||
needs: ci
|
||||
# Releases: build + sign + publish, then mint the tag and Gitea release.
|
||||
# Also runs on manual dispatch, where it skips the build and just re-signs and
|
||||
# re-uploads the existing index (recovery path).
|
||||
release:
|
||||
needs: detect
|
||||
if: needs.detect.outputs.is_release == 'true' || github.event_name == 'workflow_dispatch'
|
||||
runs-on: docker
|
||||
env:
|
||||
ANDROID_HOME: /opt/android-sdk
|
||||
ANDROID_SDK_ROOT: /opt/android-sdk
|
||||
VERSION: ${{ needs.detect.outputs.version }}
|
||||
VERSION_CODE: ${{ needs.detect.outputs.version_code }}
|
||||
IS_RELEASE: ${{ needs.detect.outputs.is_release }}
|
||||
PRERELEASE: ${{ needs.detect.outputs.prerelease }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
@@ -121,31 +142,26 @@ jobs:
|
||||
$SUDO apk add --no-cache jq
|
||||
fi
|
||||
|
||||
# Tag-only build steps. On a manual workflow_dispatch (ref = a branch,
|
||||
# not a tag) these are skipped: the job then just re-signs the existing
|
||||
# index with the configured repo key and re-uploads — used for key
|
||||
# rotation / repo recovery without publishing a new APK.
|
||||
- name: Set version from git tag
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x ./gradlew
|
||||
|
||||
# The committed versionName is the source of truth. Pin versionCode to the
|
||||
# value derived from it so the published APK's code is always
|
||||
# MAJOR*10000 + MINOR*100 + PATCH even if the committed code was forgotten.
|
||||
- name: Pin versionCode to versionName
|
||||
if: env.IS_RELEASE == 'true'
|
||||
run: |
|
||||
set -e
|
||||
RAW_TAG="${GITHUB_REF_NAME:-${GITHUB_REF##*/}}"
|
||||
VERSION="${RAW_TAG#v}"
|
||||
MAJOR=$(echo "$VERSION" | cut -d. -f1)
|
||||
MINOR=$(echo "$VERSION" | cut -d. -f2)
|
||||
PATCH=$(echo "$VERSION" | cut -d. -f3)
|
||||
MAJOR=${MAJOR:-0}; MINOR=${MINOR:-0}; PATCH=${PATCH:-0}
|
||||
VERSION_CODE=$(( MAJOR * 10000 + MINOR * 100 + PATCH ))
|
||||
echo "Version: $VERSION, VersionCode: $VERSION_CODE"
|
||||
sed -i "s/versionName = \".*\"/versionName = \"$VERSION\"/" app/build.gradle.kts
|
||||
sed -i "s/versionCode = .*/versionCode = $VERSION_CODE/" app/build.gradle.kts
|
||||
grep -E 'versionName|versionCode' app/build.gradle.kts
|
||||
# Export for later steps (F-Droid changelog, mapping asset name).
|
||||
echo "VERSION=$VERSION" >> "$GITHUB_ENV"
|
||||
echo "VERSION_CODE=$VERSION_CODE" >> "$GITHUB_ENV"
|
||||
|
||||
# Test the exact commit being shipped (only on a real release).
|
||||
- name: Unit tests
|
||||
if: env.IS_RELEASE == 'true'
|
||||
run: ./gradlew testDebugUnitTest
|
||||
|
||||
- name: Setup Android Keystore
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
if: env.IS_RELEASE == 'true'
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
||||
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
|
||||
@@ -160,11 +176,8 @@ jobs:
|
||||
storeFile=upload-keystore.jks
|
||||
EOF
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x ./gradlew
|
||||
|
||||
- name: Build release APK
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
if: env.IS_RELEASE == 'true'
|
||||
run: ./gradlew assembleRelease
|
||||
|
||||
- name: Setup F-Droid Server Tools
|
||||
@@ -202,8 +215,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
# Fail loudly if the repo key is not configured. NEVER auto-generate
|
||||
# one: a fresh key changes the repo fingerprint and breaks every
|
||||
# user's pinned repo. (Replaces the old `fdroid update --create-key`
|
||||
# path, which silently rotated the key on a wiped server.)
|
||||
# user's pinned repo.
|
||||
if [ -z "${FDROID_KEYSTORE_BASE64:-}" ] || [ -z "${FDROID_CONFIG_BASE64:-}" ]; then
|
||||
echo "ERROR: FDROID_KEYSTORE_BASE64 / FDROID_CONFIG_BASE64 secrets are not set." >&2
|
||||
echo "Refusing to continue — will not auto-generate a new repo key." >&2
|
||||
@@ -216,42 +228,33 @@ jobs:
|
||||
mkdir -p fdroid/repo/icons
|
||||
|
||||
- name: Copy new APK to repo
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
if: env.IS_RELEASE == 'true'
|
||||
run: |
|
||||
set -e
|
||||
mkdir -p fdroid/repo
|
||||
REF_NAME="${GITHUB_REF_NAME:-${GITHUB_REF##*/}}"
|
||||
SAFE_REF_NAME="$(echo "$REF_NAME" | tr '/ ' '__' | tr -cd '[:alnum:]_.-')"
|
||||
if [ -z "$SAFE_REF_NAME" ]; then
|
||||
SAFE_REF_NAME="${GITHUB_SHA:-manual}"
|
||||
fi
|
||||
cp app/build/outputs/apk/release/app-release.apk "fdroid/repo/floret_${SAFE_REF_NAME}.apk"
|
||||
cp app/build/outputs/apk/release/app-release.apk "fdroid/repo/agendula_v${VERSION}.apk"
|
||||
|
||||
- name: Copy metadata to F-Droid repo
|
||||
# Per-version "What's New": ensure this version's changelog exists in the
|
||||
# fastlane tree (committed at release-cut time for the official repo; this
|
||||
# regenerates it from CHANGELOG.md so the self-hosted repo never depends on
|
||||
# the commit having happened). The transform below then carries it across.
|
||||
- name: Ensure this version's changelog is in the fastlane tree
|
||||
if: env.IS_RELEASE == 'true'
|
||||
run: bash scripts/sync_changelog_to_fastlane.sh
|
||||
|
||||
- name: Build F-Droid metadata from fastlane (single source of truth)
|
||||
run: |
|
||||
mkdir -p fdroid/metadata
|
||||
cp -r fdroid-metadata/* fdroid/metadata/
|
||||
|
||||
# Per-version "What's New" for F-Droid clients: the tag's CHANGELOG
|
||||
# section written to changelogs/<versionCode>.txt (same extraction as the
|
||||
# Gitea release notes). en-US only — F-Droid falls back to it for locales
|
||||
# without their own changelog. fdroid update bakes this into the index.
|
||||
- name: Generate F-Droid changelog for this version
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
run: |
|
||||
set -e
|
||||
awk -v ver="$VERSION" '
|
||||
$0 ~ "^## \\[" ver "\\]" { flag = 1; next }
|
||||
/^## \[/ { flag = 0 }
|
||||
flag' CHANGELOG.md > /tmp/changelog.txt
|
||||
sed -i -e '/./,$!d' /tmp/changelog.txt
|
||||
if [ ! -s /tmp/changelog.txt ]; then
|
||||
echo "See CHANGELOG.md for $VERSION." > /tmp/changelog.txt
|
||||
fi
|
||||
CL_DIR="fdroid/metadata/de.jeanlucmakiola.floret/en-US/changelogs"
|
||||
mkdir -p "$CL_DIR"
|
||||
cp /tmp/changelog.txt "$CL_DIR/${VERSION_CODE}.txt"
|
||||
echo "Wrote $CL_DIR/${VERSION_CODE}.txt"
|
||||
# App-level control file (Categories/License/links) for the self-hosted
|
||||
# repo's `fdroid update`.
|
||||
cp fdroid-metadata/de.jeanlucmakiola.agendula.yml fdroid/metadata/
|
||||
# Localized text + graphics + per-version changelogs come from the SAME
|
||||
# fastlane tree the official F-Droid repo harvests from source,
|
||||
# transformed into the F-Droid repo "localized" layout. One source of
|
||||
# truth, both channels.
|
||||
bash scripts/fastlane_to_fdroid_localized.sh \
|
||||
fastlane/metadata/android \
|
||||
fdroid/metadata/de.jeanlucmakiola.agendula
|
||||
|
||||
- name: Generate F-Droid Index
|
||||
run: |
|
||||
@@ -272,97 +275,47 @@ jobs:
|
||||
SFTP
|
||||
# Publish the signed repo/ plus metadata/ (descriptions, screenshots,
|
||||
# per-version changelogs) so changelog history survives across
|
||||
# releases. keystore.p12 and config.yml are NEVER uploaded, so they
|
||||
# can't re-enter the web-served tree; nginx serves only repo/ anyway.
|
||||
# releases. keystore.p12 and config.yml are NEVER uploaded.
|
||||
sshpass -p "$PASS" scp $SSH_OPTS -r fdroid/repo fdroid/metadata "$USER@$HOST:dev/fdroid/"
|
||||
|
||||
# Archive the R8 mapping so user crash stacktraces stay deobfuscatable.
|
||||
# Attached to the Gitea release (it's not an APK, so it fits the
|
||||
# no-binaries rule). Best-effort: never fail a release over it.
|
||||
- name: Attach R8 mapping to Gitea release
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
continue-on-error: true
|
||||
# The APK is published and the index re-signed — now record the release.
|
||||
# Creating it with target_commitish makes Gitea create the vX.Y.Z tag at
|
||||
# this commit, so the tag only ever marks a fully-shipped release (and a
|
||||
# failure before here leaves no tag, so re-running the workflow retries).
|
||||
- name: Create tag + Gitea release
|
||||
if: env.IS_RELEASE == 'true'
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
SHA: ${{ github.sha }}
|
||||
run: |
|
||||
set -e
|
||||
MAP="app/build/outputs/mapping/release/mapping.txt"
|
||||
if [ ! -f "$MAP" ]; then echo "No mapping.txt (R8 off?) — skipping."; exit 0; fi
|
||||
TAG="${GITHUB_REF_NAME:-${GITHUB_REF##*/}}"
|
||||
ASSET="mapping-${VERSION:-$TAG}.txt.gz"
|
||||
gzip -c "$MAP" > "/tmp/$ASSET"
|
||||
# The release is created by the gitea-release job; ensure it exists
|
||||
# (idempotent) so this job doesn't race it to a 404.
|
||||
ID=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty')
|
||||
if [ -z "$ID" ]; then
|
||||
ID=$(curl -s -X POST -H "Authorization: token $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\"}" \
|
||||
"$API/releases" | jq -r '.id // empty')
|
||||
fi
|
||||
if [ -z "$ID" ]; then echo "Could not resolve release id — skipping."; exit 0; fi
|
||||
# Replace any prior asset of the same name (re-run safe).
|
||||
OLD=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" \
|
||||
| jq -r --arg n "$ASSET" '.[] | select(.name==$n) | .id')
|
||||
[ -n "$OLD" ] && curl -s -X DELETE -H "Authorization: token $TOKEN" "$API/releases/$ID/assets/$OLD" >/dev/null || true
|
||||
curl -s -X POST -H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@/tmp/$ASSET" \
|
||||
"$API/releases/$ID/assets?name=$ASSET" -o /dev/null -w "asset upload HTTP %{http_code}\n"
|
||||
|
||||
# A Gitea release per tag, carrying the tag's CHANGELOG section as its
|
||||
# notes. Deliberately no APK assets — distribution stays with the F-Droid
|
||||
# repo; the release is the human-readable record. Gated on the tests-only
|
||||
# ci job (not the deploy) so notes appear even if the F-Droid upload has
|
||||
# an infrastructure hiccup.
|
||||
gitea-release:
|
||||
needs: ci
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
runs-on: docker
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Extract changelog section for this tag
|
||||
run: |
|
||||
set -e
|
||||
TAG="${GITHUB_REF_NAME:-${GITHUB_REF##*/}}"
|
||||
VERSION="${TAG#v}"
|
||||
# Everything between "## [<version>]" and the next "## [" heading.
|
||||
TAG="v$VERSION"
|
||||
# Notes = this version's CHANGELOG section.
|
||||
awk -v ver="$VERSION" '
|
||||
$0 ~ "^## \\[" ver "\\]" { flag = 1; next }
|
||||
/^## \[/ { flag = 0 }
|
||||
flag' CHANGELOG.md > release-notes.md
|
||||
# Trim leading blank lines.
|
||||
sed -i -e '/./,$!d' release-notes.md
|
||||
if [ ! -s release-notes.md ]; then
|
||||
echo "_No changelog entry for ${VERSION} — see CHANGELOG.md._" > release-notes.md
|
||||
fi
|
||||
echo "--- release notes ---"
|
||||
cat release-notes.md
|
||||
|
||||
- name: Create Gitea release
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
run: |
|
||||
set -e
|
||||
TAG="${GITHUB_REF_NAME:-${GITHUB_REF##*/}}"
|
||||
python3 - "$TAG" <<'PY' > payload.json
|
||||
python3 - "$TAG" "$SHA" "$PRERELEASE" <<'PY' > payload.json
|
||||
import json, sys
|
||||
print(json.dumps({
|
||||
"tag_name": sys.argv[1],
|
||||
"target_commitish": sys.argv[2],
|
||||
"name": sys.argv[1],
|
||||
"body": open("release-notes.md").read(),
|
||||
"draft": False,
|
||||
"prerelease": False,
|
||||
# Pre-1.0 releases are flagged as pre-releases (see detect job).
|
||||
"prerelease": sys.argv[3] == "true",
|
||||
}))
|
||||
PY
|
||||
# Upsert: the build-and-deploy job may have created a bare release
|
||||
# first (to attach the mapping asset), so PATCH the notes if it
|
||||
# exists, otherwise POST a new one. Both paths are re-run safe.
|
||||
# Upsert (re-run safe): PATCH if a release for the tag already exists,
|
||||
# else POST a new one (which also creates the tag at target_commitish).
|
||||
curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" > existing.json
|
||||
ID=$(python3 -c "import json,sys; d=json.load(open('existing.json')); print(d.get('id',''))" 2>/dev/null || true)
|
||||
ID=$(jq -r '.id // empty' existing.json 2>/dev/null || true)
|
||||
if [ -n "$ID" ]; then
|
||||
CODE=$(curl -s -o response.json -w '%{http_code}' -X PATCH \
|
||||
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
@@ -376,6 +329,140 @@ jobs:
|
||||
fi
|
||||
cat response.json
|
||||
if [ "$CODE" != "$OK" ]; then
|
||||
echo "Release upsert failed with HTTP $CODE (expected $OK)"
|
||||
echo "Release upsert failed with HTTP $CODE (expected $OK)" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Created/updated release $TAG at $SHA"
|
||||
|
||||
# Archive the R8 mapping so user crash stacktraces stay deobfuscatable.
|
||||
# Attached to the release (it's not an APK, so it fits the no-binaries
|
||||
# rule). Best-effort: never fail a release over it.
|
||||
- name: Attach R8 mapping to Gitea release
|
||||
if: env.IS_RELEASE == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
run: |
|
||||
set -e
|
||||
MAP="app/build/outputs/mapping/release/mapping.txt"
|
||||
if [ ! -f "$MAP" ]; then echo "No mapping.txt (R8 off?) — skipping."; exit 0; fi
|
||||
TAG="v$VERSION"
|
||||
ASSET="mapping-${VERSION}.txt.gz"
|
||||
gzip -c "$MAP" > "/tmp/$ASSET"
|
||||
ID=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty')
|
||||
if [ -z "$ID" ]; then echo "Could not resolve release id — skipping."; exit 0; fi
|
||||
# Replace any prior asset of the same name (re-run safe).
|
||||
OLD=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" \
|
||||
| jq -r --arg n "$ASSET" '.[] | select(.name==$n) | .id')
|
||||
[ -n "$OLD" ] && curl -s -X DELETE -H "Authorization: token $TOKEN" "$API/releases/$ID/assets/$OLD" >/dev/null || true
|
||||
curl -s -X POST -H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@/tmp/$ASSET" \
|
||||
"$API/releases/$ID/assets?name=$ASSET" -o /dev/null -w "asset upload HTTP %{http_code}\n"
|
||||
|
||||
# Mirror the release to the Codeberg mirror as a direct-download channel
|
||||
# for users who don't want F-Droid. Gitea already push-mirrors branches +
|
||||
# tags to Codeberg, but releases aren't git objects so they don't sync —
|
||||
# we create the release there over the API and attach the signed APK plus
|
||||
# a SHA-256 checksum. The APK is identical to the F-Droid one (same app
|
||||
# key), so this adds no trust surface. Best-effort: a Codeberg outage
|
||||
# (it 504s under load) must never fail an already-published F-Droid
|
||||
# release. Needs the CODEBERG_RELEASE_TOKEN secret; skips cleanly if unset.
|
||||
- name: Publish release to Codeberg
|
||||
if: env.IS_RELEASE == 'true'
|
||||
# NOT continue-on-error: this step reported green through 0.2.1, 0.2.2,
|
||||
# 0.3.0, 0.3.1 and 0.3.2 while never once publishing, which is how a
|
||||
# crash-fix release reached F-Droid but not the Codeberg/Obtainium
|
||||
# users who needed it. A broken mirror must fail the release loudly.
|
||||
env:
|
||||
TOKEN: ${{ secrets.CODEBERG_RELEASE_TOKEN }}
|
||||
API: https://codeberg.org/api/v1/repos/jlmakiola/agendula
|
||||
run: |
|
||||
set -e
|
||||
if [ -z "${TOKEN:-}" ]; then
|
||||
echo "CODEBERG_RELEASE_TOKEN not set — skipping Codeberg publish."
|
||||
exit 0
|
||||
fi
|
||||
TAG="v$VERSION"
|
||||
APK="app/build/outputs/apk/release/app-release.apk"
|
||||
if [ ! -f "$APK" ]; then echo "No release APK found — skipping." >&2; exit 1; fi
|
||||
ASSET_APK="agendula_v${VERSION}.apk"
|
||||
ASSET_SUM="${ASSET_APK}.sha256"
|
||||
cp "$APK" "/tmp/$ASSET_APK"
|
||||
( cd /tmp && sha256sum "$ASSET_APK" > "$ASSET_SUM" )
|
||||
|
||||
# Release notes: reuse the section extracted for the Gitea release,
|
||||
# fall back to the CHANGELOG entry if that step's file is gone.
|
||||
if [ ! -s release-notes.md ]; then
|
||||
awk -v ver="$VERSION" '
|
||||
$0 ~ "^## \\[" ver "\\]" { flag = 1; next }
|
||||
/^## \[/ { flag = 0 }
|
||||
flag' CHANGELOG.md > release-notes.md
|
||||
sed -i -e '/./,$!d' release-notes.md
|
||||
fi
|
||||
[ -s release-notes.md ] || echo "_See CHANGELOG.md for ${VERSION}._" > release-notes.md
|
||||
# Never mint the tag here. Gitea's push mirror owns getting it to
|
||||
# Codeberg; this step's only job is to attach a release to a tag that
|
||||
# has already landed. That split matters because every way of creating
|
||||
# a tag from here — git push, or a release POST carrying
|
||||
# target_commitish for a tag Codeberg lacks — is a ref WRITE, and ref
|
||||
# writes are what fail on this repo ("cannot lock references" on push,
|
||||
# an empty-bodied 500 on the API). Attaching to a tag that is already
|
||||
# present needs no ref write and succeeds.
|
||||
#
|
||||
# So: wait for the mirror, verify, then attach. If the tag never shows
|
||||
# up, fail — do NOT fall back to creating it, which is what produced
|
||||
# the silent breakage across 0.2.1 through 0.3.2.
|
||||
TAG_OK=""
|
||||
for i in $(seq 1 30); do
|
||||
if [ "$(curl -s -o /dev/null -w '%{http_code}' \
|
||||
-H "Authorization: token $TOKEN" "$API/tags/$TAG")" = "200" ]; then
|
||||
TAG_OK=1; echo "Codeberg has $TAG (after ~$((i*10))s)"; break
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
if [ -z "$TAG_OK" ]; then
|
||||
echo "Codeberg never received $TAG from the push mirror (waited 300s)." >&2
|
||||
echo "Not creating it here: ref writes to this repo fail, so that" >&2
|
||||
echo "would 500. Check the mirror, then re-run once the tag is there." >&2
|
||||
exit 1
|
||||
fi
|
||||
# No target_commitish: the tag exists, so the API must attach to it
|
||||
# rather than resolve a commit and mint one.
|
||||
python3 - "$TAG" "$PRERELEASE" <<'PY' > cb-payload.json
|
||||
import json, sys
|
||||
tag, pre = sys.argv[1:3]
|
||||
print(json.dumps({
|
||||
"tag_name": tag,
|
||||
"name": tag,
|
||||
"body": open("release-notes.md").read(),
|
||||
"draft": False,
|
||||
# Pre-1.0 releases are flagged as pre-releases (see detect job).
|
||||
"prerelease": pre == "true",
|
||||
}))
|
||||
PY
|
||||
# Upsert (re-run safe): a release already attached to this tag is
|
||||
# PATCHed in place, so re-running never disturbs a published release.
|
||||
ID=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty')
|
||||
if [ -n "$ID" ]; then
|
||||
curl -s -o /dev/null -w "release PATCH HTTP %{http_code}\n" -X PATCH \
|
||||
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
-d @cb-payload.json "$API/releases/$ID"
|
||||
else
|
||||
curl -s -o cb-response.json -w "release POST HTTP %{http_code}\n" -X POST \
|
||||
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
-d @cb-payload.json "$API/releases"
|
||||
ID=$(jq -r '.id // empty' cb-response.json 2>/dev/null || true)
|
||||
fi
|
||||
if [ -z "$ID" ]; then echo "Could not resolve Codeberg release id." >&2; exit 1; fi
|
||||
|
||||
# Attach APK + checksum, replacing any prior asset of the same name.
|
||||
for A in "$ASSET_APK" "$ASSET_SUM"; do
|
||||
OLD=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" \
|
||||
| jq -r --arg n "$A" '.[] | select(.name==$n) | .id')
|
||||
[ -n "$OLD" ] && curl -s -X DELETE -H "Authorization: token $TOKEN" "$API/releases/$ID/assets/$OLD" >/dev/null || true
|
||||
curl -s -X POST -H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@/tmp/$A" \
|
||||
"$API/releases/$ID/assets?name=$A" -o /dev/null -w "asset $A HTTP %{http_code}\n"
|
||||
done
|
||||
echo "Published $TAG to Codeberg."
|
||||
|
||||
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
[submodule "floret-kit"]
|
||||
path = floret-kit
|
||||
url = https://gitea.jeanlucmakiola.de/makiolaj/floret-kit.git
|
||||
50
CHANGELOG.md
50
CHANGELOG.md
@@ -1,11 +1,57 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project are documented here. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/); the latest released git tag is
|
||||
the source of truth for version codes (see Calendula's `docs/RELEASING.md`).
|
||||
[Keep a Changelog](https://keepachangelog.com/); the `versionName` committed in
|
||||
`app/build.gradle.kts` is the source of truth for a release (see
|
||||
`docs/RELEASING.md`), and the `vX.Y.Z` tag is minted by the pipeline.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.3.2] - 2026-07-20
|
||||
|
||||
### Fixed
|
||||
- Releases reach the Codeberg download channel again. 0.3.1 published to
|
||||
F-Droid but never appeared on Codeberg, so if you install from there — or
|
||||
through Obtainium — this is the release that finally carries 0.3.0's
|
||||
launch-crash fix. The app itself is unchanged from 0.3.1.
|
||||
|
||||
## [0.3.1] - 2026-07-20
|
||||
|
||||
### Fixed
|
||||
- Agendula no longer crashes on launch. Every 0.3.0 install was affected: the
|
||||
release build stripped a constructor that the background-work scheduler needs
|
||||
to open its database, and that happens before the app draws anything.
|
||||
|
||||
## [0.3.0] - 2026-07-19
|
||||
|
||||
### Added
|
||||
- Reminders: Agendula now delivers your due reminders itself. A one-time setup
|
||||
step explains this and asks for notification access, and a master switch in
|
||||
Settings turns the whole thing off again.
|
||||
- A Settings screen, from the gear on the overview: appearance and theme, which
|
||||
fields the task form shows, your default list, and reminder defaults.
|
||||
- The overview leads with Today — a progress ring showing how much of today
|
||||
you've finished — followed by a live preview of what's coming up next.
|
||||
- Search across every task, open or completed, from the top bar.
|
||||
- A proper app icon.
|
||||
|
||||
### Changed
|
||||
- A tidier top bar: no app title, with search and settings pinned to the right.
|
||||
|
||||
## [0.2.2] - 2026-07-19
|
||||
|
||||
### Fixed
|
||||
- Release automation now reliably mirrors each release to the Codeberg mirror
|
||||
(signed APK + SHA-256 checksum). The 0.2.1 attempt failed when the release tag
|
||||
had already been synced to Codeberg.
|
||||
|
||||
## [0.2.1] - 2026-07-19
|
||||
|
||||
### Added
|
||||
- Releases are now also published to the Codeberg mirror as a direct download:
|
||||
each release carries the signed APK plus a SHA-256 checksum, for users who
|
||||
don't use F-Droid.
|
||||
|
||||
## [0.2.0] - 2026-06-27
|
||||
|
||||
### Added
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Contributing to Floret
|
||||
# Contributing to Agendula
|
||||
|
||||
Thanks for your interest in Floret — a Material 3 Expressive task app that's a
|
||||
Thanks for your interest in Agendula — a Material 3 Expressive task app that's a
|
||||
pure front-end over the OpenTasks `TaskContract` provider, with no own database
|
||||
or sync stack. Before diving in, skim [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)
|
||||
(how it's built), [`docs/ROADMAP.md`](docs/ROADMAP.md) (what's next), and
|
||||
@@ -30,11 +30,12 @@ would expose provider details to a ViewModel or the UI, it's in the wrong layer.
|
||||
```sh
|
||||
./gradlew :app:assembleDebug # build the debug APK
|
||||
./gradlew :app:testDebugUnitTest # JVM unit tests (JUnit5 + Truth + Turbine)
|
||||
./gradlew lintDebug # Android lint (CI runs this on every push)
|
||||
./gradlew lintDebug # Android lint (CI runs this on every PR)
|
||||
```
|
||||
|
||||
CI (`.gitea/workflows/ci.yaml`) runs lint → unit tests → debug build on every
|
||||
push, so run these locally before opening a PR. Keep CI green.
|
||||
CI (`.gitea/workflows/ci.yaml`) runs a reproducible-release invariant check,
|
||||
then lint → unit tests → debug build on every pull request, so run these locally
|
||||
before opening a PR. Keep CI green.
|
||||
|
||||
## Where to put code
|
||||
|
||||
@@ -75,12 +76,14 @@ push, so run these locally before opening a PR. Keep CI green.
|
||||
- If your change shifts the architecture or completes a milestone, update
|
||||
[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) / [`docs/ROADMAP.md`](docs/ROADMAP.md)
|
||||
in the same PR.
|
||||
- Don't bump `versionName` / `versionCode` by hand — the git tag drives those at
|
||||
release time.
|
||||
- Don't bump `versionName` / `versionCode` in a regular PR — the committed
|
||||
`versionName` is bumped only when **cutting a release** (that bump reaching
|
||||
`main` is what triggers the release; the pipeline then mints the tag). See
|
||||
[`docs/RELEASING.md`](docs/RELEASING.md).
|
||||
|
||||
## Scope
|
||||
|
||||
Floret stays true to its thesis: a front-end over **open** task backends
|
||||
Agendula stays true to its thesis: a front-end over **open** task backends
|
||||
(CalDAV / iCalendar / DecSync via the OpenTasks provider). Proprietary backends
|
||||
(Google Tasks, Microsoft To Do) are out of scope by design — they'd mean owning
|
||||
a sync stack. v1 targets the OpenTasks contract (OpenTasks + tasks.org); jtx's
|
||||
|
||||
14
README.md
14
README.md
@@ -1,6 +1,6 @@
|
||||
<div align="center">
|
||||
|
||||
<h1>Floret</h1>
|
||||
<h1>Agendula</h1>
|
||||
|
||||
<p><strong>A modern Material 3 Expressive task app for Android.</strong><br>
|
||||
Reads, writes, and reminds — on top of an existing tasks provider, with no own
|
||||
@@ -13,14 +13,16 @@ sync stack.</p>
|
||||
|
||||
</div>
|
||||
|
||||
Floret is the task-list sibling to [Calendula](https://gitea.jeanlucmakiola.de/makiolaj/calendula).
|
||||
Where Calendula is a pure front-end over Android's `CalendarContract`, Floret is
|
||||
Agendula is the task-list sibling to [Calendula](https://gitea.jeanlucmakiola.de/makiolaj/calendula).
|
||||
Where Calendula is a pure front-end over Android's `CalendarContract`, Agendula is
|
||||
a pure front-end over the **OpenTasks `TaskContract` provider** — the store that
|
||||
DAVx5 (and SmoothSync, DecSync, …) syncs your CalDAV `VTODO` tasks into. No own
|
||||
database, no reinvented sync.
|
||||
|
||||
A Calendula flower head is botanically made of many small *florets* — the
|
||||
individual items that make up the bloom. Floret is those items: your tasks.
|
||||
The name rhymes with its sibling on purpose: **Agendula** is *agenda* — Latin for
|
||||
“things to be done” — given Calendula's `-ula` ending. Calendula keeps your days;
|
||||
Agendula keeps your to-dos. (A Calendula flower head is botanically a cluster of
|
||||
many small *florets* — so the two apps are florets of one bloom.)
|
||||
|
||||
> **Status: data layer done, UI in progress.** The full non-visual stack over
|
||||
> the `TaskContract` provider — provider resolution, live-updating reads,
|
||||
@@ -32,7 +34,7 @@ individual items that make up the bloom. Floret is those items: your tasks.
|
||||
|
||||
## Sync sources (by design)
|
||||
|
||||
Floret works with anything that writes to the tasks provider — **DAVx5**
|
||||
Agendula works with anything that writes to the tasks provider — **DAVx5**
|
||||
(CalDAV), **SmoothSync**, **CalDAV-Sync**, **DecSync CC**, or any Android sync
|
||||
adapter — because it builds on the provider, not on any one sync app. Google
|
||||
Tasks / Microsoft To Do are out of scope by design (proprietary; they would mean
|
||||
|
||||
@@ -16,20 +16,21 @@ val keystoreProperties = Properties().apply {
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "de.jeanlucmakiola.floret"
|
||||
namespace = "de.jeanlucmakiola.agendula"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "de.jeanlucmakiola.floret"
|
||||
applicationId = "de.jeanlucmakiola.agendula"
|
||||
minSdk = 29
|
||||
targetSdk = 36
|
||||
// The git tag is the single source of truth for released builds: at
|
||||
// release time .gitea/workflows/release.yaml derives both fields from
|
||||
// the tag, with versionCode = MAJOR*10000 + MINOR*100 + PATCH
|
||||
// (e.g. v2.0.0 -> 20000). These committed values are the dev/local
|
||||
// default; keep them matching the latest released tag. See docs/RELEASING.md.
|
||||
versionCode = 200
|
||||
versionName = "0.2.0"
|
||||
// These committed values ARE the source of truth for a release: merging
|
||||
// a bumped versionName into main triggers .gitea/workflows/release.yaml,
|
||||
// which builds this version and then creates the matching vX.Y.Z tag +
|
||||
// release itself (versionCode is pinned to MAJOR*10000 + MINOR*100 +
|
||||
// PATCH from versionName, e.g. 0.2.0 -> 200). The Gitea release is marked
|
||||
// as a pre-release while MAJOR is 0. See docs/RELEASING.md.
|
||||
versionCode = 302
|
||||
versionName = "0.3.2"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
@@ -47,6 +48,11 @@ android {
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// Keep release builds reproducible for F-Droid: don't let AGP embed
|
||||
// build-environment git metadata (META-INF/version-control-info.textproto),
|
||||
// whose `revision`/path content varies by build machine and is the only
|
||||
// thing that otherwise differs from a clean from-source rebuild.
|
||||
vcsInfo { include = false }
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
proguardFiles(
|
||||
@@ -61,6 +67,22 @@ android {
|
||||
applicationIdSuffix = ".debug"
|
||||
isMinifyEnabled = false
|
||||
}
|
||||
// A locally-installable twin of `release`: same R8 shrinking + obfuscation
|
||||
// and resource shrinking, but debug-signed and given its own applicationId
|
||||
// suffix so it installs alongside both the production app (signed with the
|
||||
// real key) and the debug build. Used to smoke-test a release candidate on
|
||||
// a real device before merging to main — R8-only breakage and first-run/
|
||||
// permission states don't surface in the unminified debug build, nor on a
|
||||
// device that already holds the permission. Never published. See
|
||||
// docs/RELEASING.md.
|
||||
create("releaseTest") {
|
||||
initWith(getByName("release"))
|
||||
applicationIdSuffix = ".releasetest"
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
matchingFallbacks += "release"
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
@@ -73,6 +95,16 @@ android {
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
// Don't embed AGP's dependency-metadata block in the APK signing block. It's
|
||||
// a Play-oriented blob, and F-Droid's reproducible-build scanner rejects any
|
||||
// "extra signing block" — so leaving it in blocks publishing to the official
|
||||
// repo. It lives in the signing block, not the zip entries, so disabling it
|
||||
// doesn't change the build output (reproducibility is unaffected).
|
||||
dependenciesInfo {
|
||||
includeInApk = false
|
||||
includeInBundle = false
|
||||
}
|
||||
|
||||
packaging {
|
||||
resources {
|
||||
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
||||
@@ -120,6 +152,12 @@ dependencies {
|
||||
|
||||
implementation(libs.kotlinx.datetime)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation("de.jeanlucmakiola.floret:core-time")
|
||||
implementation("de.jeanlucmakiola.floret:core-reminders")
|
||||
implementation("de.jeanlucmakiola.floret:core-locale")
|
||||
implementation("de.jeanlucmakiola.floret:core-crash")
|
||||
implementation("de.jeanlucmakiola.floret:identity")
|
||||
implementation("de.jeanlucmakiola.floret:components")
|
||||
|
||||
debugImplementation(libs.androidx.ui.tooling)
|
||||
debugImplementation(libs.androidx.ui.test.manifest)
|
||||
|
||||
15
app/proguard-rules.pro
vendored
15
app/proguard-rules.pro
vendored
@@ -2,5 +2,20 @@
|
||||
-keep class dagger.hilt.** { *; }
|
||||
-keep @dagger.hilt.android.HiltAndroidApp class *
|
||||
|
||||
# Room instantiates its generated <Database>_Impl reflectively through a no-arg
|
||||
# constructor. R8 under AGP 9 keeps the class but prunes that constructor, since
|
||||
# nothing calls it directly — Room then throws InstantiationException, reported
|
||||
# as "Failed to create an instance of ...". We pull Room in transitively via
|
||||
# Glance -> WorkManager, whose WorkDatabase is built by WorkManagerInitializer
|
||||
# at startup, so the app died on launch in every minified build (issue #1).
|
||||
-keep class * extends androidx.room.RoomDatabase { <init>(); }
|
||||
|
||||
# WorkManager likewise looks its workers up by name and calls this constructor
|
||||
# reflectively — same pruning, but it only bites once a worker actually runs
|
||||
# (Glance's widget updates), so keep it explicitly rather than wait for it.
|
||||
-keep class * extends androidx.work.ListenableWorker {
|
||||
<init>(android.content.Context, androidx.work.WorkerParameters);
|
||||
}
|
||||
|
||||
# Compose Compiler may keep its own; defaults are fine
|
||||
-dontwarn org.jetbrains.annotations.**
|
||||
|
||||
@@ -30,15 +30,16 @@
|
||||
</queries>
|
||||
|
||||
<application
|
||||
android:name=".FloretApp"
|
||||
android:name=".AgendulaApp"
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:localeConfig="@xml/locales_config"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Floret"
|
||||
android:theme="@style/Theme.Agendula"
|
||||
tools:targetApi="35">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
@@ -51,6 +52,14 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Standalone crash-report surface; MainActivity routes here on a
|
||||
startup crash-loop. Not exported, kept out of recents. -->
|
||||
<activity
|
||||
android:name=".ui.crash.CrashReportActivity"
|
||||
android:exported="false"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask" />
|
||||
|
||||
<!-- Reminder alarm fires here (internal PendingIntent → not exported). -->
|
||||
<receiver
|
||||
android:name=".data.reminders.DueReminderReceiver"
|
||||
@@ -76,6 +85,17 @@
|
||||
<data android:scheme="content" android:host="org.dmfs.tasks" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<!-- Persists the per-app language on API < 33, where the platform
|
||||
per-app-languages API is unavailable. On 33+ this is a no-op. -->
|
||||
<service
|
||||
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
|
||||
android:enabled="false"
|
||||
android:exported="false">
|
||||
<meta-data
|
||||
android:name="autoStoreLocales"
|
||||
android:value="true" />
|
||||
</service>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret
|
||||
package de.jeanlucmakiola.agendula
|
||||
|
||||
import android.app.Application
|
||||
import dagger.hilt.EntryPoint
|
||||
@@ -6,22 +6,35 @@ import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.EntryPointAccessors
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import de.jeanlucmakiola.floret.data.reminders.ReminderScheduler
|
||||
import de.jeanlucmakiola.agendula.data.reminders.ReminderScheduler
|
||||
import de.jeanlucmakiola.floret.crash.CrashConfig
|
||||
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Application entry point. Registered as android:name=".FloretApp". Besides
|
||||
* Application entry point. Registered as android:name=".AgendulaApp". Besides
|
||||
* Hilt init, it kicks off a reminder re-sync on launch (independent of any UI),
|
||||
* so alarms reflect tasks synced while the app was closed.
|
||||
*/
|
||||
@HiltAndroidApp
|
||||
class FloretApp : Application() {
|
||||
class AgendulaApp : Application() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
// Install first thing so startup crashes are captured too (privacy-
|
||||
// respecting, on-device; the user submits the report by hand).
|
||||
CrashReporter.install(
|
||||
this,
|
||||
CrashConfig(
|
||||
appLabel = getString(R.string.app_name),
|
||||
newIssueUrl = getString(R.string.report_issue_url),
|
||||
chooseIssueUrl = getString(R.string.report_issue_url),
|
||||
issueTitle = getString(R.string.crash_report_issue_title),
|
||||
),
|
||||
)
|
||||
val scheduler = EntryPointAccessors
|
||||
.fromApplication(this, ReminderEntryPoint::class.java)
|
||||
.reminderScheduler()
|
||||
114
app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt
Normal file
114
app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt
Normal file
@@ -0,0 +1,114 @@
|
||||
package de.jeanlucmakiola.agendula
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
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.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import de.jeanlucmakiola.agendula.data.demo.DemoSeeder
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.ui.RootScreen
|
||||
import de.jeanlucmakiola.agendula.ui.crash.CrashReportActivity
|
||||
import de.jeanlucmakiola.agendula.ui.settings.SettingsViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.theme.AgendulaTheme
|
||||
import de.jeanlucmakiola.floret.crash.CrashReportDialog
|
||||
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||
import de.jeanlucmakiola.floret.crash.submitCrashReport
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Single activity. The theme follows [SettingsViewModel]; [RootScreen] is the
|
||||
* (replaceable) functional scaffold over the real data layer. Task-detail intent
|
||||
* routing for reminder taps lands with the full UI.
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
@Inject lateinit var demoSeeder: DemoSeeder
|
||||
|
||||
// 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.
|
||||
private var pendingCrashReport by mutableStateOf<String?>(null)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
// If the app keeps crashing as it starts, the main UI can't be trusted
|
||||
// to come up. Route to the standalone report screen instead of
|
||||
// re-entering the crashing graph.
|
||||
if (CrashReporter.isCrashLoop(this)) {
|
||||
startActivity(Intent(this, CrashReportActivity::class.java))
|
||||
finish()
|
||||
return
|
||||
}
|
||||
|
||||
enableEdgeToEdge()
|
||||
|
||||
// Surface a single captured crash as a dialog on the next launch.
|
||||
if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this)
|
||||
|
||||
// Debug-only sample data: `am start ... --ez agendula_seed true`. Seeds a
|
||||
// local (non-syncing) demo list once; no-op without the extra.
|
||||
if (BuildConfig.DEBUG && intent.getBooleanExtra(EXTRA_SEED, false)) {
|
||||
lifecycleScope.launch { runCatching { demoSeeder.seed() } }
|
||||
}
|
||||
setContent {
|
||||
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
||||
val ui by settingsViewModel.state.collectAsStateWithLifecycle()
|
||||
val darkTheme = when (ui.settings.themeMode) {
|
||||
ThemeMode.SYSTEM -> isSystemInDarkTheme()
|
||||
ThemeMode.LIGHT -> false
|
||||
ThemeMode.DARK -> true
|
||||
}
|
||||
AgendulaTheme(darkTheme = darkTheme, dynamicColor = ui.settings.dynamicColor) {
|
||||
RootScreen(modifier = Modifier.fillMaxSize())
|
||||
pendingCrashReport?.let { report ->
|
||||
CrashReportDialog(
|
||||
report = report,
|
||||
onSend = {
|
||||
submitCrashReport(this@MainActivity, report)
|
||||
CrashReporter.clearReport(this@MainActivity)
|
||||
pendingCrashReport = null
|
||||
},
|
||||
onDismiss = {
|
||||
CrashReporter.dismissPrompt(this@MainActivity)
|
||||
pendingCrashReport = null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
// A successful start breaks any loop; reset the timing trail so a later
|
||||
// ordinary crash isn't mistaken for a loop.
|
||||
CrashReporter.markHealthy(this)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
|
||||
private const val EXTRA_SEED = "agendula_seed"
|
||||
|
||||
/** Opens the app focused on a task (reminder taps). Routing lands with the UI. */
|
||||
fun taskIntent(context: Context, taskId: Long): Intent =
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
putExtra(EXTRA_TASK_ID, taskId)
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package de.jeanlucmakiola.floret.data.demo
|
||||
package de.jeanlucmakiola.agendula.data.demo
|
||||
|
||||
import de.jeanlucmakiola.floret.data.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.floret.domain.DayWindow
|
||||
import de.jeanlucmakiola.floret.domain.Priority
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -16,10 +16,10 @@ import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* Debug-only one-shot sample data. Creates a **local, device-only** list
|
||||
* ("Floret Demo") — so nothing syncs to a CalDAV server — and fills it with
|
||||
* ("Agendula Demo") — so nothing syncs to a CalDAV server — and fills it with
|
||||
* tasks spread across overdue / today / upcoming / no-date / completed so every
|
||||
* smart list shows content. Idempotent: skips if the demo list already exists.
|
||||
* Triggered from [de.jeanlucmakiola.floret.MainActivity] only in debug builds.
|
||||
* Triggered from [de.jeanlucmakiola.agendula.MainActivity] only in debug builds.
|
||||
*/
|
||||
@Singleton
|
||||
class DemoSeeder @Inject constructor(
|
||||
@@ -47,14 +47,14 @@ class DemoSeeder @Inject constructor(
|
||||
repository.createTask(TaskForm(title = "Gather receipts", listId = listId, parentId = invoiceId))
|
||||
repository.createTask(TaskForm(title = "Book train tickets", listId = listId, due = at(te + 6 * day), priority = Priority.LOW))
|
||||
repository.createTask(TaskForm(title = "Read Compose 1.5 release notes", listId = listId))
|
||||
repository.createTask(TaskForm(title = "Sketch the Floret app icon", listId = listId))
|
||||
repository.createTask(TaskForm(title = "Sketch the Agendula app icon", listId = listId))
|
||||
|
||||
val done = repository.createTask(TaskForm(title = "Renew domain name", listId = listId, due = at(ts - 2 * day)))
|
||||
repository.setCompleted(done, completed = true)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DEMO_LIST = "Floret Demo"
|
||||
const val DEMO_LIST = "Agendula Demo"
|
||||
const val DEMO_COLOR = 0xFF7A5C6B.toInt()
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.di
|
||||
package de.jeanlucmakiola.agendula.data.di
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
@@ -10,16 +10,16 @@ import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import de.jeanlucmakiola.floret.data.tasks.AndroidTasksDataSource
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksDataSource
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepositoryImpl
|
||||
import de.jeanlucmakiola.agendula.data.tasks.AndroidTasksDataSource
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepositoryImpl
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import javax.inject.Singleton
|
||||
|
||||
private val Context.floretDataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = "floret_prefs",
|
||||
private val Context.agendulaDataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = "agendula_prefs",
|
||||
)
|
||||
|
||||
@Module
|
||||
@@ -42,7 +42,7 @@ object DataProvideModule {
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
|
||||
context.floretDataStore
|
||||
context.agendulaDataStore
|
||||
|
||||
@Provides
|
||||
@IoDispatcher
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.di
|
||||
package de.jeanlucmakiola.agendula.data.di
|
||||
|
||||
import javax.inject.Qualifier
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
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.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.longPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFormField
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverrideCodec
|
||||
import de.jeanlucmakiola.floret.reminders.applyReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderLeadsFor
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
enum class ThemeMode { SYSTEM, LIGHT, DARK }
|
||||
|
||||
data class Settings(
|
||||
val themeMode: ThemeMode = ThemeMode.SYSTEM,
|
||||
val dynamicColor: Boolean = true,
|
||||
/** The list a new task defaults to; `null` = first available. */
|
||||
val defaultListId: Long? = null,
|
||||
/** Default minutes before due to remind; 0 = at due time. */
|
||||
val reminderLeadMinutes: Int = 0,
|
||||
/** Master switch for due reminders; off clears every scheduled alarm. */
|
||||
val remindersEnabled: Boolean = true,
|
||||
/** Whether the inline "add a subtask" row shows on expanded task-list groups. */
|
||||
val showAddSubtaskRow: Boolean = true,
|
||||
/**
|
||||
* Add affordance for a list: `false` = the floating "New task" button (opens
|
||||
* the editor); `true` = a quick-add bar pinned to the bottom of a real list.
|
||||
* Smart lists always use the button (they have no single list to add into).
|
||||
*/
|
||||
val bottomAddBar: Boolean = false,
|
||||
/**
|
||||
* Per-list overrides of [reminderLeadMinutes]: a list present in the map
|
||||
* overrides the global default (an empty list = no reminder); absent =
|
||||
* inherit. Agendula offers a single reminder, so each override is a
|
||||
* one-element (or empty) list.
|
||||
*/
|
||||
val perListReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Optional edit-form fields shown by default; the rest sit behind "More fields". */
|
||||
val defaultEditFields: Set<TaskFormField> = emptySet(),
|
||||
) {
|
||||
/** The lead time for a task in [listId]: its override if set, else the global default. */
|
||||
fun reminderLeadFor(listId: Long): Int? =
|
||||
perListReminderOverride.reminderLeadsFor(listId, listOf(reminderLeadMinutes)).firstOrNull()
|
||||
}
|
||||
|
||||
/** App preferences, backed by DataStore. Mirrors Calendula's prefs shape. */
|
||||
@Singleton
|
||||
class SettingsPrefs @Inject constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
val settings: Flow<Settings> = dataStore.data.map { p ->
|
||||
Settings(
|
||||
themeMode = p[THEME_MODE]?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() }
|
||||
?: ThemeMode.SYSTEM,
|
||||
dynamicColor = p[DYNAMIC_COLOR] ?: true,
|
||||
defaultListId = p[DEFAULT_LIST_ID]?.takeIf { it > 0 },
|
||||
reminderLeadMinutes = p[REMINDER_LEAD] ?: 0,
|
||||
remindersEnabled = p[REMINDERS_ENABLED] ?: true,
|
||||
showAddSubtaskRow = p[SHOW_ADD_SUBTASK_ROW] ?: true,
|
||||
bottomAddBar = p[BOTTOM_ADD_BAR] ?: false,
|
||||
perListReminderOverride = reminderCodec.parse(p[LIST_REMINDER_OVERRIDE]),
|
||||
defaultEditFields = p[DEFAULT_EDIT_FIELDS].orEmpty()
|
||||
.mapNotNull { name -> runCatching { TaskFormField.valueOf(name) }.getOrNull() }
|
||||
.toSet(),
|
||||
)
|
||||
}
|
||||
|
||||
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 setDefaultListId(id: Long?) = dataStore.edit {
|
||||
if (id == null) it.remove(DEFAULT_LIST_ID) else it[DEFAULT_LIST_ID] = id
|
||||
}
|
||||
|
||||
suspend fun setReminderLeadMinutes(minutes: Int) = dataStore.edit { it[REMINDER_LEAD] = minutes }
|
||||
|
||||
/** One-time reminder onboarding gate; false until the step has been shown. */
|
||||
val reminderOnboardingDone: Flow<Boolean> = dataStore.data.map { it[REMINDER_ONBOARDING_DONE] ?: false }
|
||||
|
||||
suspend fun setReminderOnboardingDone() = dataStore.edit { it[REMINDER_ONBOARDING_DONE] = true }
|
||||
|
||||
suspend fun setRemindersEnabled(enabled: Boolean) = dataStore.edit { it[REMINDERS_ENABLED] = enabled }
|
||||
|
||||
suspend fun setShowAddSubtaskRow(show: Boolean) = dataStore.edit { it[SHOW_ADD_SUBTASK_ROW] = show }
|
||||
|
||||
suspend fun setBottomAddBar(enabled: Boolean) = dataStore.edit { it[BOTTOM_ADD_BAR] = enabled }
|
||||
|
||||
/** Set (or clear, via [ReminderOverride.Inherit]) a list's reminder override. */
|
||||
suspend fun setListReminderOverride(listId: Long, override: ReminderOverride) = dataStore.edit { p ->
|
||||
val current = reminderCodec.parse(p[LIST_REMINDER_OVERRIDE]).toMutableMap()
|
||||
current.applyReminderOverride(listId, override)
|
||||
p[LIST_REMINDER_OVERRIDE] = reminderCodec.serialize(current)
|
||||
}
|
||||
|
||||
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 REMINDERS_ENABLED = booleanPreferencesKey("reminders_enabled")
|
||||
val SHOW_ADD_SUBTASK_ROW = booleanPreferencesKey("show_add_subtask_row")
|
||||
val BOTTOM_ADD_BAR = booleanPreferencesKey("bottom_add_bar")
|
||||
val REMINDER_ONBOARDING_DONE = booleanPreferencesKey("reminder_onboarding_done")
|
||||
val LIST_REMINDER_OVERRIDE = stringPreferencesKey("list_reminder_override")
|
||||
val DEFAULT_EDIT_FIELDS = stringSetPreferencesKey("default_edit_fields")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Agendula's stored dialect for the per-list override map: `id:minutes` entries
|
||||
* joined by `;` (the family default). Fixed at release — don't change without a
|
||||
* data migration.
|
||||
*/
|
||||
private val reminderCodec = ReminderOverrideCodec.DEFAULT
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.reminders
|
||||
package de.jeanlucmakiola.agendula.data.reminders
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
@@ -1,13 +1,16 @@
|
||||
package de.jeanlucmakiola.floret.data.reminders
|
||||
package de.jeanlucmakiola.agendula.data.reminders
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.net.toUri
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksDataSource
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -21,6 +24,7 @@ class DueReminderReceiver : BroadcastReceiver() {
|
||||
|
||||
@Inject lateinit var dataSource: TasksDataSource
|
||||
@Inject lateinit var notifier: TaskNotifier
|
||||
@Inject lateinit var settingsPrefs: SettingsPrefs
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
@@ -30,6 +34,7 @@ class DueReminderReceiver : BroadcastReceiver() {
|
||||
val pending = goAsync()
|
||||
scope.launch {
|
||||
try {
|
||||
if (!settingsPrefs.settings.first().remindersEnabled) return@launch
|
||||
val task = runCatching { dataSource.task(taskId) }.getOrNull()
|
||||
if (task != null && !task.isClosed) notifier.postDue(task)
|
||||
} finally {
|
||||
@@ -39,9 +44,16 @@ class DueReminderReceiver : BroadcastReceiver() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXTRA_TASK_ID = "de.jeanlucmakiola.floret.extra.TASK_ID"
|
||||
private const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
|
||||
|
||||
fun intent(context: Context, taskId: Long): Intent =
|
||||
Intent(context, DueReminderReceiver::class.java).putExtra(EXTRA_TASK_ID, taskId)
|
||||
/**
|
||||
* [triggerAt] rides in the intent *data*, not just an extra: PendingIntent
|
||||
* identity ignores extras, so two occurrences of the same recurring task
|
||||
* would otherwise collapse into one alarm under FLAG_UPDATE_CURRENT.
|
||||
*/
|
||||
fun intent(context: Context, taskId: Long, triggerAt: Long): Intent =
|
||||
Intent(context, DueReminderReceiver::class.java)
|
||||
.setData("agendula://reminder/$taskId/$triggerAt".toUri())
|
||||
.putExtra(EXTRA_TASK_ID, taskId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package de.jeanlucmakiola.agendula.data.reminders
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.SystemClock
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Re-syncs reminders whenever the tasks provider changes — covers external sync
|
||||
* (DAVx5 pulling new/edited tasks) while Agendula isn't in the foreground. The
|
||||
* manifest filter targets both known authorities; best-effort (the in-app
|
||||
* ContentObserver covers the foreground case regardless).
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class ProviderChangeReceiver : BroadcastReceiver() {
|
||||
|
||||
@Inject lateinit var scheduler: ReminderScheduler
|
||||
@Inject lateinit var providerResolver: ProviderResolver
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
// The receiver has to stay exported to hear the provider's broadcast, and
|
||||
// the sender holds no permission we could require — so validate the
|
||||
// broadcast itself. Without this, any installed app can spam a full
|
||||
// re-sync (an unbounded provider read) by firing a matching intent.
|
||||
if (intent.action != Intent.ACTION_PROVIDER_CHANGED) return
|
||||
val authority = providerResolver.resolve()?.authority ?: return
|
||||
if (intent.data?.host != authority) return
|
||||
// External sync can fire these in bursts; one re-sync per burst is plenty.
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
synchronized(Companion) {
|
||||
if (now - lastSyncAt < MIN_SYNC_INTERVAL_MS) return
|
||||
lastSyncAt = now
|
||||
}
|
||||
|
||||
val pending = goAsync()
|
||||
scope.launch {
|
||||
try {
|
||||
scheduler.sync()
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MIN_SYNC_INTERVAL_MS = 10_000L
|
||||
|
||||
@Volatile
|
||||
var lastSyncAt = -MIN_SYNC_INTERVAL_MS
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package de.jeanlucmakiola.agendula.data.reminders
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* The self-scheduled due-reminder engine. Tasks providers don't deliver
|
||||
* reminders, so Agendula reads upcoming due tasks and arms one exact [AlarmManager]
|
||||
* alarm each, within a rolling window. Re-run on app start, boot and provider
|
||||
* change; it diffs against [ScheduledReminderStore] so only changed alarms move.
|
||||
*/
|
||||
@Singleton
|
||||
class ReminderScheduler @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val dataSource: TasksDataSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val store: ScheduledReminderStore,
|
||||
private val providerResolver: ProviderResolver,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
) {
|
||||
suspend fun sync() = withContext(io) {
|
||||
val provider = providerResolver.resolve()
|
||||
val settings = settingsPrefs.settings.first()
|
||||
if (provider == null || !providerResolver.hasPermission(provider) || !settings.remindersEnabled) {
|
||||
clearAll()
|
||||
return@withContext
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
val horizon = now + WINDOW_MS
|
||||
val tasks = runCatching { dataSource.tasks(TaskQuery(includeCompleted = false)) }
|
||||
.getOrElse { return@withContext }
|
||||
|
||||
// One reminder per *occurrence*: the instances view yields a row per
|
||||
// occurrence, all sharing a taskId, so this is a Set rather than a
|
||||
// taskId-keyed Map — keying by task would collapse a daily recurring task
|
||||
// down to one arbitrary reminder (the query is unsorted, so which one
|
||||
// survived was provider-defined).
|
||||
// Per-task leads, stored as Alarm property rows. One query for all of them.
|
||||
val perTask = runCatching { dataSource.alarms() }.getOrElse { emptyMap() }
|
||||
|
||||
val desired = tasks
|
||||
.filter { !it.isClosed && it.due != null }
|
||||
.mapNotNull { task ->
|
||||
// A reminder set on the task itself wins; otherwise the task's list
|
||||
// may override the global lead, or opt out entirely (override =
|
||||
// null), in which case it gets no reminder at all.
|
||||
val lead = perTask[task.taskId]
|
||||
?: settings.reminderLeadFor(task.listId)
|
||||
?: return@mapNotNull null
|
||||
ScheduledReminder(
|
||||
taskId = task.taskId,
|
||||
triggerAt = task.due!!.toEpochMilliseconds() - lead.coerceAtLeast(0) * 60_000L,
|
||||
)
|
||||
}
|
||||
// The lower bound trails `now` so a reminder missed while the device was
|
||||
// off still fires once on boot instead of being silently dropped —
|
||||
// setExactAndAllowWhileIdle delivers a past trigger immediately. Anything
|
||||
// already armed stays armed (the diff below), so it can't re-fire.
|
||||
.filter { it.triggerAt in (now - MISSED_GRACE_MS)..horizon }
|
||||
.toSet()
|
||||
|
||||
val previous = store.all()
|
||||
(previous - desired).forEach { cancel(it) }
|
||||
(desired - previous).forEach { schedule(it) }
|
||||
store.replace(desired)
|
||||
}
|
||||
|
||||
private fun alarmManager(): AlarmManager = context.getSystemService(AlarmManager::class.java)
|
||||
|
||||
private fun pendingIntent(reminder: ScheduledReminder, create: Boolean): PendingIntent? {
|
||||
val flags = (if (create) PendingIntent.FLAG_UPDATE_CURRENT else PendingIntent.FLAG_NO_CREATE) or
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
return PendingIntent.getBroadcast(
|
||||
context,
|
||||
reminder.requestCode,
|
||||
DueReminderReceiver.intent(context, reminder.taskId, reminder.triggerAt),
|
||||
flags,
|
||||
)
|
||||
}
|
||||
|
||||
private fun schedule(reminder: ScheduledReminder) {
|
||||
val triggerAt = reminder.triggerAt
|
||||
val pi = pendingIntent(reminder, create = true) ?: return
|
||||
val am = alarmManager()
|
||||
val canExact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || am.canScheduleExactAlarms()
|
||||
if (canExact) {
|
||||
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pi)
|
||||
} else {
|
||||
am.set(AlarmManager.RTC_WAKEUP, triggerAt, pi)
|
||||
}
|
||||
}
|
||||
|
||||
private fun cancel(reminder: ScheduledReminder) {
|
||||
pendingIntent(reminder, create = false)?.let {
|
||||
alarmManager().cancel(it)
|
||||
it.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun clearAll() {
|
||||
store.all().forEach { cancel(it) }
|
||||
store.replace(emptySet())
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val WINDOW_MS = 30L * 24 * 60 * 60 * 1000 // 30 days
|
||||
/** How long after its trigger a missed reminder is still worth firing. */
|
||||
const val MISSED_GRACE_MS = 6L * 60 * 60 * 1000 // 6 hours
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package de.jeanlucmakiola.agendula.data.reminders
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||
import kotlinx.coroutines.flow.first
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* One armed alarm. A recurring task has many occurrences sharing a [taskId], so
|
||||
* the trigger time is part of the identity — keying by task alone would collapse
|
||||
* a daily task down to a single reminder.
|
||||
*/
|
||||
data class ScheduledReminder(val taskId: Long, val triggerAt: Long) {
|
||||
/**
|
||||
* Request code for this alarm's PendingIntent. Derived from both fields so
|
||||
* sibling occurrences don't share (and overwrite) one alarm slot.
|
||||
*/
|
||||
val requestCode: Int get() = (taskId * 31 + triggerAt).hashCode()
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers which task reminders are currently armed, so [ReminderScheduler] can
|
||||
* diff against a fresh computation and touch only the alarms that changed.
|
||||
* Persisted in DataStore as a set of `taskId|trigger` strings.
|
||||
*/
|
||||
@Singleton
|
||||
class ScheduledReminderStore @Inject constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
suspend fun all(): Set<ScheduledReminder> =
|
||||
dataStore.data.first()[KEY].orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split('|')
|
||||
val id = parts.getOrNull(0)?.toLongOrNull()
|
||||
val at = parts.getOrNull(1)?.toLongOrNull()
|
||||
if (id != null && at != null) ScheduledReminder(id, at) else null
|
||||
}.toSet()
|
||||
|
||||
suspend fun replace(scheduled: Set<ScheduledReminder>) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[KEY] = scheduled.map { "${it.taskId}|${it.triggerAt}" }.toSet()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val KEY = stringSetPreferencesKey("scheduled_reminders")
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.reminders
|
||||
package de.jeanlucmakiola.agendula.data.reminders
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
@@ -12,9 +12,9 @@ import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import de.jeanlucmakiola.floret.MainActivity
|
||||
import de.jeanlucmakiola.floret.R
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.agendula.MainActivity
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import java.time.Instant as JInstant
|
||||
import java.time.ZoneId
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.ContentUris
|
||||
@@ -9,12 +9,13 @@ import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Instances
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Instances
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Properties
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import java.time.ZoneId
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
@@ -98,6 +99,50 @@ class AndroidTasksDataSource @Inject constructor(
|
||||
if (rows == 0) throw TaskWriteFailedException("update task $taskId")
|
||||
}
|
||||
|
||||
override fun updateInstance(instanceId: Long, form: TaskForm) {
|
||||
val values = TaskWriteMapper.instanceValues(form, ZoneId.systemDefault().id)
|
||||
val uri = TasksContract.instanceUri(authority(), instanceId)
|
||||
val rows = resolver.update(uri, values.toContentValues(), null, null)
|
||||
if (rows == 0) throw TaskWriteFailedException("update instance $instanceId")
|
||||
}
|
||||
|
||||
override fun setAlarm(taskId: Long, minutesBeforeDue: Int?) {
|
||||
val uri = TasksContract.propertiesUri(authority())
|
||||
// Replace rather than update: the provider's AlarmHandler re-validates the
|
||||
// whole row on every update, so a partial edit throws — and delete+insert
|
||||
// means we never have to track property_id.
|
||||
resolver.delete(
|
||||
uri,
|
||||
"${Properties.TASK_ID} = ? AND ${Properties.MIMETYPE} = ?",
|
||||
arrayOf(taskId.toString(), TasksContract.Alarm.MIMETYPE),
|
||||
)
|
||||
if (minutesBeforeDue != null) {
|
||||
resolver.insert(uri, TaskWriteMapper.alarmValues(taskId, minutesBeforeDue).toContentValues())
|
||||
?: throw TaskWriteFailedException("set alarm for task $taskId")
|
||||
}
|
||||
}
|
||||
|
||||
override fun alarms(): Map<Long, Int> {
|
||||
val uri = TasksContract.propertiesUri(authority())
|
||||
val projection = arrayOf(Properties.TASK_ID, TasksContract.Alarm.MINUTES_BEFORE)
|
||||
return resolver.query(
|
||||
uri,
|
||||
projection,
|
||||
"${Properties.MIMETYPE} = ?",
|
||||
arrayOf(TasksContract.Alarm.MIMETYPE),
|
||||
null,
|
||||
)?.use { c ->
|
||||
val reader = CursorColumnReader(c)
|
||||
buildMap {
|
||||
while (c.moveToNext()) {
|
||||
val id = reader.getLong(Properties.TASK_ID)
|
||||
val minutes = reader.getInt(TasksContract.Alarm.MINUTES_BEFORE)
|
||||
if (id != null && minutes != null) put(id, minutes)
|
||||
}
|
||||
}
|
||||
} ?: emptyMap()
|
||||
}
|
||||
|
||||
override fun setCompleted(taskId: Long, completed: Boolean) {
|
||||
val values = TaskWriteMapper.completionValues(completed, System.currentTimeMillis())
|
||||
val rows = resolver.update(taskUri(authority(), taskId), values.toContentValues(), null, null)
|
||||
@@ -127,9 +172,16 @@ class AndroidTasksDataSource @Inject constructor(
|
||||
val observer = object : ContentObserver(Handler(Looper.getMainLooper())) {
|
||||
override fun onChange(selfChange: Boolean) = onChange()
|
||||
}
|
||||
// Register both or neither: if the second call throws, the first
|
||||
// registration would otherwise leak (no AutoCloseable was handed back yet).
|
||||
try {
|
||||
resolver.registerContentObserver(TasksContract.instancesUri(provider.authority), true, observer)
|
||||
resolver.registerContentObserver(TasksContract.listsUri(provider.authority), true, observer)
|
||||
return AutoCloseable { resolver.unregisterContentObserver(observer) }
|
||||
} catch (e: RuntimeException) {
|
||||
runCatching { resolver.unregisterContentObserver(observer) }
|
||||
throw e
|
||||
}
|
||||
return AutoCloseable { runCatching { resolver.unregisterContentObserver(observer) } }
|
||||
}
|
||||
|
||||
private fun Map<String, Any?>.toContentValues(): ContentValues {
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import android.database.Cursor
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
/** No tasks provider (OpenTasks / tasks.org) is installed on the device. */
|
||||
class ProviderUnavailableException :
|
||||
@@ -0,0 +1,31 @@
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.retryWhen
|
||||
|
||||
private const val BASE_RETRY_MS = 1_000L
|
||||
private const val MAX_RETRY_MS = 30_000L
|
||||
|
||||
/** 1s, 2s, 4s … capped at 30s, so a permanently-absent provider costs little. */
|
||||
private fun retryDelayMs(attempt: Long): Long =
|
||||
(BASE_RETRY_MS shl attempt.coerceAtMost(5).toInt()).coerceAtMost(MAX_RETRY_MS)
|
||||
|
||||
/**
|
||||
* Recover a provider-backed flow without killing it.
|
||||
*
|
||||
* Provider reads fail for reasons that resolve on their own: the read permission
|
||||
* isn't granted yet (first launch collects before the permission gate), or the
|
||||
* provider app is mid-update. A terminal `catch` swallows the failure *and*
|
||||
* cancels the upstream, so the flow never produces again — the screen stays empty
|
||||
* until the process restarts, even after the user grants the permission.
|
||||
*
|
||||
* This emits [fallback] instead and keeps retrying with a capped backoff, so the
|
||||
* collector recovers on its own once the provider becomes readable.
|
||||
*/
|
||||
fun <T> Flow<T>.recoveringFromProviderFailure(fallback: () -> T): Flow<T> =
|
||||
retryWhen { _, attempt ->
|
||||
emit(fallback())
|
||||
delay(retryDelayMs(attempt))
|
||||
true
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
@@ -8,7 +8,7 @@ import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* A tasks provider Floret can talk to. The same dmfs `TaskProvider` backs every
|
||||
* A tasks provider Agendula can talk to. The same dmfs `TaskProvider` backs every
|
||||
* candidate, so the [TasksContract] columns apply regardless of which is present.
|
||||
*/
|
||||
data class TaskProvider(
|
||||
@@ -1,12 +1,12 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Instances
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
import de.jeanlucmakiola.floret.domain.priorityFromICal
|
||||
import de.jeanlucmakiola.floret.domain.statusFromInt
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Instances
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.priorityFromICal
|
||||
import de.jeanlucmakiola.agendula.domain.statusFromInt
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** Maps a provider row (via [ColumnReader]) to a domain model. Pure + testable. */
|
||||
@@ -38,7 +38,14 @@ object TaskMapper {
|
||||
listName = r.getString(Tasks.LIST_NAME),
|
||||
accountName = r.getString(Tasks.ACCOUNT_NAME),
|
||||
parentId = r.getLong(Tasks.PARENT_ID),
|
||||
isRecurring = r.getBoolean(Instances.IS_RECURRING),
|
||||
// Derived from the rule columns rather than the `is_recurring` column
|
||||
// alone: that column only exists from OpenTasks 1.4.0 (DB 23) and is
|
||||
// absent on tasks.org's bundled provider (DB 22), where reading it
|
||||
// would silently report every recurring task as one-off — and route
|
||||
// its edits onto the series anchor.
|
||||
isRecurring = r.getString(Tasks.RRULE) != null ||
|
||||
r.getString(Tasks.RDATE) != null ||
|
||||
r.getBoolean(Instances.IS_RECURRING),
|
||||
distanceFromCurrent = r.getInt(Instances.DISTANCE_FROM_CURRENT),
|
||||
created = instant(Tasks.CREATED),
|
||||
lastModified = instant(Tasks.LAST_MODIFIED),
|
||||
@@ -0,0 +1,24 @@
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Lists
|
||||
|
||||
/** Column lists requested from the provider. Order is irrelevant; we read by name. */
|
||||
object TaskProjections {
|
||||
|
||||
val LISTS: Array<String> = arrayOf(
|
||||
Lists.ID,
|
||||
Lists.NAME,
|
||||
Lists.COLOR,
|
||||
Lists.VISIBLE,
|
||||
Lists.SYNC_ENABLED,
|
||||
Lists.OWNER,
|
||||
Lists.ACCOUNT_NAME,
|
||||
Lists.ACCOUNT_TYPE,
|
||||
)
|
||||
|
||||
// No `instances` projection on purpose: that read passes `projection = null`
|
||||
// (all columns), because the view's shape differs across provider versions —
|
||||
// tasks.org's bundled OpenTasks has no `is_recurring`, for one. A fixed list
|
||||
// here would drift out of sync with the by-name mapper and quietly drop
|
||||
// columns it depends on. See AndroidTasksDataSource.queryInstances.
|
||||
}
|
||||
@@ -1,9 +1,21 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.floret.domain.toICal
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Alarm
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Properties
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.domain.toICal
|
||||
import kotlin.time.Instant
|
||||
|
||||
private const val MILLIS_PER_DAY = 24L * 60 * 60 * 1000
|
||||
|
||||
/** Floor to UTC midnight when [allDay], else pass through unchanged. */
|
||||
private fun Instant.forAllDay(allDay: Boolean): Instant =
|
||||
if (!allDay) this
|
||||
else Instant.fromEpochMilliseconds(
|
||||
Math.floorDiv(toEpochMilliseconds(), MILLIS_PER_DAY) * MILLIS_PER_DAY,
|
||||
)
|
||||
|
||||
/**
|
||||
* Turns a [TaskForm] / mutation into a name→value map. Pure (no ContentValues),
|
||||
@@ -39,8 +51,17 @@ object TaskWriteMapper {
|
||||
}
|
||||
}
|
||||
put(Tasks.IS_ALLDAY, if (form.isAllDay) 1 else 0)
|
||||
put(Tasks.DTSTART, form.start?.toEpochMilliseconds())
|
||||
put(Tasks.DUE, form.due?.toEpochMilliseconds())
|
||||
// All-day tasks are date-only in iCalendar. The provider reads them back
|
||||
// through DateTime.toAllDay(), which drops the time-of-day and resolves the
|
||||
// remaining date against UTC — so a local-midnight instant lands on the
|
||||
// previous day for anyone west of UTC. Pin all-day values to UTC midnight.
|
||||
put(Tasks.DTSTART, form.start?.forAllDay(form.isAllDay)?.toEpochMilliseconds())
|
||||
put(Tasks.DUE, form.due?.forAllDay(form.isAllDay)?.toEpochMilliseconds())
|
||||
// DUE and DURATION are mutually exclusive. The provider's Validating
|
||||
// processor evaluates the *merged* row (supplied values over the stored
|
||||
// ones), so writing DUE onto a task that already carries a DURATION throws
|
||||
// "Only one of DUE or DURATION must be supplied." Clear it alongside.
|
||||
put(Tasks.DURATION, null)
|
||||
put(Tasks.PARENT_ID, form.parentId)
|
||||
// The provider treats a null tz as local time; set it explicitly for
|
||||
// timed tasks so the stored instant is unambiguous across zones.
|
||||
@@ -48,6 +69,16 @@ object TaskWriteMapper {
|
||||
put(Tasks.TZ, if (timed) tzId else null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Values for an update through the *instances* URI (a recurring occurrence).
|
||||
* The provider clones the row into an override and strips list/recurrence
|
||||
* fields as it goes, so LIST_ID and PARENT_ID are dropped here rather than
|
||||
* written and silently ignored — moving one occurrence between lists or
|
||||
* parents isn't a thing the override model expresses.
|
||||
*/
|
||||
fun instanceValues(form: TaskForm, tzId: String): Map<String, Any?> =
|
||||
taskValues(form, tzId) - Tasks.LIST_ID - Tasks.PARENT_ID
|
||||
|
||||
fun completionValues(completed: Boolean, nowMillis: Long): Map<String, Any?> =
|
||||
if (completed) {
|
||||
mapOf(
|
||||
@@ -63,6 +94,19 @@ object TaskWriteMapper {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A reminder for [taskId], as an Alarm property row. The provider's validator
|
||||
* requires MINUTES_BEFORE, REFERENCE (non-negative) and ALARM_TYPE on every
|
||||
* write, so all three are always present.
|
||||
*/
|
||||
fun alarmValues(taskId: Long, minutesBeforeDue: Int): Map<String, Any?> = mapOf(
|
||||
Properties.TASK_ID to taskId,
|
||||
Properties.MIMETYPE to Alarm.MIMETYPE,
|
||||
Alarm.MINUTES_BEFORE to minutesBeforeDue,
|
||||
Alarm.REFERENCE to Alarm.REFERENCE_DUE,
|
||||
Alarm.ALARM_TYPE to Alarm.TYPE_MESSAGE,
|
||||
)
|
||||
|
||||
fun localListValues(name: String, color: Int): Map<String, Any?> = mapOf(
|
||||
Lists.NAME to name.trim(),
|
||||
Lists.COLOR to color,
|
||||
@@ -1,9 +1,9 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import android.net.Uri
|
||||
|
||||
/**
|
||||
* The subset of the OpenTasks `TaskContract` that Floret uses, vendored as
|
||||
* The subset of the OpenTasks `TaskContract` that Agendula uses, vendored as
|
||||
* Kotlin constants. Derived from `org.dmfs.tasks.contract.TaskContract`
|
||||
* (Apache-2.0, dmfs GmbH):
|
||||
* https://github.com/dmfs/opentasks/blob/master/opentasks-contract/src/main/java/org/dmfs/tasks/contract/TaskContract.java
|
||||
@@ -25,7 +25,7 @@ object TasksContract {
|
||||
const val PARAM_ACCOUNT_TYPE = "account_type"
|
||||
const val LOAD_PROPERTIES = "load_properties"
|
||||
|
||||
/** Account used for local, device-only task lists Floret owns. */
|
||||
/** Account used for local, device-only task lists Agendula owns. */
|
||||
const val LOCAL_ACCOUNT_NAME = "Local"
|
||||
const val LOCAL_ACCOUNT_TYPE = "org.dmfs.account.LOCAL"
|
||||
|
||||
@@ -66,6 +66,9 @@ object TasksContract {
|
||||
const val IS_ALLDAY = "is_allday"
|
||||
const val TZ = "tz"
|
||||
const val RRULE = "rrule"
|
||||
const val RDATE = "rdate"
|
||||
/** Set on an override row — the master occurrence this one replaces. */
|
||||
const val ORIGINAL_INSTANCE_ID = "original_instance_id"
|
||||
const val PARENT_ID = "parent_id"
|
||||
const val SORTING = "sorting"
|
||||
const val CREATED = "created"
|
||||
@@ -85,7 +88,7 @@ object TasksContract {
|
||||
* The `instances` view — one row per task occurrence, with recurrence
|
||||
* resolved and absolute [INSTANCE_START]/[INSTANCE_DUE] timestamps. Inherits
|
||||
* every [Tasks] column (title, status, …) plus the instance-only columns
|
||||
* below. This is Floret's read source.
|
||||
* below. This is Agendula's read source.
|
||||
*/
|
||||
object Instances {
|
||||
const val PATH = "instances"
|
||||
@@ -98,6 +101,50 @@ object TasksContract {
|
||||
const val IS_RECURRING = "is_recurring"
|
||||
}
|
||||
|
||||
/** The `properties` table — per-task side rows, discriminated by [Properties.MIMETYPE]. */
|
||||
object Properties {
|
||||
const val PATH = "properties"
|
||||
const val PROPERTY_ID = "property_id"
|
||||
const val TASK_ID = "task_id"
|
||||
const val MIMETYPE = "mimetype"
|
||||
}
|
||||
|
||||
/**
|
||||
* An alarm property row — a per-task reminder lead.
|
||||
*
|
||||
* Storage and sync format *only*: the provider fires nothing (its alarm
|
||||
* scheduling is commented out and the internal `alarms` table is never
|
||||
* populated), so [de.jeanlucmakiola.agendula.data.reminders.ReminderScheduler]
|
||||
* still arms the real AlarmManager alarm. Writing it here is what makes the
|
||||
* lead survive a sync and show up in other OpenTasks clients.
|
||||
*
|
||||
* The columns are the generic `dataN` slots; the meanings below are the
|
||||
* Alarm property's contract for them.
|
||||
*/
|
||||
object Alarm {
|
||||
const val MIMETYPE = "vnd.android.cursor.item/alarm"
|
||||
|
||||
/** `data0` — minutes from the reference date; positive means *before* it. */
|
||||
const val MINUTES_BEFORE = "data0"
|
||||
|
||||
/** `data1` — which date to count from. */
|
||||
const val REFERENCE = "data1"
|
||||
|
||||
/** `data2` — optional message shown with the alarm. */
|
||||
const val MESSAGE = "data2"
|
||||
|
||||
/** `data3` — alarm kind. Must be present, and non-zero to count as an alarm. */
|
||||
const val ALARM_TYPE = "data3"
|
||||
|
||||
const val REFERENCE_DUE = 1
|
||||
const val REFERENCE_START = 2
|
||||
|
||||
/** 0 (NOTHING) is excluded from the provider's `has_alarms` count — use MESSAGE. */
|
||||
const val TYPE_MESSAGE = 1
|
||||
}
|
||||
|
||||
fun propertiesUri(authority: String): Uri = Uri.parse("content://$authority/${Properties.PATH}")
|
||||
|
||||
// --- status values (TaskColumns.STATUS_*) --------------------------------
|
||||
const val STATUS_NEEDS_ACTION = 0
|
||||
const val STATUS_IN_PROCESS = 1
|
||||
@@ -112,6 +159,15 @@ object TasksContract {
|
||||
fun tasksUri(authority: String): Uri = Uri.parse("content://$authority/${Tasks.PATH}")
|
||||
fun instancesUri(authority: String): Uri = Uri.parse("content://$authority/${Instances.PATH}")
|
||||
|
||||
/**
|
||||
* A single occurrence. Updating through this URI is how a *recurring* task is
|
||||
* edited: the provider clones the row into an override task
|
||||
* (`original_instance_id` set, recurrence fields stripped) instead of moving
|
||||
* the series anchor, which is what writing to `tasks/<id>` would do.
|
||||
*/
|
||||
fun instanceUri(authority: String, instanceId: Long): Uri =
|
||||
Uri.parse("content://$authority/${Instances.PATH}/$instanceId")
|
||||
|
||||
/** Append the sync-adapter params required to write local-account rows. */
|
||||
fun asSyncAdapter(uri: Uri, accountName: String, accountType: String): Uri =
|
||||
uri.buildUpon()
|
||||
@@ -0,0 +1,51 @@
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
|
||||
/** What to fetch from the provider. Smart-list date logic is applied above this. */
|
||||
data class TaskQuery(
|
||||
val listId: Long? = null,
|
||||
val includeCompleted: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Domain-shaped, synchronous seam over the tasks ContentResolver. Returns parsed
|
||||
* lists so [TasksRepositoryImpl] can be tested with a fake on the JVM. All Cursor
|
||||
* and ContentObserver handling lives in [AndroidTasksDataSource].
|
||||
*/
|
||||
interface TasksDataSource {
|
||||
fun taskLists(): List<TaskList>
|
||||
fun tasks(query: TaskQuery): List<Task>
|
||||
fun task(taskId: Long): Task?
|
||||
fun subtasks(parentTaskId: Long): List<Task>
|
||||
|
||||
fun insertTask(form: TaskForm): Long
|
||||
fun updateTask(taskId: Long, form: TaskForm)
|
||||
|
||||
/**
|
||||
* Update a single occurrence of a recurring task, addressed by its *instance*
|
||||
* row id. The provider forks an override task rather than moving the series
|
||||
* anchor — which is what [updateTask] would do, since a recurring task's
|
||||
* start/due are read from the instances view.
|
||||
*/
|
||||
fun updateInstance(instanceId: Long, form: TaskForm)
|
||||
/**
|
||||
* Set (or clear, with `null`) the per-task reminder lead, stored as an Alarm
|
||||
* property row. The provider never fires it — [de.jeanlucmakiola.agendula
|
||||
* .data.reminders.ReminderScheduler] does — but persisting it here is what
|
||||
* syncs the lead and shares it with other OpenTasks clients.
|
||||
*/
|
||||
fun setAlarm(taskId: Long, minutesBeforeDue: Int?)
|
||||
|
||||
/** Every task's reminder lead, by task id. One query, for the scheduler. */
|
||||
fun alarms(): Map<Long, Int>
|
||||
|
||||
fun setCompleted(taskId: Long, completed: Boolean)
|
||||
fun deleteTask(taskId: Long)
|
||||
fun createLocalList(name: String, color: Int): Long
|
||||
|
||||
/** Observe any change to tasks/lists; [onChange] fires on a background thread. */
|
||||
fun registerObserver(onChange: () -> Unit): AutoCloseable
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskDetail
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskDetail
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** Whether Floret can use the tasks provider right now. Drives onboarding. */
|
||||
/** Whether Agendula can use the tasks provider right now. Drives onboarding. */
|
||||
enum class ProviderStatus { READY, NEEDS_PERMISSION, NO_PROVIDER }
|
||||
|
||||
/**
|
||||
@@ -19,6 +19,13 @@ enum class ProviderStatus { READY, NEEDS_PERMISSION, NO_PROVIDER }
|
||||
interface TasksRepository {
|
||||
fun taskLists(): Flow<List<TaskList>>
|
||||
fun tasks(filter: TaskFilter): Flow<List<Task>>
|
||||
|
||||
/**
|
||||
* The direct children of [parentId], re-emitting live like the other flows.
|
||||
* Lets a smart-list view pull a parent's full subtask set on demand — those
|
||||
* children are usually filtered out of the list's own (date-based) query.
|
||||
*/
|
||||
fun subtasks(parentId: Long): Flow<List<Task>>
|
||||
fun taskDetail(taskId: Long): Flow<TaskDetail?>
|
||||
|
||||
suspend fun createTask(form: TaskForm): Long
|
||||
@@ -32,6 +39,13 @@ interface TasksRepository {
|
||||
suspend fun updateTask(taskId: Long, form: TaskForm, expectedLastModified: Instant? = null)
|
||||
suspend fun setCompleted(taskId: Long, completed: Boolean)
|
||||
suspend fun deleteTask(taskId: Long)
|
||||
|
||||
/**
|
||||
* The per-task reminder lead in minutes before due, or `null` if the task has
|
||||
* none (in which case the list's / global setting applies). Read when the edit
|
||||
* form loads so saving can't silently drop it.
|
||||
*/
|
||||
suspend fun reminderFor(taskId: Long): Int?
|
||||
suspend fun createLocalList(name: String, color: Int): Long
|
||||
|
||||
/** Synchronous snapshot for the permission/onboarding gate. */
|
||||
@@ -1,14 +1,14 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import de.jeanlucmakiola.floret.data.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.domain.DayWindow
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskDetail
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.floret.domain.TaskFiltering
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
import de.jeanlucmakiola.floret.domain.TaskSorting
|
||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskDetail
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFiltering
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
@@ -35,6 +35,12 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
|
||||
override fun tasks(filter: TaskFilter): Flow<List<Task>> = observing { loadTasks(filter) }
|
||||
|
||||
override fun subtasks(parentId: Long): Flow<List<Task>> = observing {
|
||||
dataSource.subtasks(parentId)
|
||||
.filter { it.taskId != parentId }
|
||||
.sortedWith(TaskSorting.DEFAULT)
|
||||
}
|
||||
|
||||
override fun taskDetail(taskId: Long): Flow<TaskDetail?> = observing {
|
||||
dataSource.task(taskId)?.let { task ->
|
||||
TaskDetail(
|
||||
@@ -74,19 +80,40 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
}
|
||||
|
||||
override suspend fun createTask(form: TaskForm): Long =
|
||||
withContext(io) { dataSource.insertTask(form) }
|
||||
withContext(io) {
|
||||
val id = dataSource.insertTask(form)
|
||||
form.reminderMinutesBeforeDue?.let { dataSource.setAlarm(id, it) }
|
||||
id
|
||||
}
|
||||
|
||||
override suspend fun reminderFor(taskId: Long): Int? =
|
||||
withContext(io) { runCatching { dataSource.alarms()[taskId] }.getOrNull() }
|
||||
|
||||
override suspend fun updateTask(taskId: Long, form: TaskForm, expectedLastModified: Instant?) =
|
||||
withContext(io) {
|
||||
// Conflict-safe overwrite: re-read just before writing and bail if the
|
||||
// provider's last_modified moved since the form captured it (external
|
||||
// sync / another app). A null baseline means "force / overwrite anyway".
|
||||
// Re-read just before writing: it settles the conflict check *and* tells
|
||||
// us which URI to write through.
|
||||
val current = dataSource.task(taskId)
|
||||
// Conflict-safe overwrite: bail if the provider's last_modified moved
|
||||
// since the form captured it (external sync / another app). A null
|
||||
// baseline means "force / overwrite anyway".
|
||||
if (expectedLastModified != null) {
|
||||
val current = dataSource.task(taskId)?.lastModified
|
||||
if (current != null && current != expectedLastModified) throw TaskConflictException(taskId)
|
||||
val seen = current?.lastModified
|
||||
if (seen != null && seen != expectedLastModified) throw TaskConflictException(taskId)
|
||||
}
|
||||
// Write the reminder first: forking a recurring occurrence copies the
|
||||
// task's properties onto the new override row, so setting the alarm
|
||||
// beforehand is what carries it across.
|
||||
dataSource.setAlarm(taskId, form.reminderMinutesBeforeDue)
|
||||
// A recurring task's start/due come from the instances view, so writing
|
||||
// them back to tasks/<id> would re-anchor the whole series. Going through
|
||||
// the occurrence lets the provider fork an override instead.
|
||||
if (current != null && current.isRecurring) {
|
||||
dataSource.updateInstance(current.id, form)
|
||||
} else {
|
||||
dataSource.updateTask(taskId, form)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun setCompleted(taskId: Long, completed: Boolean) =
|
||||
withContext(io) { dataSource.setCompleted(taskId, completed) }
|
||||
@@ -0,0 +1,42 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import java.time.ZoneId
|
||||
import java.time.ZoneOffset
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* All-day tasks are date-only in iCalendar. OpenTasks reads them back through
|
||||
* `DateTime.toAllDay()`, which discards the time-of-day and resolves the
|
||||
* remaining date against UTC — so the storage convention is **UTC midnight of
|
||||
* the intended calendar date, with a null timezone**. Timed tasks, by contrast,
|
||||
* are ordinary instants rendered in the device's zone.
|
||||
*
|
||||
* These two conventions disagree about which day a given instant is, which is
|
||||
* why every all-day value needs an explicit conversion rather than a raw
|
||||
* `Instant` passed straight through.
|
||||
*/
|
||||
|
||||
/** UTC midnight of [date] — the storage form for an all-day value. */
|
||||
fun allDayInstantOf(date: java.time.LocalDate): Instant =
|
||||
Instant.fromEpochMilliseconds(date.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli())
|
||||
|
||||
/**
|
||||
* The calendar date this instant denotes: read in UTC for [allDay] values,
|
||||
* in [zone] for timed ones.
|
||||
*/
|
||||
fun Instant.calendarDate(allDay: Boolean, zone: ZoneId = ZoneId.systemDefault()): java.time.LocalDate =
|
||||
java.time.Instant.ofEpochMilli(toEpochMilliseconds())
|
||||
.atZone(if (allDay) ZoneOffset.UTC else zone)
|
||||
.toLocalDate()
|
||||
|
||||
/**
|
||||
* Move an instant across the two conventions when the all-day switch flips, so
|
||||
* the day the user is looking at stays put. Without this, toggling all-day off
|
||||
* turns a UTC-midnight value into "02:00" in Berlin (or the previous day, 19:00,
|
||||
* in New York) — reading to the user as "the time reset itself".
|
||||
*/
|
||||
fun Instant.rebasedForAllDay(allDay: Boolean, zone: ZoneId = ZoneId.systemDefault()): Instant =
|
||||
if (allDay) allDayInstantOf(calendarDate(allDay = false, zone = zone))
|
||||
else Instant.fromEpochMilliseconds(
|
||||
calendarDate(allDay = true).atStartOfDay(zone).toInstant().toEpochMilli(),
|
||||
)
|
||||
@@ -1,6 +1,6 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** A task list (the `tasklists` table). Lists group under their account. */
|
||||
@@ -14,7 +14,7 @@ data class TaskList(
|
||||
val isVisible: Boolean,
|
||||
val owner: String?,
|
||||
) {
|
||||
/** A device-only list Floret (or another app) created locally, not synced. */
|
||||
/** A device-only list Agendula (or another app) created locally, not synced. */
|
||||
val isLocal: Boolean get() = accountType == TasksContract.LOCAL_ACCOUNT_TYPE
|
||||
}
|
||||
|
||||
@@ -48,6 +48,12 @@ data class Task(
|
||||
val listName: String?,
|
||||
val accountName: String?,
|
||||
val parentId: Long?,
|
||||
/**
|
||||
* This row carries a recurrence rule, so [id] is one occurrence of a series
|
||||
* and [start]/[due] are that occurrence's resolved times — *not* the master's
|
||||
* anchor. Edits must go through the instances URI (see
|
||||
* [de.jeanlucmakiola.agendula.data.tasks.TasksContract.instanceUri]).
|
||||
*/
|
||||
val isRecurring: Boolean,
|
||||
val distanceFromCurrent: Int?,
|
||||
val created: Instant?,
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import kotlin.time.Instant
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* A validated create/edit form. Kept free of Android types so ViewModels and
|
||||
* tests can build and validate it on the JVM. The data layer turns it into
|
||||
* provider ContentValues ([de.jeanlucmakiola.floret.data.tasks.TaskWriteMapper]).
|
||||
* provider ContentValues ([de.jeanlucmakiola.agendula.data.tasks.TaskWriteMapper]).
|
||||
*/
|
||||
data class TaskForm(
|
||||
val title: String,
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import kotlin.time.Instant
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
/** Default task ordering, extracted so it's unit-testable without the repository. */
|
||||
object TaskSorting {
|
||||
@@ -1,7 +1,8 @@
|
||||
package de.jeanlucmakiola.floret.ui
|
||||
package de.jeanlucmakiola.agendula.ui
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.Crossfade
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -10,21 +11,27 @@ import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.floret.R
|
||||
import de.jeanlucmakiola.floret.data.tasks.ProviderStatus
|
||||
import de.jeanlucmakiola.floret.ui.navigation.FloretNavHost
|
||||
import de.jeanlucmakiola.floret.ui.permission.PermissionViewModel
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderStatus
|
||||
import de.jeanlucmakiola.agendula.ui.navigation.AgendulaNavHost
|
||||
import de.jeanlucmakiola.agendula.ui.permission.PermissionViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.permission.ReminderOnboardingScreen
|
||||
import de.jeanlucmakiola.agendula.ui.permission.ReminderOnboardingViewModel
|
||||
|
||||
/**
|
||||
* App root: gates on the tasks-provider permission, then hands off to
|
||||
* [FloretNavHost] (lists → task list → detail / edit).
|
||||
* [AgendulaNavHost] (lists → task list → detail / edit).
|
||||
*/
|
||||
@Composable
|
||||
fun RootScreen(
|
||||
@@ -36,6 +43,18 @@ fun RootScreen(
|
||||
ActivityResultContracts.RequestMultiplePermissions(),
|
||||
) { permissionViewModel.refresh() }
|
||||
|
||||
// Re-check on every resume, not just after the in-app request: the user may
|
||||
// have granted the permission (or installed a provider) in system Settings and
|
||||
// come back, and otherwise the gate would hold until the process restarts.
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) permissionViewModel.refresh()
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
|
||||
when (permission.status) {
|
||||
ProviderStatus.NO_PROVIDER -> Gate(
|
||||
modifier = modifier,
|
||||
@@ -49,7 +68,31 @@ fun RootScreen(
|
||||
action = stringResource(R.string.onboarding_permission_button),
|
||||
onAction = { launcher.launch(permission.permissionsToRequest.toTypedArray()) },
|
||||
)
|
||||
ProviderStatus.READY -> FloretNavHost(modifier = modifier)
|
||||
ProviderStatus.READY -> ReadyGate(modifier = modifier)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Second one-time gate after the provider grant: the reminder onboarding step.
|
||||
* [ReminderOnboardingViewModel.onboardingDone] is null until DataStore's first
|
||||
* emission — render nothing for that frame rather than flash the wrong screen.
|
||||
* A cross-fade eases the hand-off to the app instead of snapping.
|
||||
*/
|
||||
@Composable
|
||||
private fun ReadyGate(
|
||||
modifier: Modifier = Modifier,
|
||||
onboardingViewModel: ReminderOnboardingViewModel = hiltViewModel(),
|
||||
) {
|
||||
val done by onboardingViewModel.onboardingDone.collectAsStateWithLifecycle()
|
||||
Crossfade(targetState = done, label = "reminderOnboardingGate") { state ->
|
||||
when (state) {
|
||||
true -> AgendulaNavHost(modifier = modifier)
|
||||
false -> ReminderOnboardingScreen(
|
||||
onFinished = onboardingViewModel::finish,
|
||||
modifier = modifier,
|
||||
)
|
||||
null -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.jeanlucmakiola.floret.ui.common
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -22,24 +23,10 @@ import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* Soften a raw provider colour toward a pastel that fits the active theme —
|
||||
* keeps the hue (lists stay recognisable), caps saturation so harsh sync
|
||||
* colours stop screaming, pins brightness to read on light and dark. Copied
|
||||
* from Calendula so the families' colours behave identically.
|
||||
*/
|
||||
fun pastelize(rawArgb: Int, dark: Boolean): Color {
|
||||
val hsv = FloatArray(3)
|
||||
android.graphics.Color.colorToHSV(rawArgb, hsv)
|
||||
hsv[1] = (hsv[1] * 0.6f).coerceIn(0.25f, 0.65f)
|
||||
hsv[2] = if (dark) 0.82f else 0.72f
|
||||
return Color(android.graphics.Color.HSVToColor(hsv))
|
||||
}
|
||||
|
||||
/**
|
||||
* Leading avatar for a task list: a neutral round chip holding a checklist glyph
|
||||
* tinted in the list's (pastelised) colour — the Calendula calendar-chip pattern,
|
||||
* with a task icon for Floret.
|
||||
* with a task icon for Agendula.
|
||||
*/
|
||||
@Composable
|
||||
fun ListColorChip(color: Int, modifier: Modifier = Modifier) {
|
||||
@@ -0,0 +1,20 @@
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* Zone helpers shared by the date/time pickers. All-day conversions live in
|
||||
* [de.jeanlucmakiola.agendula.domain.AllDayTime] — these cover the timed case,
|
||||
* where the device zone is the right frame of reference.
|
||||
*/
|
||||
|
||||
private val zone: ZoneId get() = ZoneId.systemDefault()
|
||||
|
||||
internal fun Instant.toLocalTime(): LocalTime =
|
||||
java.time.Instant.ofEpochMilli(toEpochMilliseconds()).atZone(zone).toLocalTime()
|
||||
|
||||
internal fun localToInstant(date: LocalDate, time: LocalTime): Instant =
|
||||
Instant.fromEpochMilliseconds(date.atTime(time).atZone(zone).toInstant().toEpochMilli())
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.jeanlucmakiola.floret.ui.common
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -21,7 +22,7 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.isSpecified
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.floret.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
|
||||
/**
|
||||
* Priority has no semantic Material role (M3 only ships `error` for danger), so
|
||||
@@ -44,6 +45,27 @@ fun priorityFill(priority: Priority, dark: Boolean): Color {
|
||||
return Color(android.graphics.Color.HSVToColor(hsv))
|
||||
}
|
||||
|
||||
/**
|
||||
* Foreground tint (icon/text) for a priority level — the same red/amber/green as
|
||||
* [priorityFill], but kept saturated enough to read as a small glyph directly on
|
||||
* the surface rather than as a soft fill. Used by the task list's quiet meta line,
|
||||
* where priority is a tinted flag instead of a filled pill. [Priority.NONE] is
|
||||
* unspecified (callers render it neutral / omit it).
|
||||
*/
|
||||
fun priorityAccent(priority: Priority, dark: Boolean): Color {
|
||||
val base = when (priority) {
|
||||
Priority.HIGH -> 0xFFE53935.toInt() // red
|
||||
Priority.MEDIUM -> 0xFFFB8C00.toInt() // orange-amber (darker than the fill for contrast)
|
||||
Priority.LOW -> 0xFF43A047.toInt() // green
|
||||
Priority.NONE -> return Color.Unspecified
|
||||
}
|
||||
val hsv = FloatArray(3)
|
||||
android.graphics.Color.colorToHSV(base, hsv)
|
||||
hsv[1] = if (dark) 0.55f else 0.85f
|
||||
hsv[2] = if (dark) 0.85f else 0.62f // light on dark surfaces; deep on light ones
|
||||
return Color(android.graphics.Color.HSVToColor(hsv))
|
||||
}
|
||||
|
||||
/**
|
||||
* A coloured status pill for a task's priority: a flag plus the level's [label],
|
||||
* filled in that level's pastel hue. Used read-only in the list and detail
|
||||
@@ -90,14 +112,14 @@ fun PriorityChip(
|
||||
|
||||
val body: @Composable () -> Unit = {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (showIcon) {
|
||||
Icon(Icons.Rounded.Flag, contentDescription = null, tint = iconTint, modifier = Modifier.size(15.dp))
|
||||
Icon(Icons.Rounded.Flag, contentDescription = null, tint = iconTint, modifier = Modifier.size(14.dp))
|
||||
}
|
||||
Text(label, style = MaterialTheme.typography.labelMedium, color = content)
|
||||
Text(label, style = MaterialTheme.typography.labelSmall, color = content)
|
||||
}
|
||||
}
|
||||
val shape = RoundedCornerShape(50)
|
||||
@@ -0,0 +1,37 @@
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
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.floret.reminders.ReminderUnit
|
||||
|
||||
/** Common reminder lead times offered as quick picks in the reminder pickers. */
|
||||
val REMINDER_PRESETS = listOf(0, 5, 10, 30, 60, 1_440)
|
||||
|
||||
@StringRes
|
||||
fun reminderUnitLabel(unit: ReminderUnit): Int = when (unit) {
|
||||
ReminderUnit.Minutes -> R.string.reminder_unit_minutes
|
||||
ReminderUnit.Hours -> R.string.reminder_unit_hours
|
||||
ReminderUnit.Days -> R.string.reminder_unit_days
|
||||
ReminderUnit.Weeks -> R.string.reminder_unit_weeks
|
||||
}
|
||||
|
||||
/**
|
||||
* Humanise a reminder lead time (minutes before due) into one line: "At time of
|
||||
* task" (0), "10 minutes before", "1 hour before", … Shared by the reminder
|
||||
* pickers and the settings summaries so the wording never drifts. Ported from
|
||||
* Calendula.
|
||||
*/
|
||||
@Composable
|
||||
fun reminderLeadTimeLabel(minutes: Int): String = when {
|
||||
minutes <= 0 -> stringResource(R.string.reminder_at_due)
|
||||
minutes % 10_080 == 0 ->
|
||||
pluralStringResource(R.plurals.reminder_weeks, minutes / 10_080, minutes / 10_080)
|
||||
minutes % 1_440 == 0 ->
|
||||
pluralStringResource(R.plurals.reminder_days, minutes / 1_440, minutes / 1_440)
|
||||
minutes % 60 == 0 ->
|
||||
pluralStringResource(R.plurals.reminder_hours, minutes / 60, minutes / 60)
|
||||
else -> pluralStringResource(R.plurals.reminder_minutes, minutes, minutes)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.components.DialogAmountField
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderUnit
|
||||
import de.jeanlucmakiola.floret.reminders.decomposeReminderMinutes
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
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.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
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.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
|
||||
/**
|
||||
* Reminder lead-time picker, full-screen: the grouped list of preset lead times
|
||||
* plus a "Custom" row that expands an inline amount field + unit selector.
|
||||
* [allowInherit] adds a "Use default" row (per-list overrides); [allowNone] adds
|
||||
* a "None" row. Returns the choice as a [ReminderOverride]. Ported from
|
||||
* Calendula's ReminderDefaultPicker.
|
||||
*/
|
||||
@Composable
|
||||
fun ReminderLeadPicker(
|
||||
title: String,
|
||||
selected: ReminderOverride,
|
||||
allowInherit: Boolean,
|
||||
allowNone: Boolean,
|
||||
onSelect: (ReminderOverride) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
presets: List<Int> = REMINDER_PRESETS,
|
||||
) {
|
||||
// Agendula is single-reminder: an override carries a one-element list, so
|
||||
// take the single value for this single-select picker.
|
||||
val selectedMinutes = (selected as? ReminderOverride.Minutes)?.minutes?.firstOrNull()
|
||||
val customSelected = selectedMinutes != null && selectedMinutes !in presets
|
||||
val seed = decomposeReminderMinutes(selectedMinutes?.takeIf { customSelected })
|
||||
|
||||
var customExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var amountText by rememberSaveable { mutableStateOf(seed.amount?.toString() ?: "") }
|
||||
var unit by rememberSaveable { mutableStateOf(seed.unit) }
|
||||
|
||||
val options = buildList {
|
||||
if (allowInherit) add(ReminderOverride.Inherit)
|
||||
if (allowNone) add(ReminderOverride.None)
|
||||
presets.forEach { add(ReminderOverride.Minutes(listOf(it))) }
|
||||
}
|
||||
val rowCount = options.size + 1 // + the custom row
|
||||
|
||||
FullScreenPicker(title = title, onDismiss = onDismiss) {
|
||||
options.forEachIndexed { index, option ->
|
||||
val isSelected = option == selected
|
||||
GroupedRow(
|
||||
title = reminderOverrideLabel(option),
|
||||
position = positionOf(index, rowCount),
|
||||
selected = isSelected,
|
||||
onClick = {
|
||||
onSelect(option)
|
||||
onDismiss()
|
||||
},
|
||||
)
|
||||
}
|
||||
// Expanded, the Custom row connects downward into the editor card so the
|
||||
// two read as one grouped container.
|
||||
GroupedRow(
|
||||
title = if (customSelected) {
|
||||
stringResource(R.string.reminder_custom_with_value, reminderLeadTimeLabel(selectedMinutes!!))
|
||||
} else {
|
||||
stringResource(R.string.reminder_custom)
|
||||
},
|
||||
position = if (customExpanded) Position.Top else positionOf(options.size, rowCount),
|
||||
selected = customSelected,
|
||||
onClick = { customExpanded = !customExpanded },
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = customExpanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
CustomReminderEditor(
|
||||
amountText = amountText,
|
||||
onAmountChange = { amountText = it },
|
||||
unit = unit,
|
||||
onUnitChange = { unit = it },
|
||||
onConfirm = { minutes ->
|
||||
onSelect(ReminderOverride.Minutes(listOf(minutes)))
|
||||
onDismiss()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CustomReminderEditor(
|
||||
amountText: String,
|
||||
onAmountChange: (String) -> Unit,
|
||||
unit: ReminderUnit,
|
||||
onUnitChange: (ReminderUnit) -> Unit,
|
||||
onConfirm: (Int) -> Unit,
|
||||
) {
|
||||
val amount = amountText.toIntOrNull()?.takeIf { it in 1..999 }
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
// A Position.Bottom shape: tight top corners meeting the row, full bottom.
|
||||
shape = RoundedCornerShape(topStart = 6.dp, topEnd = 6.dp, bottomStart = 22.dp, bottomEnd = 22.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
ReminderUnit.entries.forEachIndexed { index, entry ->
|
||||
SegmentedButton(
|
||||
selected = unit == entry,
|
||||
onClick = { onUnitChange(entry) },
|
||||
shape = SegmentedButtonDefaults.itemShape(index, ReminderUnit.entries.size),
|
||||
label = { Text(stringResource(reminderUnitLabel(entry))) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
DialogAmountField(value = amountText, onValueChange = onAmountChange, placeholder = "10")
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Text(
|
||||
text = amount?.let { reminderLeadTimeLabel(it * unit.minutesFactor) }
|
||||
?: stringResource(R.string.reminder_custom_amount),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(16.dp))
|
||||
FilledTonalButton(
|
||||
onClick = { amount?.let { onConfirm(it * unit.minutesFactor) } },
|
||||
enabled = amount != null,
|
||||
) {
|
||||
Text(stringResource(R.string.reminder_custom_set))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun reminderOverrideLabel(override: ReminderOverride): String = when (override) {
|
||||
ReminderOverride.Inherit -> stringResource(R.string.reminder_use_default)
|
||||
ReminderOverride.None -> stringResource(R.string.reminder_none)
|
||||
is ReminderOverride.Minutes -> reminderLeadTimeLabel(override.minutes.first())
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package de.jeanlucmakiola.agendula.ui.common
|
||||
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
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.toShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.graphics.shapes.RoundedPolygon
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@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,
|
||||
) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
// 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),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package de.jeanlucmakiola.agendula.ui.crash
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.ui.Modifier
|
||||
import de.jeanlucmakiola.agendula.ui.theme.AgendulaTheme
|
||||
import de.jeanlucmakiola.floret.crash.CrashReportDialog
|
||||
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||
import de.jeanlucmakiola.floret.crash.submitCrashReport
|
||||
|
||||
/**
|
||||
* Standalone surface for a captured crash report. [MainActivity] routes here
|
||||
* when it detects a startup crash-loop (see [CrashReporter.isCrashLoop]): the
|
||||
* main UI can't be trusted to start, so this screen stays clear of the app's
|
||||
* Hilt graph, DataStore-backed theme and Compose content — it only reads the
|
||||
* report file and shows the kit's report dialog. Plain [AgendulaTheme] defaults
|
||||
* (follow-system, dynamic colour) avoid touching anything that might be the
|
||||
* cause of the crash. The reusable machinery lives in floret-kit's core-crash.
|
||||
*/
|
||||
class CrashReportActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val report = CrashReporter.pendingReport(this)
|
||||
if (report == null) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
AgendulaTheme {
|
||||
// Opaque backdrop so the dialog doesn't float over a bare task.
|
||||
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {}
|
||||
CrashReportDialog(
|
||||
report = report,
|
||||
onSend = {
|
||||
submitCrashReport(this, report)
|
||||
CrashReporter.clearReport(this)
|
||||
finish()
|
||||
},
|
||||
onDismiss = {
|
||||
CrashReporter.clearReport(this)
|
||||
finish()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
// Reaching this screen breaks the loop; reset the timing trail so a
|
||||
// later ordinary crash isn't mistaken for a loop.
|
||||
CrashReporter.markHealthy(this)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.ui.detail
|
||||
package de.jeanlucmakiola.agendula.ui.detail
|
||||
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.background
|
||||
@@ -67,16 +67,16 @@ import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.floret.R
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskDetail
|
||||
import de.jeanlucmakiola.floret.ui.common.GroupedSurface
|
||||
import de.jeanlucmakiola.floret.ui.common.PriorityChip
|
||||
import de.jeanlucmakiola.floret.ui.common.formatDate
|
||||
import de.jeanlucmakiola.floret.ui.common.formatTime
|
||||
import de.jeanlucmakiola.floret.ui.common.pastelize
|
||||
import de.jeanlucmakiola.floret.ui.common.positionOf
|
||||
import de.jeanlucmakiola.floret.ui.tasklist.priorityLabel
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskDetail
|
||||
import de.jeanlucmakiola.floret.components.GroupedSurface
|
||||
import de.jeanlucmakiola.agendula.ui.common.PriorityChip
|
||||
import de.jeanlucmakiola.floret.time.formatDate
|
||||
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
|
||||
|
||||
/**
|
||||
* One task's detail. Each fact is its own tonal card with a leading icon (the
|
||||
@@ -246,7 +246,7 @@ private fun DetailBody(
|
||||
}
|
||||
|
||||
// Priority — a coloured status chip in the level's hue.
|
||||
if (task.priority != de.jeanlucmakiola.floret.domain.Priority.NONE) {
|
||||
if (task.priority != de.jeanlucmakiola.agendula.domain.Priority.NONE) {
|
||||
add {
|
||||
DetailCard(
|
||||
icon = Icons.Rounded.Flag,
|
||||
@@ -501,13 +501,16 @@ private fun taskWhenLines(task: Task): Pair<String, String?>? {
|
||||
val due = task.due
|
||||
return when {
|
||||
start != null && due != null -> {
|
||||
val sameDay = start.formatDate() == due.formatDate()
|
||||
val primary = if (sameDay) due.formatDate() else "${start.formatDate()} – ${due.formatDate()}"
|
||||
val secondary = if (task.isAllDay) null else "${start.formatTime()} – ${due.formatTime()}"
|
||||
val allDay = task.isAllDay
|
||||
val sameDay = start.formatDate(allDay) == due.formatDate(allDay)
|
||||
val primary =
|
||||
if (sameDay) due.formatDate(allDay)
|
||||
else "${start.formatDate(allDay)} – ${due.formatDate(allDay)}"
|
||||
val secondary = if (allDay) null else "${start.formatTime()} – ${due.formatTime()}"
|
||||
primary to secondary
|
||||
}
|
||||
due != null -> due.formatDate() to if (task.isAllDay) null else due.formatTime()
|
||||
start != null -> start.formatDate() to if (task.isAllDay) null else start.formatTime()
|
||||
due != null -> due.formatDate(task.isAllDay) to if (task.isAllDay) null else due.formatTime()
|
||||
start != null -> start.formatDate(task.isAllDay) to if (task.isAllDay) null else start.formatTime()
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
package de.jeanlucmakiola.floret.ui.detail
|
||||
package de.jeanlucmakiola.agendula.ui.detail
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskDetail
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskDetail
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -42,7 +42,7 @@ class TaskDetailViewModel @Inject constructor(
|
||||
if (detail == null) TaskDetailUiState.NotFound else TaskDetailUiState.Content(detail)
|
||||
}
|
||||
.onStart { emit(TaskDetailUiState.Loading) }
|
||||
.catch { emit(TaskDetailUiState.NotFound) }
|
||||
.recoveringFromProviderFailure { TaskDetailUiState.NotFound }
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), TaskDetailUiState.Loading)
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
package de.jeanlucmakiola.floret.ui.edit
|
||||
package de.jeanlucmakiola.agendula.ui.edit
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
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.clickable
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
@@ -85,27 +80,29 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.floret.R
|
||||
import de.jeanlucmakiola.floret.domain.DayWindow
|
||||
import de.jeanlucmakiola.floret.domain.Priority
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskFormError
|
||||
import de.jeanlucmakiola.floret.domain.TaskFormField
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
import de.jeanlucmakiola.floret.domain.TaskSection
|
||||
import de.jeanlucmakiola.floret.domain.TaskSections
|
||||
import de.jeanlucmakiola.floret.ui.common.GroupedRow
|
||||
import de.jeanlucmakiola.floret.ui.common.InlineTextField
|
||||
import de.jeanlucmakiola.floret.ui.common.OptionCard
|
||||
import de.jeanlucmakiola.floret.ui.common.priorityFill
|
||||
import de.jeanlucmakiola.floret.ui.common.formatDate
|
||||
import de.jeanlucmakiola.floret.ui.common.formatTime
|
||||
import de.jeanlucmakiola.floret.ui.common.localToInstant
|
||||
import de.jeanlucmakiola.floret.ui.common.pastelize
|
||||
import de.jeanlucmakiola.floret.ui.common.positionOf
|
||||
import de.jeanlucmakiola.floret.ui.common.toLocalDate
|
||||
import de.jeanlucmakiola.floret.ui.common.toLocalTime
|
||||
import de.jeanlucmakiola.floret.ui.tasklist.priorityLabel
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFormError
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFormField
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSection
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSections
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.OptionalFormSection
|
||||
import de.jeanlucmakiola.floret.components.InlineTextField
|
||||
import de.jeanlucmakiola.floret.components.OptionCard
|
||||
import de.jeanlucmakiola.agendula.ui.common.priorityFill
|
||||
import de.jeanlucmakiola.floret.time.formatDate
|
||||
import de.jeanlucmakiola.floret.time.formatTime
|
||||
import de.jeanlucmakiola.agendula.ui.common.localToInstant
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
|
||||
import de.jeanlucmakiola.agendula.domain.calendarDate
|
||||
import de.jeanlucmakiola.agendula.ui.common.toLocalTime
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.priorityLabel
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.time.ZoneOffset
|
||||
@@ -119,7 +116,7 @@ import kotlin.time.Instant
|
||||
* "When" card with the all-day toggle and tappable schedule rows, a tappable
|
||||
* list card, and the optional Description / Priority / Reminder sections that
|
||||
* unfold from "More fields" (which ones start open is a setting). Validated
|
||||
* through the M1 [TaskEditViewModel] / [de.jeanlucmakiola.floret.domain.TaskForm];
|
||||
* through the M1 [TaskEditViewModel] / [de.jeanlucmakiola.agendula.domain.TaskForm];
|
||||
* the VM flips `saved` once the write lands, which pops us back.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@@ -182,7 +179,7 @@ private fun EditContent(
|
||||
val accent = selectedList?.let { pastelize(it.color, dark) } ?: MaterialTheme.colorScheme.primary
|
||||
val gap = 12.dp
|
||||
|
||||
var pickerTarget by remember { mutableStateOf<PickerTarget?>(null) }
|
||||
var pickerTarget by rememberSaveable { mutableStateOf<PickerTarget?>(null) }
|
||||
var showListPicker by rememberSaveable { mutableStateOf(false) }
|
||||
var showParentPicker by rememberSaveable { mutableStateOf(false) }
|
||||
var showReminderPicker by rememberSaveable { mutableStateOf(false) }
|
||||
@@ -545,17 +542,6 @@ private fun EditContent(
|
||||
* open instead of popping in. (Initially-visible sections render without
|
||||
* animating on the first frame they're added.)
|
||||
*/
|
||||
@Composable
|
||||
private fun OptionalFormSection(visible: Boolean, content: @Composable ColumnScope.() -> Unit) {
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = expandVertically() + fadeIn(),
|
||||
exit = shrinkVertically() + fadeOut(),
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth(), content = content)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One info card mirroring the detail screen's card: tonal container, leading
|
||||
* icon in the gutter, value to the right. Optionally clickable as a whole.
|
||||
@@ -668,7 +654,7 @@ private fun ScheduleRow(
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = value.formatDate(),
|
||||
text = value.formatDate(allDay),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = valueColor,
|
||||
modifier = Modifier.clickable(onClick = onPick).padding(vertical = 8.dp, horizontal = 6.dp),
|
||||
@@ -704,12 +690,15 @@ private fun DateTimePickerFlow(
|
||||
onResult: (Instant) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var pendingDate by remember { mutableStateOf<java.time.LocalDate?>(null) }
|
||||
var showTime by remember { mutableStateOf(false) }
|
||||
var pendingDate by rememberSaveable { mutableStateOf<java.time.LocalDate?>(null) }
|
||||
var showTime by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
if (!showTime) {
|
||||
// M3's DatePicker speaks UTC millis. An all-day value is already UTC-based,
|
||||
// a timed one is read in the device zone — calendarDate picks the right frame
|
||||
// so the dialog opens on the day the rest of the UI shows.
|
||||
val initialMillis = (initial ?: nowInstant())
|
||||
.toLocalDate().atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
|
||||
.calendarDate(allDay).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
|
||||
val dateState = rememberDatePickerState(initialSelectedDateMillis = initialMillis)
|
||||
DatePickerDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -718,7 +707,7 @@ private fun DateTimePickerFlow(
|
||||
val millis = dateState.selectedDateMillis ?: run { onDismiss(); return@TextButton }
|
||||
val date = java.time.Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate()
|
||||
if (allDay) {
|
||||
onResult(localToInstant(date, LocalTime.MIDNIGHT))
|
||||
onResult(allDayInstantOf(date))
|
||||
} else {
|
||||
pendingDate = date
|
||||
showTime = true
|
||||
@@ -853,7 +842,7 @@ private fun ParentPickerSheet(
|
||||
item(key = "none") {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.edit_parent_none),
|
||||
position = de.jeanlucmakiola.floret.ui.common.Position.Alone,
|
||||
position = de.jeanlucmakiola.floret.components.Position.Alone,
|
||||
selected = selectedId == null,
|
||||
minHeight = 56.dp,
|
||||
onClick = { choose(null) },
|
||||
@@ -880,7 +869,7 @@ private fun ParentPickerSheet(
|
||||
GroupedRow(
|
||||
title = task.title.ifBlank { stringResource(R.string.task_untitled) },
|
||||
position = positionOf(index, section.tasks.size),
|
||||
summary = task.due?.formatDate(),
|
||||
summary = task.due?.formatDate(task.isAllDay),
|
||||
selected = task.taskId == selectedId,
|
||||
minHeight = 56.dp,
|
||||
onClick = { choose(task.taskId) },
|
||||
@@ -1,20 +1,21 @@
|
||||
package de.jeanlucmakiola.floret.ui.edit
|
||||
package de.jeanlucmakiola.agendula.ui.edit
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.floret.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.floret.data.reminders.ReminderScheduler
|
||||
import de.jeanlucmakiola.floret.data.tasks.TaskConflictException
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.floret.domain.Priority
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.floret.domain.TaskFormError
|
||||
import de.jeanlucmakiola.floret.domain.TaskFormField
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
import de.jeanlucmakiola.floret.domain.populatedFields
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.reminders.ReminderScheduler
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TaskConflictException
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFormError
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFormField
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.populatedFields
|
||||
import de.jeanlucmakiola.agendula.domain.rebasedForAllDay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -70,6 +71,15 @@ class TaskEditViewModel @Inject constructor(
|
||||
|
||||
private var editingTaskId: Long? = null
|
||||
|
||||
/**
|
||||
* Whether the form has already been populated. The host `LaunchedEffect`
|
||||
* re-fires whenever the composition restarts — an Activity recreation
|
||||
* (rotation, theme/font/display-size change, split-screen, unfolding) — while
|
||||
* this ViewModel survives on the nav back stack. Without this guard the
|
||||
* rebind would overwrite in-progress edits with the untouched provider row.
|
||||
*/
|
||||
private var bound = false
|
||||
|
||||
/** `last_modified` captured when the form loaded — the conflict-check baseline. */
|
||||
private var baselineLastModified: Instant? = null
|
||||
|
||||
@@ -78,6 +88,8 @@ class TaskEditViewModel @Inject constructor(
|
||||
|
||||
/** Start a fresh task, optionally pre-selecting a list / parent. */
|
||||
fun bindNew(presetListId: Long? = null, parentId: Long? = null) {
|
||||
if (bound) return
|
||||
bound = true
|
||||
editingTaskId = null
|
||||
baselineLastModified = null
|
||||
viewModelScope.launch {
|
||||
@@ -103,6 +115,8 @@ class TaskEditViewModel @Inject constructor(
|
||||
|
||||
/** Load an existing task for editing. */
|
||||
fun bindEdit(taskId: Long) {
|
||||
if (bound && editingTaskId == taskId) return
|
||||
bound = true
|
||||
editingTaskId = taskId
|
||||
viewModelScope.launch {
|
||||
defaultFields = settingsPrefs.settings.first().defaultEditFields
|
||||
@@ -126,6 +140,7 @@ class TaskEditViewModel @Inject constructor(
|
||||
priority = task.priority,
|
||||
parentId = task.parentId,
|
||||
percentComplete = task.percentComplete,
|
||||
reminderMinutesBeforeDue = repository.reminderFor(taskId),
|
||||
lists = lists,
|
||||
parentCandidates = loadParents(task.listId, selfId = taskId),
|
||||
),
|
||||
@@ -178,7 +193,19 @@ class TaskEditViewModel @Inject constructor(
|
||||
|
||||
fun onStartChange(value: Instant?) = update { it.copy(start = value) }
|
||||
fun onDueChange(value: Instant?) = update { it.copy(due = value) }
|
||||
fun onAllDayChange(value: Boolean) = update { it.copy(isAllDay = value) }
|
||||
/**
|
||||
* All-day and timed values use different conventions (UTC midnight vs. a real
|
||||
* instant in the device zone), so the switch has to move the timestamps too —
|
||||
* flipping the flag alone makes an all-day task read back as "02:00", which
|
||||
* looks to the user like the time reset itself.
|
||||
*/
|
||||
fun onAllDayChange(value: Boolean) = update {
|
||||
it.copy(
|
||||
isAllDay = value,
|
||||
start = it.start?.rebasedForAllDay(value),
|
||||
due = it.due?.rebasedForAllDay(value),
|
||||
)
|
||||
}
|
||||
fun onPriorityChange(value: Priority) = update { it.copy(priority = value) }
|
||||
fun onPercentChange(value: Int?) = update { it.copy(percentComplete = value?.coerceIn(0, 100)) }
|
||||
fun onParentChange(parentId: Long?) = update { it.copy(parentId = parentId) }
|
||||
@@ -0,0 +1,689 @@
|
||||
package de.jeanlucmakiola.agendula.ui.lists
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.expandHorizontally
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkHorizontally
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
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.PaddingValues
|
||||
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.statusBarsPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
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.ChevronRight
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.ErrorOutline
|
||||
import androidx.compose.material.icons.rounded.Flag
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material.icons.rounded.Today
|
||||
import androidx.compose.material.icons.rounded.Upcoming
|
||||
import androidx.compose.material3.CircularWavyProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
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.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.ui.common.ActionShapes
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.agendula.ui.common.ListColorChip
|
||||
import de.jeanlucmakiola.agendula.ui.common.ShapedActionButton
|
||||
import de.jeanlucmakiola.agendula.ui.common.priorityAccent
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.priorityLabel
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.time.formatDateTimeCompact
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
/**
|
||||
* Home: a Today progress hero (wavy ring over tasks due today), an Overdue + All
|
||||
* 2-up of tonal tiles, a live preview of the next upcoming tasks, then the user's
|
||||
* lists grouped by account. Tapping a tile opens that smart list, an upcoming row
|
||||
* opens that task, and the FAB starts a new task. The search action in the top bar
|
||||
* slides open into a full-width field that filters every task by title.
|
||||
*/
|
||||
@Composable
|
||||
fun ListsScreen(
|
||||
onOpenFilter: (TaskFilter) -> Unit,
|
||||
onOpenTask: (Long) -> Unit,
|
||||
onNewTask: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: ListsViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var searchActive by rememberSaveable { mutableStateOf(false) }
|
||||
val closeSearch = {
|
||||
query = ""
|
||||
searchActive = false
|
||||
}
|
||||
// System back closes search before leaving the screen.
|
||||
BackHandler(enabled = searchActive, onBack = closeSearch)
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier,
|
||||
topBar = {
|
||||
HomeTopBar(
|
||||
searchActive = searchActive,
|
||||
query = query,
|
||||
onQueryChange = { query = it },
|
||||
onToggleSearch = { if (searchActive) closeSearch() else searchActive = true },
|
||||
onOpenSettings = onOpenSettings,
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
// The FAB would otherwise float over the search results.
|
||||
if (!searchActive) {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onNewTask,
|
||||
icon = { Icon(Icons.Rounded.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.new_task)) },
|
||||
)
|
||||
}
|
||||
},
|
||||
) { inner ->
|
||||
Box(Modifier.fillMaxSize().padding(top = inner.calculateTopPadding())) {
|
||||
when (val s = state) {
|
||||
ListsUiState.Loading -> Unit // brief; avoids a flash before first emission
|
||||
ListsUiState.Failure ->
|
||||
CenteredMessage(stringResource(R.string.lists_failure), PaddingValues(0.dp))
|
||||
is ListsUiState.Content -> {
|
||||
ListsContent(
|
||||
state = s,
|
||||
onOpenFilter = onOpenFilter,
|
||||
onOpenTask = onOpenTask,
|
||||
topPadding = 0.dp,
|
||||
bottomPadding = inner.calculateBottomPadding() + 96.dp,
|
||||
)
|
||||
// While searching with a non-blank query, results cover the home
|
||||
// content; an empty query leaves the home content visible behind
|
||||
// the open field.
|
||||
if (searchActive) {
|
||||
SearchResults(
|
||||
query = query,
|
||||
allTasks = s.allTasks,
|
||||
onOpenTask = { taskId ->
|
||||
closeSearch()
|
||||
onOpenTask(taskId)
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ListsContent(
|
||||
state: ListsUiState.Content,
|
||||
onOpenFilter: (TaskFilter) -> Unit,
|
||||
onOpenTask: (Long) -> Unit,
|
||||
topPadding: androidx.compose.ui.unit.Dp,
|
||||
bottomPadding: androidx.compose.ui.unit.Dp,
|
||||
) {
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(
|
||||
top = topPadding,
|
||||
bottom = bottomPadding,
|
||||
),
|
||||
) {
|
||||
item {
|
||||
TodayHero(
|
||||
done = state.todayDone,
|
||||
total = state.todayTotal,
|
||||
onClick = { onOpenFilter(TaskFilter.Smart(SmartList.TODAY)) },
|
||||
)
|
||||
}
|
||||
// Overdue + All sit below the Today hero as a quieter 2-up; Upcoming is no
|
||||
// longer a count tile — it becomes the live preview further down.
|
||||
item {
|
||||
SmartPairRow(
|
||||
counts = state.smartCounts.filter {
|
||||
it.smart == SmartList.OVERDUE || it.smart == SmartList.ALL
|
||||
},
|
||||
onOpenFilter = onOpenFilter,
|
||||
)
|
||||
}
|
||||
|
||||
if (state.upcoming.isNotEmpty()) {
|
||||
item { SectionHeader(stringResource(R.string.smart_upcoming)) }
|
||||
item {
|
||||
UpcomingPreview(
|
||||
tasks = state.upcoming,
|
||||
onOpenTask = onOpenTask,
|
||||
onViewAll = { onOpenFilter(TaskFilter.Smart(SmartList.UPCOMING)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (state.groups.isEmpty()) {
|
||||
item { CenteredMessage(stringResource(R.string.lists_empty), PaddingValues(top = 24.dp)) }
|
||||
} else {
|
||||
item { SectionHeader(stringResource(R.string.lists_header)) }
|
||||
state.groups.forEach { group ->
|
||||
item(key = "acct-${group.accountName}") { AccountHeader(group.accountName) }
|
||||
itemsIndexed(group.lists, key = { _, o -> o.list.id }) { index, overview ->
|
||||
GroupedRow(
|
||||
title = overview.list.name,
|
||||
position = positionOf(index, group.lists.size),
|
||||
minHeight = 72.dp,
|
||||
leading = { ListColorChip(overview.list.color) },
|
||||
trailing = {
|
||||
if (overview.openCount > 0) {
|
||||
Text(
|
||||
overview.openCount.toString(),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
onClick = { onOpenFilter(TaskFilter.OfList(overview.list.id)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The home top bar. There is no title — the launcher icon already says which app
|
||||
* this is. Settings is pinned at the right; the search action sits just left of it
|
||||
* and stays put. Tapping search unfurls a pill to its left (the field grows out
|
||||
* from the icon's side) while the search icon remains as the bar's fixed trailing
|
||||
* icon, so neither action moves.
|
||||
*/
|
||||
@Composable
|
||||
private fun HomeTopBar(
|
||||
searchActive: Boolean,
|
||||
query: String,
|
||||
onQueryChange: (String) -> Unit,
|
||||
onToggleSearch: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
) {
|
||||
Surface(color = MaterialTheme.colorScheme.surface) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.statusBarsPadding()
|
||||
.height(72.dp)
|
||||
.padding(horizontal = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
// Search occupies the flexible space left of settings. Pulled into its
|
||||
// own composable so AnimatedVisibility resolves to the plain overload —
|
||||
// a RowScope receiver in here would make that call ambiguous.
|
||||
SearchSlot(
|
||||
searchActive = searchActive,
|
||||
query = query,
|
||||
onQueryChange = onQueryChange,
|
||||
onToggleSearch = onToggleSearch,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
ShapedActionButton(
|
||||
shape = ActionShapes.Settings,
|
||||
icon = Icons.Rounded.Settings,
|
||||
contentDescription = stringResource(R.string.settings_title),
|
||||
onClick = onOpenSettings,
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
size = 48.dp,
|
||||
iconSize = 26.dp,
|
||||
spinIcon = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The search action and the field it unfurls. The magnifier is pinned to the end
|
||||
* (right) of this slot and never moves; tapping it toggles search. When active a
|
||||
* pill expands leftward from it ([expandHorizontally] anchored at the end) holding
|
||||
* the query field, so the icon reads as the bar's fixed trailing icon.
|
||||
*/
|
||||
@Composable
|
||||
private fun SearchSlot(
|
||||
searchActive: Boolean,
|
||||
query: String,
|
||||
onQueryChange: (String) -> Unit,
|
||||
onToggleSearch: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Box(modifier = modifier, contentAlignment = Alignment.CenterEnd) {
|
||||
AnimatedVisibility(
|
||||
visible = searchActive,
|
||||
enter = expandHorizontally(tween(300), expandFrom = Alignment.End) + fadeIn(tween(280)),
|
||||
exit = shrinkHorizontally(tween(220), shrinkTowards = Alignment.End) + fadeOut(tween(140)),
|
||||
) {
|
||||
SearchPill(
|
||||
query = query,
|
||||
onQueryChange = onQueryChange,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
// Always on top, at the end — the bar's fixed search icon and toggle.
|
||||
ShapedActionButton(
|
||||
shape = ActionShapes.Search,
|
||||
icon = Icons.Rounded.Search,
|
||||
contentDescription = stringResource(R.string.home_search_hint),
|
||||
onClick = onToggleSearch,
|
||||
size = 48.dp,
|
||||
iconSize = 26.dp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The expanding search input pill: the query field (auto-focused on open) and a
|
||||
* clear button once there is text. Its trailing 48dp is left empty for the search
|
||||
* icon that [SearchSlot] overlays at the end.
|
||||
*/
|
||||
@Composable
|
||||
private fun SearchPill(
|
||||
query: String,
|
||||
onQueryChange: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { focusRequester.requestFocus() }
|
||||
Surface(
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
modifier = modifier.height(52.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(start = 18.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
BasicTextField(
|
||||
value = query,
|
||||
onValueChange = onQueryChange,
|
||||
singleLine = true,
|
||||
textStyle = MaterialTheme.typography.bodyLarge.copy(
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(),
|
||||
modifier = Modifier.weight(1f).focusRequester(focusRequester),
|
||||
decorationBox = { innerField ->
|
||||
Box(contentAlignment = Alignment.CenterStart) {
|
||||
if (query.isEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.home_search_hint),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
innerField()
|
||||
}
|
||||
},
|
||||
)
|
||||
if (query.isNotEmpty()) {
|
||||
IconButton(onClick = { onQueryChange("") }) {
|
||||
Icon(
|
||||
Icons.Rounded.Close,
|
||||
contentDescription = stringResource(R.string.home_search_clear),
|
||||
)
|
||||
}
|
||||
}
|
||||
// Space reserved for the search icon SearchSlot overlays at the end.
|
||||
Spacer(Modifier.width(48.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search results overlaying the home content: tasks whose title matches the query,
|
||||
* across every list (completed included), open ones first. A blank query renders
|
||||
* nothing so the home content shows through behind the open field.
|
||||
*/
|
||||
@Composable
|
||||
private fun SearchResults(
|
||||
query: String,
|
||||
allTasks: List<Task>,
|
||||
onOpenTask: (Long) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
if (query.isBlank()) return
|
||||
val results = remember(query, allTasks) {
|
||||
val q = query.trim()
|
||||
allTasks
|
||||
.filter { it.title.contains(q, ignoreCase = true) }
|
||||
.sortedWith(compareBy({ it.isCompleted }, { it.title.lowercase() }))
|
||||
}
|
||||
Surface(modifier = modifier, color = MaterialTheme.colorScheme.surface) {
|
||||
if (results.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.TopCenter) {
|
||||
Text(
|
||||
text = stringResource(R.string.home_search_empty, query.trim()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
items(results, key = { it.id }) { task ->
|
||||
UpcomingRow(task = task, onClick = { onOpenTask(task.taskId) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The day's momentum: a wavy progress ring over "x of y done" for tasks due today.
|
||||
* Tapping opens the Today list. When nothing is due today it drops the ring and
|
||||
* reads as a calm, finished state rather than an empty 0.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
private fun TodayHero(done: Int, total: Int, onClick: () -> Unit) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
val corner by animateDpAsState(if (pressed) 34.dp else 22.dp, label = "todayCorner")
|
||||
val left = total - done
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
shape = RoundedCornerShape(corner),
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
interactionSource = interaction,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(140.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxSize().padding(20.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(Icons.Rounded.Today, contentDescription = null, modifier = Modifier.size(20.dp))
|
||||
Text(stringResource(R.string.smart_today), style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
val headline = when {
|
||||
total == 0 -> stringResource(R.string.home_today_empty)
|
||||
left == 0 -> stringResource(R.string.home_today_all_done)
|
||||
else -> stringResource(R.string.home_today_progress, done, total)
|
||||
}
|
||||
Text(headline, style = MaterialTheme.typography.headlineSmall)
|
||||
if (total > 0 && left > 0) {
|
||||
Text(
|
||||
stringResource(R.string.home_today_remaining, left),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (total > 0) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(84.dp)) {
|
||||
CircularWavyProgressIndicator(
|
||||
progress = { done.toFloat() / total },
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
trackColor = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.22f),
|
||||
)
|
||||
Text("$done/$total", style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Overdue + All as a 2-up row of the existing tonal tiles. */
|
||||
@Composable
|
||||
private fun SmartPairRow(counts: List<SmartCount>, onOpenFilter: (TaskFilter) -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
counts.forEach { smart ->
|
||||
SmartCard(
|
||||
count = smart,
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = { onOpenFilter(TaskFilter.Smart(smart.smart)) },
|
||||
)
|
||||
}
|
||||
if (counts.size == 1) Spacer(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
/** A grouped card previewing the next few upcoming tasks, with a "view all" tail. */
|
||||
@Composable
|
||||
private fun UpcomingPreview(
|
||||
tasks: List<Task>,
|
||||
onOpenTask: (Long) -> Unit,
|
||||
onViewAll: () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
) {
|
||||
Column {
|
||||
tasks.forEach { task ->
|
||||
UpcomingRow(task = task, onClick = { onOpenTask(task.taskId) })
|
||||
}
|
||||
Surface(onClick = onViewAll, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.home_upcoming_view_all),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Icon(
|
||||
Icons.Rounded.ChevronRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One slim upcoming row: list-colour avatar, title, then a quiet meta line of the
|
||||
* relative due date and (if set) a tinted priority flag — the same calm one-line
|
||||
* treatment as the task list, minus the swipe machinery.
|
||||
*/
|
||||
@Composable
|
||||
private fun UpcomingRow(task: Task, onClick: () -> Unit) {
|
||||
val dark = isSystemInDarkTheme()
|
||||
val muted = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
val metaStyle = MaterialTheme.typography.bodySmall
|
||||
Surface(onClick = onClick, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 60.dp).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
ListColorChip(task.effectiveColor)
|
||||
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
task.title,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
upcomingDueLabel(task)?.let { Text(it, style = metaStyle, color = muted) }
|
||||
if (task.priority != Priority.NONE) {
|
||||
Text("·", style = metaStyle, color = muted)
|
||||
Icon(
|
||||
Icons.Rounded.Flag,
|
||||
contentDescription = null,
|
||||
tint = priorityAccent(task.priority, dark),
|
||||
modifier = Modifier.size(13.dp),
|
||||
)
|
||||
Text(priorityLabel(task.priority), style = metaStyle, color = muted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** "Today" / "Tomorrow" for the near dates, else the compact date. */
|
||||
@Composable
|
||||
private fun upcomingDueLabel(task: Task): String? {
|
||||
val due = task.due ?: return null
|
||||
val zone = remember { ZoneId.systemDefault() }
|
||||
val today = remember { LocalDate.now(zone) }
|
||||
val dueDate = remember(due) {
|
||||
java.time.Instant.ofEpochMilli(due.toEpochMilliseconds()).atZone(zone).toLocalDate()
|
||||
}
|
||||
return when (dueDate) {
|
||||
today -> stringResource(R.string.home_due_today)
|
||||
today.plusDays(1) -> stringResource(R.string.home_due_tomorrow)
|
||||
else -> due.formatDateTimeCompact(task.isAllDay)
|
||||
}
|
||||
}
|
||||
|
||||
private data class SmartStyle(val icon: ImageVector, val labelRes: Int, val container: Color, val onContainer: Color)
|
||||
|
||||
@Composable
|
||||
private fun smartStyle(smart: SmartList): SmartStyle {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
return when (smart) {
|
||||
SmartList.TODAY -> SmartStyle(Icons.Rounded.Today, R.string.smart_today, colors.primaryContainer, colors.onPrimaryContainer)
|
||||
SmartList.OVERDUE -> SmartStyle(Icons.Rounded.ErrorOutline, R.string.smart_overdue, colors.errorContainer, colors.onErrorContainer)
|
||||
SmartList.UPCOMING -> SmartStyle(Icons.Rounded.Upcoming, R.string.smart_upcoming, colors.tertiaryContainer, colors.onTertiaryContainer)
|
||||
else -> SmartStyle(Icons.AutoMirrored.Rounded.ListAlt, R.string.smart_all, colors.secondaryContainer, colors.onSecondaryContainer)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean tonal tile. The expressive touch is subtle: rounded corners gently morph
|
||||
* rounder on press (the same quiet shape behaviour as the lists), not a loud
|
||||
* silhouette.
|
||||
*/
|
||||
@Composable
|
||||
private fun SmartCard(count: SmartCount, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val style = smartStyle(count.smart)
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
val corner by animateDpAsState(if (pressed) 34.dp else 22.dp, label = "smartCorner")
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
shape = RoundedCornerShape(corner),
|
||||
color = style.container,
|
||||
contentColor = style.onContainer,
|
||||
interactionSource = interaction,
|
||||
modifier = modifier.height(116.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||
verticalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Icon(style.icon, contentDescription = null)
|
||||
Column {
|
||||
Text(count.count.toString(), style = MaterialTheme.typography.headlineMedium)
|
||||
Text(stringResource(style.labelRes), style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionHeader(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 16.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AccountHeader(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 12.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CenteredMessage(text: String, inner: PaddingValues) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize().padding(inner).padding(32.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package de.jeanlucmakiola.agendula.ui.lists
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
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.SmartList
|
||||
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 kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import java.time.ZoneId
|
||||
import javax.inject.Inject
|
||||
import kotlin.time.Clock
|
||||
|
||||
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)
|
||||
|
||||
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>,
|
||||
/** Every task (open and completed) — the corpus the home search filters. */
|
||||
val allTasks: List<Task>,
|
||||
) : ListsUiState
|
||||
}
|
||||
|
||||
private const val UPCOMING_PREVIEW = 3
|
||||
|
||||
/** The home overview: smart lists with live counts, then user lists by account. */
|
||||
@HiltViewModel
|
||||
class ListsViewModel @Inject constructor(
|
||||
repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
val state: StateFlow<ListsUiState> =
|
||||
combine(
|
||||
repository.taskLists(),
|
||||
repository.tasks(TaskFilter.Smart(SmartList.ALL)),
|
||||
// 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)),
|
||||
) { lists, openTasks, completedTasks ->
|
||||
buildContent(lists, openTasks, completedTasks) as ListsUiState
|
||||
}.recoveringFromProviderFailure { ListsUiState.Failure }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListsUiState.Loading)
|
||||
|
||||
private fun buildContent(
|
||||
lists: List<TaskList>,
|
||||
openTasks: List<Task>,
|
||||
completedTasks: List<Task>,
|
||||
): ListsUiState.Content {
|
||||
val (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
|
||||
// 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 }
|
||||
fun count(smart: SmartList) =
|
||||
topLevel.count { TaskFiltering.matches(it, TaskFilter.Smart(smart), todayStart, todayEnd) }
|
||||
|
||||
val smartCounts = listOf(
|
||||
SmartCount(SmartList.TODAY, count(SmartList.TODAY)),
|
||||
SmartCount(SmartList.OVERDUE, count(SmartList.OVERDUE)),
|
||||
SmartCount(SmartList.UPCOMING, count(SmartList.UPCOMING)),
|
||||
SmartCount(SmartList.ALL, topLevel.size),
|
||||
)
|
||||
|
||||
// Today ring: completed vs. total tasks *due today*. The numerator is the
|
||||
// top-level completed tasks whose due date falls in today's window; the
|
||||
// denominator adds the still-open ones (the Today smart count above).
|
||||
val openToday = count(SmartList.TODAY)
|
||||
val completedDueToday = completedTasks.count {
|
||||
!it.isSubtask && it.due != null && it.due >= todayStart && it.due < todayEnd
|
||||
}
|
||||
val todayTotal = openToday + completedDueToday
|
||||
|
||||
// Upcoming preview: the next handful of open tasks due tomorrow onward,
|
||||
// already sorted by the repository's default ordering.
|
||||
val upcoming = topLevel
|
||||
.filter { TaskFiltering.matches(it, TaskFilter.Smart(SmartList.UPCOMING), todayStart, todayEnd) }
|
||||
.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) },
|
||||
)
|
||||
}
|
||||
.sortedBy { it.accountName.lowercase() }
|
||||
return ListsUiState.Content(
|
||||
smartCounts = smartCounts,
|
||||
groups = groups,
|
||||
todayDone = completedDueToday,
|
||||
todayTotal = todayTotal,
|
||||
upcoming = upcoming,
|
||||
allTasks = openTasks + completedTasks,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package de.jeanlucmakiola.floret.ui.navigation
|
||||
package de.jeanlucmakiola.agendula.ui.navigation
|
||||
|
||||
import androidx.compose.animation.EnterTransition
|
||||
import androidx.compose.animation.ExitTransition
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -12,14 +12,15 @@ import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.floret.ui.detail.TaskDetailScreen
|
||||
import de.jeanlucmakiola.floret.ui.detail.TaskDetailViewModel
|
||||
import de.jeanlucmakiola.floret.ui.edit.TaskEditScreen
|
||||
import de.jeanlucmakiola.floret.ui.edit.TaskEditViewModel
|
||||
import de.jeanlucmakiola.floret.ui.lists.ListsScreen
|
||||
import de.jeanlucmakiola.floret.ui.tasklist.TaskListScreen
|
||||
import de.jeanlucmakiola.floret.ui.tasklist.TaskListViewModel
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.ui.detail.TaskDetailScreen
|
||||
import de.jeanlucmakiola.agendula.ui.detail.TaskDetailViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.edit.TaskEditScreen
|
||||
import de.jeanlucmakiola.agendula.ui.edit.TaskEditViewModel
|
||||
import de.jeanlucmakiola.agendula.ui.lists.ListsScreen
|
||||
import de.jeanlucmakiola.agendula.ui.settings.SettingsScreen
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.TaskListScreen
|
||||
import de.jeanlucmakiola.agendula.ui.tasklist.TaskListViewModel
|
||||
|
||||
/**
|
||||
* The single in-app back stack: lists → task list → detail / edit.
|
||||
@@ -31,9 +32,8 @@ import de.jeanlucmakiola.floret.ui.tasklist.TaskListViewModel
|
||||
* unaware of the nav library.
|
||||
*/
|
||||
@Composable
|
||||
fun FloretNavHost(modifier: Modifier = Modifier) {
|
||||
fun AgendulaNavHost(modifier: Modifier = Modifier) {
|
||||
val nav = rememberNavController()
|
||||
val slide = rememberNavSlideSpec()
|
||||
|
||||
NavHost(
|
||||
navController = nav,
|
||||
@@ -41,20 +41,27 @@ fun FloretNavHost(modifier: Modifier = Modifier) {
|
||||
modifier = modifier,
|
||||
// Only the screen on top moves; the background is always held static.
|
||||
// Forward is a plain fade-in over the held screen — calm, not a slide.
|
||||
// Back (and the predictive-back drag, which drives popExit) is the snappy
|
||||
// slide-out to the right, revealing the held screen unmoved.
|
||||
// Back is the predictive-back peek: navigation-compose composes the
|
||||
// screen being revealed underneath and seeks popExit with the gesture, so
|
||||
// the leaving screen scales down to reveal the (unmoved) previous screen.
|
||||
enterTransition = { fadeIn() },
|
||||
exitTransition = { ExitTransition.None },
|
||||
popEnterTransition = { EnterTransition.None },
|
||||
popExitTransition = { slideOutHorizontally(slide) { it } + fadeOut() },
|
||||
popExitTransition = { scaleOut(targetScale = 0.9f) + fadeOut() },
|
||||
) {
|
||||
composable(Dest.LISTS) {
|
||||
ListsScreen(
|
||||
onOpenFilter = { filter -> nav.navigate(Dest.TaskList.build(filter)) },
|
||||
onOpenTask = { taskId -> nav.navigate(Dest.TaskDetail.build(taskId)) },
|
||||
onNewTask = { nav.navigate(Dest.TaskEdit.buildNew()) },
|
||||
onOpenSettings = { nav.navigate(Dest.SETTINGS) },
|
||||
)
|
||||
}
|
||||
|
||||
composable(Dest.SETTINGS) {
|
||||
SettingsScreen(onBack = { nav.popBackStack() })
|
||||
}
|
||||
|
||||
composable(Dest.TaskList.route, arguments = Dest.TaskList.arguments) { entry ->
|
||||
val args = entry.arguments
|
||||
val filter = Dest.TaskList.filterOf(
|
||||
@@ -1,9 +1,9 @@
|
||||
package de.jeanlucmakiola.floret.ui.navigation
|
||||
package de.jeanlucmakiola.agendula.ui.navigation
|
||||
|
||||
import androidx.navigation.NavType
|
||||
import androidx.navigation.navArgument
|
||||
import de.jeanlucmakiola.floret.domain.SmartList
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
|
||||
/**
|
||||
* String-based route table for the app's [androidx.navigation.NavHost].
|
||||
@@ -23,6 +23,9 @@ object Dest {
|
||||
/** Home — smart lists + the user's lists. */
|
||||
const val LISTS = "lists"
|
||||
|
||||
/** App preferences. */
|
||||
const val SETTINGS = "settings"
|
||||
|
||||
/**
|
||||
* One [TaskFilter]'s tasks. Carries *either* `listId` (a real list) *or*
|
||||
* `smart` (a [SmartList] name); whichever is set decides the filter.
|
||||
@@ -0,0 +1,36 @@
|
||||
package de.jeanlucmakiola.agendula.ui.permission
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* Agendula's onboarding hero: an icon in the brand squircle. Each app keeps its
|
||||
* own hero; the surrounding shell comes from floret-kit's OnboardingScaffold.
|
||||
*/
|
||||
@Composable
|
||||
internal fun SquircleHero(icon: ImageVector) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(128.dp)
|
||||
.clip(RoundedCornerShape(34.dp))
|
||||
.background(MaterialTheme.colorScheme.primaryContainer),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.size(56.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package de.jeanlucmakiola.floret.ui.permission
|
||||
package de.jeanlucmakiola.agendula.ui.permission
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.floret.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.floret.data.tasks.ProviderStatus
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderStatus
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -0,0 +1,114 @@
|
||||
package de.jeanlucmakiola.agendula.ui.permission
|
||||
|
||||
import android.Manifest
|
||||
import android.os.Build
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Edit
|
||||
import androidx.compose.material.icons.rounded.Notifications
|
||||
import androidx.compose.material.icons.rounded.Schedule
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.floret.components.BenefitRow
|
||||
import de.jeanlucmakiola.floret.components.OnboardingScaffold
|
||||
import de.jeanlucmakiola.floret.components.OnboardingSpace
|
||||
|
||||
/**
|
||||
* One-time onboarding step after the tasks-provider grant: explains that Agendula
|
||||
* delivers due reminders itself (tasks providers don't broadcast reminders) and
|
||||
* requests `POST_NOTIFICATIONS` (a system dialog on API 33+ only).
|
||||
*
|
||||
* Reminders default ON: [onFinished] gets true from the primary action even if
|
||||
* the system dialog is declined — the OS permission is the real gate, and the
|
||||
* Settings toggle re-requests it. "Not now" turns the in-app toggle off.
|
||||
*/
|
||||
@Composable
|
||||
fun ReminderOnboardingScreen(
|
||||
onFinished: (remindersEnabled: Boolean) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val launcher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission(),
|
||||
) { onFinished(true) }
|
||||
|
||||
OnboardingScaffold(
|
||||
modifier = modifier,
|
||||
hero = { SquircleHero(Icons.Rounded.Notifications) },
|
||||
actions = {
|
||||
Button(
|
||||
onClick = {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
onFinished(true)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().height(56.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.reminder_onboarding_enable_button),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
}
|
||||
TextButton(
|
||||
onClick = { onFinished(false) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.reminder_onboarding_skip_button))
|
||||
}
|
||||
},
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.app_name).uppercase(),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
letterSpacing = 2.sp,
|
||||
)
|
||||
Spacer(Modifier.height(OnboardingSpace.xs))
|
||||
Text(
|
||||
text = stringResource(R.string.reminder_onboarding_title),
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.reminder_onboarding_body),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(OnboardingSpace.xl))
|
||||
|
||||
BenefitRow(
|
||||
icon = Icons.Rounded.Notifications,
|
||||
title = stringResource(R.string.reminder_benefit_delivery_title),
|
||||
body = stringResource(R.string.reminder_benefit_delivery_body),
|
||||
)
|
||||
Spacer(Modifier.height(OnboardingSpace.sm))
|
||||
BenefitRow(
|
||||
icon = Icons.Rounded.Schedule,
|
||||
title = stringResource(R.string.reminder_benefit_timing_title),
|
||||
body = stringResource(R.string.reminder_benefit_timing_body),
|
||||
)
|
||||
Spacer(Modifier.height(OnboardingSpace.sm))
|
||||
BenefitRow(
|
||||
icon = Icons.Rounded.Edit,
|
||||
title = stringResource(R.string.reminder_benefit_reversible_title),
|
||||
body = stringResource(R.string.reminder_benefit_reversible_body),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package de.jeanlucmakiola.agendula.ui.permission
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Gates the one-time reminder onboarding step shown after the tasks-provider
|
||||
* grant. [onboardingDone] is null until DataStore's first emission so the step
|
||||
* neither flashes for users who completed it nor gets skipped.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class ReminderOnboardingViewModel @Inject constructor(
|
||||
private val prefs: SettingsPrefs,
|
||||
) : ViewModel() {
|
||||
|
||||
val onboardingDone: StateFlow<Boolean?> = prefs.reminderOnboardingDone
|
||||
.map { done -> done as Boolean? }
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5_000L),
|
||||
initialValue = null,
|
||||
)
|
||||
|
||||
/** Close the step, recording whether due reminders stay on. */
|
||||
fun finish(remindersEnabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
prefs.setRemindersEnabled(remindersEnabled)
|
||||
prefs.setReminderOnboardingDone()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
package de.jeanlucmakiola.agendula.ui.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.app.AlarmManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
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.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.padding
|
||||
import androidx.compose.foundation.layout.requiredSize
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.Notes
|
||||
import androidx.compose.material.icons.filled.BugReport
|
||||
import androidx.compose.material.icons.filled.Code
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Favorite
|
||||
import androidx.compose.material.icons.filled.Gavel
|
||||
import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.Palette
|
||||
import androidx.compose.material.icons.filled.Tune
|
||||
import androidx.compose.material.icons.rounded.AccountTree
|
||||
import androidx.compose.material.icons.rounded.Circle
|
||||
import androidx.compose.material.icons.rounded.Flag
|
||||
import androidx.compose.material.icons.rounded.Percent
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
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.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.colorResource
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.net.toUri
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFormField
|
||||
import de.jeanlucmakiola.floret.components.AboutCard
|
||||
import de.jeanlucmakiola.floret.components.AboutLink
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.LanguagePickerRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.agendula.ui.common.ReminderLeadPicker
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import de.jeanlucmakiola.agendula.ui.common.reminderLeadTimeLabel
|
||||
|
||||
/** The settings sub-screens reached from the hub's category rows. */
|
||||
private enum class SettingsSection { Appearance, TaskForm, Reminders }
|
||||
|
||||
/**
|
||||
* Token-based accent for a leading icon chip (container / on-container pair),
|
||||
* so each accent stays correctly paired across theme, dark mode and dynamic
|
||||
* colour.
|
||||
*/
|
||||
private enum class ChipAccent { Neutral, Primary, Tertiary }
|
||||
|
||||
/**
|
||||
* Settings, structured (after Calendula) as a category hub with sliding
|
||||
* sub-screens. The hub and the sub-screens share [CollapsingScaffold] and the
|
||||
* grouped-row card system; option lists use the full-screen [OptionPicker].
|
||||
* A full-screen destination; [onBack] pops it.
|
||||
*/
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
onBack: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: SettingsViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
var section by rememberSaveable { mutableStateOf<SettingsSection?>(null) }
|
||||
|
||||
// Inside a sub-screen, system back (button or gesture) returns to the hub
|
||||
// rather than popping the whole Settings destination to the lists overview.
|
||||
BackHandler(enabled = section != null) { section = null }
|
||||
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.surface),
|
||||
) {
|
||||
SettingsHub(onBack = onBack, onOpenSection = { section = it })
|
||||
|
||||
SlideInSection(visible = section == SettingsSection.Appearance) {
|
||||
AppearanceScreen(state = state, viewModel = viewModel, onBack = { section = null })
|
||||
}
|
||||
SlideInSection(visible = section == SettingsSection.TaskForm) {
|
||||
TaskFormScreen(state = state, viewModel = viewModel, onBack = { section = null })
|
||||
}
|
||||
SlideInSection(visible = section == SettingsSection.Reminders) {
|
||||
RemindersScreen(state = state, viewModel = viewModel, onBack = { section = null })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SlideInSection(visible: Boolean, content: @Composable () -> Unit) {
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = slideInHorizontally { it } + fadeIn(),
|
||||
exit = slideOutHorizontally { it } + fadeOut(),
|
||||
) { content() }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hub
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun SettingsHub(
|
||||
onBack: () -> Unit,
|
||||
onOpenSection: (SettingsSection) -> Unit,
|
||||
) {
|
||||
CollapsingScaffold(title = stringResource(R.string.settings_title), onBack = onBack) {
|
||||
Box(Modifier.padding(horizontal = 16.dp)) {
|
||||
AboutCard(
|
||||
logo = { AppLogo() },
|
||||
appName = stringResource(R.string.app_name),
|
||||
author = stringResource(R.string.settings_about_author),
|
||||
primaryLinks = listOf(
|
||||
AboutLink(
|
||||
icon = Icons.Default.Code,
|
||||
label = stringResource(R.string.settings_about_source),
|
||||
url = stringResource(R.string.about_source_url),
|
||||
),
|
||||
AboutLink(
|
||||
icon = Icons.Default.Gavel,
|
||||
label = stringResource(R.string.settings_license),
|
||||
url = stringResource(R.string.about_license_url),
|
||||
),
|
||||
),
|
||||
highlightLink = AboutLink(
|
||||
icon = Icons.Default.Favorite,
|
||||
label = stringResource(R.string.settings_about_support),
|
||||
url = stringResource(R.string.about_support_url),
|
||||
),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_section_appearance),
|
||||
summary = stringResource(R.string.settings_appearance_subtitle),
|
||||
position = Position.Top,
|
||||
leading = { CategoryIcon(Icons.Default.Palette, ChipAccent.Neutral) },
|
||||
onClick = { onOpenSection(SettingsSection.Appearance) },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_section_task_form),
|
||||
summary = stringResource(R.string.settings_task_form_subtitle),
|
||||
position = Position.Middle,
|
||||
leading = { CategoryIcon(Icons.Default.Tune, ChipAccent.Tertiary) },
|
||||
onClick = { onOpenSection(SettingsSection.TaskForm) },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_section_reminders),
|
||||
summary = stringResource(R.string.settings_reminders_subtitle),
|
||||
position = Position.Middle,
|
||||
leading = { CategoryIcon(Icons.Default.Notifications, ChipAccent.Primary) },
|
||||
onClick = { onOpenSection(SettingsSection.Reminders) },
|
||||
)
|
||||
LanguagePickerRow(
|
||||
position = Position.Middle,
|
||||
title = stringResource(R.string.settings_language),
|
||||
autoLabel = stringResource(R.string.settings_language_auto),
|
||||
localesConfig = R.xml.locales_config,
|
||||
leading = { CategoryIcon(Icons.Default.Language, ChipAccent.Neutral) },
|
||||
)
|
||||
ReportProblemRow(position = Position.Bottom)
|
||||
|
||||
AppVersionText()
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the project's issue tracker; no data leaves the device until submitted. */
|
||||
@Composable
|
||||
private fun ReportProblemRow(position: Position) {
|
||||
val context = LocalContext.current
|
||||
val issueUrl = stringResource(R.string.report_issue_url)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_report_problem),
|
||||
summary = stringResource(R.string.settings_report_problem_hint),
|
||||
position = position,
|
||||
leading = { CategoryIcon(Icons.Default.BugReport, ChipAccent.Neutral) },
|
||||
onClick = { openUrl(context, issueUrl) },
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sub-screens
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun AppearanceScreen(
|
||||
state: SettingsUiState,
|
||||
viewModel: SettingsViewModel,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val dynamicColorAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
var showTheme by remember { mutableStateOf(false) }
|
||||
|
||||
CollapsingScaffold(title = stringResource(R.string.settings_section_appearance), onBack = onBack) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_theme),
|
||||
summary = stringResource(themeLabel(state.settings.themeMode)),
|
||||
position = Position.Top,
|
||||
onClick = { showTheme = true },
|
||||
)
|
||||
GroupedRow(
|
||||
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)
|
||||
},
|
||||
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
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showTheme) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.settings_theme),
|
||||
options = ThemeMode.entries,
|
||||
selected = state.settings.themeMode,
|
||||
label = { stringResource(themeLabel(it)) },
|
||||
onSelect = viewModel::setThemeMode,
|
||||
onDismiss = { showTheme = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TaskFormScreen(
|
||||
state: SettingsUiState,
|
||||
viewModel: SettingsViewModel,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var showDefaultList by remember { mutableStateOf(false) }
|
||||
|
||||
CollapsingScaffold(title = stringResource(R.string.settings_section_task_form), onBack = onBack) {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_form_fields_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val fields = TaskFormField.entries
|
||||
fields.forEachIndexed { index, field ->
|
||||
val checked = field in state.settings.defaultEditFields
|
||||
GroupedRow(
|
||||
title = stringResource(formFieldLabel(field)),
|
||||
position = positionOf(index, fields.size),
|
||||
leading = {
|
||||
Icon(
|
||||
imageVector = formFieldIcon(field),
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
Switch(checked = checked, onCheckedChange = { viewModel.setFormFieldDefault(field, it) })
|
||||
},
|
||||
onClick = { viewModel.setFormFieldDefault(field, !checked) },
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_list),
|
||||
summary = defaultListLabel(state),
|
||||
position = Position.Top,
|
||||
onClick = { showDefaultList = true },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_add_subtask_row),
|
||||
summary = stringResource(R.string.settings_add_subtask_row_hint),
|
||||
position = Position.Middle,
|
||||
trailing = {
|
||||
Switch(
|
||||
checked = state.settings.showAddSubtaskRow,
|
||||
onCheckedChange = viewModel::setShowAddSubtaskRow,
|
||||
)
|
||||
},
|
||||
onClick = { viewModel.setShowAddSubtaskRow(!state.settings.showAddSubtaskRow) },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_bottom_add_bar),
|
||||
summary = stringResource(R.string.settings_bottom_add_bar_hint),
|
||||
position = Position.Bottom,
|
||||
trailing = {
|
||||
Switch(
|
||||
checked = state.settings.bottomAddBar,
|
||||
onCheckedChange = viewModel::setBottomAddBar,
|
||||
)
|
||||
},
|
||||
onClick = { viewModel.setBottomAddBar(!state.settings.bottomAddBar) },
|
||||
)
|
||||
}
|
||||
|
||||
if (showDefaultList) {
|
||||
val dark = isSystemInDarkTheme()
|
||||
// null = first available list; the rest are real list ids.
|
||||
val options = remember(state.lists) { listOf<Long?>(null) + state.lists.map { it.id } }
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.settings_default_list),
|
||||
options = options,
|
||||
selected = state.settings.defaultListId,
|
||||
label = { id -> state.lists.firstOrNull { it.id == id }?.name ?: stringResource(R.string.settings_default_list_first) },
|
||||
leading = { id ->
|
||||
state.lists.firstOrNull { it.id == id }?.let { list ->
|
||||
Icon(Icons.Rounded.Circle, contentDescription = null, tint = pastelize(list.color, dark))
|
||||
}
|
||||
},
|
||||
onSelect = { viewModel.setDefaultList(it) },
|
||||
onDismiss = { showDefaultList = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RemindersScreen(
|
||||
state: SettingsUiState,
|
||||
viewModel: SettingsViewModel,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val notifLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission(),
|
||||
) { /* pref already set; a denial just leaves the OS gate shut */ }
|
||||
val toggleReminders: (Boolean) -> Unit = { enabled ->
|
||||
viewModel.setRemindersEnabled(enabled)
|
||||
if (enabled &&
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
notifLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
val canExact = rememberExactAlarmAllowed(context)
|
||||
val exactAlarmRow = showExactAlarmRow()
|
||||
val dark = isSystemInDarkTheme()
|
||||
var showOffset by remember { mutableStateOf(false) }
|
||||
var perListExpanded by remember { mutableStateOf(false) }
|
||||
var listPickerId by remember { mutableStateOf<Long?>(null) }
|
||||
val lists = state.lists.filter { it.id > 0L }
|
||||
|
||||
CollapsingScaffold(title = stringResource(R.string.settings_section_reminders), onBack = onBack) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_reminders),
|
||||
summary = stringResource(R.string.settings_reminders_hint),
|
||||
position = Position.Top,
|
||||
trailing = { Switch(checked = state.settings.remindersEnabled, onCheckedChange = toggleReminders) },
|
||||
onClick = { toggleReminders(!state.settings.remindersEnabled) },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = reminderLeadTimeLabel(state.settings.reminderLeadMinutes),
|
||||
position = if (exactAlarmRow) Position.Middle else Position.Bottom,
|
||||
onClick = { showOffset = true },
|
||||
)
|
||||
if (exactAlarmRow) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_exact_alarms),
|
||||
summary = stringResource(
|
||||
if (canExact) R.string.settings_exact_alarms_allowed
|
||||
else R.string.settings_exact_alarms_blocked,
|
||||
),
|
||||
position = Position.Bottom,
|
||||
onClick = if (canExact) null else ({ context.openExactAlarmSettings() }),
|
||||
)
|
||||
}
|
||||
|
||||
// Per-list overrides: the whole section folds behind one header. Each
|
||||
// list may keep, drop, or replace the global default for its tasks.
|
||||
if (lists.isNotEmpty()) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
// The header and the list rows form one connected run: the header
|
||||
// opens its bottom (Top) when expanded, and the last list rounds it off.
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_list_reminders_title),
|
||||
summary = stringResource(R.string.settings_list_reminders_hint),
|
||||
position = if (perListExpanded) Position.Top else Position.Alone,
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = if (perListExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = { perListExpanded = !perListExpanded },
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = perListExpanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
Column {
|
||||
lists.forEachIndexed { index, list ->
|
||||
GroupedRow(
|
||||
title = list.name,
|
||||
summary = listOverrideSummary(
|
||||
listOverrideChoice(state, list.id),
|
||||
state.settings.reminderLeadMinutes,
|
||||
),
|
||||
// Every list is mid-run under the header; the last rounds off.
|
||||
position = if (index == lists.lastIndex) Position.Bottom else Position.Middle,
|
||||
leading = {
|
||||
Icon(Icons.Rounded.Circle, contentDescription = null, tint = pastelize(list.color, dark))
|
||||
},
|
||||
onClick = { listPickerId = list.id },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showOffset) {
|
||||
ReminderLeadPicker(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
selected = ReminderOverride.Minutes(listOf(state.settings.reminderLeadMinutes)),
|
||||
allowInherit = false,
|
||||
allowNone = false,
|
||||
onSelect = { if (it is ReminderOverride.Minutes) viewModel.setReminderLeadMinutes(it.minutes.first()) },
|
||||
onDismiss = { showOffset = false },
|
||||
)
|
||||
}
|
||||
listPickerId?.let { id ->
|
||||
ReminderLeadPicker(
|
||||
title = state.lists.firstOrNull { it.id == id }?.name
|
||||
?: stringResource(R.string.settings_default_reminder),
|
||||
selected = listOverrideChoice(state, id),
|
||||
allowInherit = true,
|
||||
allowNone = true,
|
||||
onSelect = { viewModel.setListReminderOverride(id, it) },
|
||||
onDismiss = { listPickerId = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The stored override for [listId], as a picker choice (absent → inherit). */
|
||||
private fun listOverrideChoice(state: SettingsUiState, listId: Long): ReminderOverride =
|
||||
state.settings.perListReminderOverride.reminderOverrideFor(listId)
|
||||
|
||||
/** Row summary for a list: its override, or the inherited global default. */
|
||||
@Composable
|
||||
private fun listOverrideSummary(choice: ReminderOverride, globalDefault: Int): String = when (choice) {
|
||||
ReminderOverride.Inherit ->
|
||||
stringResource(R.string.settings_list_reminder_inherits, reminderLeadTimeLabel(globalDefault))
|
||||
ReminderOverride.None -> stringResource(R.string.reminder_none)
|
||||
is ReminderOverride.Minutes -> reminderLeadTimeLabel(choice.minutes.first())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// About + shared building blocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun AppLogo() {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(72.dp)
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.background(colorResource(R.color.ic_launcher_background)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.ic_launcher_foreground),
|
||||
contentDescription = stringResource(R.string.settings_about_logo_desc),
|
||||
modifier = Modifier.requiredSize(108.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AppVersionText() {
|
||||
val context = LocalContext.current
|
||||
val versionName = remember {
|
||||
runCatching { context.packageManager.getPackageInfo(context.packageName, 0).versionName }
|
||||
.getOrNull() ?: "—"
|
||||
}
|
||||
Text(
|
||||
text = stringResource(R.string.settings_about_version, versionName),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** Leading circular icon chip; colours come from the M3 scheme via a token pair. */
|
||||
@Composable
|
||||
private fun CategoryIcon(icon: ImageVector, accent: ChipAccent) {
|
||||
val scheme = MaterialTheme.colorScheme
|
||||
val (background, iconColor) = when (accent) {
|
||||
ChipAccent.Neutral -> scheme.surfaceContainerHighest to scheme.onSurfaceVariant
|
||||
ChipAccent.Primary -> scheme.primaryContainer to scheme.onPrimaryContainer
|
||||
ChipAccent.Tertiary -> scheme.tertiaryContainer to scheme.onTertiaryContainer
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier.size(40.dp).clip(CircleShape).background(background),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = iconColor, modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun defaultListLabel(state: SettingsUiState): String =
|
||||
state.lists.firstOrNull { it.id == state.settings.defaultListId }?.name
|
||||
?: stringResource(R.string.settings_default_list_first)
|
||||
|
||||
private fun openUrl(context: Context, url: String) {
|
||||
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri())) }
|
||||
}
|
||||
|
||||
private fun themeLabel(mode: ThemeMode): Int = when (mode) {
|
||||
ThemeMode.SYSTEM -> R.string.settings_theme_system
|
||||
ThemeMode.LIGHT -> R.string.settings_theme_light
|
||||
ThemeMode.DARK -> R.string.settings_theme_dark
|
||||
}
|
||||
|
||||
private fun formFieldLabel(field: TaskFormField): Int = when (field) {
|
||||
TaskFormField.Description -> R.string.field_description
|
||||
TaskFormField.Priority -> R.string.edit_priority_label
|
||||
TaskFormField.Progress -> R.string.edit_progress_label
|
||||
TaskFormField.Parent -> R.string.edit_parent_label
|
||||
TaskFormField.Reminder -> R.string.edit_reminder_label
|
||||
}
|
||||
|
||||
private fun formFieldIcon(field: TaskFormField): ImageVector = when (field) {
|
||||
TaskFormField.Description -> Icons.AutoMirrored.Rounded.Notes
|
||||
TaskFormField.Priority -> Icons.Rounded.Flag
|
||||
TaskFormField.Progress -> Icons.Rounded.Percent
|
||||
TaskFormField.Parent -> Icons.Rounded.AccountTree
|
||||
TaskFormField.Reminder -> Icons.Default.Notifications
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact-alarm control is only meaningful on API 31-32 (SCHEDULE_EXACT_ALARM,
|
||||
* revocable). On 33+ the app holds USE_EXACT_ALARM (always granted), so the row
|
||||
* would be a permanent no-op — hide it there.
|
||||
*/
|
||||
private fun showExactAlarmRow(): Boolean =
|
||||
Build.VERSION.SDK_INT in Build.VERSION_CODES.S..Build.VERSION_CODES.S_V2
|
||||
|
||||
@Composable
|
||||
private fun rememberExactAlarmAllowed(context: Context): Boolean {
|
||||
var allowed by remember {
|
||||
mutableStateOf(
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
|
||||
context.getSystemService(AlarmManager::class.java).canScheduleExactAlarms(),
|
||||
)
|
||||
}
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
DisposableEffect(lifecycle) {
|
||||
val obs = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
allowed = context.getSystemService(AlarmManager::class.java).canScheduleExactAlarms()
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(obs)
|
||||
onDispose { lifecycle.removeObserver(obs) }
|
||||
}
|
||||
return allowed
|
||||
}
|
||||
|
||||
private fun Context.openExactAlarmSettings() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
runCatching {
|
||||
startActivity(
|
||||
Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM).setData("package:$packageName".toUri()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package de.jeanlucmakiola.agendula.ui.settings
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
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.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFormField
|
||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
data class SettingsUiState(
|
||||
val settings: Settings = Settings(),
|
||||
val lists: List<TaskList> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Drives both the Settings screen and the app theme (MainActivity collects the
|
||||
* same instance), so a theme change applies app-wide at once.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class SettingsViewModel @Inject constructor(
|
||||
private val prefs: SettingsPrefs,
|
||||
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.
|
||||
val state: StateFlow<SettingsUiState> =
|
||||
combine(
|
||||
prefs.settings,
|
||||
repository.taskLists().recoveringFromProviderFailure { emptyList() },
|
||||
) { settings, lists ->
|
||||
SettingsUiState(settings, lists)
|
||||
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SettingsUiState())
|
||||
|
||||
fun setThemeMode(mode: ThemeMode) = viewModelScope.launch { prefs.setThemeMode(mode) }
|
||||
fun setDynamicColor(enabled: Boolean) = viewModelScope.launch { prefs.setDynamicColor(enabled) }
|
||||
fun setDefaultList(id: Long?) = viewModelScope.launch { prefs.setDefaultListId(id) }
|
||||
fun setReminderLeadMinutes(minutes: Int) = viewModelScope.launch { prefs.setReminderLeadMinutes(minutes) }
|
||||
fun setRemindersEnabled(enabled: Boolean) = viewModelScope.launch { prefs.setRemindersEnabled(enabled) }
|
||||
fun setShowAddSubtaskRow(show: Boolean) = viewModelScope.launch { prefs.setShowAddSubtaskRow(show) }
|
||||
fun setBottomAddBar(enabled: Boolean) = viewModelScope.launch { prefs.setBottomAddBar(enabled) }
|
||||
|
||||
/** Toggle whether [field] shows by default on a new task's edit form. */
|
||||
fun setFormFieldDefault(field: TaskFormField, enabled: Boolean) = viewModelScope.launch {
|
||||
val current = state.value.settings.defaultEditFields
|
||||
prefs.setDefaultEditFields(if (enabled) current + field else current - field)
|
||||
}
|
||||
|
||||
/** Set (or clear, via [ReminderOverride.Inherit]) a list's reminder override. */
|
||||
fun setListReminderOverride(listId: Long, override: ReminderOverride) =
|
||||
viewModelScope.launch { prefs.setListReminderOverride(listId, override) }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.ui.tasklist
|
||||
package de.jeanlucmakiola.agendula.ui.tasklist
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
@@ -21,6 +21,12 @@ import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.ime
|
||||
import androidx.compose.foundation.layout.isImeVisible
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
import androidx.compose.foundation.layout.union
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
@@ -39,6 +45,7 @@ import androidx.compose.material.icons.rounded.Check
|
||||
import androidx.compose.material.icons.rounded.Checklist
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.ExpandMore
|
||||
import androidx.compose.material.icons.rounded.Flag
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
@@ -67,6 +74,7 @@ import kotlinx.coroutines.delay
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
@@ -80,20 +88,19 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.floret.R
|
||||
import de.jeanlucmakiola.floret.domain.DayWindow
|
||||
import de.jeanlucmakiola.floret.domain.Priority
|
||||
import de.jeanlucmakiola.floret.domain.SmartList
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.floret.domain.TaskSection
|
||||
import de.jeanlucmakiola.floret.domain.TaskSections
|
||||
import de.jeanlucmakiola.floret.ui.common.ListNameChip
|
||||
import de.jeanlucmakiola.floret.ui.common.Position
|
||||
import de.jeanlucmakiola.floret.ui.common.PriorityChip
|
||||
import de.jeanlucmakiola.floret.ui.common.formatDateTime
|
||||
import de.jeanlucmakiola.floret.ui.common.pastelize
|
||||
import de.jeanlucmakiola.floret.ui.common.positionOf
|
||||
import de.jeanlucmakiola.agendula.R
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||
import de.jeanlucmakiola.agendula.domain.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSection
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSections
|
||||
import de.jeanlucmakiola.agendula.ui.common.priorityAccent
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.time.formatDateTimeCompact
|
||||
import de.jeanlucmakiola.floret.components.pastelize
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Clock
|
||||
|
||||
@@ -115,7 +122,13 @@ fun TaskListScreen(
|
||||
) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
|
||||
val listName = (state as? TaskListUiState.Content)?.listName
|
||||
val content = state as? TaskListUiState.Content
|
||||
val listName = content?.listName
|
||||
val listId = (filter as? TaskFilter.OfList)?.listId
|
||||
// One add affordance, never two: a real list with the setting on gets a pinned
|
||||
// bottom quick-add bar; everything else (incl. smart lists, which have no single
|
||||
// target list) gets the floating "New task" button.
|
||||
val showBottomAddBar = content?.bottomAddBar == true && listId != null
|
||||
|
||||
// Swipe-delete hides the row at once, then a floating "Deleted · Undo" chip
|
||||
// gives an undo window: Undo restores it, otherwise the delete commits. A
|
||||
@@ -150,11 +163,18 @@ fun TaskListScreen(
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (!showBottomAddBar) {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onNewTask,
|
||||
icon = { Icon(Icons.Rounded.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.new_task)) },
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
if (showBottomAddBar) {
|
||||
listId?.let { id -> QuickAddBar(onAdd = { title -> viewModel.quickAdd(title, id) }) }
|
||||
}
|
||||
},
|
||||
) { inner ->
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
@@ -163,19 +183,27 @@ fun TaskListScreen(
|
||||
TaskListUiState.Failure -> CenteredMessage(stringResource(R.string.task_list_failure), inner)
|
||||
is TaskListUiState.Content -> TaskListBody(s, filter, inner, onOpenTask, onRequestDelete, viewModel)
|
||||
}
|
||||
// A FAB-height band anchored at the bottom-start with the FAB's own
|
||||
// margin; centring the chip in it lines the chip up beside the bottom-end
|
||||
// FAB at exactly its height, rather than sitting a touch above it.
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.padding(start = 16.dp, bottom = inner.calculateBottomPadding() + 16.dp)
|
||||
.height(56.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
UndoChip(
|
||||
visible = undoTarget != null,
|
||||
onUndo = {
|
||||
undoTarget?.let { viewModel.undoDelete(it.taskId) }
|
||||
undoTarget = null
|
||||
},
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(bottom = inner.calculateBottomPadding() + 24.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A compact floating "snackchip" for an undoable delete — a rounded pill (not a
|
||||
@@ -251,20 +279,34 @@ private fun TaskListBody(
|
||||
val childrenByParent = remember(state.tasks) {
|
||||
state.tasks.filter { it.isSubtask }.groupBy { it.parentId!! }
|
||||
}
|
||||
// In a smart list a parent's subtasks are usually filtered out (they're undated
|
||||
// or due other days), so we pull them on demand. Report only expanded parents
|
||||
// whose full child set isn't already in this view; the VM then observes those
|
||||
// children live. In a real list that set is empty, so no extra queries run.
|
||||
val tasksById = remember(state.tasks) { state.tasks.associateBy { it.taskId } }
|
||||
val parentsNeedingChildren = expandedParents.filter { id ->
|
||||
val parent = tasksById[id]
|
||||
parent != null && (childrenByParent[id]?.size ?: 0) != parent.subtaskTotal
|
||||
}.toSet()
|
||||
LaunchedEffect(parentsNeedingChildren) { viewModel.setLazyChildParents(parentsNeedingChildren) }
|
||||
val lazyChildren by viewModel.lazyChildren.collectAsStateWithLifecycle()
|
||||
// A parent's full child set: the rows already in this view when we hold them
|
||||
// all, otherwise the lazily-loaded set fetched for smart lists.
|
||||
fun childrenOf(task: Task): List<Task> {
|
||||
val inList = childrenByParent[task.taskId].orEmpty()
|
||||
return if (inList.size == task.subtaskTotal) inList else lazyChildren[task.taskId].orEmpty()
|
||||
}
|
||||
|
||||
// When the bottom quick-add bar is shown it already lives in the scaffold's
|
||||
// bottomBar (so `inner` covers it); otherwise reserve room to clear the FAB.
|
||||
val bottomBarShown = state.bottomAddBar && listId != null
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(
|
||||
top = inner.calculateTopPadding() + 8.dp,
|
||||
bottom = inner.calculateBottomPadding() + 96.dp,
|
||||
bottom = inner.calculateBottomPadding() + if (bottomBarShown) 16.dp else 96.dp,
|
||||
),
|
||||
) {
|
||||
if (listId != null) {
|
||||
item(key = "inline-add") {
|
||||
InlineAdd(onAdd = { title -> viewModel.quickAdd(title, listId) })
|
||||
}
|
||||
}
|
||||
|
||||
if (state.tasks.isEmpty()) {
|
||||
item(key = "empty") { EmptyState(stringResource(R.string.task_list_empty)) }
|
||||
}
|
||||
@@ -295,38 +337,51 @@ private fun TaskListBody(
|
||||
val rows = buildList {
|
||||
val topLevel = section.tasks
|
||||
topLevel.forEachIndexed { p, task ->
|
||||
val children = childrenByParent[task.taskId].orEmpty()
|
||||
// Only expandable when we hold every child: true in a real
|
||||
// list, but a smart list may omit children due on other
|
||||
// days, and a half-shown set would mislead.
|
||||
val canExpand = task.subtaskTotal > 0 && children.size == task.subtaskTotal
|
||||
// The full child set — already in this view for a real list,
|
||||
// or fetched on demand for a smart list (childrenOf). A parent
|
||||
// is expandable whenever it has children; until a smart list's
|
||||
// set has loaded the group simply shows nothing extra.
|
||||
val children = childrenOf(task)
|
||||
val canExpand = task.subtaskTotal > 0
|
||||
val isExpanded = canExpand && task.taskId in expandedParents
|
||||
val hasExpansionContent = children.isNotEmpty() || state.showAddSubtaskRow
|
||||
// Top-level tasks keep their own connected run — full top
|
||||
// only on the first, full bottom only on the last — so the
|
||||
// task after an expanded one stays mid-run (small top). An
|
||||
// expanded parent's bottom opens (small) to meet its subtasks.
|
||||
val parentPosition = cornerPosition(
|
||||
topFull = p == 0,
|
||||
bottomFull = if (isExpanded) false else p == topLevel.lastIndex,
|
||||
bottomFull = if (isExpanded && hasExpansionContent) false else p == topLevel.lastIndex,
|
||||
)
|
||||
add(RenderRow(ListRow.Parent(task, canExpand, isExpanded), parentPosition))
|
||||
if (isExpanded) {
|
||||
// Subtasks connect up to the parent (small top) and to
|
||||
// each other; the inline add row below closes the group,
|
||||
// so every subtask is mid-run (small top + bottom).
|
||||
children.sortedBy { it.isCompleted }.forEach { sub ->
|
||||
add(RenderRow(ListRow.Sub(sub), cornerPosition(topFull = false, bottomFull = false)))
|
||||
// When the add row is hidden (M5 setting), the last subtask
|
||||
// instead rounds the group off (full bottom).
|
||||
val sorted = children.sortedBy { it.isCompleted }
|
||||
sorted.forEachIndexed { c, sub ->
|
||||
// Subtasks connect up to the parent (small top); with the
|
||||
// add row present every subtask is mid-run, otherwise the
|
||||
// last one closes the group (full bottom).
|
||||
val closesGroup = !state.showAddSubtaskRow && c == sorted.lastIndex
|
||||
add(RenderRow(ListRow.Sub(sub), cornerPosition(topFull = false, bottomFull = closesGroup)))
|
||||
}
|
||||
// The add row rounds the group off (full bottom),
|
||||
// independent of whatever top-level task follows.
|
||||
if (state.showAddSubtaskRow) {
|
||||
add(RenderRow(ListRow.AddSub(task), cornerPosition(topFull = false, bottomFull = true)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
itemsIndexed(rows, key = { _, r -> r.row.key }) { index, r ->
|
||||
val lastInRun = index == rows.lastIndex
|
||||
// animateItem so an (un)expanding group fades its subtasks in/out
|
||||
// and slides the rows below — clean whether the children were
|
||||
// already loaded (real list) or arrive a frame later (smart list).
|
||||
val rowModifier = Modifier.animateItem()
|
||||
when (val row = r.row) {
|
||||
is ListRow.Parent -> TaskRow(
|
||||
modifier = rowModifier,
|
||||
task = row.task,
|
||||
position = r.position,
|
||||
lastInRun = lastInRun,
|
||||
@@ -350,6 +405,7 @@ private fun TaskListBody(
|
||||
onClick = { onOpenTask(row.task.taskId) },
|
||||
)
|
||||
is ListRow.Sub -> SubtaskRow(
|
||||
modifier = rowModifier,
|
||||
task = row.task,
|
||||
position = r.position,
|
||||
lastInRun = lastInRun,
|
||||
@@ -357,6 +413,7 @@ private fun TaskListBody(
|
||||
onClick = { onOpenTask(row.task.taskId) },
|
||||
)
|
||||
is ListRow.AddSub -> AddSubtaskRow(
|
||||
modifier = rowModifier,
|
||||
position = r.position,
|
||||
lastInRun = lastInRun,
|
||||
onAdd = { viewModel.quickAddSubtask(row.parent, it) },
|
||||
@@ -369,9 +426,9 @@ private fun TaskListBody(
|
||||
}
|
||||
|
||||
/** Inline "add a task" — title only, into the current list. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun InlineAdd(onAdd: (String) -> Unit) {
|
||||
private fun InlineAdd(onAdd: (String) -> Unit, elevated: Boolean = false) {
|
||||
var text by remember { mutableStateOf("") }
|
||||
fun submit() {
|
||||
if (text.isNotBlank()) {
|
||||
@@ -379,10 +436,25 @@ private fun InlineAdd(onAdd: (String) -> Unit) {
|
||||
text = ""
|
||||
}
|
||||
}
|
||||
// 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()
|
||||
}
|
||||
Surface(
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.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 = 8.dp),
|
||||
) {
|
||||
TextField(
|
||||
value = text,
|
||||
@@ -410,6 +482,23 @@ private fun InlineAdd(onAdd: (String) -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bottom quick-add field: [InlineAdd] pinned as the scaffold's bottomBar, but
|
||||
* with no bar plate of its own — the rounded field floats on the screen background
|
||||
* (its own shadow lifting it off the list). Rides above the keyboard and clears the
|
||||
* navigation bar (ime ∪ navigation-bar insets).
|
||||
*/
|
||||
@Composable
|
||||
private fun QuickAddBar(onAdd: (String) -> Unit) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.windowInsetsPadding(WindowInsets.ime.union(WindowInsets.navigationBars)),
|
||||
) {
|
||||
InlineAdd(onAdd = onAdd, elevated = true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One task row: a tonal grouped-card surface (corners from [position], morphing
|
||||
* rounder on press — the app's shape family) wrapped in a swipe box. Swiping
|
||||
@@ -429,6 +518,7 @@ private fun TaskRow(
|
||||
onToggle: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val dismissState = rememberSwipeToDismissBoxState(
|
||||
confirmValueChange = { value ->
|
||||
@@ -449,7 +539,7 @@ private fun TaskRow(
|
||||
|
||||
SwipeToDismissBox(
|
||||
state = dismissState,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).then(gap),
|
||||
modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp).then(gap),
|
||||
// dismissDirection (not targetValue) tracks the live drag, so the colour +
|
||||
// icon reveal as you swipe rather than only once the threshold is crossed.
|
||||
backgroundContent = { SwipeBackground(dismissState.dismissDirection, task.isCompleted) },
|
||||
@@ -476,10 +566,11 @@ private fun TaskRowContent(
|
||||
val full by animateDpAsState(if (pressed) 36.dp else 22.dp, label = "fullCorner")
|
||||
val small by animateDpAsState(if (pressed) 36.dp else 6.dp, label = "smallCorner")
|
||||
val dark = isSystemInDarkTheme()
|
||||
val due = task.due?.formatDateTime(task.isAllDay)
|
||||
val due = task.due?.formatDateTimeCompact(task.isAllDay)
|
||||
val listName = task.listName?.takeIf { showListName && it.isNotBlank() }
|
||||
val hasSupporting = due != null || listName != null || subtaskTotal > 0 ||
|
||||
task.priority != Priority.NONE
|
||||
// Everything secondary collapses into one quiet supporting line below the title.
|
||||
val hasMeta = task.priority != Priority.NONE || due != null || subtaskTotal > 0 ||
|
||||
listName != null
|
||||
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
@@ -520,30 +611,18 @@ private fun TaskRowContent(
|
||||
MaterialTheme.colorScheme.onSurface
|
||||
},
|
||||
)
|
||||
if (hasSupporting) {
|
||||
if (hasMeta) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
// Flow so the chips wrap to a further line when due date + list
|
||||
// + subtask progress can't share one (e.g. a dated task with
|
||||
// subtasks), rather than squeezing the trailing chip.
|
||||
FlowRow(
|
||||
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
itemVerticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (task.priority != Priority.NONE) {
|
||||
PriorityChip(task.priority, priorityLabel(task.priority))
|
||||
}
|
||||
if (due != null) {
|
||||
Text(
|
||||
text = due,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
TaskMetaLine(
|
||||
priority = task.priority,
|
||||
due = due,
|
||||
subtaskDone = subtaskDone,
|
||||
subtaskTotal = subtaskTotal,
|
||||
listName = listName,
|
||||
listColor = task.effectiveColor,
|
||||
dark = dark,
|
||||
)
|
||||
}
|
||||
if (listName != null) ListNameChip(listName, task.effectiveColor)
|
||||
if (subtaskTotal > 0) SubtaskCountChip(subtaskDone, subtaskTotal)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Trailing area is only ever the expand control, so the row's right
|
||||
// edge stays put whether or not the task has children (priority now
|
||||
@@ -555,32 +634,86 @@ private fun TaskRowContent(
|
||||
}
|
||||
}
|
||||
|
||||
/** A small neutral pill showing subtask progress, e.g. "3 / 5". */
|
||||
/**
|
||||
* The single low-emphasis supporting line under a task title: priority, due date,
|
||||
* subtask progress and (in mixed views) the list name, joined by middots. The text
|
||||
* is quiet `onSurfaceVariant` throughout; the only colour is the priority flag and
|
||||
* the list name (tinted to its list) — so even a fully-populated row stays calm and
|
||||
* one line instead of a stack of filled pills.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun SubtaskCountChip(done: Int, total: Int) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
shape = RoundedCornerShape(50),
|
||||
private fun TaskMetaLine(
|
||||
priority: Priority,
|
||||
due: String?,
|
||||
subtaskDone: Int,
|
||||
subtaskTotal: Int,
|
||||
listName: String?,
|
||||
listColor: Int,
|
||||
dark: Boolean,
|
||||
) {
|
||||
val muted = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
val style = MaterialTheme.typography.bodySmall
|
||||
val segments = buildList<@Composable () -> Unit> {
|
||||
if (priority != Priority.NONE) {
|
||||
add {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Rounded.ListAlt,
|
||||
Icons.Rounded.Flag,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(14.dp),
|
||||
tint = priorityAccent(priority, dark),
|
||||
modifier = Modifier.size(13.dp),
|
||||
)
|
||||
Text(priorityLabel(priority), style = style, color = muted)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (due != null) add { Text(due, style = style, color = muted) }
|
||||
if (subtaskTotal > 0) {
|
||||
add {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Rounded.ListAlt,
|
||||
contentDescription = null,
|
||||
tint = muted,
|
||||
modifier = Modifier.size(13.dp),
|
||||
)
|
||||
Text("$subtaskDone / $subtaskTotal", style = style, color = muted)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (listName != null) {
|
||||
add {
|
||||
Text(
|
||||
text = "$done / $total",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
listName,
|
||||
style = style,
|
||||
color = pastelize(listColor, dark),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
FlowRow(
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
itemVerticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
segments.forEachIndexed { i, segment ->
|
||||
// A middot between segments — its own flow item, so the line can still
|
||||
// wrap gracefully when truly everything is set on a narrow screen.
|
||||
if (i > 0) {
|
||||
Text("·", style = style, color = muted, modifier = Modifier.padding(horizontal = 6.dp))
|
||||
}
|
||||
segment()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The inline "add a subtask" row that closes an expanded group — a [BasicTextField]
|
||||
@@ -593,6 +726,7 @@ private fun AddSubtaskRow(
|
||||
position: Position,
|
||||
lastInRun: Boolean,
|
||||
onAdd: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var text by remember { mutableStateOf("") }
|
||||
fun submit() {
|
||||
@@ -606,7 +740,7 @@ private fun AddSubtaskRow(
|
||||
shape = cardShape(position, 22.dp, 6.dp),
|
||||
// Same tone as the subtask rows it closes, so the group reads as one unit.
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).then(gap),
|
||||
modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp).then(gap),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp).padding(start = 12.dp, end = 8.dp),
|
||||
@@ -719,6 +853,7 @@ private fun SubtaskRow(
|
||||
lastInRun: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
@@ -732,7 +867,7 @@ private fun SubtaskRow(
|
||||
// reads as a distinct, recessive tone — the nesting cue alongside shape.
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
interactionSource = interaction,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).then(gap),
|
||||
modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp).then(gap),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
@@ -1,20 +1,22 @@
|
||||
package de.jeanlucmakiola.floret.ui.tasklist
|
||||
package de.jeanlucmakiola.agendula.ui.tasklist
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
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.Task
|
||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
@@ -30,7 +32,14 @@ sealed interface TaskListUiState {
|
||||
* [TaskFilter.OfList] (for the top-bar title), `null` for smart lists —
|
||||
* the screen falls back to the smart label in that case.
|
||||
*/
|
||||
data class Content(val tasks: List<Task>, val listName: String? = null) : TaskListUiState
|
||||
data class Content(
|
||||
val tasks: List<Task>,
|
||||
val listName: String? = null,
|
||||
/** Whether the inline "add a subtask" row shows on expanded groups (M5 setting). */
|
||||
val showAddSubtaskRow: Boolean = true,
|
||||
/** Whether a real list uses the bottom quick-add bar instead of the FAB. */
|
||||
val bottomAddBar: Boolean = false,
|
||||
) : TaskListUiState
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,6 +51,7 @@ sealed interface TaskListUiState {
|
||||
@HiltViewModel
|
||||
class TaskListViewModel @Inject constructor(
|
||||
private val repository: TasksRepository,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) : ViewModel() {
|
||||
|
||||
private val filter = MutableStateFlow<TaskFilter?>(null)
|
||||
@@ -62,19 +72,57 @@ class TaskListViewModel @Inject constructor(
|
||||
tasks.map { TaskListUiState.Content(it) }
|
||||
}
|
||||
// Drop rows pending an undoable delete so the row vanishes on swipe
|
||||
// while the actual provider delete waits for the snackbar to commit.
|
||||
combine(content, pendingDeletes) { st, pending ->
|
||||
// while the actual provider delete waits for the snackbar to commit,
|
||||
// and fold in the live UI settings (add-subtask row, bottom add bar).
|
||||
val uiPrefs = settingsPrefs.settings.map { it.showAddSubtaskRow to it.bottomAddBar }
|
||||
combine(content, pendingDeletes, uiPrefs) { st, pending, (showRow, bottomBar) ->
|
||||
if (st is TaskListUiState.Content) {
|
||||
st.copy(tasks = st.tasks.filter { it.taskId !in pending })
|
||||
st.copy(
|
||||
tasks = st.tasks.filter { it.taskId !in pending },
|
||||
showAddSubtaskRow = showRow,
|
||||
bottomAddBar = bottomBar,
|
||||
)
|
||||
} else {
|
||||
st
|
||||
}
|
||||
}
|
||||
.onStart { emit(TaskListUiState.Loading) }
|
||||
.catch { emit(TaskListUiState.Failure) }
|
||||
// Recover rather than terminate: a provider hiccup (mid-update,
|
||||
// permission not yet granted) shows Failure but keeps retrying,
|
||||
// so the screen heals itself instead of staying stuck.
|
||||
.recoveringFromProviderFailure { TaskListUiState.Failure }
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), TaskListUiState.Loading)
|
||||
|
||||
/**
|
||||
* Parents the screen has expanded whose children it can't pull from the list
|
||||
* itself — i.e. smart lists, where the date filter drops a parent's subtasks.
|
||||
* For each we observe the full child set live (below), so the group can expand.
|
||||
*/
|
||||
private val lazyChildParents = MutableStateFlow<Set<Long>>(emptySet())
|
||||
|
||||
/**
|
||||
* The on-demand child sets, keyed by parent id, kept live. Empty for real
|
||||
* lists (the screen reports no parents there, since it already holds every
|
||||
* child) so no redundant queries run.
|
||||
*/
|
||||
val lazyChildren: StateFlow<Map<Long, List<Task>>> =
|
||||
lazyChildParents
|
||||
.flatMapLatest { ids ->
|
||||
if (ids.isEmpty()) {
|
||||
flowOf(emptyMap())
|
||||
} else {
|
||||
combine(ids.map { id -> repository.subtasks(id).map { id to it } }) { it.toMap() }
|
||||
}
|
||||
}
|
||||
// Without this an exception here escapes stateIn's coroutine, past
|
||||
// viewModelScope's SupervisorJob, and crashes the process.
|
||||
.recoveringFromProviderFailure { emptyMap() }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())
|
||||
|
||||
/** The screen reports which expanded parents need their children fetched. */
|
||||
fun setLazyChildParents(ids: Set<Long>) { lazyChildParents.value = ids }
|
||||
|
||||
fun bind(taskFilter: TaskFilter) { filter.value = taskFilter }
|
||||
|
||||
fun toggleComplete(task: Task) = viewModelScope.launch {
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.ui.theme
|
||||
package de.jeanlucmakiola.agendula.ui.theme
|
||||
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
@@ -12,14 +12,14 @@ import androidx.compose.ui.graphics.Color
|
||||
*
|
||||
* Placeholder until branding lands; refine alongside the launcher icon.
|
||||
*/
|
||||
val FloretSeed: Color = Color(0xFF7A5C6B)
|
||||
val AgendulaSeed: Color = Color(0xFF7A5C6B)
|
||||
|
||||
/**
|
||||
* Fallback light scheme for devices without dynamic color (API < 31) or when
|
||||
* the user disables it. Dynamic color (API 31+) is the real path; these are a
|
||||
* hand-picked approximation of the tonal palette generated from [FloretSeed].
|
||||
* hand-picked approximation of the tonal palette generated from [AgendulaSeed].
|
||||
*/
|
||||
val FloretLightFallback = lightColorScheme(
|
||||
val AgendulaLightFallback = lightColorScheme(
|
||||
primary = Color(0xFF6A4E5B),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
primaryContainer = Color(0xFFF6D9E5),
|
||||
@@ -32,7 +32,7 @@ val FloretLightFallback = lightColorScheme(
|
||||
onSurface = Color(0xFF1F1A1C),
|
||||
)
|
||||
|
||||
val FloretDarkFallback = darkColorScheme(
|
||||
val AgendulaDarkFallback = darkColorScheme(
|
||||
primary = Color(0xFFE2BAC9),
|
||||
onPrimary = Color(0xFF402533),
|
||||
primaryContainer = Color(0xFF583B49),
|
||||
@@ -0,0 +1,28 @@
|
||||
package de.jeanlucmakiola.agendula.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import de.jeanlucmakiola.floret.identity.FloretExpressiveTheme
|
||||
|
||||
/**
|
||||
* Agendula's theme: the family's [FloretExpressiveTheme] machinery (dynamic
|
||||
* colour on API 31+, system light/dark, the standard motion scheme) fed with
|
||||
* Agendula's own identity — its seed-derived fallback schemes
|
||||
* ([AgendulaLightFallback] / [AgendulaDarkFallback]) and [AgendulaTypography].
|
||||
* The mechanics live in floret-kit; the look stays here.
|
||||
*/
|
||||
@Composable
|
||||
fun AgendulaTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
dynamicColor: Boolean = true,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
FloretExpressiveTheme(
|
||||
lightScheme = AgendulaLightFallback,
|
||||
darkScheme = AgendulaDarkFallback,
|
||||
darkTheme = darkTheme,
|
||||
dynamicColor = dynamicColor,
|
||||
typography = AgendulaTypography,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.ui.theme
|
||||
package de.jeanlucmakiola.agendula.ui.theme
|
||||
|
||||
import androidx.compose.material3.Typography
|
||||
|
||||
@@ -7,4 +7,4 @@ import androidx.compose.material3.Typography
|
||||
* land in a later UI-design iteration; the defaults keep the M0 foundation lean
|
||||
* (same posture as Calendula's scaffolding).
|
||||
*/
|
||||
val FloretTypography = Typography()
|
||||
val AgendulaTypography = Typography()
|
||||
@@ -1,69 +0,0 @@
|
||||
package de.jeanlucmakiola.floret
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
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.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import de.jeanlucmakiola.floret.data.demo.DemoSeeder
|
||||
import de.jeanlucmakiola.floret.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.ui.RootScreen
|
||||
import de.jeanlucmakiola.floret.ui.settings.SettingsViewModel
|
||||
import de.jeanlucmakiola.floret.ui.theme.FloretTheme
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Single activity. The theme follows [SettingsViewModel]; [RootScreen] is the
|
||||
* (replaceable) functional scaffold over the real data layer. Task-detail intent
|
||||
* routing for reminder taps lands with the full UI.
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
@Inject lateinit var demoSeeder: DemoSeeder
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
// Debug-only sample data: `am start ... --ez floret_seed true`. Seeds a
|
||||
// local (non-syncing) demo list once; no-op without the extra.
|
||||
if (BuildConfig.DEBUG && intent.getBooleanExtra(EXTRA_SEED, false)) {
|
||||
lifecycleScope.launch { runCatching { demoSeeder.seed() } }
|
||||
}
|
||||
setContent {
|
||||
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
||||
val ui by settingsViewModel.state.collectAsStateWithLifecycle()
|
||||
val darkTheme = when (ui.settings.themeMode) {
|
||||
ThemeMode.SYSTEM -> isSystemInDarkTheme()
|
||||
ThemeMode.LIGHT -> false
|
||||
ThemeMode.DARK -> true
|
||||
}
|
||||
FloretTheme(darkTheme = darkTheme, dynamicColor = ui.settings.dynamicColor) {
|
||||
RootScreen(modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_TASK_ID = "de.jeanlucmakiola.floret.extra.TASK_ID"
|
||||
private const val EXTRA_SEED = "floret_seed"
|
||||
|
||||
/** Opens the app focused on a task (reminder taps). Routing lands with the UI. */
|
||||
fun taskIntent(context: Context, taskId: Long): Intent =
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
putExtra(EXTRA_TASK_ID, taskId)
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.longPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||
import de.jeanlucmakiola.floret.domain.TaskFormField
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
enum class ThemeMode { SYSTEM, LIGHT, DARK }
|
||||
|
||||
data class Settings(
|
||||
val themeMode: ThemeMode = ThemeMode.SYSTEM,
|
||||
val dynamicColor: Boolean = true,
|
||||
/** The list a new task defaults to; `null` = first available. */
|
||||
val defaultListId: Long? = null,
|
||||
/** Default minutes before due to remind; 0 = at due time. */
|
||||
val reminderLeadMinutes: Int = 0,
|
||||
/** Optional edit-form fields shown by default; the rest sit behind "More fields". */
|
||||
val defaultEditFields: Set<TaskFormField> = emptySet(),
|
||||
)
|
||||
|
||||
/** App preferences, backed by DataStore. Mirrors Calendula's prefs shape. */
|
||||
@Singleton
|
||||
class SettingsPrefs @Inject constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
val settings: Flow<Settings> = dataStore.data.map { p ->
|
||||
Settings(
|
||||
themeMode = p[THEME_MODE]?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() }
|
||||
?: ThemeMode.SYSTEM,
|
||||
dynamicColor = p[DYNAMIC_COLOR] ?: true,
|
||||
defaultListId = p[DEFAULT_LIST_ID]?.takeIf { it > 0 },
|
||||
reminderLeadMinutes = p[REMINDER_LEAD] ?: 0,
|
||||
defaultEditFields = p[DEFAULT_EDIT_FIELDS].orEmpty()
|
||||
.mapNotNull { name -> runCatching { TaskFormField.valueOf(name) }.getOrNull() }
|
||||
.toSet(),
|
||||
)
|
||||
}
|
||||
|
||||
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 setDefaultListId(id: Long?) = dataStore.edit {
|
||||
if (id == null) it.remove(DEFAULT_LIST_ID) else it[DEFAULT_LIST_ID] = id
|
||||
}
|
||||
|
||||
suspend fun setReminderLeadMinutes(minutes: Int) = dataStore.edit { it[REMINDER_LEAD] = minutes }
|
||||
|
||||
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_EDIT_FIELDS = stringSetPreferencesKey("default_edit_fields")
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.data.reminders
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Re-syncs reminders whenever the tasks provider changes — covers external sync
|
||||
* (DAVx5 pulling new/edited tasks) while Floret isn't in the foreground. The
|
||||
* manifest filter targets both known authorities; best-effort (the in-app
|
||||
* ContentObserver covers the foreground case regardless).
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class ProviderChangeReceiver : BroadcastReceiver() {
|
||||
|
||||
@Inject lateinit var scheduler: ReminderScheduler
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val pending = goAsync()
|
||||
scope.launch {
|
||||
try {
|
||||
scheduler.sync()
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.data.reminders
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.floret.data.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.floret.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.floret.data.tasks.TaskQuery
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksDataSource
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* The self-scheduled due-reminder engine. Tasks providers don't deliver
|
||||
* reminders, so Floret reads upcoming due tasks and arms one exact [AlarmManager]
|
||||
* alarm each, within a rolling window. Re-run on app start, boot and provider
|
||||
* change; it diffs against [ScheduledReminderStore] so only changed alarms move.
|
||||
*/
|
||||
@Singleton
|
||||
class ReminderScheduler @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val dataSource: TasksDataSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val store: ScheduledReminderStore,
|
||||
private val providerResolver: ProviderResolver,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
) {
|
||||
suspend fun sync() = withContext(io) {
|
||||
val provider = providerResolver.resolve()
|
||||
if (provider == null || !providerResolver.hasPermission(provider)) {
|
||||
clearAll()
|
||||
return@withContext
|
||||
}
|
||||
val lead = settingsPrefs.settings.first().reminderLeadMinutes.coerceAtLeast(0)
|
||||
val now = System.currentTimeMillis()
|
||||
val horizon = now + WINDOW_MS
|
||||
val tasks = runCatching { dataSource.tasks(TaskQuery(includeCompleted = false)) }
|
||||
.getOrElse { return@withContext }
|
||||
|
||||
val desired = tasks
|
||||
.filter { !it.isClosed && it.due != null }
|
||||
.associate { it.taskId to (it.due!!.toEpochMilliseconds() - lead * 60_000L) }
|
||||
.filterValues { it in now..horizon }
|
||||
|
||||
val previous = store.all()
|
||||
(previous.keys - desired.keys).forEach { cancel(it) }
|
||||
desired.forEach { (taskId, triggerAt) ->
|
||||
if (previous[taskId] != triggerAt) schedule(taskId, triggerAt)
|
||||
}
|
||||
store.replace(desired)
|
||||
}
|
||||
|
||||
private fun alarmManager(): AlarmManager = context.getSystemService(AlarmManager::class.java)
|
||||
|
||||
private fun pendingIntent(taskId: Long, create: Boolean): PendingIntent? {
|
||||
val flags = (if (create) PendingIntent.FLAG_UPDATE_CURRENT else PendingIntent.FLAG_NO_CREATE) or
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
return PendingIntent.getBroadcast(context, taskId.toInt(), DueReminderReceiver.intent(context, taskId), flags)
|
||||
}
|
||||
|
||||
private fun schedule(taskId: Long, triggerAt: Long) {
|
||||
val pi = pendingIntent(taskId, create = true) ?: return
|
||||
val am = alarmManager()
|
||||
val canExact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || am.canScheduleExactAlarms()
|
||||
if (canExact) {
|
||||
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pi)
|
||||
} else {
|
||||
am.set(AlarmManager.RTC_WAKEUP, triggerAt, pi)
|
||||
}
|
||||
}
|
||||
|
||||
private fun cancel(taskId: Long) {
|
||||
pendingIntent(taskId, create = false)?.let {
|
||||
alarmManager().cancel(it)
|
||||
it.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun clearAll() {
|
||||
store.all().keys.forEach { cancel(it) }
|
||||
store.replace(emptyMap())
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val WINDOW_MS = 30L * 24 * 60 * 60 * 1000 // 30 days
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.data.reminders
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||
import kotlinx.coroutines.flow.first
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Remembers which task reminders are currently scheduled (taskId → trigger time),
|
||||
* so [ReminderScheduler] can diff against a fresh computation and cancel only the
|
||||
* alarms that changed. Persisted in DataStore as a set of `taskId|trigger` strings.
|
||||
*/
|
||||
@Singleton
|
||||
class ScheduledReminderStore @Inject constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
suspend fun all(): Map<Long, Long> =
|
||||
dataStore.data.first()[KEY].orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split('|')
|
||||
val id = parts.getOrNull(0)?.toLongOrNull()
|
||||
val at = parts.getOrNull(1)?.toLongOrNull()
|
||||
if (id != null && at != null) id to at else null
|
||||
}.toMap()
|
||||
|
||||
suspend fun replace(scheduled: Map<Long, Long>) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[KEY] = scheduled.entries.map { "${it.key}|${it.value}" }.toSet()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val KEY = stringSetPreferencesKey("scheduled_reminders")
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Instances
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Tasks
|
||||
|
||||
/** Column lists requested from the provider. Order is irrelevant; we read by name. */
|
||||
object TaskProjections {
|
||||
|
||||
val LISTS: Array<String> = arrayOf(
|
||||
Lists.ID,
|
||||
Lists.NAME,
|
||||
Lists.COLOR,
|
||||
Lists.VISIBLE,
|
||||
Lists.SYNC_ENABLED,
|
||||
Lists.OWNER,
|
||||
Lists.ACCOUNT_NAME,
|
||||
Lists.ACCOUNT_TYPE,
|
||||
)
|
||||
|
||||
/** Read from the `instances` view (inherits all task columns). */
|
||||
val INSTANCES: Array<String> = arrayOf(
|
||||
Tasks.ID,
|
||||
Instances.TASK_ID,
|
||||
Tasks.LIST_ID,
|
||||
Tasks.TITLE,
|
||||
Tasks.DESCRIPTION,
|
||||
Tasks.LOCATION,
|
||||
Tasks.URL,
|
||||
Tasks.PRIORITY,
|
||||
Tasks.STATUS,
|
||||
Tasks.PERCENT_COMPLETE,
|
||||
Tasks.COMPLETED,
|
||||
Tasks.IS_ALLDAY,
|
||||
Tasks.TZ,
|
||||
Instances.INSTANCE_START,
|
||||
Instances.INSTANCE_DUE,
|
||||
Tasks.TASK_COLOR,
|
||||
Tasks.LIST_COLOR,
|
||||
Tasks.LIST_NAME,
|
||||
Tasks.ACCOUNT_NAME,
|
||||
Tasks.PARENT_ID,
|
||||
Instances.IS_RECURRING,
|
||||
Instances.DISTANCE_FROM_CURRENT,
|
||||
Tasks.CREATED,
|
||||
Tasks.LAST_MODIFIED,
|
||||
)
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
|
||||
/** What to fetch from the provider. Smart-list date logic is applied above this. */
|
||||
data class TaskQuery(
|
||||
val listId: Long? = null,
|
||||
val includeCompleted: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Domain-shaped, synchronous seam over the tasks ContentResolver. Returns parsed
|
||||
* lists so [TasksRepositoryImpl] can be tested with a fake on the JVM. All Cursor
|
||||
* and ContentObserver handling lives in [AndroidTasksDataSource].
|
||||
*/
|
||||
interface TasksDataSource {
|
||||
fun taskLists(): List<TaskList>
|
||||
fun tasks(query: TaskQuery): List<Task>
|
||||
fun task(taskId: Long): Task?
|
||||
fun subtasks(parentTaskId: Long): List<Task>
|
||||
|
||||
fun insertTask(form: TaskForm): Long
|
||||
fun updateTask(taskId: Long, form: TaskForm)
|
||||
fun setCompleted(taskId: Long, completed: Boolean)
|
||||
fun deleteTask(taskId: Long)
|
||||
fun createLocalList(name: String, color: Int): Long
|
||||
|
||||
/** Observe any change to tasks/lists; [onChange] fires on a background thread. */
|
||||
fun registerObserver(onChange: () -> Unit): AutoCloseable
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** Local-day boundaries used by the smart-list predicates. Pure + testable. */
|
||||
object DayWindow {
|
||||
|
||||
/** Returns `[startOfToday, startOfTomorrow)` in [zone] for the instant [now]. */
|
||||
fun today(now: Instant, zone: ZoneId): Pair<Instant, Instant> {
|
||||
val date = java.time.Instant.ofEpochMilli(now.toEpochMilliseconds())
|
||||
.atZone(zone)
|
||||
.toLocalDate()
|
||||
val start = date.atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val end = date.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
return Instant.fromEpochMilliseconds(start) to Instant.fromEpochMilliseconds(end)
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.common
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Clear
|
||||
import androidx.compose.material.icons.rounded.Event
|
||||
import androidx.compose.material3.DatePicker
|
||||
import androidx.compose.material3.DatePickerDialog
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
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.material3.TimePicker
|
||||
import androidx.compose.material3.rememberDatePickerState
|
||||
import androidx.compose.material3.rememberTimePickerState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import de.jeanlucmakiola.floret.R
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.time.ZoneOffset
|
||||
import kotlin.time.Instant
|
||||
|
||||
private val zone: ZoneId get() = ZoneId.systemDefault()
|
||||
|
||||
internal fun Instant.toLocalDate(): LocalDate =
|
||||
java.time.Instant.ofEpochMilli(toEpochMilliseconds()).atZone(zone).toLocalDate()
|
||||
|
||||
internal fun Instant.toLocalTime(): LocalTime =
|
||||
java.time.Instant.ofEpochMilli(toEpochMilliseconds()).atZone(zone).toLocalTime()
|
||||
|
||||
internal fun localToInstant(date: LocalDate, time: LocalTime): Instant =
|
||||
Instant.fromEpochMilliseconds(date.atTime(time).atZone(zone).toInstant().toEpochMilli())
|
||||
|
||||
/**
|
||||
* A labelled date(-time) field for the edit form: a tonal row showing the
|
||||
* current value (or nothing), tappable to pick a date and — unless [allDay] —
|
||||
* a time. A clear affordance appears once a value is set. Emits `null` when
|
||||
* cleared. Styled to match the app's rounded tonal family.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DateTimeField(
|
||||
label: String,
|
||||
value: Instant?,
|
||||
allDay: Boolean,
|
||||
onChange: (Instant?) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var showDatePicker by remember { mutableStateOf(false) }
|
||||
var showTimePicker by remember { mutableStateOf(false) }
|
||||
var pendingDate by remember { mutableStateOf<LocalDate?>(null) }
|
||||
|
||||
Surface(
|
||||
onClick = { showDatePicker = true },
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(Icons.Rounded.Event, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
text = value?.formatDateTime(allDay) ?: stringResource(R.string.edit_set),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
}
|
||||
if (value != null) {
|
||||
IconButton(onClick = { onChange(null) }) {
|
||||
Icon(Icons.Rounded.Clear, contentDescription = stringResource(R.string.edit_clear))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showDatePicker) {
|
||||
val initialMillis = (value ?: Instant.fromEpochMilliseconds(System.currentTimeMillis()))
|
||||
.toLocalDate().atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
|
||||
val dateState = rememberDatePickerState(initialSelectedDateMillis = initialMillis)
|
||||
DatePickerDialog(
|
||||
onDismissRequest = { showDatePicker = false },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
showDatePicker = false
|
||||
val millis = dateState.selectedDateMillis ?: return@TextButton
|
||||
val date = java.time.Instant.ofEpochMilli(millis)
|
||||
.atZone(ZoneOffset.UTC).toLocalDate()
|
||||
if (allDay) {
|
||||
onChange(localToInstant(date, LocalTime.MIDNIGHT))
|
||||
} else {
|
||||
pendingDate = date
|
||||
showTimePicker = true
|
||||
}
|
||||
},
|
||||
) { Text(stringResource(android.R.string.ok)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDatePicker = false }) {
|
||||
Text(stringResource(android.R.string.cancel))
|
||||
}
|
||||
},
|
||||
) { DatePicker(state = dateState) }
|
||||
}
|
||||
|
||||
if (showTimePicker) {
|
||||
val base = value ?: Instant.fromEpochMilliseconds(System.currentTimeMillis())
|
||||
val timeState = rememberTimePickerState(
|
||||
initialHour = base.toLocalTime().hour,
|
||||
initialMinute = base.toLocalTime().minute,
|
||||
)
|
||||
Dialog(onDismissRequest = { showTimePicker = false }) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
TimePicker(state = timeState)
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
) {
|
||||
TextButton(onClick = { showTimePicker = false }) {
|
||||
Text(stringResource(android.R.string.cancel))
|
||||
}
|
||||
TextButton(onClick = {
|
||||
showTimePicker = false
|
||||
val date = pendingDate ?: return@TextButton
|
||||
onChange(localToInstant(date, LocalTime.of(timeState.hour, timeState.minute)))
|
||||
}) { Text(stringResource(android.R.string.ok)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.common
|
||||
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.format.FormatStyle
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* Locale-aware display formatting for the [kotlin.time.Instant]s the domain
|
||||
* uses. Kept tiny and dependency-free; the data layer stores instants, the UI
|
||||
* renders them in the device's zone and locale.
|
||||
*/
|
||||
private val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
|
||||
private val timeFormatter: DateTimeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
|
||||
|
||||
private fun Instant.atSystemZone() =
|
||||
java.time.Instant.ofEpochMilli(toEpochMilliseconds())
|
||||
.atZone(ZoneId.systemDefault())
|
||||
|
||||
/** Medium localized date, e.g. "18 Jun 2026". */
|
||||
fun Instant.formatDate(): String = atSystemZone().format(dateFormatter)
|
||||
|
||||
/** Short localized time, e.g. "14:30". */
|
||||
fun Instant.formatTime(): String = atSystemZone().format(timeFormatter)
|
||||
|
||||
/** Date alone for all-day items, otherwise date + time. */
|
||||
fun Instant.formatDateTime(allDay: Boolean): String =
|
||||
if (allDay) formatDate() else "${formatDate()} · ${formatTime()}"
|
||||
@@ -1,130 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.common
|
||||
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.ListItemDefaults
|
||||
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.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* Position of a row within a grouped list (the Android-15 settings pattern): a
|
||||
* run of rows shares one rounded container, full corners at the group's outer
|
||||
* edges and small corners between, separated by small gaps. Copied from
|
||||
* Calendula so the two apps read as one family.
|
||||
*/
|
||||
enum class Position { Top, Middle, Bottom, Alone }
|
||||
|
||||
fun positionOf(index: Int, count: Int): Position = when {
|
||||
count <= 1 -> Position.Alone
|
||||
index == 0 -> Position.Top
|
||||
index == count - 1 -> Position.Bottom
|
||||
else -> Position.Middle
|
||||
}
|
||||
|
||||
/** Corner radii for a grouped segment: full at the group's outer edges, small between. */
|
||||
fun groupedShape(position: Position, full: Dp, small: Dp): Shape = when (position) {
|
||||
Position.Alone -> RoundedCornerShape(full)
|
||||
Position.Top -> RoundedCornerShape(topStart = full, topEnd = full, bottomStart = small, bottomEnd = small)
|
||||
Position.Middle -> RoundedCornerShape(small)
|
||||
Position.Bottom -> RoundedCornerShape(topStart = small, topEnd = small, bottomStart = full, bottomEnd = full)
|
||||
}
|
||||
|
||||
/**
|
||||
* One segment of a grouped list: a tonal [Surface] whose corner radii come from
|
||||
* [position] (so a run reads as a single rounded card), with a small gap below
|
||||
* all but the last. Corners morph rounder on press — the expressive shape play.
|
||||
* The caller supplies [content] and any horizontal inset via [modifier], so the
|
||||
* same primitive serves both the 16dp-inset lists and full-width detail cards.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GroupedSurface(
|
||||
position: Position,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: (() -> Unit)? = null,
|
||||
color: Color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
val full by animateDpAsState(if (pressed) 36.dp else 22.dp, label = "fullCorner")
|
||||
val small by animateDpAsState(if (pressed) 36.dp else 6.dp, label = "smallCorner")
|
||||
val shape = groupedShape(position, full, small)
|
||||
val gap = when (position) {
|
||||
Position.Top, Position.Middle -> Modifier.padding(bottom = 2.dp)
|
||||
Position.Bottom, Position.Alone -> Modifier
|
||||
}
|
||||
val base = modifier.fillMaxWidth().then(gap)
|
||||
if (onClick != null) {
|
||||
Surface(onClick = onClick, color = color, shape = shape, interactionSource = interaction, modifier = base) { content() }
|
||||
} else {
|
||||
Surface(color = color, shape = shape, modifier = base) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One row in a grouped list: an M3 [ListItem] over a [GroupedSurface] (the
|
||||
* tonal, position-shaped, press-morphing family container). Insets 16dp like
|
||||
* the lists overview.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GroupedRow(
|
||||
title: String,
|
||||
position: Position,
|
||||
modifier: Modifier = Modifier,
|
||||
summary: String? = null,
|
||||
selected: Boolean = false,
|
||||
minHeight: Dp = 72.dp,
|
||||
leading: @Composable (() -> Unit)? = null,
|
||||
trailing: @Composable (() -> Unit)? = null,
|
||||
onClick: (() -> Unit)? = null,
|
||||
) {
|
||||
val itemColors = if (selected) {
|
||||
ListItemDefaults.colors(
|
||||
containerColor = Color.Transparent,
|
||||
headlineColor = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
leadingIconColor = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
supportingColor = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
trailingIconColor = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
)
|
||||
} else {
|
||||
ListItemDefaults.colors(containerColor = Color.Transparent)
|
||||
}
|
||||
val containerColor = if (selected) {
|
||||
MaterialTheme.colorScheme.secondaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceContainerHigh
|
||||
}
|
||||
GroupedSurface(
|
||||
position = position,
|
||||
modifier = modifier.padding(horizontal = 16.dp),
|
||||
onClick = onClick,
|
||||
color = containerColor,
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text(title) },
|
||||
supportingContent = summary?.let { text -> { Text(text) } },
|
||||
leadingContent = leading,
|
||||
trailingContent = trailing,
|
||||
colors = itemColors,
|
||||
modifier = Modifier.heightIn(min = minHeight),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.common
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.isSpecified
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* The app's borderless text input: no underline, no outline, just the tonal
|
||||
* card behind it. Floret uses this inside a tonal [androidx.compose.material3.Surface]
|
||||
* for the edit form (title + cards), so anything that takes text reads as one
|
||||
* family rather than a boxed Material field. Ported from Calendula so the two
|
||||
* apps share one input style.
|
||||
*/
|
||||
@Composable
|
||||
fun InlineTextField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
placeholder: String,
|
||||
modifier: Modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 4.dp),
|
||||
textStyle: TextStyle = MaterialTheme.typography.titleMedium,
|
||||
singleLine: Boolean = true,
|
||||
minLines: Int = 1,
|
||||
keyboardType: KeyboardType = KeyboardType.Text,
|
||||
capitalization: KeyboardCapitalization = KeyboardCapitalization.Sentences,
|
||||
imeAction: ImeAction = ImeAction.Default,
|
||||
/** Invoked when the IME action key (e.g. Done) is pressed. */
|
||||
onImeAction: (() -> Unit)? = null,
|
||||
) {
|
||||
val resolvedStyle = textStyle.copy(
|
||||
color = if (textStyle.color.isSpecified) {
|
||||
textStyle.color
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurface
|
||||
},
|
||||
)
|
||||
BasicTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
textStyle = resolvedStyle,
|
||||
singleLine = singleLine,
|
||||
minLines = minLines,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = keyboardType,
|
||||
capitalization = capitalization,
|
||||
imeAction = imeAction,
|
||||
),
|
||||
keyboardActions = onImeAction?.let { action ->
|
||||
KeyboardActions(onAny = { action() })
|
||||
} ?: KeyboardActions.Default,
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||
decorationBox = { innerTextField ->
|
||||
Box {
|
||||
if (value.isEmpty()) {
|
||||
// Clearly fainter than typed text, so a hint never reads as
|
||||
// prefilled content.
|
||||
Text(
|
||||
text = placeholder,
|
||||
style = resolvedStyle,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
|
||||
)
|
||||
}
|
||||
innerTextField()
|
||||
}
|
||||
},
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.common
|
||||
|
||||
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.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
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.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.isSpecified
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* The app's standard pick in a selection dialog: a full-width tonal card,
|
||||
* optionally with a leading icon and a supporting line; the selected option is
|
||||
* highlighted. Stack with 8dp gaps inside an AlertDialog — the only sanctioned
|
||||
* selection-modal style (no radio rows, no bare text lists). Ported from
|
||||
* Calendula so the families' dialogs read identically.
|
||||
*/
|
||||
@Composable
|
||||
fun OptionCard(
|
||||
label: String,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
icon: ImageVector? = null,
|
||||
/** Icon tint override, e.g. a list colour; unspecified follows selection. */
|
||||
iconTint: Color = Color.Unspecified,
|
||||
supportingText: String? = null,
|
||||
selected: Boolean = false,
|
||||
/** Label colour override, e.g. primary for an emphasised entry. */
|
||||
labelColor: Color = Color.Unspecified,
|
||||
) {
|
||||
val contentColor = if (selected) {
|
||||
MaterialTheme.colorScheme.onSecondaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurface
|
||||
}
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
color = if (selected) {
|
||||
MaterialTheme.colorScheme.secondaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceContainerHighest
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
if (icon != null) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
tint = when {
|
||||
iconTint.isSpecified -> iconTint
|
||||
selected -> MaterialTheme.colorScheme.onSecondaryContainer
|
||||
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
}
|
||||
Column {
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = if (labelColor.isSpecified) labelColor else contentColor,
|
||||
)
|
||||
if (supportingText != null) {
|
||||
Text(
|
||||
text = supportingText,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (selected) {
|
||||
MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.8f)
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.lists
|
||||
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
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.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
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.ErrorOutline
|
||||
import androidx.compose.material.icons.rounded.Today
|
||||
import androidx.compose.material.icons.rounded.Upcoming
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.MediumTopAppBar
|
||||
import androidx.compose.material3.Scaffold
|
||||
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.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.floret.R
|
||||
import de.jeanlucmakiola.floret.domain.SmartList
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.floret.ui.common.GroupedRow
|
||||
import de.jeanlucmakiola.floret.ui.common.ListColorChip
|
||||
import de.jeanlucmakiola.floret.ui.common.positionOf
|
||||
|
||||
/**
|
||||
* Home: smart lists (Today / Overdue / Upcoming / All) as tonal cards with live
|
||||
* counts, then the user's lists grouped by account. Tapping a card or row opens
|
||||
* that task list; the FAB starts a new task.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ListsScreen(
|
||||
onOpenFilter: (TaskFilter) -> Unit,
|
||||
onNewTask: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: ListsViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
|
||||
topBar = {
|
||||
MediumTopAppBar(
|
||||
title = { Text(stringResource(R.string.app_name)) },
|
||||
scrollBehavior = scrollBehavior,
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onNewTask,
|
||||
icon = { Icon(Icons.Rounded.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.new_task)) },
|
||||
)
|
||||
},
|
||||
) { inner ->
|
||||
when (val s = state) {
|
||||
ListsUiState.Loading -> Unit // brief; avoids a flash before first emission
|
||||
ListsUiState.Failure -> CenteredMessage(stringResource(R.string.lists_failure), inner)
|
||||
is ListsUiState.Content -> ListsContent(s, inner, onOpenFilter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ListsContent(
|
||||
state: ListsUiState.Content,
|
||||
inner: PaddingValues,
|
||||
onOpenFilter: (TaskFilter) -> Unit,
|
||||
) {
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(
|
||||
top = inner.calculateTopPadding(),
|
||||
bottom = inner.calculateBottomPadding() + 96.dp,
|
||||
),
|
||||
) {
|
||||
item { SmartGrid(state.smartCounts, onOpenFilter) }
|
||||
|
||||
if (state.groups.isEmpty()) {
|
||||
item { CenteredMessage(stringResource(R.string.lists_empty), PaddingValues(top = 24.dp)) }
|
||||
} else {
|
||||
item { SectionHeader(stringResource(R.string.lists_header)) }
|
||||
state.groups.forEach { group ->
|
||||
item(key = "acct-${group.accountName}") { AccountHeader(group.accountName) }
|
||||
itemsIndexed(group.lists, key = { _, o -> o.list.id }) { index, overview ->
|
||||
GroupedRow(
|
||||
title = overview.list.name,
|
||||
position = positionOf(index, group.lists.size),
|
||||
minHeight = 72.dp,
|
||||
leading = { ListColorChip(overview.list.color) },
|
||||
trailing = {
|
||||
if (overview.openCount > 0) {
|
||||
Text(
|
||||
overview.openCount.toString(),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
onClick = { onOpenFilter(TaskFilter.OfList(overview.list.id)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SmartGrid(counts: List<SmartCount>, onOpenFilter: (TaskFilter) -> Unit) {
|
||||
Column(
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
counts.chunked(2).forEach { row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
row.forEach { smart ->
|
||||
SmartCard(
|
||||
count = smart,
|
||||
modifier = Modifier.weight(1f),
|
||||
onClick = { onOpenFilter(TaskFilter.Smart(smart.smart)) },
|
||||
)
|
||||
}
|
||||
if (row.size == 1) Spacer(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class SmartStyle(val icon: ImageVector, val labelRes: Int, val container: Color, val onContainer: Color)
|
||||
|
||||
@Composable
|
||||
private fun smartStyle(smart: SmartList): SmartStyle {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
return when (smart) {
|
||||
SmartList.TODAY -> SmartStyle(Icons.Rounded.Today, R.string.smart_today, colors.primaryContainer, colors.onPrimaryContainer)
|
||||
SmartList.OVERDUE -> SmartStyle(Icons.Rounded.ErrorOutline, R.string.smart_overdue, colors.errorContainer, colors.onErrorContainer)
|
||||
SmartList.UPCOMING -> SmartStyle(Icons.Rounded.Upcoming, R.string.smart_upcoming, colors.tertiaryContainer, colors.onTertiaryContainer)
|
||||
else -> SmartStyle(Icons.AutoMirrored.Rounded.ListAlt, R.string.smart_all, colors.secondaryContainer, colors.onSecondaryContainer)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean tonal tile. The expressive touch is subtle: rounded corners gently morph
|
||||
* rounder on press (the same quiet shape behaviour as the lists), not a loud
|
||||
* silhouette.
|
||||
*/
|
||||
@Composable
|
||||
private fun SmartCard(count: SmartCount, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val style = smartStyle(count.smart)
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
val corner by animateDpAsState(if (pressed) 34.dp else 22.dp, label = "smartCorner")
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
shape = RoundedCornerShape(corner),
|
||||
color = style.container,
|
||||
contentColor = style.onContainer,
|
||||
interactionSource = interaction,
|
||||
modifier = modifier.height(116.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||
verticalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Icon(style.icon, contentDescription = null)
|
||||
Column {
|
||||
Text(count.count.toString(), style = MaterialTheme.typography.headlineMedium)
|
||||
Text(stringResource(style.labelRes), style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionHeader(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 16.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AccountHeader(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 12.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CenteredMessage(text: String, inner: PaddingValues) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize().padding(inner).padding(32.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.lists
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.floret.domain.DayWindow
|
||||
import de.jeanlucmakiola.floret.domain.SmartList
|
||||
import de.jeanlucmakiola.floret.domain.Task
|
||||
import de.jeanlucmakiola.floret.domain.TaskFilter
|
||||
import de.jeanlucmakiola.floret.domain.TaskFiltering
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
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 java.time.ZoneId
|
||||
import javax.inject.Inject
|
||||
import kotlin.time.Clock
|
||||
|
||||
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)
|
||||
|
||||
sealed interface ListsUiState {
|
||||
data object Loading : ListsUiState
|
||||
data object Failure : ListsUiState
|
||||
data class Content(
|
||||
val smartCounts: List<SmartCount>,
|
||||
val groups: List<AccountGroup>,
|
||||
) : ListsUiState
|
||||
}
|
||||
|
||||
/** The home overview: smart lists with live counts, then user lists by account. */
|
||||
@HiltViewModel
|
||||
class ListsViewModel @Inject constructor(
|
||||
repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
val state: StateFlow<ListsUiState> =
|
||||
combine(
|
||||
repository.taskLists(),
|
||||
repository.tasks(TaskFilter.Smart(SmartList.ALL)),
|
||||
) { lists, openTasks ->
|
||||
buildContent(lists, openTasks) as ListsUiState
|
||||
}.catch { emit(ListsUiState.Failure) }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListsUiState.Loading)
|
||||
|
||||
private fun buildContent(lists: List<TaskList>, openTasks: List<Task>): ListsUiState.Content {
|
||||
val (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
|
||||
// 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 }
|
||||
fun count(smart: SmartList) =
|
||||
topLevel.count { TaskFiltering.matches(it, TaskFilter.Smart(smart), todayStart, todayEnd) }
|
||||
|
||||
val smartCounts = listOf(
|
||||
SmartCount(SmartList.TODAY, count(SmartList.TODAY)),
|
||||
SmartCount(SmartList.OVERDUE, count(SmartList.OVERDUE)),
|
||||
SmartCount(SmartList.UPCOMING, count(SmartList.UPCOMING)),
|
||||
SmartCount(SmartList.ALL, topLevel.size),
|
||||
)
|
||||
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) },
|
||||
)
|
||||
}
|
||||
.sortedBy { it.accountName.lowercase() }
|
||||
return ListsUiState.Content(smartCounts, groups)
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.navigation
|
||||
|
||||
import androidx.compose.animation.core.FiniteAnimationSpec
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
|
||||
/**
|
||||
* The horizontal slide spec for screen-to-screen navigation: the *fast*
|
||||
* spring-physics spec from the active motion scheme — snappy with a subtle
|
||||
* springy settle, rather than a fixed easing curve. Same choice as Calendula's
|
||||
* calendar slide, so the two apps move the same way.
|
||||
*
|
||||
* Read in composable scope so the non-composable `NavHost` transition lambdas
|
||||
* can capture it.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
fun rememberNavSlideSpec(): FiniteAnimationSpec<IntOffset> =
|
||||
MaterialTheme.motionScheme.fastSpatialSpec()
|
||||
@@ -1,43 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.settings
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.floret.data.prefs.Settings
|
||||
import de.jeanlucmakiola.floret.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.floret.data.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksRepository
|
||||
import de.jeanlucmakiola.floret.domain.TaskList
|
||||
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
|
||||
|
||||
data class SettingsUiState(
|
||||
val settings: Settings = Settings(),
|
||||
val lists: List<TaskList> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Drives both the Settings screen and the app theme (MainActivity collects the
|
||||
* same instance), so a theme change applies app-wide at once.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class SettingsViewModel @Inject constructor(
|
||||
private val prefs: SettingsPrefs,
|
||||
repository: TasksRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
val state: StateFlow<SettingsUiState> =
|
||||
combine(prefs.settings, repository.taskLists().catch { emit(emptyList()) }) { settings, lists ->
|
||||
SettingsUiState(settings, lists)
|
||||
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SettingsUiState())
|
||||
|
||||
fun setThemeMode(mode: ThemeMode) = viewModelScope.launch { prefs.setThemeMode(mode) }
|
||||
fun setDynamicColor(enabled: Boolean) = viewModelScope.launch { prefs.setDynamicColor(enabled) }
|
||||
fun setDefaultList(id: Long?) = viewModelScope.launch { prefs.setDefaultListId(id) }
|
||||
fun setReminderLeadMinutes(minutes: Int) = viewModelScope.launch { prefs.setReminderLeadMinutes(minutes) }
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package de.jeanlucmakiola.floret.ui.theme
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.MaterialExpressiveTheme
|
||||
import androidx.compose.material3.MotionScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
/**
|
||||
* App theme. Honors:
|
||||
* - System light/dark.
|
||||
* - Dynamic Color on API 31+, else falls back to the hand-tuned scheme
|
||||
* derived from [FloretSeed].
|
||||
*
|
||||
* Mirrors Calendula's theme: MaterialExpressiveTheme routes all component +
|
||||
* custom motion through MaterialTheme.motionScheme. STANDARD over expressive()
|
||||
* is the same deliberate choice — spring choreography without the overshoot.
|
||||
*
|
||||
* A Settings screen can later override dynamicColor and theme mode; the M0
|
||||
* foundation just follows the system.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
fun FloretTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
dynamicColor: Boolean = true,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val colorScheme = when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val ctx = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(ctx) else dynamicLightColorScheme(ctx)
|
||||
}
|
||||
darkTheme -> FloretDarkFallback
|
||||
else -> FloretLightFallback
|
||||
}
|
||||
|
||||
MaterialExpressiveTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = FloretTypography,
|
||||
motionScheme = MotionScheme.standard(),
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
@@ -1,22 +1,89 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Floret launcher icon foreground — PLACEHOLDER.
|
||||
Agendula launcher icon foreground.
|
||||
|
||||
A simple rounded check mark inside the 108dp adaptive-icon canvas
|
||||
(72dp safe zone). Deliberately not Calendula's calendar mark, so the two
|
||||
apps never look alike. Replace with real branding (a stylized floret)
|
||||
when the design lands — see docs/PLAN.md §9.
|
||||
Converted from design/icon/agendula_icon.svg (512x512 viewport): a rounded
|
||||
line-art task card with a check mark, plus a small Calendula bloom badge in
|
||||
the bottom-right corner — the sibling of Calendula's calendar mark.
|
||||
|
||||
Strokes render in off-white (#FAF6F0) over the plum background drawable
|
||||
(drawable/ic_launcher_background.xml = @color/ic_launcher_background, the
|
||||
hue-rotated counterpart of Calendula's slate). The same vector fills the
|
||||
<monochrome> slot so Android 13+ themed-icon launchers can recolour it.
|
||||
|
||||
Centering / scale:
|
||||
- Scale 0.66 about the canvas centre (matching Calendula's ~2.8dp stroke
|
||||
weight and generous padding).
|
||||
- The eye centres on the task CARD, not the card+bloom bounding box (the
|
||||
bloom is a small badge that overhangs the bottom-right). So vertically we
|
||||
centre the card itself: its geometric centre is y=242.76, so we pivot the
|
||||
Y-scale there and translate +13.24 to drop that centre onto the canvas
|
||||
centre (256). Horizontally the card already sits centred, so X scales
|
||||
about 256 untouched.
|
||||
-->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
android:viewportWidth="512"
|
||||
android:viewportHeight="512">
|
||||
<group
|
||||
android:pivotX="256"
|
||||
android:pivotY="242.76"
|
||||
android:scaleX="0.66"
|
||||
android:scaleY="0.66"
|
||||
android:translateY="13.24">
|
||||
<!-- Task card (rounded square, opening at the bottom-right for the bloom) -->
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeWidth="9"
|
||||
android:strokeColor="#FFFAF6F0"
|
||||
android:strokeWidth="20"
|
||||
android:strokeMiterLimit="12"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M36,55 l13,13 l25,-27" />
|
||||
android:pathData="M370.207 254.345V168.276C370.207 144.508 350.939 125.241 327.172 125.241H178.207C154.439 125.241 135.172 144.508 135.172 168.276V317.241C135.172 341.008 154.439 360.276 178.207 360.276H269.241" />
|
||||
<!-- Check mark -->
|
||||
<path
|
||||
android:strokeColor="#FFFAF6F0"
|
||||
android:strokeWidth="20"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M193 245.569L231.822 287L320 199" />
|
||||
<!-- Calendula bloom: petals around the centre -->
|
||||
<path
|
||||
android:strokeColor="#FFFAF6F0"
|
||||
android:strokeWidth="16"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M346.672 323.721C356.301 323.721 364.107 312.367 364.107 298.361C364.107 284.354 356.301 273 346.672 273C337.042 273 329.236 284.354 329.236 298.361C329.236 312.367 337.042 323.721 346.672 323.721Z" />
|
||||
<path
|
||||
android:strokeColor="#FFFAF6F0"
|
||||
android:strokeWidth="16"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M355.716 330.293C358.692 339.451 371.903 343.366 385.224 339.038C398.544 334.71 406.931 323.777 403.955 314.619C400.98 305.461 387.769 301.546 374.448 305.874C361.127 310.202 352.741 321.135 355.716 330.293Z" />
|
||||
<path
|
||||
android:strokeColor="#FFFAF6F0"
|
||||
android:strokeWidth="16"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M352.262 340.926C344.471 346.586 344.83 360.36 353.063 371.691C361.295 383.022 374.284 387.62 382.075 381.96C389.865 376.3 389.506 362.526 381.274 351.194C373.041 339.863 360.052 335.266 352.262 340.926Z" />
|
||||
<path
|
||||
android:strokeColor="#FFFAF6F0"
|
||||
android:strokeWidth="16"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M341.082 340.926C333.291 335.266 320.302 339.863 312.069 351.194C303.837 362.526 303.478 376.3 311.268 381.96C319.059 387.62 332.048 383.022 340.28 371.691C348.513 360.36 348.872 346.585 341.082 340.926Z" />
|
||||
<path
|
||||
android:strokeColor="#FFFAF6F0"
|
||||
android:strokeWidth="16"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M337.627 330.293C340.602 321.135 332.216 310.202 318.895 305.874C305.574 301.546 292.363 305.461 289.388 314.619C286.412 323.777 294.799 334.71 308.119 339.038C321.44 343.366 334.651 339.451 337.627 330.293Z" />
|
||||
<!-- Bloom centre -->
|
||||
<path
|
||||
android:strokeColor="#FFFAF6F0"
|
||||
android:strokeWidth="16"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M346.672 342.742C351.924 342.742 356.182 338.484 356.182 333.232C356.182 327.979 351.924 323.721 346.672 323.721C341.419 323.721 337.161 327.979 337.161 333.232C337.161 338.484 341.419 342.742 346.672 342.742Z" />
|
||||
</group>
|
||||
</vector>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<resources>
|
||||
<string name="app_name">Floret</string>
|
||||
<string name="app_name">Agendula</string>
|
||||
<string name="app_tagline">A modern Material 3 Expressive task app.\nComing into bloom.</string>
|
||||
|
||||
<!-- Generic -->
|
||||
@@ -98,6 +98,20 @@
|
||||
<string name="reminder_1_hour">1 hour before</string>
|
||||
<string name="reminder_1_day">1 day before</string>
|
||||
|
||||
<!-- Reminder custom lead time + per-list overrides -->
|
||||
<string name="reminder_custom">Custom</string>
|
||||
<string name="reminder_custom_with_value">Custom (%1$s)</string>
|
||||
<string name="reminder_custom_set">Set</string>
|
||||
<string name="reminder_custom_amount">Enter an amount</string>
|
||||
<string name="reminder_use_default">Use default</string>
|
||||
<string name="reminder_unit_minutes">Minutes</string>
|
||||
<string name="reminder_unit_hours">Hours</string>
|
||||
<string name="reminder_unit_days">Days</string>
|
||||
<string name="reminder_unit_weeks">Weeks</string>
|
||||
<string name="settings_list_reminders_title">Per-list reminders</string>
|
||||
<string name="settings_list_reminders_hint">Override the default reminder for individual lists</string>
|
||||
<string name="settings_list_reminder_inherits">Default (%1$s)</string>
|
||||
|
||||
<!-- Form validation -->
|
||||
<string name="error_blank_title">Enter a title.</string>
|
||||
<string name="error_no_list">Choose a list.</string>
|
||||
@@ -115,6 +129,23 @@
|
||||
<string name="smart_all">All</string>
|
||||
<string name="open_count">%1$d open</string>
|
||||
|
||||
<!-- Home: Today progress hero -->
|
||||
<string name="home_today_progress">%1$d of %2$d done</string>
|
||||
<string name="home_today_remaining">%1$d left</string>
|
||||
<string name="home_today_all_done">All done 🎉</string>
|
||||
<string name="home_today_empty">Nothing due today 🎉</string>
|
||||
|
||||
<!-- Home: Upcoming preview -->
|
||||
<string name="home_upcoming_view_all">View all</string>
|
||||
<string name="home_due_today">Today</string>
|
||||
<string name="home_due_tomorrow">Tomorrow</string>
|
||||
|
||||
<!-- Home: search -->
|
||||
<string name="home_search_hint">Search tasks</string>
|
||||
<string name="home_search_clear">Clear search</string>
|
||||
<string name="home_search_close">Close search</string>
|
||||
<string name="home_search_empty">No tasks match “%1$s”</string>
|
||||
|
||||
<!-- Reminders -->
|
||||
<string name="reminder_due_at">Due %1$s</string>
|
||||
<string name="reminder_channel_name">Task reminders</string>
|
||||
@@ -122,10 +153,86 @@
|
||||
|
||||
<!-- Provider / permission onboarding -->
|
||||
<string name="onboarding_no_provider_title">A tasks app is needed</string>
|
||||
<string name="onboarding_no_provider_body">Floret shows and edits the tasks stored by OpenTasks or tasks.org, synced by DAVx5. Install one of them to get started.</string>
|
||||
<string name="onboarding_no_provider_body">Agendula shows and edits the tasks stored by OpenTasks or tasks.org, synced by DAVx5. Install one of them to get started.</string>
|
||||
<string name="onboarding_permission_title">Allow access to your tasks</string>
|
||||
<string name="onboarding_permission_body">Floret needs permission to read and write your tasks. That\'s the only thing it ever asks for.</string>
|
||||
<string name="onboarding_permission_body">Agendula needs permission to read and write your tasks. That\'s the only thing it ever asks for.</string>
|
||||
<string name="onboarding_permission_button">Grant task access</string>
|
||||
<string name="onboarding_install_opentasks">Install OpenTasks</string>
|
||||
<string name="onboarding_install_tasksorg">Install tasks.org</string>
|
||||
|
||||
<!-- Reminder onboarding (one-time, after the provider grant) -->
|
||||
<string name="reminder_onboarding_title">Never miss what\'s due</string>
|
||||
<string name="reminder_onboarding_body">Tasks apps don\'t send reminders themselves, so Agendula delivers them for you. Turn them on to get a notification when a task is due.</string>
|
||||
<string name="reminder_onboarding_enable_button">Enable reminders</string>
|
||||
<string name="reminder_onboarding_skip_button">Not now</string>
|
||||
<string name="reminder_benefit_delivery_title">Agendula reminds you</string>
|
||||
<string name="reminder_benefit_delivery_body">It schedules a notification for each task with a due date.</string>
|
||||
<string name="reminder_benefit_timing_title">On your schedule</string>
|
||||
<string name="reminder_benefit_timing_body">Choose how far ahead to be reminded in Settings.</string>
|
||||
<string name="reminder_benefit_reversible_title">Change it anytime</string>
|
||||
<string name="reminder_benefit_reversible_body">Turn reminders off whenever you like — it\'s just a switch.</string>
|
||||
|
||||
<!-- Settings -->
|
||||
<string name="settings_title">Settings</string>
|
||||
<string name="settings_section_appearance">Appearance</string>
|
||||
<string name="settings_appearance_subtitle">Theme and colour</string>
|
||||
<string name="settings_section_task_form">Task form</string>
|
||||
<string name="settings_task_form_subtitle">Default fields, list and subtasks</string>
|
||||
<string name="settings_reminders_subtitle">Notifications for due tasks</string>
|
||||
<string name="settings_form_fields_hint">Fields shown by default on a new task. The rest sit behind \"More fields\".</string>
|
||||
<string name="settings_dynamic_color_unavailable">Available on Android 12 and later</string>
|
||||
<!-- About -->
|
||||
<string name="settings_about_author">by Jean-Luc Makiola</string>
|
||||
<string name="settings_about_source">Source</string>
|
||||
<string name="settings_license">License</string>
|
||||
<string name="settings_about_support">Support development</string>
|
||||
<string name="settings_about_version">Version %1$s</string>
|
||||
<string name="settings_about_logo_desc">Agendula app icon</string>
|
||||
<string name="settings_language">App language</string>
|
||||
<string name="settings_language_auto">System default</string>
|
||||
<string name="settings_report_problem">Report a problem</string>
|
||||
<string name="settings_report_problem_hint">Open the issue tracker</string>
|
||||
<string name="about_source_url" translatable="false">https://gitea.jeanlucmakiola.de/makiolaj/agendula</string>
|
||||
<string name="crash_report_issue_title">Crash report</string>
|
||||
<string name="report_issue_url" translatable="false">https://gitea.jeanlucmakiola.de/makiolaj/agendula/issues/new</string>
|
||||
<string name="about_license_url" translatable="false">https://gitea.jeanlucmakiola.de/makiolaj/agendula/src/branch/main/LICENSE</string>
|
||||
<string name="about_support_url" translatable="false">https://ko-fi.com/jeanlucmakiola</string>
|
||||
<string name="settings_theme">Theme</string>
|
||||
<string name="settings_theme_system">Follow system</string>
|
||||
<string name="settings_theme_light">Light</string>
|
||||
<string name="settings_theme_dark">Dark</string>
|
||||
<string name="settings_dynamic_color">Dynamic colour</string>
|
||||
<string name="settings_dynamic_color_hint">Use colours from your wallpaper</string>
|
||||
<string name="settings_section_reminders">Reminders</string>
|
||||
<string name="settings_reminders">Due reminders</string>
|
||||
<string name="settings_reminders_hint">Notify me when a task is due</string>
|
||||
<string name="settings_default_reminder">When to remind</string>
|
||||
<string name="settings_exact_alarms">Exact timing</string>
|
||||
<string name="settings_exact_alarms_allowed">Reminders fire at the exact time</string>
|
||||
<string name="settings_exact_alarms_blocked">Blocked — tap to allow exact reminders</string>
|
||||
<string name="settings_section_tasks">Tasks</string>
|
||||
<string name="settings_default_list">Default list</string>
|
||||
<string name="settings_default_list_first">First available list</string>
|
||||
<string name="settings_add_subtask_row">Show \"add a subtask\" row</string>
|
||||
<string name="settings_add_subtask_row_hint">An add field at the end of an expanded task\'s subtasks</string>
|
||||
<string name="settings_bottom_add_bar">Bottom quick-add bar</string>
|
||||
<string name="settings_bottom_add_bar_hint">Add tasks from a bar pinned to the bottom of a list, instead of the floating button</string>
|
||||
|
||||
<!-- Reminder lead times (custom amounts) -->
|
||||
<plurals name="reminder_minutes">
|
||||
<item quantity="one">%1$d minute before</item>
|
||||
<item quantity="other">%1$d minutes before</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_hours">
|
||||
<item quantity="one">%1$d hour before</item>
|
||||
<item quantity="other">%1$d hours before</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_days">
|
||||
<item quantity="one">%1$d day before</item>
|
||||
<item quantity="other">%1$d days before</item>
|
||||
</plurals>
|
||||
<plurals name="reminder_weeks">
|
||||
<item quantity="one">%1$d week before</item>
|
||||
<item quantity="other">%1$d weeks before</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<style name="Theme.Floret" parent="android:Theme.Material.Light.NoActionBar">
|
||||
<style name="Theme.Agendula" parent="android:Theme.Material.Light.NoActionBar">
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
<item name="android:windowLightStatusBar">true</item>
|
||||
|
||||
11
app/src/main/res/xml/locales_config.xml
Normal file
11
app/src/main/res/xml/locales_config.xml
Normal file
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
The languages Agendula ships translations for. Single source of truth: each
|
||||
entry needs a matching res/values-<tag>/strings.xml, and is surfaced in both
|
||||
the in-app language picker (parsed at runtime by AppLanguage) and the system
|
||||
per-app language settings (Android 13+, via android:localeConfig). To add a
|
||||
translation, drop in the values-<tag> folder and add one <locale> line here.
|
||||
-->
|
||||
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<locale android:name="en" />
|
||||
</locale-config>
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
/** A [ColumnReader] backed by a Map, so mappers test without a real Cursor. */
|
||||
class MapColumnReader(private val values: Map<String, Any?>) : ColumnReader {
|
||||
@@ -1,11 +1,11 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Instances
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.floret.domain.Priority
|
||||
import de.jeanlucmakiola.floret.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Instances
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class TaskMapperTest {
|
||||
@@ -50,6 +50,31 @@ class TaskMapperTest {
|
||||
assertThat(task.isSubtask).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recurrence is detected from rrule when is_recurring is absent`() {
|
||||
// tasks.org's bundled provider is DB 22 and has no `is_recurring` column;
|
||||
// reading it alone would report the series as one-off and send its edits
|
||||
// to the master row, re-anchoring the whole thing.
|
||||
val task = TaskMapper.task(
|
||||
MapColumnReader(mapOf(Tasks.ID to 1L, Tasks.RRULE to "FREQ=WEEKLY;BYDAY=MO")),
|
||||
)
|
||||
assertThat(task.isRecurring).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recurrence is detected from rdate alone`() {
|
||||
val task = TaskMapper.task(
|
||||
MapColumnReader(mapOf(Tasks.ID to 1L, Tasks.RDATE to "20260720T090000Z")),
|
||||
)
|
||||
assertThat(task.isRecurring).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a plain task is not recurring`() {
|
||||
val task = TaskMapper.task(MapColumnReader(mapOf(Tasks.ID to 1L, Tasks.TITLE to "One-off")))
|
||||
assertThat(task.isRecurring).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `falls back to instance id when task_id missing, and list color when no task color`() {
|
||||
val task = TaskMapper.task(
|
||||
@@ -1,10 +1,10 @@
|
||||
package de.jeanlucmakiola.floret.data.tasks
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.floret.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.floret.domain.Priority
|
||||
import de.jeanlucmakiola.floret.domain.TaskForm
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Lists
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
|
||||
import de.jeanlucmakiola.agendula.domain.Priority
|
||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.time.Instant
|
||||
|
||||
@@ -85,6 +85,57 @@ class TaskWriteMapperTest {
|
||||
assertThat(values[Tasks.TZ]).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `all-day timestamps are pinned to UTC midnight`() {
|
||||
// 2026-07-20T22:00Z — i.e. local midnight on the 21st in Berlin (UTC+2).
|
||||
// The provider resolves all-day dates against UTC, so storing this as-is
|
||||
// would land the task on the 20th for anyone reading it back.
|
||||
val berlinMidnight = Instant.fromEpochMilliseconds(1_784_412_000_000L)
|
||||
val values = TaskWriteMapper.taskValues(
|
||||
TaskForm(title = "Holiday", listId = 1L, start = berlinMidnight, due = berlinMidnight, isAllDay = true),
|
||||
tzId = "Europe/Berlin",
|
||||
)
|
||||
|
||||
val dayMs = 24L * 60 * 60 * 1000
|
||||
assertThat(values[Tasks.DUE] as Long % dayMs).isEqualTo(0L)
|
||||
assertThat(values[Tasks.DTSTART] as Long % dayMs).isEqualTo(0L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `timed timestamps are written untouched`() {
|
||||
val at = Instant.fromEpochMilliseconds(1_784_412_345_678L)
|
||||
val values = TaskWriteMapper.taskValues(
|
||||
TaskForm(title = "Standup", listId = 1L, start = at, due = at),
|
||||
tzId = "Europe/Berlin",
|
||||
)
|
||||
assertThat(values[Tasks.DTSTART]).isEqualTo(1_784_412_345_678L)
|
||||
assertThat(values[Tasks.DUE]).isEqualTo(1_784_412_345_678L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `duration is always cleared so it cannot collide with due`() {
|
||||
// The provider validates the *merged* row and throws "Only one of DUE or
|
||||
// DURATION must be supplied" if the stored row still carries a duration.
|
||||
val values = TaskWriteMapper.taskValues(
|
||||
TaskForm(title = "x", listId = 1L, due = Instant.fromEpochMilliseconds(5_000L)),
|
||||
tzId = "UTC",
|
||||
)
|
||||
assertThat(values.containsKey(Tasks.DURATION)).isTrue()
|
||||
assertThat(values[Tasks.DURATION]).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `instance values drop list and parent, which an override cannot express`() {
|
||||
val form = TaskForm(title = "x", listId = 4L, parentId = 7L, due = Instant.fromEpochMilliseconds(1_000L))
|
||||
val values = TaskWriteMapper.instanceValues(form, tzId = "UTC")
|
||||
|
||||
assertThat(values.containsKey(Tasks.LIST_ID)).isFalse()
|
||||
assertThat(values.containsKey(Tasks.PARENT_ID)).isFalse()
|
||||
// …but still carries the edit itself.
|
||||
assertThat(values[Tasks.TITLE]).isEqualTo("x")
|
||||
assertThat(values[Tasks.DUE]).isEqualTo(1_000L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `completion sets status, percent and timestamp, un-completion clears them`() {
|
||||
val done = TaskWriteMapper.completionValues(completed = true, nowMillis = 999L)
|
||||
@@ -97,6 +148,22 @@ class TaskWriteMapperTest {
|
||||
assertThat(undone[Tasks.COMPLETED]).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `alarm carries every column the provider's validator demands`() {
|
||||
val values = TaskWriteMapper.alarmValues(taskId = 12L, minutesBeforeDue = 30)
|
||||
|
||||
assertThat(values[TasksContract.Properties.TASK_ID]).isEqualTo(12L)
|
||||
assertThat(values[TasksContract.Properties.MIMETYPE])
|
||||
.isEqualTo("vnd.android.cursor.item/alarm")
|
||||
assertThat(values[TasksContract.Alarm.MINUTES_BEFORE]).isEqualTo(30)
|
||||
// REFERENCE must be present and non-negative, ALARM_TYPE present and
|
||||
// non-zero (0 is excluded from the provider's has_alarms count).
|
||||
assertThat(values[TasksContract.Alarm.REFERENCE]).isEqualTo(TasksContract.Alarm.REFERENCE_DUE)
|
||||
assertThat(values[TasksContract.Alarm.ALARM_TYPE]).isEqualTo(TasksContract.Alarm.TYPE_MESSAGE)
|
||||
// property_id must be absent or the insert is rejected.
|
||||
assertThat(values.containsKey(TasksContract.Properties.PROPERTY_ID)).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `local list uses the LOCAL account`() {
|
||||
val values = TaskWriteMapper.localListValues("Inbox", 0x123)
|
||||
@@ -0,0 +1,60 @@
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import kotlin.time.Instant
|
||||
|
||||
class AllDayTimeTest {
|
||||
|
||||
private val berlin = ZoneId.of("Europe/Berlin") // UTC+2 in July
|
||||
private val newYork = ZoneId.of("America/New_York") // UTC-4 in July
|
||||
private val julyTwentieth = LocalDate.of(2026, 7, 20)
|
||||
|
||||
@Test
|
||||
fun `an all-day instant is UTC midnight of its date`() {
|
||||
val instant = allDayInstantOf(julyTwentieth)
|
||||
assertThat(instant.toEpochMilliseconds() % (24L * 60 * 60 * 1000)).isEqualTo(0L)
|
||||
assertThat(instant.calendarDate(allDay = true)).isEqualTo(julyTwentieth)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an all-day date reads the same everywhere, unlike a timed one`() {
|
||||
val allDay = allDayInstantOf(julyTwentieth)
|
||||
// The whole point: zone must not change which day an all-day value denotes.
|
||||
assertThat(allDay.calendarDate(allDay = true, zone = berlin)).isEqualTo(julyTwentieth)
|
||||
assertThat(allDay.calendarDate(allDay = true, zone = newYork)).isEqualTo(julyTwentieth)
|
||||
// Read as a timed value in New York it would slip to the 19th — the bug.
|
||||
assertThat(allDay.calendarDate(allDay = false, zone = newYork)).isEqualTo(julyTwentieth.minusDays(1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `toggling all-day off keeps the day and lands on local midnight`() {
|
||||
val allDay = allDayInstantOf(julyTwentieth)
|
||||
val timed = allDay.rebasedForAllDay(allDay = false, zone = berlin)
|
||||
|
||||
assertThat(timed.calendarDate(allDay = false, zone = berlin)).isEqualTo(julyTwentieth)
|
||||
val local = java.time.Instant.ofEpochMilli(timed.toEpochMilliseconds()).atZone(berlin)
|
||||
assertThat(local.toLocalTime()).isEqualTo(java.time.LocalTime.MIDNIGHT)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `toggling all-day on keeps the day the user was looking at`() {
|
||||
// 2026-07-20T23:30 in Berlin — late enough that a naive UTC read slips a day.
|
||||
val lateEvening = Instant.fromEpochMilliseconds(
|
||||
julyTwentieth.atTime(23, 30).atZone(berlin).toInstant().toEpochMilli(),
|
||||
)
|
||||
val allDay = lateEvening.rebasedForAllDay(allDay = true, zone = berlin)
|
||||
|
||||
assertThat(allDay.calendarDate(allDay = true)).isEqualTo(julyTwentieth)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `round-tripping the toggle is stable`() {
|
||||
val original = allDayInstantOf(julyTwentieth)
|
||||
val there = original.rebasedForAllDay(allDay = false, zone = newYork)
|
||||
val back = there.rebasedForAllDay(allDay = true, zone = newYork)
|
||||
assertThat(back).isEqualTo(original)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.jeanlucmakiola.floret.domain
|
||||
package de.jeanlucmakiola.agendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user