mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-21 12:02:20 +01:00
Compare commits
65 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e0a4f71953 | |||
| 1190e2d079 | |||
| 9d63c33fa7 | |||
| 6c2c365a69 | |||
| 3cd04e60dc | |||
| a79b0175d5 | |||
| abd8793e60 | |||
| d56edbc413 | |||
| 9a0cc89941 | |||
| 51a31579c8 | |||
| 5add5fa55f | |||
| ffd30b0476 | |||
| 893eea4901 | |||
| eec847bb6c | |||
| 0c76dfd839 | |||
| 801d7a0199 | |||
| 86e702b5e2 | |||
| 9663738843 | |||
| 0fbedaeecf | |||
| 1c2fb2e451 | |||
| 098ed29ec7 | |||
| c02d9b2ea4 | |||
| 801a0b4bab | |||
| a936d07a7e | |||
| 03b6a455cb | |||
| b0c556b745 | |||
| 26d6a68ac0 | |||
| e6322f7f3e | |||
| 642467dc1d | |||
| 6cd3470502 | |||
| 3d8d358abd | |||
| a3d089fee3 | |||
| 3ce43b56df | |||
| 15a0899119 | |||
| eb6a9cf8c3 | |||
| 49144a2c49 | |||
| dfd60d4f7b | |||
| f793545468 | |||
| 76d4e58641 | |||
| 617e1ec879 | |||
| 649a324f8a | |||
| 4eca59bac9 | |||
| f4b4a034b7 | |||
| 57d304600e | |||
| ded7486244 | |||
| 8068205d0c | |||
| 91a9ee5295 | |||
| 0982565fdc | |||
| 957ddc7ddc | |||
| e7ef648757 | |||
| dc2799e36a | |||
| 2dc502bbb6 | |||
| c9c30b1ee5 | |||
| ff12f4e171 | |||
| 43e4b4070d | |||
| 45627f7075 | |||
| 60ce1a6d71 | |||
| 445712dea3 | |||
| 752c3704b2 | |||
| f25d22da20 | |||
| 737d09d37c | |||
| 83d05c637a | |||
| 07e5d2149c | |||
| 832f9ab7da | |||
| 3b200b60e7 |
62
.github/workflows/dependency-freshness.yml
vendored
62
.github/workflows/dependency-freshness.yml
vendored
@ -1,62 +0,0 @@
|
|||||||
name: dependency freshness
|
|
||||||
|
|
||||||
# Every dependency on its ecosystem's newest STABLE release, enforced on push
|
|
||||||
# as well as at commit time. The local pre-commit hook only sees the manifests
|
|
||||||
# in a commit and can be skipped entirely by a fresh clone that never ran
|
|
||||||
# `pre-commit install`; this runs `--all` over the whole repo.
|
|
||||||
#
|
|
||||||
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
|
|
||||||
# passes, because `--no-verify` is banned locally and a hook that hard-failed
|
|
||||||
# on a flaky connection would leave no way to commit. A runner is always
|
|
||||||
# online, so here an undeterminable answer is a real failure.
|
|
||||||
#
|
|
||||||
# Expect this to go red for reasons this repo's commit did not cause: an
|
|
||||||
# upstream release overnight is enough. That is the chosen behaviour -- the
|
|
||||||
# alternative is a gate that only notices staleness when someone remembers to
|
|
||||||
# look.
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
dependency-freshness:
|
|
||||||
name: dependencies on newest stable
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
# The gate lives in the shared utils repo so every repo resolves the
|
|
||||||
# same "latest stable" the same way. Checking it out beats vendoring a
|
|
||||||
# copy, which is exactly how a gate and its survey start disagreeing.
|
|
||||||
- name: Check out the shared gate
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: kuhyx/utils
|
|
||||||
path: .utils
|
|
||||||
|
|
||||||
# "3.x", never a pinned minor: the Python target IS the interpreter the
|
|
||||||
# gate runs under (registries/toolchain.python_installed), so a runner
|
|
||||||
# held a release behind this machine reports a repo's `requires-python`
|
|
||||||
# as excluding "latest" while the same check passes locally. flax-docs-mcp
|
|
||||||
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.x"
|
|
||||||
|
|
||||||
- name: Install the gate's two runtime dependencies
|
|
||||||
run: python -m pip install --upgrade pyyaml packaging
|
|
||||||
|
|
||||||
- name: Cache registry lookups
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.cache/dep-freshness
|
|
||||||
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
|
|
||||||
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
|
|
||||||
restore-keys: dep-freshness-
|
|
||||||
|
|
||||||
- name: Every dependency is on newest stable
|
|
||||||
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict
|
|
||||||
14
.github/workflows/pre-commit.yml
vendored
14
.github/workflows/pre-commit.yml
vendored
@ -25,14 +25,14 @@ jobs:
|
|||||||
skip: ""
|
skip: ""
|
||||||
- group: rest
|
- group: rest
|
||||||
hooks: ""
|
hooks: ""
|
||||||
skip: mypy,pylint
|
skip: mypy,pylint,dependency-freshness
|
||||||
name: pre-commit (${{ matrix.group }})
|
name: pre-commit (${{ matrix.group }})
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
# The file-length, md-naming and dependency-freshness hooks delegate to
|
# The file-length and md-naming hooks delegate to the shared gates in
|
||||||
# the shared gates in kuhyx/utils, which a runner does not have at
|
# kuhyx/utils, which a runner does not have at $HOME/src/utils. Only
|
||||||
# $HOME/src/utils. Only the rest group runs them.
|
# the rest group runs them.
|
||||||
- name: Check out the shared gates
|
- name: Check out the shared gates
|
||||||
if: matrix.group == 'rest'
|
if: matrix.group == 'rest'
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@ -59,9 +59,9 @@ jobs:
|
|||||||
# mypy and pylint bring their own hook environments, so they need only
|
# mypy and pylint bring their own hook environments, so they need only
|
||||||
# pre-commit. The rest group's language: system patch-targets hook
|
# pre-commit. The rest group's language: system patch-targets hook
|
||||||
# imports diet_guard and every patched module (requests, gatelock,
|
# imports diet_guard and every patched module (requests, gatelock,
|
||||||
# crdt_sync, freedays, mcp, pydantic), and dependency-freshness needs
|
# crdt_sync, freedays, mcp, pydantic) -- so it keeps the full
|
||||||
# pyyaml and packaging -- so it keeps the full requirements.txt. That
|
# requirements.txt. That install used to run in the one job, with plain
|
||||||
# install used to run in the one job, with plain pip, for ~24 s.
|
# pip, for ~24 s.
|
||||||
- name: Install pre-commit and the system hooks' imports
|
- name: Install pre-commit and the system hooks' imports
|
||||||
run: |
|
run: |
|
||||||
if [[ "${{ matrix.group }}" == rest ]]; then
|
if [[ "${{ matrix.group }}" == rest ]]; then
|
||||||
|
|||||||
6
.github/workflows/release-apk.yml
vendored
6
.github/workflows/release-apk.yml
vendored
@ -60,7 +60,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: 3.47.9
|
flutter-version: 3.50.1
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
@ -108,7 +108,9 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
flutter build apk --release \
|
flutter build apk --release \
|
||||||
--build-name="${{ steps.ver.outputs.semver }}" \
|
--build-name="${{ steps.ver.outputs.semver }}" \
|
||||||
--build-number="${{ steps.vc.outputs.code }}"
|
--build-number="${{ steps.vc.outputs.code }}" \
|
||||||
|
--dart-define=APP_BUILD="${{ steps.vc.outputs.code }}" \
|
||||||
|
--dart-define=APP_VERSION="${{ steps.ver.outputs.semver }}"
|
||||||
|
|
||||||
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
||||||
# the debug key if key.properties is misplaced, producing a green build
|
# the debug key if key.properties is misplaced, producing a green build
|
||||||
|
|||||||
@ -29,7 +29,7 @@ repos:
|
|||||||
args: [--pytest-test-first]
|
args: [--pytest-test-first]
|
||||||
# Shared fakes and fixtures, not test modules. Split out of conftest.py
|
# Shared fakes and fixtures, not test modules. Split out of conftest.py
|
||||||
# and test_sync.py only because those files passed the 250-line cap.
|
# and test_sync.py only because those files passed the 250-line cap.
|
||||||
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects)\.py$
|
exclude: ^diet_guard/tests/_(tk_fakes(_containers|_canvas)?|gate_layout_probe|gate_focus_probe|gate_measurement|gate_keyboard_probe|gate_fixtures|sync_fakes|kuchnia_fakes|state_redirects|claude_redirects|claude_fakes|claude_worker_fakes)\.py$
|
||||||
- id: check-ast
|
- id: check-ast
|
||||||
- id: mixed-line-ending
|
- id: mixed-line-ending
|
||||||
args: [--fix=lf]
|
args: [--fix=lf]
|
||||||
@ -96,6 +96,10 @@ repos:
|
|||||||
rev: v3.3.2
|
rev: v3.3.2
|
||||||
hooks:
|
hooks:
|
||||||
- id: pylint
|
- id: pylint
|
||||||
|
# pre-commit itself runs on 3.15 and `python3` resolves to it; this
|
||||||
|
# pylint's --jobs=4 pickles with dill, which crashes there
|
||||||
|
# (no `co_lnotab`). The repo targets 3.14.
|
||||||
|
language_version: python3.14
|
||||||
args:
|
args:
|
||||||
- --rcfile=pyproject.toml
|
- --rcfile=pyproject.toml
|
||||||
- --fail-under=10
|
- --fail-under=10
|
||||||
@ -107,10 +111,14 @@ repos:
|
|||||||
# direct URLs for one distribution, so any pin that drifts from
|
# direct URLs for one distribution, so any pin that drifts from
|
||||||
# the manifest becomes an unresolvable hook environment rather
|
# the manifest becomes an unresolvable hook environment rather
|
||||||
# than merely an old one.
|
# than merely an old one.
|
||||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
|
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.0#subdirectory=gatelock
|
||||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
|
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
|
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
|
||||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.3.0#subdirectory=sickdays
|
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays
|
||||||
|
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.0#subdirectory=kuhy_credit
|
||||||
|
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.2.1#subdirectory=rtdb_relay
|
||||||
|
- claude-agent-sdk==0.2.184
|
||||||
|
- httpx==0.28.1
|
||||||
- mcp>=2,<3
|
- mcp>=2,<3
|
||||||
- pydantic
|
- pydantic
|
||||||
- defusedxml==0.7.1
|
- defusedxml==0.7.1
|
||||||
@ -274,7 +282,7 @@ repos:
|
|||||||
# patch target statically so a stale path fails the commit instead.
|
# patch target statically so a stale path fails the commit instead.
|
||||||
- id: patch-targets
|
- id: patch-targets
|
||||||
name: test patch targets resolve
|
name: test patch targets resolve
|
||||||
entry: python3 scripts/check_patch_targets.py
|
entry: python3 scripts/check_patch_targets.py diet_guard
|
||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
files: ^diet_guard/
|
files: ^diet_guard/
|
||||||
|
|||||||
131
AGENTS.md
131
AGENTS.md
@ -1,51 +1,57 @@
|
|||||||
# CLAUDE.md — diet_guard
|
# CLAUDE.md — diet_guard
|
||||||
|
|
||||||
A log-to-unlock gate. Every ~15 min `diet-guard-gate.timer` checks whether a
|
A log-to-unlock gate. Every ~15 min `diet-guard-gate.timer` checks whether a meal slot (08:00,
|
||||||
meal slot (08:00, 12:00, 16:00, 20:00 by default — the schedule is
|
12:00, 16:00, 20:00 by default — the schedule is user-configurable, see below) elapsed unlogged; if
|
||||||
user-configurable, see below) elapsed unlogged; if so it opens a
|
so it opens a fullscreen Tk window that blocks the desktop until the user logs what they ate. It
|
||||||
fullscreen Tk window that blocks the desktop until the user logs what they
|
also tracks a daily calorie/macro budget, seeded from biometrics at `init` and freely editable
|
||||||
ate. It also tracks a daily calorie/macro budget, seeded from biometrics at
|
afterward on either device. A History tab (`_gatelock_calendar.py`) and the phone's Calendar screen
|
||||||
`init` and freely editable afterward on either device. A History tab
|
show adherence, streaks, a YTD tally and weekly/monthly averages, all derived from `_daystatus.py` /
|
||||||
(`_gatelock_calendar.py`) and the phone's Calendar screen show adherence,
|
`day_status_service.dart` and `_averages.py` / `average_service.dart`.
|
||||||
streaks, a YTD tally and weekly/monthly averages, all derived from
|
|
||||||
`_daystatus.py` / `day_status_service.dart` and `_averages.py` /
|
|
||||||
`average_service.dart`.
|
|
||||||
|
|
||||||
`docs/DOCS-design.md` holds the original spec (slot timing, the Tue/Wed/Thu
|
`docs/DOCS-design.md` holds the original spec (slot timing, the Tue/Wed/Thu catch-up rule).
|
||||||
catch-up rule).
|
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
- One sync tick: `python -m diet_guard sync`
|
- One sync tick: `python -m diet_guard sync`
|
||||||
- Averages: `python -m diet_guard averages`; Body: `body`, `weight KG`, `profile`, `plan-week`
|
- Averages: `python -m diet_guard averages`; Body: `body`, `weight KG`, `profile`, `plan-week`
|
||||||
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
|
- Prune dead sync peers (dry run): `python -m diet_guard prune-peers`
|
||||||
|
- "Send to Claude" worker: `python -m diet_guard claude-worker` ([relay](docs/DOCS-claude-relay.md), [screen](docs/DOCS-log-screen.md))
|
||||||
- Install: `bash install.sh` (production); app: `cd app && bash install_arch.sh`; run app: `bash run.sh`; phone: `flutter build apk --release`
|
- Install: `bash install.sh` (production); app: `cd app && bash install_arch.sh`; run app: `bash run.sh`; phone: `flutter build apk --release`
|
||||||
- run: `python -m diet_guard gate --demo`
|
- run: `python -m diet_guard gate --demo`
|
||||||
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`
|
- test: `python -m pytest -n auto -p no:sugar -q` (python, 100% branch bar from pyproject) then `cd app && flutter test --reporter=compact`
|
||||||
- test-changed: `scripts/test_changed.sh` (maps py and app/ dart changes to their tests, no coverage)
|
- test-changed: `scripts/test_changed.sh` (maps py and app/ dart changes to their tests, no coverage)
|
||||||
- lint: `pre-commit run --all-files`
|
- lint: `pre-commit run --all-files`
|
||||||
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov)
|
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov)
|
||||||
|
- deploy: `bash scripts/deploy.sh` (pull ~/src/diet-guard, system-Python install, desktop app; health-checked)
|
||||||
- coverage-gaps: `coverage-gaps coverage.lcov`
|
- coverage-gaps: `coverage-gaps coverage.lcov`
|
||||||
|
|
||||||
## Scheduling
|
## Scheduling
|
||||||
|
|
||||||
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15:00`,
|
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15:00`, `Persistent=true`), not
|
||||||
`Persistent=true`), not boot-relative — a boot-relative timer collided with
|
boot-relative — a boot-relative timer collided with fullscreen games grabbing input.
|
||||||
fullscreen games grabbing input. `diet-guard-gate.service` is `Type=oneshot`
|
`diet-guard-gate.service` is `Type=oneshot` and exits 0 at once when no lock is due (free/sick day:
|
||||||
and exits 0 at once when no lock is due (free/sick day: [docs/DOCS-sick-days.md](docs/DOCS-sick-days.md)).
|
[docs/DOCS-sick-days.md](docs/DOCS-sick-days.md)). Needs `DISPLAY`/`XAUTHORITY`; see the unit file
|
||||||
Needs `DISPLAY`/`XAUTHORITY`; see the unit file and `wait_for_display()`.
|
and `wait_for_display()`.
|
||||||
|
|
||||||
## Cross-device sync
|
## Cross-device sync
|
||||||
|
|
||||||
A sync tick pulls every other device's log from `kuhyx/syncs`
|
A sync tick pulls every other device's log from `kuhyx/syncs` (`diet-guard-sync/`, dumb file storage
|
||||||
(`diet-guard-sync/`, dumb file storage via the REST Contents API), merges
|
via the REST Contents API), merges (`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
|
||||||
(`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
|
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food bank, pushes back.
|
||||||
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food
|
|
||||||
bank, pushes back.
|
|
||||||
|
|
||||||
**On the PC, sync is event-driven — there is no periodic timer.** The old
|
**End-to-end encrypted** (since 2026-11-12, `_sync_e2e.py` / `app/lib/services/sync_e2e.dart`):
|
||||||
`diet-guard-sync.timer` (~15 min) was deleted: it paid a network round-trip on
|
everything lives on `diet-guard-sync/devices-e2e` (revs `revs-e2e`, header `diet-guard-sync/e2e`),
|
||||||
every idle tick to approximate the two moments state actually changes here.
|
fields sealed with a key from the shared passphrase (`~/.config/crdt-sync/password`; keystore + lock
|
||||||
|
icon in Settings on the phone). Record ids, tombstones and clocks stay clear, so the food banks' ids
|
||||||
|
(food names) are visible. The old plaintext `diet-guard-sync/devices` (and its `export_keys.json`
|
||||||
|
keyring) is copied over and never written or deleted. Locked = `SyncError` / `SyncLockedException`:
|
||||||
|
nothing is pulled or pushed. The PC keeps its derived key and copy memo in
|
||||||
|
`~/.local/share/diet_guard/e2e`. The wake-alarm weigh-ins come from `wake-alarm-sync/devices-e2e`
|
||||||
|
(own header).
|
||||||
|
|
||||||
|
**On the PC, sync is event-driven — there is no periodic timer.** The old `diet-guard-sync.timer`
|
||||||
|
(~15 min) was deleted: it paid a network round-trip on every idle tick to approximate the two
|
||||||
|
moments state actually changes here.
|
||||||
|
|
||||||
- **Before a lock** — `_cli_gate._should_lock` runs the cheap local
|
- **Before a lock** — `_cli_gate._should_lock` runs the cheap local
|
||||||
`gate_is_due()` first and pulls *only* when a lock is otherwise due, so a
|
`gate_is_due()` first and pulls *only* when a lock is otherwise due, so a
|
||||||
@ -109,19 +115,18 @@ every idle tick to approximate the two moments state actually changes here.
|
|||||||
|
|
||||||
## Production dependency installation
|
## Production dependency installation
|
||||||
|
|
||||||
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new
|
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new non-stdlib dependency must
|
||||||
non-stdlib dependency must go into system Python's user site-packages:
|
go into system Python's user site-packages:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
/usr/bin/python3 -m pip install --user --break-system-packages -e .
|
/usr/bin/python3 -m pip install --user --break-system-packages -e .
|
||||||
```
|
```
|
||||||
|
|
||||||
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv.
|
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv. Installing only into `.venv`
|
||||||
Installing only into `.venv` caused a 3-day production outage (2026-06-19).
|
caused a 3-day production outage (2026-06-19).
|
||||||
|
|
||||||
Run `install.sh` from a **durable** clone (`~/src/diet-guard`), never a scratch
|
Run `install.sh` from a **durable** clone (`~/src/diet-guard`), never a scratch dir — it does `pip
|
||||||
dir — it does `pip install -e`, so the clone must persist for `git pull` to
|
install -e`, so the clone must persist for `git pull` to reach the running service.
|
||||||
reach the running service.
|
|
||||||
|
|
||||||
## Operational gotchas
|
## Operational gotchas
|
||||||
|
|
||||||
@ -156,16 +161,14 @@ reach the running service.
|
|||||||
|
|
||||||
## The companion app's desktop target is a web build
|
## The companion app's desktop target is a web build
|
||||||
|
|
||||||
`app/` builds for **Android** and **web** only. There is no `app/linux/` —
|
`app/` builds for **Android** and **web** only. There is no `app/linux/` — Flutter's GTK embedder
|
||||||
Flutter's GTK embedder manages ~20fps at 3840x2160 where the same Dart in
|
manages ~20fps at 3840x2160 where the same Dart in Chrome sustains ~144fps
|
||||||
Chrome sustains ~144fps (`~/src/todo/docs/DOCS-desktop-performance-findings.md`). The
|
(`~/src/todo/docs/DOCS-desktop-performance-findings.md`). The desktop app is the web build served by
|
||||||
desktop app is the web build served by `bin/diet_guard_desktop.dart` in a
|
`bin/diet_guard_desktop.dart` in a Chrome `--app` window.
|
||||||
Chrome `--app` window.
|
|
||||||
|
|
||||||
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io`
|
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io` only in `*_io.dart`
|
||||||
only in `*_io.dart` seams and `lib/desktop/`, port 8732 and the
|
seams and `lib/desktop/`, port 8732 and the `diet-guard-desktop` Chrome profile pinned (IndexedDB is
|
||||||
`diet-guard-desktop` Chrome profile pinned (IndexedDB is keyed by origin, so
|
keyed by origin, so changing either hides the entire local food log).
|
||||||
changing either hides the entire local food log).
|
|
||||||
|
|
||||||
- Branch on `kIsWeb` *before* any `Platform.is…`, which itself throws on web.
|
- Branch on `kIsWeb` *before* any `Platform.is…`, which itself throws on web.
|
||||||
`dart:io` does not fail a web compile — it throws at runtime, so the symptom
|
`dart:io` does not fail a web compile — it throws at runtime, so the symptom
|
||||||
@ -178,19 +181,17 @@ changing either hides the entire local food log).
|
|||||||
|
|
||||||
## The meal schedule
|
## The meal schedule
|
||||||
|
|
||||||
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and
|
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and how many meals fall
|
||||||
how many meals fall between them; interior slots round to the 15-min grid.
|
between them; interior slots round to the 15-min grid. Default `(480, 1200, 4)` is the old hardcoded
|
||||||
Default `(480, 1200, 4)` is the old hardcoded 08/12/16/20. The load-bearing
|
08/12/16/20. The load-bearing rules (integer-only arithmetic, the additive `slot`+`slot_min` /
|
||||||
rules (integer-only arithmetic, the additive `slot`+`slot_min` /
|
`f`/`l`/`n`+`fm`/`lm` wire, the count clamp, the `last + 120 min` cutoff, nearest-slot
|
||||||
`f`/`l`/`n`+`fm`/`lm` wire, the count clamp, the `last + 120 min` cutoff,
|
satisfaction), the forward-only history, and the two edit surfaces are in
|
||||||
nearest-slot satisfaction), the forward-only history, and the two edit
|
[docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) — read it before touching `_slots.py` /
|
||||||
surfaces are in [docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) —
|
`_slot_wire.py` / `slot.dart`.
|
||||||
read it before touching `_slots.py` / `_slot_wire.py` / `slot.dart`.
|
|
||||||
|
|
||||||
## Averages (`_averages.py` / `average_service.dart`)
|
## Averages (`_averages.py` / `average_service.dart`)
|
||||||
|
|
||||||
Three load-bearing rules; changing any silently changes what "under budget"
|
Three load-bearing rules; changing any silently changes what "under budget" means:
|
||||||
means:
|
|
||||||
|
|
||||||
- **Denominator is logged days, not elapsed days.** An unlogged day is not a
|
- **Denominator is logged days, not elapsed days.** An unlogged day is not a
|
||||||
zero-kcal day.
|
zero-kcal day.
|
||||||
@ -200,10 +201,9 @@ means:
|
|||||||
week" is empty on a Monday, and reports `no logged days yet` rather than a
|
week" is empty on a Monday, and reports `no logged days yet` rather than a
|
||||||
fake average.
|
fake average.
|
||||||
|
|
||||||
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` /
|
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` / `kOverBudgetYellowCeiling` **by
|
||||||
`kOverBudgetYellowCeiling` **by import, not by copy**. The MCP `get_averages`
|
import, not by copy**. The MCP `get_averages` tool drops `avg_budget` (budget secrecy on the network
|
||||||
tool drops `avg_budget` (budget secrecy on the network only); the CLI, gate and
|
only); the CLI, gate and phone show both.
|
||||||
phone show both.
|
|
||||||
|
|
||||||
## Do NOT
|
## Do NOT
|
||||||
|
|
||||||
@ -217,18 +217,18 @@ phone show both.
|
|||||||
(`2.5.round() == 3`), so a float path silently desyncs the two devices —
|
(`2.5.round() == 3`), so a float path silently desyncs the two devices —
|
||||||
and a slot one device offers while the other does not is a checkpoint that
|
and a slot one device offers while the other does not is a checkpoint that
|
||||||
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
|
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
|
||||||
- Don't re-add the meal builder, "repeat last meal", the reward prompt, or
|
- Don't re-add the meal builder, "repeat last meal" or the reward prompt
|
||||||
**meal photos** — all removed deliberately, enforced by
|
(removed deliberately, `app/test/repo_invariants_test.dart`). A meal photo is
|
||||||
`app/test/repo_invariants_test.dart`. Photos also took `image_picker`, the
|
transient input to Claude only (2026-11-17): never stored, on a `FoodEntry`
|
||||||
blob stores, the `/blobs/` route and the `CAMERA` permission; re-adding them
|
or synced; the invariants test asserts no image bytes reach a record.
|
||||||
means syncing image blobs too.
|
|
||||||
- Don't strip the `components` field: nothing writes it, but historical
|
- Don't strip the `components` field: nothing writes it, but historical
|
||||||
composite entries and the food bank read it, and it is part of the sync wire
|
composite entries and the food bank read it, and it is part of the sync wire
|
||||||
format.
|
format.
|
||||||
- Don't let the catering import log unattended (delivered ≠ eaten), don't let
|
- Catering logs itself since 2026-11-17 (kuhy overrode "delivered ≠ eaten":
|
||||||
its Python and Dart halves drift (one shared fixture gates them), and don't
|
"LOG EVEN WITHOUT TAP"): v5 ids `kuchnia:<date>:<dishId>`, undo tombstones.
|
||||||
make the synced password machine-local — the phone could not then fetch.
|
Don't let its Python and Dart halves drift (shared fixtures) or make the
|
||||||
[docs](docs/DOCS-kuchnia-wikinga.md), [phone](docs/DOCS-kuchnia-wikinga-phone.md).
|
synced password machine-local. [docs](docs/DOCS-kuchnia-wikinga.md),
|
||||||
|
[phone](docs/DOCS-kuchnia-wikinga-phone.md).
|
||||||
- Don't add a dependency without the production install-path check above.
|
- Don't add a dependency without the production install-path check above.
|
||||||
- Don't reintroduce a seal/`chattr +i` on the budget file.
|
- Don't reintroduce a seal/`chattr +i` on the budget file.
|
||||||
- Don't re-add a Linux embedder target, and don't change the wrapper's port or
|
- Don't re-add a Linux embedder target, and don't change the wrapper's port or
|
||||||
@ -240,8 +240,7 @@ phone show both.
|
|||||||
## Flutter/Dart AI rules
|
## Flutter/Dart AI rules
|
||||||
|
|
||||||
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
||||||
via `~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically.
|
via `~/.claude/CLAUDE.md`. Re-fetch periodically. Split across five files for the 250-line cap._
|
||||||
Split across five files to stay under the 250-line cap._
|
|
||||||
|
|
||||||
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
|
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
|
||||||
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)
|
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)
|
||||||
|
|||||||
@ -87,6 +87,15 @@ bash scripts/setup_mcp.sh # create the venv and install diet_guard[mcp]
|
|||||||
Then restart Claude Code in this repo and approve the project MCP server
|
Then restart Claude Code in this repo and approve the project MCP server
|
||||||
(registered in `.mcp.json`).
|
(registered in `.mcp.json`).
|
||||||
|
|
||||||
|
## Error reports
|
||||||
|
|
||||||
|
Every uncaught, thread or Tk callback error, and any freeze of the gate window
|
||||||
|
over 1 s, goes to the shared app-errors spool as app `diet-guard-gate`
|
||||||
|
through `gatelock.error_report` (`diet_guard/_errors.py`, installed by the
|
||||||
|
CLI). The PC's `app-errors` timer turns each one into a ticket on the
|
||||||
|
todoImplementer board (kuhyx/utils `DOCS-app-errors.md`). Nothing shows on
|
||||||
|
screen. The Flutter app reports on its own, as `diet-guard`.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@ -19,6 +19,12 @@
|
|||||||
only, foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, so the
|
only, foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, so the
|
||||||
WorkManager isolate never reads Health Connect. -->
|
WorkManager isolate never reads Health Connect. -->
|
||||||
<uses-permission android:name="android.permission.health.READ_STEPS"/>
|
<uses-permission android:name="android.permission.health.READ_STEPS"/>
|
||||||
|
<!-- Camera for the meal photo sent to Claude (meal_photo_source.dart); the
|
||||||
|
runtime permission is requested before the camera opens. A photo is
|
||||||
|
transient input: it is never stored or synced. Not every device has a
|
||||||
|
camera, and the gallery path works without one. -->
|
||||||
|
<uses-permission android:name="android.permission.CAMERA"/>
|
||||||
|
<uses-feature android:name="android.hardware.camera" android:required="false"/>
|
||||||
<!-- Deliberately NOT requesting SCHEDULE_EXACT_ALARM: the background
|
<!-- Deliberately NOT requesting SCHEDULE_EXACT_ALARM: the background
|
||||||
check is a 15-minute WorkManager periodic task, not exact alarms
|
check is a 15-minute WorkManager periodic task, not exact alarms
|
||||||
(more robust against OEM background-kill; +/-15 min is accepted, see
|
(more robust against OEM background-kill; +/-15 min is accepted, see
|
||||||
|
|||||||
@ -1,4 +1,7 @@
|
|||||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
org.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=1G -XX:ReservedCodeCacheSize=256m -XX:+UseSerialGC -XX:TieredStopAtLevel=1
|
||||||
|
org.gradle.caching=true
|
||||||
|
org.gradle.parallel=true
|
||||||
|
kotlin.compiler.execution.strategy=in-process
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
# This newDsl flag was added by the Flutter template
|
# This newDsl flag was added by the Flutter template
|
||||||
android.newDsl=false
|
android.newDsl=false
|
||||||
|
|||||||
@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
|||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip
|
||||||
|
|||||||
35
app/lib/desktop/error_page.dart
Normal file
35
app/lib/desktop/error_page.dart
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
/// A wordless page for an error the window itself loaded: Chrome would
|
||||||
|
/// otherwise paint its own "This page isn't working" sentences over an
|
||||||
|
/// empty error body. Only the title carries the app's name (OS-level label).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// HTML page with only an icon — no words painted by the browser.
|
||||||
|
const String errorIconPage =
|
||||||
|
'<!doctype html><html><head><meta charset="utf-8"> '
|
||||||
|
'<title>Diet Guard</title> '
|
||||||
|
'<style>html,body{margin:0;height:100%; '
|
||||||
|
'background:#211D1B;display:flex;align-items:center; '
|
||||||
|
'justify-content:center}</style></head><body> '
|
||||||
|
'<svg width="96" height="96" viewBox="0 0 24 24" fill="none" '
|
||||||
|
'stroke="#A39892" stroke-width="2" stroke-linecap="round" '
|
||||||
|
'aria-hidden="true"><circle cx="12" cy="12" r="9"/> '
|
||||||
|
'<line x1="5.6" y1="18.4" x2="18.4" y2="5.6"/></svg></body></html>';
|
||||||
|
|
||||||
|
/// Whether [request] is the window loading a page, not the app's fetch().
|
||||||
|
bool isNavigation(HttpRequest request) =>
|
||||||
|
request.headers.value('sec-fetch-mode') == 'navigate';
|
||||||
|
|
||||||
|
/// Replaces an error answer to a page load with [errorIconPage]. Does
|
||||||
|
/// nothing for fetch() calls, successes, or a response already written.
|
||||||
|
void paintErrorIcon(HttpRequest request) {
|
||||||
|
final response = request.response;
|
||||||
|
if (!isNavigation(request) || response.statusCode < 400) return;
|
||||||
|
try {
|
||||||
|
response.headers.contentType = ContentType.html;
|
||||||
|
response.write(errorIconPage);
|
||||||
|
} on Exception {
|
||||||
|
return; // body already sent: leave it alone
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -19,6 +19,7 @@ library;
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/desktop/error_page.dart' show isNavigation;
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
/// GitHub's REST API base, which [GitHubProxy] fronts.
|
/// GitHub's REST API base, which [GitHubProxy] fronts.
|
||||||
@ -177,8 +178,13 @@ class GitHubProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _passThrough(HttpRequest request, http.Response response) {
|
void _passThrough(HttpRequest request, http.Response response) {
|
||||||
|
request.response.statusCode = response.statusCode;
|
||||||
|
if (isNavigation(request)) {
|
||||||
|
// Top-level navigation (window load) must not paint error JSON; the app's
|
||||||
|
// own fetch() calls never send 'navigate', so they still get the body.
|
||||||
|
return;
|
||||||
|
}
|
||||||
request.response
|
request.response
|
||||||
..statusCode = response.statusCode
|
|
||||||
..headers.contentType = ContentType.json
|
..headers.contentType = ContentType.json
|
||||||
..add(response.bodyBytes);
|
..add(response.bodyBytes);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -24,6 +24,7 @@ import 'dart:io';
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
|
||||||
import 'package:diet_guard_app/desktop/content_types.dart' as content_types;
|
import 'package:diet_guard_app/desktop/content_types.dart' as content_types;
|
||||||
|
import 'package:diet_guard_app/desktop/error_page.dart';
|
||||||
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
||||||
import 'package:diet_guard_app/services/desktop_wrapper.dart';
|
import 'package:diet_guard_app/services/desktop_wrapper.dart';
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
@ -91,6 +92,7 @@ class WrapperServer {
|
|||||||
} on Exception {
|
} on Exception {
|
||||||
request.response.statusCode = HttpStatus.internalServerError;
|
request.response.statusCode = HttpStatus.internalServerError;
|
||||||
}
|
}
|
||||||
|
paintErrorIcon(request);
|
||||||
await request.response.close();
|
await request.response.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,11 +3,17 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show AppErrors, AppErrorsConfig, AppErrorsRouteObserver, installAppErrors;
|
||||||
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
import 'package:diet_guard_app/screens/log_meal_screen.dart';
|
||||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||||
import 'package:diet_guard_app/services/background_tasks.dart';
|
import 'package:diet_guard_app/services/background_tasks.dart';
|
||||||
import 'package:diet_guard_app/services/body_service.dart';
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_firebase.dart';
|
||||||
|
import 'package:diet_guard_app/services/firebase_client.dart' show openFirebase;
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/frame_stats.dart';
|
import 'package:diet_guard_app/services/frame_stats.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||||
@ -17,13 +23,31 @@ import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
|||||||
import 'package:diet_guard_app/services/notification_service.dart';
|
import 'package:diet_guard_app/services/notification_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
Future<void> main() async {
|
Future<void> main() async {
|
||||||
WidgetsFlutterBinding.ensureInitialized();
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
// Every error and every wait over 1 s goes to the PC's app-errors ingest,
|
||||||
|
// which files a board ticket (kuhyx/utils DOCS-app-errors.md). The release
|
||||||
|
// build passes the versionCode and name as dart-defines (release-apk.yml).
|
||||||
|
final errors = await installAppErrors(
|
||||||
|
const AppErrorsConfig(
|
||||||
|
app: 'diet-guard',
|
||||||
|
repo: 'kuhyx/diet-guard',
|
||||||
|
package: 'diet_guard_app',
|
||||||
|
// 0 unless the release build passes --dart-define=APP_BUILD.
|
||||||
|
// ignore: avoid_redundant_argument_values
|
||||||
|
build: int.fromEnvironment('APP_BUILD'),
|
||||||
|
version: String.fromEnvironment('APP_VERSION'),
|
||||||
|
),
|
||||||
|
);
|
||||||
// Before anything that stamps an Hlc or syncs: until this resolves, the
|
// Before anything that stamps an Hlc or syncs: until this resolves, the
|
||||||
// device id falls back to the pre-migration role constant.
|
// device id falls back to the pre-migration role constant.
|
||||||
await initSyncDeviceId();
|
final deviceId = await initSyncDeviceId();
|
||||||
|
errors.connect(
|
||||||
|
sink: () async => (await openFirebase())?.patchValues,
|
||||||
|
deviceId: () async => deviceId,
|
||||||
|
);
|
||||||
await LogStorageService.init();
|
await LogStorageService.init();
|
||||||
await AppSettingsService.init();
|
await AppSettingsService.init();
|
||||||
await BudgetHistoryService.init();
|
await BudgetHistoryService.init();
|
||||||
@ -32,6 +56,8 @@ Future<void> main() async {
|
|||||||
await KuchniaCredentialService.init();
|
await KuchniaCredentialService.init();
|
||||||
await BodyService.init();
|
await BodyService.init();
|
||||||
await KuchniaQueueService.init();
|
await KuchniaQueueService.init();
|
||||||
|
// The sparkle button's transport; until this line it fails closed.
|
||||||
|
claudeRelay = RtdbClaudeRelay.firebase();
|
||||||
final notifications = await NotificationService.init();
|
final notifications = await NotificationService.init();
|
||||||
// Deliberately *not* awaited before the first frame: the browser's
|
// Deliberately *not* awaited before the first frame: the browser's
|
||||||
// `Notification.requestPermission()` does not complete until the user
|
// `Notification.requestPermission()` does not complete until the user
|
||||||
@ -51,19 +77,25 @@ Future<void> main() async {
|
|||||||
// coverage:ignore-start
|
// coverage:ignore-start
|
||||||
if (frameStatsEnabled) startFrameStats();
|
if (frameStatsEnabled) startFrameStats();
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
runApp(const DietGuardApp());
|
runApp(DietGuardApp(errors: errors));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Root widget for the Diet Guard companion app.
|
/// Root widget for the Diet Guard companion app.
|
||||||
class DietGuardApp extends StatelessWidget {
|
class DietGuardApp extends StatelessWidget {
|
||||||
/// Creates the [DietGuardApp] root widget.
|
/// Creates the [DietGuardApp] root widget.
|
||||||
const DietGuardApp({super.key});
|
const DietGuardApp({this.errors, super.key});
|
||||||
|
|
||||||
|
/// App-wide error reporting; null in widget tests.
|
||||||
|
final AppErrors? errors;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return MaterialApp(
|
return MaterialApp(
|
||||||
title: 'Diet Guard',
|
title: 'Diet Guard',
|
||||||
theme: buildAppTheme(),
|
theme: buildAppTheme(),
|
||||||
|
navigatorObservers: [
|
||||||
|
if (errors case final errors?) AppErrorsRouteObserver(errors),
|
||||||
|
],
|
||||||
home: const LogMealScreen(),
|
home: const LogMealScreen(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -20,6 +20,7 @@ class KuchniaDish {
|
|||||||
required this.grams,
|
required this.grams,
|
||||||
required this.priority,
|
required this.priority,
|
||||||
required this.slotLabel,
|
required this.slotLabel,
|
||||||
|
this.dishId = '',
|
||||||
});
|
});
|
||||||
|
|
||||||
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
|
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
|
||||||
@ -52,6 +53,17 @@ class KuchniaDish {
|
|||||||
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
|
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
|
||||||
final String slotLabel;
|
final String slotLabel;
|
||||||
|
|
||||||
|
/// The panel's own id for this meal (`deliveryMealId`), as a string, or ''
|
||||||
|
/// when the payload carried none.
|
||||||
|
///
|
||||||
|
/// Never written to the bank record or the log: it only feeds [autologKey].
|
||||||
|
final String dishId;
|
||||||
|
|
||||||
|
/// The dish half of the auto-log entry id: [dishId], else [bankKey].
|
||||||
|
///
|
||||||
|
/// Mirrors the fixture `tests/fixtures/kuchnia_autolog_ids.json`.
|
||||||
|
String get autologKey => dishId.isNotEmpty ? dishId : bankKey;
|
||||||
|
|
||||||
/// The curated-bank record for this dish.
|
/// The curated-bank record for this dish.
|
||||||
///
|
///
|
||||||
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
|
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
|
||||||
|
|||||||
@ -18,6 +18,8 @@ import 'package:diet_guard_app/services/body_prefs.dart';
|
|||||||
import 'package:diet_guard_app/services/body_service.dart';
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
import 'package:diet_guard_app/services/health_steps.dart';
|
import 'package:diet_guard_app/services/health_steps.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/activity_card.dart';
|
import 'package:diet_guard_app/widgets/body/activity_card.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||||
@ -27,7 +29,7 @@ import 'package:diet_guard_app/widgets/body/goal_card.dart';
|
|||||||
import 'package:diet_guard_app/widgets/body/profile_card.dart';
|
import 'package:diet_guard_app/widgets/body/profile_card.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/week_plan_card.dart';
|
import 'package:diet_guard_app/widgets/body/week_plan_card.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/weight_card.dart';
|
import 'package:diet_guard_app/widgets/body/weight_card.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
export 'package:diet_guard_app/screens/body_screen_data.dart';
|
export 'package:diet_guard_app/screens/body_screen_data.dart';
|
||||||
|
|
||||||
@ -109,22 +111,13 @@ class _BodyScreenState extends State<BodyScreen> {
|
|||||||
final (exercise, _, _) = bodyExercise(body, bio, today);
|
final (exercise, _, _) = bodyExercise(body, bio, today);
|
||||||
final tiles = _tiles(body, bio, exercise);
|
final tiles = _tiles(body, bio, exercise);
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Body')),
|
appBar: AppBar(),
|
||||||
body: Padding(
|
body: Padding(
|
||||||
padding: const EdgeInsets.all(AppSpacing.md),
|
padding: const EdgeInsets.all(AppSpacing.md),
|
||||||
child: Center(
|
child: Center(
|
||||||
child: ConstrainedBox(
|
child: ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||||
child: Column(
|
child: BodyTileGrid(tiles: tiles),
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
BodyTileGrid(tiles: tiles),
|
|
||||||
const SizedBox(height: AppSpacing.sm),
|
|
||||||
BodyNote(
|
|
||||||
'Age ${bodyAgeText(body, today)} · synced with the PC.',
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@ -159,8 +152,12 @@ class _BodyScreenState extends State<BodyScreen> {
|
|||||||
) {
|
) {
|
||||||
final weight = body.latestWeight?.$2;
|
final weight = body.latestWeight?.$2;
|
||||||
final bodyFat = body.latestBodyFat?.$2;
|
final bodyFat = body.latestBodyFat?.$2;
|
||||||
|
final age = bodyAgeText(body, DateTime.now());
|
||||||
final profile = BodyTileSpec(
|
final profile = BodyTileSpec(
|
||||||
title: 'Profile',
|
semanticLabel: 'Profile',
|
||||||
|
icon: Icons.person,
|
||||||
|
value: age,
|
||||||
|
valueIcon: age == null ? null : Icons.cake,
|
||||||
builder: (_) => ProfileCard(onSaved: _onChanged),
|
builder: (_) => ProfileCard(onSaved: _onChanged),
|
||||||
);
|
);
|
||||||
final goal = bio == null
|
final goal = bio == null
|
||||||
@ -174,45 +171,65 @@ class _BodyScreenState extends State<BodyScreen> {
|
|||||||
return [
|
return [
|
||||||
if (_profileAtTop) profile,
|
if (_profileAtTop) profile,
|
||||||
BodyTileSpec(
|
BodyTileSpec(
|
||||||
title: 'Daily calorie target',
|
semanticLabel: 'Daily calorie target',
|
||||||
value: goal == null ? null : '$goal kcal',
|
icon: Icons.flag,
|
||||||
|
value: goal == null ? null : '$goal',
|
||||||
|
valueIcon: goal == null ? null : MacroKind.kcal.icon,
|
||||||
builder: (_) => bio == null
|
builder: (_) => bio == null
|
||||||
? BodySection(
|
? BodySection(
|
||||||
title: 'Daily calorie target',
|
semanticLabel: 'Daily calorie target',
|
||||||
children: [BodyNote(bodyMissingNote(body))],
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
for (final icon in bodyMissingIcons(body))
|
||||||
|
StatusCue(
|
||||||
|
kind: CueKind.warn,
|
||||||
|
icon: icon,
|
||||||
|
semanticLabel: bodyMissingNote(body),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
)
|
)
|
||||||
: GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
|
: GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
|
||||||
),
|
),
|
||||||
BodyTileSpec(
|
BodyTileSpec(
|
||||||
title: 'Weight',
|
semanticLabel: 'Weight',
|
||||||
|
icon: Icons.monitor_weight,
|
||||||
value: weight == null ? null : formatKg(weight),
|
value: weight == null ? null : formatKg(weight),
|
||||||
builder: (_) => WeightCard(onChanged: _onChanged),
|
builder: (_) => WeightCard(onChanged: _onChanged),
|
||||||
),
|
),
|
||||||
if (bio != null) ...[
|
if (bio != null) ...[
|
||||||
BodyTileSpec(
|
BodyTileSpec(
|
||||||
title: 'BMI',
|
semanticLabel: 'BMI',
|
||||||
|
icon: Icons.accessibility_new,
|
||||||
value: oneDecimal(bmiReport(bio).bmi),
|
value: oneDecimal(bmiReport(bio).bmi),
|
||||||
builder: (_) => BmiCard(bio: bio),
|
builder: (_) => BmiCard(bio: bio),
|
||||||
),
|
),
|
||||||
BodyTileSpec(
|
BodyTileSpec(
|
||||||
title: 'Ideal weight',
|
semanticLabel: 'Ideal weight',
|
||||||
|
icon: Icons.balance,
|
||||||
builder: (_) => IdealWeightCard(bio: bio),
|
builder: (_) => IdealWeightCard(bio: bio),
|
||||||
),
|
),
|
||||||
BodyTileSpec(
|
BodyTileSpec(
|
||||||
title: 'Resting metabolism (BMR)',
|
semanticLabel: 'Resting metabolism (BMR)',
|
||||||
value: '${whole(tableBmr(bio, bodyFat).value!)} kcal',
|
icon: Icons.bedtime,
|
||||||
|
value: whole(tableBmr(bio, bodyFat).value!),
|
||||||
|
valueIcon: MacroKind.kcal.icon,
|
||||||
builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat),
|
builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
BodyTileSpec(
|
BodyTileSpec(
|
||||||
title: 'Activity',
|
semanticLabel: 'Activity',
|
||||||
|
icon: Icons.directions_run,
|
||||||
builder: (_) => ValueListenableBuilder<bool>(
|
builder: (_) => ValueListenableBuilder<bool>(
|
||||||
valueListenable: _canConnectSteps,
|
valueListenable: _canConnectSteps,
|
||||||
builder: (_, canConnect, _) => _activityCard(canConnect: canConnect),
|
builder: (_, canConnect, _) => _activityCard(canConnect: canConnect),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
BodyTileSpec(
|
BodyTileSpec(
|
||||||
title: 'Week planner (info only)',
|
semanticLabel: 'Week planner',
|
||||||
|
icon: Icons.calendar_view_week,
|
||||||
builder: (_) => WeekPlanCard(
|
builder: (_) => WeekPlanCard(
|
||||||
defaultTarget: AppSettingsService.dailyKcalGoal,
|
defaultTarget: AppSettingsService.dailyKcalGoal,
|
||||||
logged: _logged,
|
logged: _logged,
|
||||||
@ -220,7 +237,8 @@ class _BodyScreenState extends State<BodyScreen> {
|
|||||||
),
|
),
|
||||||
if (!_profileAtTop) profile,
|
if (!_profileAtTop) profile,
|
||||||
BodyTileSpec(
|
BodyTileSpec(
|
||||||
title: 'Body fat',
|
semanticLabel: 'Body fat',
|
||||||
|
icon: Icons.percent,
|
||||||
value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %',
|
value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %',
|
||||||
builder: (_) => BodyFatCard(onChanged: _onChanged),
|
builder: (_) => BodyFatCard(onChanged: _onChanged),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import 'package:diet_guard_app/services/body_calc.dart';
|
|||||||
import 'package:diet_guard_app/services/body_service.dart';
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
import 'package:diet_guard_app/services/body_steps.dart';
|
import 'package:diet_guard_app/services/body_steps.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart' show IconData, Icons;
|
||||||
|
|
||||||
/// Builds the person from the stored profile and newest weight, or null
|
/// Builds the person from the stored profile and newest weight, or null
|
||||||
/// when anything the formulas need is missing.
|
/// when anything the formulas need is missing.
|
||||||
@ -61,7 +62,16 @@ Map<String, double> kcalByDay(DayLog log) => {
|
|||||||
.fold<double>(0, (sum, food) => sum + food.kcal),
|
.fold<double>(0, (sum, food) => sum + food.kcal),
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Why the numbers are missing.
|
/// Glyphs of the inputs still missing (profile, weight), in the order the
|
||||||
|
/// user should supply them; the visible counterpart of [bodyMissingNote].
|
||||||
|
List<IconData> bodyMissingIcons(BodyService body) => [
|
||||||
|
if (body.birth == null || body.heightCm == null || body.sex == null)
|
||||||
|
Icons.person,
|
||||||
|
if (body.latestWeight == null) Icons.monitor_weight,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Spoken reason the numbers are missing (screen readers, tests; never
|
||||||
|
/// painted).
|
||||||
String bodyMissingNote(BodyService body) {
|
String bodyMissingNote(BodyService body) {
|
||||||
if (body.latestWeight == null && body.birth == null) {
|
if (body.latestWeight == null && body.birth == null) {
|
||||||
return 'Set your profile and enter your weight to see BMI, ideal '
|
return 'Set your profile and enter your weight to see BMI, ideal '
|
||||||
@ -71,8 +81,8 @@ String bodyMissingNote(BodyService body) {
|
|||||||
return 'Set your profile (birth date, height, sex) to see the numbers.';
|
return 'Set your profile (birth date, height, sex) to see the numbers.';
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The age line value.
|
/// The age in whole years, or null while no birth date is stored.
|
||||||
String bodyAgeText(BodyService body, DateTime today) {
|
String? bodyAgeText(BodyService body, DateTime today) {
|
||||||
final birth = DateTime.tryParse(body.birth ?? '');
|
final birth = DateTime.tryParse(body.birth ?? '');
|
||||||
return birth == null ? 'unknown' : '${ageOn(birth, today)}';
|
return birth == null ? null : '${ageOn(birth, today)}';
|
||||||
}
|
}
|
||||||
|
|||||||
@ -9,6 +9,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/models/day_status.dart';
|
import 'package:diet_guard_app/models/day_status.dart';
|
||||||
import 'package:diet_guard_app/models/period_average.dart';
|
import 'package:diet_guard_app/models/period_average.dart';
|
||||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||||
@ -17,11 +18,13 @@ import 'package:diet_guard_app/services/average_service.dart';
|
|||||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||||
import 'package:diet_guard_app/services/day_status_service.dart';
|
import 'package:diet_guard_app/services/day_status_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
import 'package:diet_guard_app/widgets/average_summary_row.dart';
|
import 'package:diet_guard_app/widgets/average_summary_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/day_status_calendar.dart';
|
import 'package:diet_guard_app/widgets/day_status_calendar.dart';
|
||||||
import 'package:diet_guard_app/widgets/streak_summary_row.dart';
|
import 'package:diet_guard_app/widgets/streak_summary_row.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Screen showing the budget-adherence calendar, streaks, and budget entry.
|
/// Screen showing the budget-adherence calendar, streaks, and budget entry.
|
||||||
class CalendarScreen extends StatefulWidget {
|
class CalendarScreen extends StatefulWidget {
|
||||||
@ -151,11 +154,10 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
if (_loading) {
|
if (_loading) {
|
||||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
return const Scaffold(body: WaitWatch.centered('calendar.load'));
|
||||||
}
|
}
|
||||||
final theme = Theme.of(context);
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Calendar')),
|
appBar: AppBar(),
|
||||||
body: SingleChildScrollView(
|
body: SingleChildScrollView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
child: Column(
|
child: Column(
|
||||||
@ -168,11 +170,10 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
|||||||
if (_budgetStatus != null)
|
if (_budgetStatus != null)
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(top: 4),
|
padding: const EdgeInsets.only(top: 4),
|
||||||
child: Text(
|
child: StatusCue(
|
||||||
_budgetStatus!,
|
key: ValueKey(_budgetStatus),
|
||||||
style: TextStyle(
|
kind: _budgetError ? CueKind.error : CueKind.ok,
|
||||||
color: _budgetError ? theme.colorScheme.error : null,
|
semanticLabel: _budgetStatus!,
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
@ -215,7 +216,11 @@ class _BudgetRow extends StatelessWidget {
|
|||||||
return Row(
|
return Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: [
|
children: [
|
||||||
const Text('Daily budget (kcal):'),
|
Icon(
|
||||||
|
MacroKind.kcal.icon,
|
||||||
|
color: MacroKind.kcal.color,
|
||||||
|
semanticLabel: 'Daily budget (kcal)',
|
||||||
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: 90,
|
width: 90,
|
||||||
@ -230,7 +235,10 @@ class _BudgetRow extends StatelessWidget {
|
|||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
onPressed: onEditOrSave,
|
onPressed: onEditOrSave,
|
||||||
child: Text(editing ? 'Save' : 'Edit'),
|
child: Icon(
|
||||||
|
editing ? Icons.check : Icons.edit,
|
||||||
|
semanticLabel: editing ? 'Save' : 'Edit',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -8,9 +8,10 @@ import 'package:diet_guard_app/models/food_suggestion.dart';
|
|||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
/// Edit screen for an existing [FoodEntry].
|
/// Edit screen for an existing [FoodEntry].
|
||||||
@ -35,6 +36,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
List<FoodSuggestion> _suggestions = const [];
|
List<FoodSuggestion> _suggestions = const [];
|
||||||
String _source = 'manual';
|
String _source = 'manual';
|
||||||
String? _status;
|
String? _status;
|
||||||
|
int _rejections = 0;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@ -80,9 +82,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _onDescChanged() async {
|
Future<void> _onDescChanged() async {
|
||||||
final matches = await FoodBankService.instance.search(
|
final matches = await FoodBankService.instance.search(_descController.text);
|
||||||
_descController.text,
|
|
||||||
);
|
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _suggestions = matches);
|
setState(() => _suggestions = matches);
|
||||||
}
|
}
|
||||||
@ -104,7 +104,10 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
Future<void> _onSave() async {
|
Future<void> _onSave() async {
|
||||||
final desc = _descController.text.trim();
|
final desc = _descController.text.trim();
|
||||||
if (desc.isEmpty) {
|
if (desc.isEmpty) {
|
||||||
setState(() => _status = 'Description cannot be empty.');
|
setState(() {
|
||||||
|
_status = 'Description cannot be empty.';
|
||||||
|
_rejections++;
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final nutrition = nutritionForPortion(
|
final nutrition = nutritionForPortion(
|
||||||
@ -142,17 +145,16 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Edit meal')),
|
appBar: AppBar(),
|
||||||
body: SingleChildScrollView(
|
body: SingleChildScrollView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.restaurant,
|
||||||
|
semanticLabel: 'What did you eat?',
|
||||||
controller: _descController,
|
controller: _descController,
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'What did you eat?',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
ConstrainedBox(
|
ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxHeight: 240),
|
constraints: const BoxConstraints(maxHeight: 240),
|
||||||
@ -168,12 +170,20 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
|||||||
width: double.infinity,
|
width: double.infinity,
|
||||||
child: ElevatedButton(
|
child: ElevatedButton(
|
||||||
onPressed: _onSave,
|
onPressed: _onSave,
|
||||||
child: const Text('Save'),
|
child: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (_status != null) ...[
|
if (_status != null) ...[
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Text(_status!),
|
// New key per rejection so a repeat error shakes again.
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: StatusCue(
|
||||||
|
key: ValueKey(_rejections),
|
||||||
|
kind: CueKind.error,
|
||||||
|
semanticLabel: _status!,
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -8,6 +8,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
|
||||||
@ -15,7 +16,7 @@ import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
|||||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter_sheet.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_filter_sheet.dart';
|
||||||
import 'package:diet_guard_app/widgets/food_bank/fb_record_tile.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_record_tile.dart';
|
||||||
import 'package:diet_guard_app/widgets/food_bank/fb_tile_grid.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_tile_grid.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Browses every banked food -- log-derived and manually curated -- with
|
/// Browses every banked food -- log-derived and manually curated -- with
|
||||||
/// filtering, sorting, and an add-entry dialog.
|
/// filtering, sorting, and an add-entry dialog.
|
||||||
@ -153,15 +154,16 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
|||||||
final all = _allEntries;
|
final all = _allEntries;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('Food Bank'),
|
|
||||||
actions: [
|
actions: [
|
||||||
if (all != null)
|
if (all != null)
|
||||||
Stack(
|
Stack(
|
||||||
alignment: Alignment.center,
|
alignment: Alignment.center,
|
||||||
children: [
|
children: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.filter_list),
|
icon: const Icon(
|
||||||
tooltip: 'Filter & sort',
|
Icons.filter_list,
|
||||||
|
semanticLabel: 'Filter & sort',
|
||||||
|
),
|
||||||
onPressed: _openFilterSheet,
|
onPressed: _openFilterSheet,
|
||||||
),
|
),
|
||||||
if (_filter.isActive)
|
if (_filter.isActive)
|
||||||
@ -182,22 +184,22 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: all == null
|
body: all == null
|
||||||
? const Center(child: CircularProgressIndicator())
|
? const WaitWatch.centered('food_bank.load')
|
||||||
: _displayed.isEmpty
|
: _displayed.isEmpty
|
||||||
? Center(
|
? Center(
|
||||||
child: Text(
|
child: Icon(
|
||||||
all.isEmpty
|
all.isEmpty ? Icons.restaurant_menu : Icons.filter_list_off,
|
||||||
? 'Food bank is empty.\n'
|
size: 64,
|
||||||
'Log meals to populate it, or add entries manually.'
|
color: Theme.of(context).colorScheme.outline,
|
||||||
|
semanticLabel: all.isEmpty
|
||||||
|
? 'Food bank is empty.'
|
||||||
: 'No entries match the current filter.',
|
: 'No entries match the current filter.',
|
||||||
textAlign: TextAlign.center,
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
: FbTileGrid(records: _displayed, onOpen: _openDetail),
|
: FbTileGrid(records: _displayed, onOpen: _openDetail),
|
||||||
floatingActionButton: FloatingActionButton(
|
floatingActionButton: FloatingActionButton(
|
||||||
onPressed: _openAddDialog,
|
onPressed: _openAddDialog,
|
||||||
tooltip: 'Add manual entry',
|
child: const Icon(Icons.add, semanticLabel: 'Add manual entry'),
|
||||||
child: const Icon(Icons.add),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -28,54 +28,27 @@ class _ClientIdSetupDialogState extends State<_ClientIdSetupDialog> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
// Icon-only: the setup steps (open github.com/settings/developers, make
|
||||||
|
// an OAuth App with Device Flow, paste its client id) live in the repo
|
||||||
|
// docs, not on screen.
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
title: const Text('One-time GitHub setup needed'),
|
content: IconField(
|
||||||
content: SingleChildScrollView(
|
icon: Icons.apps,
|
||||||
child: Column(
|
semanticLabel: 'Client ID',
|
||||||
mainAxisSize: MainAxisSize.min,
|
controller: _controller,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
autofocus: true,
|
||||||
children: [
|
|
||||||
const Text(
|
|
||||||
'Diet Guard signs in via a GitHub OAuth App (no password '
|
|
||||||
'typed into this app). You only have to set this up once:',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
const Text(
|
|
||||||
'1. On any device, open '
|
|
||||||
'github.com/settings/developers → "New OAuth App".\n'
|
|
||||||
'2. Name/Homepage/Callback URL can be anything (device flow '
|
|
||||||
"doesn't use the callback) — e.g. "
|
|
||||||
'"Diet Guard" and your GitHub profile URL.\n'
|
|
||||||
'3. Check "Enable Device Flow", then click "Register '
|
|
||||||
'application".\n'
|
|
||||||
"4. Copy the Client ID shown on the app's page and paste it "
|
|
||||||
'below.',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
const Text(
|
|
||||||
'When you connect below, log in with the GitHub account that '
|
|
||||||
'has write access to kuhyx/syncs.',
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
TextField(
|
|
||||||
controller: _controller,
|
|
||||||
autofocus: true,
|
|
||||||
decoration: const InputDecoration(labelText: 'Client ID'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
IconButton(
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
child: const Text('Cancel'),
|
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||||
),
|
),
|
||||||
FilledButton(
|
IconButton.filled(
|
||||||
onPressed: () {
|
onPressed: () {
|
||||||
final id = _controller.text.trim();
|
final id = _controller.text.trim();
|
||||||
if (id.isNotEmpty) Navigator.of(context).pop(id);
|
if (id.isNotEmpty) Navigator.of(context).pop(id);
|
||||||
},
|
},
|
||||||
child: const Text('Continue'),
|
icon: const Icon(Icons.arrow_forward, semanticLabel: 'Continue'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -21,7 +21,7 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
TextEditingController get _clientIdController;
|
TextEditingController get _clientIdController;
|
||||||
|
|
||||||
bool _busy = false;
|
bool _busy = false;
|
||||||
String? _status;
|
Widget? _status;
|
||||||
String _storedToken = '';
|
String _storedToken = '';
|
||||||
SyncSettings _currentSettings() {
|
SyncSettings _currentSettings() {
|
||||||
final typed = _tokenController.text.trim();
|
final typed = _tokenController.text.trim();
|
||||||
@ -37,9 +37,18 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
clientId: _clientIdController.text.trim(),
|
clientId: _clientIdController.text.trim(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
void _showMessage(String message) {
|
|
||||||
|
/// Shows the outcome as an icon cue; [semanticLabel] is spoken, never
|
||||||
|
/// painted.
|
||||||
|
void _showCue(CueKind kind, String semanticLabel) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _status = message);
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: kind,
|
||||||
|
semanticLabel: semanticLabel,
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _connectGitHub() async {
|
Future<void> _connectGitHub() async {
|
||||||
@ -69,12 +78,12 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
_storedToken = token;
|
_storedToken = token;
|
||||||
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
|
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
|
||||||
});
|
});
|
||||||
_showMessage('Connected — syncing…');
|
_showCue(CueKind.info, 'Connected — syncing…');
|
||||||
await _currentSettings().save();
|
await _currentSettings().save();
|
||||||
await _syncAfterConnect();
|
await _syncAfterConnect();
|
||||||
}
|
}
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
_showMessage('Could not start device flow: $e');
|
_showCue(CueKind.error, 'Could not start device flow: $e');
|
||||||
} finally {
|
} finally {
|
||||||
auth.close();
|
auth.close();
|
||||||
}
|
}
|
||||||
@ -88,10 +97,10 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
try {
|
try {
|
||||||
await runSync(await syncBackend(client));
|
await runSync(await syncBackend(client));
|
||||||
await SyncHealth.recordSuccess();
|
await SyncHealth.recordSuccess();
|
||||||
_showMessage('Connected and synced.');
|
_showCue(CueKind.ok, 'Connected and synced.');
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
await SyncHealth.recordFailure();
|
await SyncHealth.recordFailure();
|
||||||
_showMessage('Connected, but sync failed: $e');
|
_showCue(CueKind.error, 'Connected, but sync failed: $e');
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
@ -102,7 +111,7 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
await _currentSettings().save();
|
await _currentSettings().save();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _busy = false);
|
setState(() => _busy = false);
|
||||||
_showMessage('Saved.');
|
_showCue(CueKind.ok, 'Saved.');
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _testConnection() async {
|
Future<void> _testConnection() async {
|
||||||
@ -111,11 +120,13 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||||
try {
|
try {
|
||||||
final ok = await client.canAccessRepo();
|
final ok = await client.canAccessRepo();
|
||||||
_showMessage(
|
if (ok) {
|
||||||
ok ? 'GitHub connection OK.' : 'GitHub connection failed.',
|
_showCue(CueKind.ok, 'GitHub connection OK.');
|
||||||
);
|
} else {
|
||||||
|
_showCue(CueKind.error, 'GitHub connection failed.');
|
||||||
|
}
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
_showMessage('GitHub connection failed: $e');
|
_showCue(CueKind.error, 'GitHub connection failed: $e');
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
if (mounted) setState(() => _busy = false);
|
if (mounted) setState(() => _busy = false);
|
||||||
@ -133,10 +144,10 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
|||||||
// *because* the banner told them syncing had stopped, so a successful
|
// *because* the banner told them syncing had stopped, so a successful
|
||||||
// run here must dismiss the warning it caused.
|
// run here must dismiss the warning it caused.
|
||||||
await SyncHealth.recordSuccess();
|
await SyncHealth.recordSuccess();
|
||||||
_showMessage('Synced.');
|
_showCue(CueKind.ok, 'Synced.');
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
await SyncHealth.recordFailure();
|
await SyncHealth.recordFailure();
|
||||||
_showMessage('Sync failed: $e');
|
_showCue(CueKind.error, 'Sync failed: $e');
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
if (mounted) setState(() => _busy = false);
|
if (mounted) setState(() => _busy = false);
|
||||||
|
|||||||
@ -8,15 +8,17 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||||
import 'package:diet_guard_app/services/sync_health.dart';
|
import 'package:diet_guard_app/services/sync_health.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:github_device_auth/github_device_auth.dart';
|
import 'package:github_device_auth/github_device_auth.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
part 'github_client_id_dialog.dart';
|
part 'github_client_id_dialog.dart';
|
||||||
part 'github_mirror_actions.dart';
|
part 'github_mirror_actions.dart';
|
||||||
@ -94,107 +96,86 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
|
|||||||
/// The token as loaded, so a platform that cannot display it (web) still
|
/// The token as loaded, so a platform that cannot display it (web) still
|
||||||
/// round-trips it instead of blanking it on the next save.
|
/// round-trips it instead of blanking it on the next save.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// Runs the OAuth device flow and, on success, fills in the token field.
|
/// Runs the OAuth device flow and, on success, fills in the token field.
|
||||||
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
if (_loading) {
|
if (_loading) {
|
||||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
return const Scaffold(body: WaitWatch.centered('github_mirror.load'));
|
||||||
}
|
}
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Advanced sync (GitHub)')),
|
// No title and no explanatory paragraph: the code glyph that opened this
|
||||||
// Centred and capped at the prose width -- see settings_screen.dart's
|
// screen names it, and the connect button is self-evident.
|
||||||
// note on why: on the desktop surface an uncapped ListView spanned the
|
appBar: AppBar(),
|
||||||
// full window, so explanatory paragraphs ran far past the readable
|
// Centred and capped at the prose width so fields do not span the
|
||||||
// line-length limit.
|
// whole window on the desktop surface.
|
||||||
body: Center(
|
body: Center(
|
||||||
child: ConstrainedBox(
|
child: ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||||
child: ListView(
|
child: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
Text(
|
|
||||||
'Syncs still mirror to GitHub until every device has moved '
|
|
||||||
'to Firebase. Authorize in your browser — no token to '
|
|
||||||
'paste.',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Align(
|
Align(
|
||||||
alignment: Alignment.centerLeft,
|
alignment: Alignment.centerLeft,
|
||||||
child: FilledButton.icon(
|
child: IconButton.filled(
|
||||||
onPressed: _connectGitHub,
|
onPressed: _connectGitHub,
|
||||||
icon: const Icon(Icons.login),
|
icon: const Icon(
|
||||||
label: const Text('Connect GitHub'),
|
Icons.login,
|
||||||
|
semanticLabel: 'Connect GitHub',
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.person_outline,
|
||||||
|
semanticLabel: 'GitHub owner',
|
||||||
controller: _ownerController,
|
controller: _ownerController,
|
||||||
decoration: const InputDecoration(labelText: 'GitHub owner'),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.folder_outlined,
|
||||||
|
semanticLabel: 'Repo',
|
||||||
controller: _repoController,
|
controller: _repoController,
|
||||||
decoration: const InputDecoration(labelText: 'Repo'),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.apps,
|
||||||
|
semanticLabel: 'OAuth App client id',
|
||||||
controller: _clientIdController,
|
controller: _clientIdController,
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'OAuth App client id',
|
|
||||||
helperText: 'Needed for the Connect GitHub button',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.key,
|
||||||
|
semanticLabel: 'Personal access token (fallback)',
|
||||||
controller: _tokenController,
|
controller: _tokenController,
|
||||||
obscureText: true,
|
obscure: true,
|
||||||
decoration: InputDecoration(
|
|
||||||
labelText: 'Personal access token (fallback)',
|
|
||||||
// Both wrapper hints are web-only; a VM test always takes
|
|
||||||
// the null branch.
|
|
||||||
// coverage:ignore-start
|
|
||||||
helperText: SyncSettings.exposesTokenValue
|
|
||||||
? null
|
|
||||||
: _storedToken.isEmpty
|
|
||||||
? 'Stored by the desktop wrapper, never by the browser'
|
|
||||||
: 'A token is stored by the desktop wrapper; type '
|
|
||||||
'here only to replace it',
|
|
||||||
// coverage:ignore-end
|
|
||||||
helperMaxLines: 2,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Wrap(
|
Wrap(
|
||||||
spacing: 8,
|
spacing: 8,
|
||||||
children: [
|
children: [
|
||||||
ElevatedButton(
|
IconButton.filled(
|
||||||
onPressed: _busy ? null : _save,
|
onPressed: _busy ? null : _save,
|
||||||
child: const Text('Save'),
|
icon: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||||
),
|
),
|
||||||
OutlinedButton(
|
// Tests the GitHub connection only (a canAccessRepo call);
|
||||||
|
// it says nothing about Firebase.
|
||||||
|
IconButton.outlined(
|
||||||
onPressed: _busy ? null : _testConnection,
|
onPressed: _busy ? null : _testConnection,
|
||||||
// Named for what it actually does: _testConnection builds
|
icon: const Icon(
|
||||||
// a GitHub client and calls canAccessRepo(). It says
|
Icons.network_check,
|
||||||
// nothing about Firebase, and the bare label implied
|
semanticLabel: 'Test GitHub connection',
|
||||||
// otherwise.
|
),
|
||||||
child: const Text('Test GitHub connection'),
|
|
||||||
),
|
),
|
||||||
ElevatedButton(
|
IconButton.filled(
|
||||||
onPressed: _busy ? null : _syncNow,
|
onPressed: _busy ? null : _syncNow,
|
||||||
child: const Text('Sync now'),
|
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (_status != null) ...[
|
if (_status != null) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
|
Align(alignment: Alignment.centerLeft, child: _status),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@ -7,6 +7,7 @@ library;
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
|
import 'package:diet_guard_app/screens/edit_entry_screen.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
@ -14,7 +15,7 @@ import 'package:diet_guard_app/widgets/history/history_filter.dart';
|
|||||||
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
|
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
|
||||||
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
||||||
import 'package:diet_guard_app/widgets/history/history_list.dart';
|
import 'package:diet_guard_app/widgets/history/history_list.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Logged meal history: every entry, grouped by day, filterable and sortable.
|
/// Logged meal history: every entry, grouped by day, filterable and sortable.
|
||||||
///
|
///
|
||||||
@ -159,15 +160,16 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
final allEntries = _allEntries;
|
final allEntries = _allEntries;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('History'),
|
|
||||||
actions: [
|
actions: [
|
||||||
if (allEntries != null)
|
if (allEntries != null)
|
||||||
Stack(
|
Stack(
|
||||||
alignment: Alignment.center,
|
alignment: Alignment.center,
|
||||||
children: [
|
children: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.filter_list),
|
icon: const Icon(
|
||||||
tooltip: 'Filter & sort',
|
Icons.filter_list,
|
||||||
|
semanticLabel: 'Filter & sort',
|
||||||
|
),
|
||||||
onPressed: _openFilterSheet,
|
onPressed: _openFilterSheet,
|
||||||
),
|
),
|
||||||
if (_filter.isActive)
|
if (_filter.isActive)
|
||||||
@ -188,11 +190,14 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: allEntries == null
|
body: allEntries == null
|
||||||
? const Center(child: CircularProgressIndicator())
|
? const WaitWatch.centered('history.load')
|
||||||
: _displayed.isEmpty
|
: _displayed.isEmpty
|
||||||
? Center(
|
? Center(
|
||||||
child: Text(
|
child: Icon(
|
||||||
allEntries.isEmpty
|
allEntries.isEmpty ? Icons.restaurant : Icons.filter_list_off,
|
||||||
|
size: 64,
|
||||||
|
color: Theme.of(context).colorScheme.outline,
|
||||||
|
semanticLabel: allEntries.isEmpty
|
||||||
? 'Nothing logged yet.'
|
? 'Nothing logged yet.'
|
||||||
: 'No entries match the current filter.',
|
: 'No entries match the current filter.',
|
||||||
),
|
),
|
||||||
|
|||||||
@ -2,12 +2,11 @@ import 'package:diet_guard_app/models/food_suggestion.dart';
|
|||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Writes [suggestion]'s name and macros into the log form's controllers.
|
/// Writes [suggestion]'s name and macros into the log form's controllers.
|
||||||
///
|
///
|
||||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap, mirroring
|
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap.
|
||||||
/// `log_meal_kuchnia_mixin.dart`'s `fillControllersFromDish`.
|
|
||||||
void fillControllersFromSuggestion(
|
void fillControllersFromSuggestion(
|
||||||
FoodSuggestion suggestion,
|
FoodSuggestion suggestion,
|
||||||
TextEditingController desc,
|
TextEditingController desc,
|
||||||
@ -32,7 +31,8 @@ Nutrition nutritionFromControllers(MacroControllers macros, String source) =>
|
|||||||
source: source,
|
source: source,
|
||||||
);
|
);
|
||||||
|
|
||||||
/// The five destination buttons in [LogMealScreen]'s app bar.
|
/// The destination buttons in [LogMealScreen]'s app bar, after [leading]
|
||||||
|
/// (the date picker).
|
||||||
///
|
///
|
||||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Returned
|
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap. Returned
|
||||||
/// as a list to be spread into `AppBar.actions`, so the bar's structure and
|
/// as a list to be spread into `AppBar.actions`, so the bar's structure and
|
||||||
@ -43,30 +43,27 @@ List<Widget> logMealAppBarActions({
|
|||||||
required VoidCallback onCalendar,
|
required VoidCallback onCalendar,
|
||||||
required VoidCallback onSettings,
|
required VoidCallback onSettings,
|
||||||
required VoidCallback onBody,
|
required VoidCallback onBody,
|
||||||
|
List<Widget> leading = const [],
|
||||||
}) => [
|
}) => [
|
||||||
|
...leading,
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.monitor_weight),
|
icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'),
|
||||||
tooltip: 'Body',
|
|
||||||
onPressed: onBody,
|
onPressed: onBody,
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.restaurant_menu),
|
icon: const Icon(Icons.restaurant_menu, semanticLabel: 'Food bank'),
|
||||||
tooltip: 'Food bank',
|
|
||||||
onPressed: onFoodBank,
|
onPressed: onFoodBank,
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.history),
|
icon: const Icon(Icons.history, semanticLabel: 'History'),
|
||||||
tooltip: 'History',
|
|
||||||
onPressed: onHistory,
|
onPressed: onHistory,
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.calendar_month),
|
icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'),
|
||||||
tooltip: 'Calendar',
|
|
||||||
onPressed: onCalendar,
|
onPressed: onCalendar,
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.settings),
|
icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'),
|
||||||
tooltip: 'Sync settings',
|
|
||||||
onPressed: onSettings,
|
onPressed: onSettings,
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
|
|||||||
137
app/lib/screens/log_meal_claude_mixin.dart
Normal file
137
app/lib/screens/log_meal_claude_mixin.dart
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
/// The sparkle button: send the typed text and/or photo to Claude.
|
||||||
|
///
|
||||||
|
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
|
||||||
|
/// ceiling. The transport is behind [ClaudeRelayClient]; this only drives the
|
||||||
|
/// button's states and shows the meal Claude logged.
|
||||||
|
///
|
||||||
|
/// The photo lives in [photo] for one send and nowhere else.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_photo_source.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/meal_action_row.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Photo attach and the Claude send, for the log screen's state.
|
||||||
|
mixin LogMealClaudeMixin<T extends StatefulWidget>
|
||||||
|
on
|
||||||
|
LogMealSyncMixin<T>,
|
||||||
|
LogMealDueMixin<T>,
|
||||||
|
LogMealLoggedMixin<T>,
|
||||||
|
LogMealFutureMixin<T> {
|
||||||
|
/// The relay this screen sends through. Supplied by the screen.
|
||||||
|
ClaudeRelayClient get relay;
|
||||||
|
|
||||||
|
/// Where photos come from. Supplied by the screen.
|
||||||
|
MealPhotoSource get photoSource;
|
||||||
|
|
||||||
|
/// The food field. Supplied by the screen.
|
||||||
|
TextEditingController get claudeDesc;
|
||||||
|
|
||||||
|
/// The macro fields. Supplied by the screen.
|
||||||
|
MacroControllers get claudeMacros;
|
||||||
|
|
||||||
|
/// The sparkle button's state.
|
||||||
|
ClaudeButtonState claudeState = ClaudeButtonState.idle;
|
||||||
|
|
||||||
|
/// The attached photo's JPEG bytes, or null. Never stored or synced.
|
||||||
|
Uint8List? photo;
|
||||||
|
|
||||||
|
StreamSubscription<ClaudeRelayEvent>? _relaySub;
|
||||||
|
String? _pendingRid;
|
||||||
|
|
||||||
|
/// Whether there is something to send (a description or a photo).
|
||||||
|
bool get canSend =>
|
||||||
|
futureDate == null &&
|
||||||
|
(claudeDesc.text.trim().isNotEmpty || photo != null);
|
||||||
|
|
||||||
|
/// Attaches a photo from [origin]; backing out keeps the current one.
|
||||||
|
Future<void> attachPhoto(PhotoOrigin origin) async {
|
||||||
|
final bytes = await photoSource.pick(origin);
|
||||||
|
if (!mounted || bytes == null) return;
|
||||||
|
setState(() => photo = bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the attached photo.
|
||||||
|
void removePhoto() => setState(() => photo = null);
|
||||||
|
|
||||||
|
/// Sends the form to Claude and follows the request's events.
|
||||||
|
void sendToClaude() {
|
||||||
|
if (!canSend) return;
|
||||||
|
final request = ClaudeRelayRequest(
|
||||||
|
requestId: newRequestId(),
|
||||||
|
slotMinute: targetSlot,
|
||||||
|
mode: dueMode ? ClaudeRelayMode.due : ClaudeRelayMode.normal,
|
||||||
|
text: claudeDesc.text.trim(),
|
||||||
|
photoJpeg: photo,
|
||||||
|
);
|
||||||
|
unawaited(_relaySub?.cancel());
|
||||||
|
_pendingRid = request.requestId;
|
||||||
|
setState(() => claudeState = ClaudeButtonState.sending);
|
||||||
|
_relaySub = relay.send(request).listen((e) => unawaited(_onEvent(e)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _onEvent(ClaudeRelayEvent event) async {
|
||||||
|
if (!mounted) return;
|
||||||
|
switch (event) {
|
||||||
|
case ClaudeRelayQueued():
|
||||||
|
setState(() => claudeState = ClaudeButtonState.queued);
|
||||||
|
case ClaudeRelayLocked():
|
||||||
|
_pendingRid = null;
|
||||||
|
setState(() => claudeState = ClaudeButtonState.locked);
|
||||||
|
case ClaudeRelayFailed():
|
||||||
|
_pendingRid = null;
|
||||||
|
setState(() => claudeState = ClaudeButtonState.error);
|
||||||
|
case ClaudeRelayLogged(:final entry):
|
||||||
|
_pendingRid = null;
|
||||||
|
// The worker logged it under the request id; the sync would deliver
|
||||||
|
// the same record, so this only shows it now and never doubles it.
|
||||||
|
final stored = await LogStorageService.instance.addIfAbsent(entry);
|
||||||
|
if (!mounted) return;
|
||||||
|
claudeDesc.clear();
|
||||||
|
claudeMacros.clear();
|
||||||
|
setState(() {
|
||||||
|
claudeState = ClaudeButtonState.idle;
|
||||||
|
photo = null;
|
||||||
|
});
|
||||||
|
showLogged([LoggedMeal(stored, LoggedOrigin.claude)]);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Withdraws a request that is still in flight or queued, because the user
|
||||||
|
/// just logged the meal here instead.
|
||||||
|
///
|
||||||
|
/// Unclaimed: the node is deleted and the stream dropped. Already claimed
|
||||||
|
/// (the PC is mid-estimate): the meal will be logged, so the stream stays
|
||||||
|
/// open and its row shows with an undo rather than the entry turning up
|
||||||
|
/// unseen after the next sync. That race is accepted, see
|
||||||
|
/// `docs/DOCS-claude-relay.md`.
|
||||||
|
Future<void> withdrawClaude() async {
|
||||||
|
final rid = _pendingRid;
|
||||||
|
final waiting =
|
||||||
|
claudeState == ClaudeButtonState.sending ||
|
||||||
|
claudeState == ClaudeButtonState.queued;
|
||||||
|
if (rid == null || !waiting) return;
|
||||||
|
if (await relay.cancel(rid)) {
|
||||||
|
_pendingRid = null;
|
||||||
|
await _relaySub?.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancels the event subscription; call from `dispose`. A request still
|
||||||
|
/// queued on the PC reaches this phone through sync instead.
|
||||||
|
void disposeClaude() => unawaited(_relaySub?.cancel());
|
||||||
|
}
|
||||||
89
app/lib/screens/log_meal_due_mixin.dart
Normal file
89
app/lib/screens/log_meal_due_mixin.dart
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
/// Due mode: some slot has elapsed with nothing logged.
|
||||||
|
///
|
||||||
|
/// The log screen then strips everything that is not "log this meal now" (the
|
||||||
|
/// app bar, sync banner, date row), hides the Android status bar, and targets
|
||||||
|
/// the oldest due slot with both the check and the sparkle. Its own file
|
||||||
|
/// because `log_meal_screen.dart` is at the repo's 250-line ceiling.
|
||||||
|
///
|
||||||
|
/// Slot arithmetic is not touched here: due slots come from `missingSlots`
|
||||||
|
/// and the nearest-slot rule from `slotForLog`, both in `models/slot.dart`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// The clock the log screen reads for "which slots are due".
|
||||||
|
///
|
||||||
|
/// A hook rather than a constructor argument so the whole screen suite can pin
|
||||||
|
/// it once (`flutter_test_config.dart` pins 07:00, before the first slot);
|
||||||
|
/// otherwise every nav and slot test would pass at night and fail by day, once
|
||||||
|
/// due mode hides the app bar.
|
||||||
|
@visibleForTesting
|
||||||
|
DateTime Function() logMealClock = DateTime.now;
|
||||||
|
|
||||||
|
/// Shows or hides the Android status bar.
|
||||||
|
///
|
||||||
|
/// `main.dart` sets no system-UI mode, so "visible" is the platform default:
|
||||||
|
/// both bars shown. [hidden] true is sticky-immersive; false puts both back.
|
||||||
|
@visibleForTesting
|
||||||
|
Future<void> Function({required bool hidden}) setStatusBarHidden = _setBars;
|
||||||
|
|
||||||
|
Future<void> _setBars({required bool hidden}) => hidden
|
||||||
|
? SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky)
|
||||||
|
: SystemChrome.setEnabledSystemUIMode(
|
||||||
|
SystemUiMode.manual,
|
||||||
|
overlays: SystemUiOverlay.values,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Due-mode state and slot targeting for the log screen's state.
|
||||||
|
mixin LogMealDueMixin<T extends StatefulWidget> on LogMealSyncMixin<T> {
|
||||||
|
/// Whether the first read of today's log has finished. Until then the
|
||||||
|
/// screen draws neither mode, so it never flashes the app bar and drops it.
|
||||||
|
bool slotsLoaded = false;
|
||||||
|
|
||||||
|
bool _statusBarHidden = false;
|
||||||
|
|
||||||
|
/// What the screen reads as "now" (see [logMealClock]).
|
||||||
|
DateTime get screenNow => logMealClock();
|
||||||
|
|
||||||
|
/// Elapsed slots with nothing logged, oldest first.
|
||||||
|
List<int> get dueSlots =>
|
||||||
|
missingSlots(screenNow, loggedSlots, MealScheduleService.current);
|
||||||
|
|
||||||
|
/// Whether the screen is in due mode.
|
||||||
|
bool get dueMode => slotsLoaded && dueSlots.isNotEmpty;
|
||||||
|
|
||||||
|
/// The slot a log or a send lands in: the oldest due slot, else the slot
|
||||||
|
/// nearest [screenNow] (`slotForLog`).
|
||||||
|
int get targetSlot => dueSlots.isNotEmpty
|
||||||
|
? dueSlots.first
|
||||||
|
: slotForLog(screenNow, MealScheduleService.current);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> refreshSlots() async {
|
||||||
|
await super.refreshSlots();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => slotsLoaded = true);
|
||||||
|
await syncStatusBar();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the status bar while in due mode and restores it on exit.
|
||||||
|
Future<void> syncStatusBar() async {
|
||||||
|
final hide = dueMode;
|
||||||
|
if (hide == _statusBarHidden) return;
|
||||||
|
_statusBarHidden = hide;
|
||||||
|
await setStatusBarHidden(hidden: hide);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the status bar back; call from `dispose`.
|
||||||
|
void restoreStatusBar() {
|
||||||
|
if (!_statusBarHidden) return;
|
||||||
|
_statusBarHidden = false;
|
||||||
|
unawaited(setStatusBarHidden(hidden: false));
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,105 +0,0 @@
|
|||||||
/// Wires "Fill all with catering" into the log form.
|
|
||||||
///
|
|
||||||
/// Its own file because `log_meal_screen.dart` and
|
|
||||||
/// `log_meal_kuchnia_mixin.dart` are both at the repo's 250-line ceiling. The
|
|
||||||
/// rule lives in `kuchnia_fill.dart` and the two-tap state in
|
|
||||||
/// `kuchnia_fill_flow.dart`; this only connects them to the screen.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
/// Drives the screen's [FillAllFlow] and tidies the screen after a fill.
|
|
||||||
mixin LogMealFillMixin<T extends StatefulWidget>
|
|
||||||
on LogMealSyncMixin<T>, LogMealKuchniaMixin<T>, LogMealFutureMixin<T> {
|
|
||||||
/// The flow behind the button. Per-screen, so leaving the screen drops an
|
|
||||||
/// armed proposal along with it.
|
|
||||||
FillAllFlow fillFlow = FillAllFlow();
|
|
||||||
|
|
||||||
/// Shows [message] in the form's status line. Supplied by the screen.
|
|
||||||
void showFillStatus(String message);
|
|
||||||
|
|
||||||
/// A proposal belongs to the date it was fetched for; picking another (or
|
|
||||||
/// going back to today) must not leave "Confirm (N)" offering it.
|
|
||||||
@override
|
|
||||||
void onLogDateChanged() {
|
|
||||||
super.onLogDateChanged();
|
|
||||||
fillFlow.cancel();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs one tap: the first proposes, a second on the same day confirms.
|
|
||||||
/// Fills the "Log for later" date when one is picked, else today.
|
|
||||||
Future<void> onFillAll() async {
|
|
||||||
final day = futureDate;
|
|
||||||
final pending = fillFlow.tap(day: day);
|
|
||||||
setState(() {}); // show the busy label while the fetch/writes run
|
|
||||||
final FillOutcome? outcome;
|
|
||||||
try {
|
|
||||||
outcome = await pending;
|
|
||||||
} on Exception catch (error) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {});
|
|
||||||
// A confirm can fail partway through its writes. Whatever did land is
|
|
||||||
// a real meal, so it is published like any other rather than waiting
|
|
||||||
// for the next tick, and the user is told the batch did not finish.
|
|
||||||
await publishAfterLog();
|
|
||||||
await refreshSlots();
|
|
||||||
if (mounted) showFillStatus('Fill all failed: $error');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {});
|
|
||||||
if (outcome == null) return;
|
|
||||||
if (outcome.written.isNotEmpty) {
|
|
||||||
await _afterFill(outcome.written, later: day != null);
|
|
||||||
}
|
|
||||||
if (!mounted) return;
|
|
||||||
showFillStatus(outcome.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Disarms a proposal without writing anything.
|
|
||||||
void onFillCancel() {
|
|
||||||
fillFlow.cancel();
|
|
||||||
showFillStatus('Fill all cancelled — nothing logged.');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Publishes the batch once and drops the filled dishes from the delivery
|
|
||||||
/// queue, so "Today's delivery (N more to go)" and the prefilled form do
|
|
||||||
/// not keep offering meals that were just logged.
|
|
||||||
///
|
|
||||||
/// A [later] fill logged another day's delivery: today's queue and form are
|
|
||||||
/// left alone, and the screen goes back to today, as after a manual
|
|
||||||
/// "Log for later" -- the picked day's slot row would otherwise be stale.
|
|
||||||
Future<void> _afterFill(
|
|
||||||
List<SlottedDish> written, {
|
|
||||||
required bool later,
|
|
||||||
}) async {
|
|
||||||
if (later) {
|
|
||||||
resetFutureLog();
|
|
||||||
await publishAfterLog();
|
|
||||||
await refreshSlots();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (KuchniaQueueService.isInitialized) {
|
|
||||||
for (final item in written) {
|
|
||||||
KuchniaQueueService.instance.markLogged(item.dish);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final offered = offeredDish;
|
|
||||||
if (offered != null &&
|
|
||||||
written.any((item) => item.dish.bankKey == offered.bankKey)) {
|
|
||||||
// The prefilled dish was just logged by the fill; leaving it in the
|
|
||||||
// form would invite a second, duplicate submit.
|
|
||||||
descController.clear();
|
|
||||||
macroControllers.clear();
|
|
||||||
}
|
|
||||||
prefillNextDish();
|
|
||||||
await publishAfterLog();
|
|
||||||
await refreshSlots();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -3,10 +3,7 @@
|
|||||||
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line cap.
|
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line cap.
|
||||||
///
|
///
|
||||||
/// Scoped to dates strictly after today: the date picker's `firstDate` is
|
/// Scoped to dates strictly after today: the date picker's `firstDate` is
|
||||||
/// tomorrow. Today's own not-yet-due slots keep using the screen's existing
|
/// tomorrow.
|
||||||
/// [SlotSelectorRow] (driven by the real `DateTime.now()`), so this mixin
|
|
||||||
/// never has to reproduce its "due" (red) coloring, which is meaningless for
|
|
||||||
/// a day that hasn't started.
|
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
@ -15,9 +12,9 @@ import 'package:diet_guard_app/models/meal_schedule.dart';
|
|||||||
import 'package:diet_guard_app/models/slot.dart';
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||||
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
|
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Adds a future-date meal-log picker to [LogMealScreen]'s state.
|
/// Adds a future-date meal-log picker to [LogMealScreen]'s state.
|
||||||
mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
||||||
@ -51,7 +48,7 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
|||||||
Future<void> _pickFutureDate() async {
|
Future<void> _pickFutureDate() async {
|
||||||
final today = DateTime.now();
|
final today = DateTime.now();
|
||||||
final tomorrow = DateTime(today.year, today.month, today.day + 1);
|
final tomorrow = DateTime(today.year, today.month, today.day + 1);
|
||||||
final picked = await showDatePicker(
|
final picked = await pickDate(
|
||||||
context: context,
|
context: context,
|
||||||
firstDate: tomorrow,
|
firstDate: tomorrow,
|
||||||
lastDate: tomorrow.add(const Duration(days: 365)),
|
lastDate: tomorrow.add(const Duration(days: 365)),
|
||||||
@ -84,51 +81,58 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
|||||||
onLogDateChanged();
|
onLogDateChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The "When" row: a "Log for later" button, or the picked date with a
|
/// The app bar's date actions: the picker (leftmost icon) and, once a date
|
||||||
/// button to change it and one to clear back to today.
|
/// is picked, a way back to today. A picked date tints the picker gold with
|
||||||
Widget buildWhenRow(BuildContext context) {
|
/// a small dot; no text is painted.
|
||||||
|
List<Widget> buildDateActions(BuildContext context) {
|
||||||
final date = _futureDate;
|
final date = _futureDate;
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final gold = Theme.of(context).colorScheme.primary;
|
||||||
return Row(
|
return [
|
||||||
children: [
|
IconButton(
|
||||||
Icon(Icons.event, size: 18, color: scheme.onSurfaceVariant),
|
// Not Icons.calendar_month: the bar's own "Calendar" nav button uses
|
||||||
const SizedBox(width: AppSpacing.xs),
|
// that, and two on screen make `find.byIcon` ambiguous.
|
||||||
Expanded(child: Text(date == null ? 'Today' : localDateKey(date))),
|
icon: Stack(
|
||||||
TextButton.icon(
|
clipBehavior: Clip.none,
|
||||||
// Not Icons.calendar_month: the app bar's own "Calendar" nav button
|
children: [
|
||||||
// already uses that, and a second one on screen makes
|
Icon(
|
||||||
// `find.byIcon` ambiguous for widget tests (and taps) alike.
|
Icons.edit_calendar,
|
||||||
icon: const Icon(Icons.date_range, size: 18),
|
color: date == null ? null : gold,
|
||||||
label: Text(date == null ? 'Log for later' : 'Change date'),
|
semanticLabel: date == null ? 'Log for later' : 'Change date',
|
||||||
onPressed: _pickFutureDate,
|
),
|
||||||
|
if (date != null)
|
||||||
|
Positioned(
|
||||||
|
top: -1,
|
||||||
|
right: -1,
|
||||||
|
child: Container(
|
||||||
|
key: const ValueKey('log-date-badge'),
|
||||||
|
width: 8,
|
||||||
|
height: 8,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: gold,
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
if (date != null)
|
onPressed: _pickFutureDate,
|
||||||
IconButton(
|
),
|
||||||
icon: const Icon(Icons.close),
|
if (date != null)
|
||||||
tooltip: 'Back to today',
|
IconButton(
|
||||||
onPressed: resetFutureLog,
|
icon: const Icon(Icons.close, semanticLabel: 'Back to today'),
|
||||||
),
|
onPressed: resetFutureLog,
|
||||||
],
|
),
|
||||||
);
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The slot row to show: [futureDate]'s own (driven by that date's logged
|
/// The slot row for a picked future date, else nothing.
|
||||||
/// slots) when a future date is picked, otherwise today's, built from the
|
///
|
||||||
/// screen's own state and [onTodaySlotSelected].
|
/// Today has no slot row any more: the screen derives today's slot (the
|
||||||
Widget buildSlotRow({
|
/// oldest due one, else the nearest). A *future* date has no due slots to
|
||||||
required Set<int> loggedSlots,
|
/// derive from, so the row survives for exactly that case.
|
||||||
required int? selectedSlot,
|
Widget buildSlotRow() {
|
||||||
required ValueChanged<int?> onTodaySlotSelected,
|
|
||||||
}) {
|
|
||||||
final date = _futureDate;
|
final date = _futureDate;
|
||||||
if (date == null) {
|
if (date == null) return const SizedBox.shrink();
|
||||||
return SlotSelectorRow(
|
|
||||||
now: DateTime.now(),
|
|
||||||
loggedSlots: loggedSlots,
|
|
||||||
selectedSlot: selectedSlot,
|
|
||||||
onSlotSelected: onTodaySlotSelected,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return SlotSelectorRow(
|
return SlotSelectorRow(
|
||||||
now: DateTime(date.year, date.month, date.day),
|
now: DateTime(date.year, date.month, date.day),
|
||||||
schedule: _futureSchedule,
|
schedule: _futureSchedule,
|
||||||
|
|||||||
@ -1,235 +0,0 @@
|
|||||||
/// Offers the day's delivered catering dishes to the log form.
|
|
||||||
///
|
|
||||||
/// Its own file because `log_meal_screen.dart` is at the repo's 250-line
|
|
||||||
/// ceiling.
|
|
||||||
///
|
|
||||||
/// **A delivered meal is not an eaten meal.** This only ever *prefills* the
|
|
||||||
/// form -- the user still taps "Log" for each dish. Nothing here writes a log
|
|
||||||
/// entry, and nothing here may start doing so: the gate would then satisfy its
|
|
||||||
/// own checkpoint from a delivery note, and the log would record what the
|
|
||||||
/// courier dropped off rather than what was eaten.
|
|
||||||
///
|
|
||||||
/// [prefillNextDish] is called from **two** places: once when the delivery
|
|
||||||
/// first arrives, and again after every successful submit. That second caller
|
|
||||||
/// is the load-bearing one. On the PC it briefly did not exist, which made the
|
|
||||||
/// "(N more to go)" promise a dead letter -- every dish after the first stayed
|
|
||||||
/// queued behind another click. `kuchnia_queue_test.dart` asserts the state
|
|
||||||
/// transition rather than "a dish was offered", because the latter passes
|
|
||||||
/// while this misbehaves.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
/// Writes [dish]'s name and macros into the log form's controllers.
|
|
||||||
///
|
|
||||||
/// Free function rather than a mixin method so the numeric formatting is
|
|
||||||
/// testable without pumping a widget.
|
|
||||||
///
|
|
||||||
/// Clears every macro field first, mirroring `_gatelock_delivery.py`'s
|
|
||||||
/// `self._clear_inputs()`. Dropping that step is what corrupted a real log
|
|
||||||
/// entry on 2026-08-23: a dish carries *per-portion* macros and leaves
|
|
||||||
/// [MacroControllers.perGrams] untouched, so a `100` left behind by an
|
|
||||||
/// earlier food-bank pick made `nutritionForPortion` read them as *per-100g*
|
|
||||||
/// and scale them by `grams / 100` -- 472 kcal logged as 1217.8.
|
|
||||||
///
|
|
||||||
/// The clear is a single call covering all six controllers rather than a
|
|
||||||
/// `perGrams.clear()` line here, so a seventh field added later cannot be
|
|
||||||
/// forgotten at this call site; `MacroControllers.clear()` is enumerated by
|
|
||||||
/// its own test.
|
|
||||||
void fillControllersFromDish(
|
|
||||||
KuchniaDish dish,
|
|
||||||
TextEditingController desc,
|
|
||||||
MacroControllers macros,
|
|
||||||
) {
|
|
||||||
macros.clear();
|
|
||||||
desc.text = dish.name;
|
|
||||||
final (grams, values) = dishFieldValues(dish);
|
|
||||||
macros.kcal.text = values.$1;
|
|
||||||
macros.protein.text = values.$2;
|
|
||||||
macros.carbs.text = values.$3;
|
|
||||||
macros.fat.text = values.$4;
|
|
||||||
macros.grams.text = grams;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wires the catering queue into a log form.
|
|
||||||
mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
|
|
||||||
/// The dish currently prefilled from the delivery, if any.
|
|
||||||
KuchniaDish? offeredDish;
|
|
||||||
|
|
||||||
/// How many delivered dishes still need logging, including the offered one.
|
|
||||||
///
|
|
||||||
/// The offered dish counts: it is prefilled, not logged, and the user has
|
|
||||||
/// still to tap for it. Excluding it made the line read "0 more" while a
|
|
||||||
/// real dish sat in the form.
|
|
||||||
int get dishesStillQueued => KuchniaQueueService.remaining;
|
|
||||||
|
|
||||||
/// The form's description field. Supplied by the screen.
|
|
||||||
TextEditingController get descController;
|
|
||||||
|
|
||||||
/// The form's macro fields. Supplied by the screen.
|
|
||||||
MacroControllers get macroControllers;
|
|
||||||
|
|
||||||
/// Called after the form is filled, so the screen can mark the source.
|
|
||||||
void onDishPrefilled() {}
|
|
||||||
|
|
||||||
/// Fills the form's fields from [dish].
|
|
||||||
///
|
|
||||||
/// Concrete here rather than an abstract hook: every implementation would be
|
|
||||||
/// the same three lines, and the screen file has no budget to spare.
|
|
||||||
void fillFormFromDish(KuchniaDish dish) {
|
|
||||||
fillControllersFromDish(dish, descController, macroControllers);
|
|
||||||
onDishPrefilled();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery, guarded so it costs at most one walk per day.
|
|
||||||
///
|
|
||||||
/// Goes through [KuchniaQueueService.refreshOnce] rather than
|
|
||||||
/// `refreshDelivery`: this is an *automatic* trigger and can fire after
|
|
||||||
/// every meal, and each unguarded refresh is a login plus three requests
|
|
||||||
/// against a third party. The settings button is the explicit ask that
|
|
||||||
/// always goes and looks.
|
|
||||||
Future<void> loadDeliveryOnce({Set<String> alreadyLogged = const {}}) async {
|
|
||||||
if (!KuchniaQueueService.isInitialized) return;
|
|
||||||
final result = await KuchniaQueueService.refreshOnce(DateTime.now());
|
|
||||||
if (!mounted || result.dishes.isEmpty) return;
|
|
||||||
// Ordered by the caterer's own meal priority, against the *user's*
|
|
||||||
// schedule -- not a hardcoded four slots. A dish offered for a slot the
|
|
||||||
// user's schedule does not have is a checkpoint that can never be met.
|
|
||||||
final ordered = dishesInSlotOrder(
|
|
||||||
result.dishes,
|
|
||||||
daySlots(MealScheduleService.current),
|
|
||||||
);
|
|
||||||
KuchniaQueueService.instance.offer(ordered, alreadyLogged: alreadyLogged);
|
|
||||||
prefillNextDish();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery, skipping dishes already logged today.
|
|
||||||
///
|
|
||||||
/// The skip matters across devices: a dish logged on the PC must not be
|
|
||||||
/// offered again here, and the food log is the only record of that.
|
|
||||||
Future<void> loadTodaysDelivery() async {
|
|
||||||
final logged = await LogStorageService.instance.todayEntries();
|
|
||||||
if (!mounted) return;
|
|
||||||
await loadDeliveryOnce(
|
|
||||||
alreadyLogged: {
|
|
||||||
for (final entry in logged) entry.desc.trim().toLowerCase(),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads today's delivery on an **explicit** user tap, unguarded.
|
|
||||||
///
|
|
||||||
/// Deliberately [refreshDelivery], not [KuchniaQueueService.refreshOnce]:
|
|
||||||
/// per `docs/kuchnia-wikinga.md`'s Triggers table, a user who asks gets a
|
|
||||||
/// look, the same as the CLI and the settings button. The guard exists to
|
|
||||||
/// rate-limit *automatic* triggers, and applying it here would make the
|
|
||||||
/// button silently do nothing for the rest of the day after the startup
|
|
||||||
/// load — the failure that has nothing to tap in the kitchen.
|
|
||||||
///
|
|
||||||
/// Still skips dishes already logged today (a dish logged on the PC must
|
|
||||||
/// not be re-offered) and still records the fetch, so a successful tap
|
|
||||||
/// also spares the automatic path a second walk.
|
|
||||||
///
|
|
||||||
/// Returns a line to show the user, or null when a dish was prefilled and
|
|
||||||
/// the form speaks for itself.
|
|
||||||
Future<String?> loadDeliveryOnTap() async {
|
|
||||||
if (!KuchniaQueueService.isInitialized) return 'Catering is not ready yet.';
|
|
||||||
final logged = await LogStorageService.instance.todayEntries();
|
|
||||||
if (!mounted) return null;
|
|
||||||
final result = await refreshDelivery(DateTime.now());
|
|
||||||
if (!mounted) return null;
|
|
||||||
if (!result.ok) return result.reason;
|
|
||||||
if (result.dishes.isEmpty) return 'No delivery today.';
|
|
||||||
await KuchniaQueueService.instance.recordFetched(DateTime.now());
|
|
||||||
if (!mounted) return null;
|
|
||||||
final ordered = dishesInSlotOrder(
|
|
||||||
result.dishes,
|
|
||||||
daySlots(MealScheduleService.current),
|
|
||||||
);
|
|
||||||
KuchniaQueueService.instance.offer(
|
|
||||||
ordered,
|
|
||||||
alreadyLogged: {
|
|
||||||
for (final entry in logged) entry.desc.trim().toLowerCase(),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (KuchniaQueueService.next == null) {
|
|
||||||
return 'All delivered dishes are already logged.';
|
|
||||||
}
|
|
||||||
prefillNextDish();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether an explicit delivery fetch is in flight.
|
|
||||||
///
|
|
||||||
/// Only guards against a double tap opening two logins at once -- it is not
|
|
||||||
/// the daily guard, which an explicit tap deliberately bypasses.
|
|
||||||
bool deliveryBusy = false;
|
|
||||||
|
|
||||||
/// Runs [loadDeliveryOnTap] and shows its outcome as a SnackBar.
|
|
||||||
///
|
|
||||||
/// Lives here rather than on the screen because `log_meal_screen.dart` is at
|
|
||||||
/// the 250-line cap, and this is the mixin's own behaviour anyway.
|
|
||||||
Future<void> loadDeliveryAndReport() async {
|
|
||||||
setState(() => deliveryBusy = true);
|
|
||||||
String? message;
|
|
||||||
try {
|
|
||||||
message = await loadDeliveryOnTap();
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => deliveryBusy = false);
|
|
||||||
}
|
|
||||||
if (!mounted || message == null) return;
|
|
||||||
ScaffoldMessenger.of(
|
|
||||||
context,
|
|
||||||
).showSnackBar(SnackBar(content: Text(message)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Prefills the form with the next queued dish, if there is one.
|
|
||||||
///
|
|
||||||
/// Safe to call when the queue is empty: it simply clears the offer.
|
|
||||||
void prefillNextDish() {
|
|
||||||
final dish = KuchniaQueueService.next;
|
|
||||||
if (dish == null) {
|
|
||||||
if (offeredDish != null) setState(() => offeredDish = null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setState(() => offeredDish = dish);
|
|
||||||
fillFormFromDish(dish);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drops the just-logged dish and immediately offers the next one.
|
|
||||||
///
|
|
||||||
/// Call this from the submit handler *after* the entry is written. This is
|
|
||||||
/// the second caller that keeps the queue alive across a submit.
|
|
||||||
void advanceQueueAfterLog(String loggedDesc) {
|
|
||||||
final dish = offeredDish;
|
|
||||||
if (dish == null) return;
|
|
||||||
if (dish.name.trim().toLowerCase() != loggedDesc.trim().toLowerCase()) {
|
|
||||||
// The user edited the description into something else, so the offered
|
|
||||||
// dish was not what they logged. Leave it queued rather than silently
|
|
||||||
// marking a dish eaten that never was.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
KuchniaQueueService.instance.markLogged(dish);
|
|
||||||
offeredDish = null;
|
|
||||||
prefillNextDish();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A short line naming what is still queued, or null when nothing is.
|
|
||||||
///
|
|
||||||
/// The leftover matters: the caterer's five meals against four default slots
|
|
||||||
/// means at least one dish is still queued when the last slot is logged. It
|
|
||||||
/// is already banked, so it is named rather than dropped silently.
|
|
||||||
String? get queueStatusLine {
|
|
||||||
final left = dishesStillQueued;
|
|
||||||
if (left <= 0) return null;
|
|
||||||
return '$left more delivered ${left == 1 ? 'dish' : 'dishes'} to log.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
82
app/lib/screens/log_meal_logged_mixin.dart
Normal file
82
app/lib/screens/log_meal_logged_mixin.dart
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
/// The meals the screen logged for the user, shown below the action row with
|
||||||
|
/// an undo, plus the catering auto-log that fills the first of them.
|
||||||
|
///
|
||||||
|
/// The rows stay until the next meal is logged. Undo tombstones that one entry
|
||||||
|
/// by id (`deleteEntry`, never `undoLastToday`: several rows can be on screen,
|
||||||
|
/// and an auto-logged dish is not necessarily the newest entry), so the
|
||||||
|
/// deterministic catering id keeps blocking a re-log on the next open.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Logged-meal rows, undo and the catering auto-log.
|
||||||
|
mixin LogMealLoggedMixin<T extends StatefulWidget>
|
||||||
|
on LogMealSyncMixin<T>, LogMealDueMixin<T> {
|
||||||
|
/// The rows under the action row, oldest first.
|
||||||
|
List<LoggedMeal> loggedRows = const [];
|
||||||
|
|
||||||
|
/// The latest open-or-resume chain. Tests await it instead of guessing how
|
||||||
|
/// long real file I/O takes (a fixed sleep flaked under load).
|
||||||
|
@visibleForTesting
|
||||||
|
Future<void> openChain = Future<void>.value();
|
||||||
|
|
||||||
|
/// Replaces the rows with [meals]: a new log retires the previous ones.
|
||||||
|
void showLogged(List<LoggedMeal> meals) {
|
||||||
|
if (mounted) setState(() => loggedRows = meals);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tombstones [meal]'s entry, drops its row and republishes.
|
||||||
|
Future<void> undoLogged(LoggedMeal meal) async {
|
||||||
|
final id = meal.entry.id;
|
||||||
|
if (id == null) return;
|
||||||
|
setState(() => loggedRows = [...loggedRows]..remove(meal));
|
||||||
|
await LogStorageService.instance.deleteEntry(id);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs the delivered dishes of the due slots, no tap needed.
|
||||||
|
///
|
||||||
|
/// The old rule "a delivered meal is not an eaten meal" was overridden by
|
||||||
|
/// kuhy on 2026-11-17 ("LOG EVEN WITHOUT TAP"). Safe to call repeatedly: the
|
||||||
|
/// ids are deterministic (see `kuchnia_autolog.dart`).
|
||||||
|
Future<void> autoLogCatering() async {
|
||||||
|
if (!dueMode) return;
|
||||||
|
final entries = await KuchniaAutoLog.instance.logDue(dueSlots);
|
||||||
|
if (!mounted || entries.isEmpty) return;
|
||||||
|
showLogged([for (final e in entries) LoggedMeal(e, LoggedOrigin.catering)]);
|
||||||
|
await publishAfterLog();
|
||||||
|
await refreshSlots();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
|
// A resume does what an open does, with one sync (autoSync is
|
||||||
|
// single-flight, so calling super too would let the auto-log run before
|
||||||
|
// the pull finished). Pause still pushes through the sync mixin.
|
||||||
|
if (state == AppLifecycleState.resumed) {
|
||||||
|
startOpenChain();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.didChangeAppLifecycleState(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts [onOpenedOrResumed] and keeps its future in [openChain].
|
||||||
|
void startOpenChain() => openChain = onOpenedOrResumed();
|
||||||
|
|
||||||
|
/// What a fresh open or a resume does: show the screen from the local log,
|
||||||
|
/// pull what other devices logged, then auto-log what is still due.
|
||||||
|
Future<void> onOpenedOrResumed() async {
|
||||||
|
unawaited(refreshSlots());
|
||||||
|
await autoSync();
|
||||||
|
await refreshSlots();
|
||||||
|
await autoLogCatering();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,8 +3,8 @@ import 'package:diet_guard_app/screens/calendar_screen.dart';
|
|||||||
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
import 'package:diet_guard_app/screens/food_bank_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/settings_screen.dart';
|
import 'package:diet_guard_app/screens/settings_screen.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// The five app-bar destinations reachable from [LogMealScreen].
|
/// The five app-bar destinations reachable from [LogMealScreen].
|
||||||
///
|
///
|
||||||
|
|||||||
@ -1,43 +1,54 @@
|
|||||||
/// Single-food meal logging screen -- the app's primary, done-criterion
|
/// Single-food meal logging screen -- the app's primary, done-criterion
|
||||||
/// screen: "I can open the diet app on my phone and fill meal I ate."
|
/// screen: "I can open the diet app on my phone and fill meal I ate."
|
||||||
|
///
|
||||||
|
/// Two modes. **Due mode** (a slot elapsed with nothing logged) shows only
|
||||||
|
/// what logging needs: the food field, suggestions, macros and the action row,
|
||||||
|
/// with the status bar hidden. **Normal mode** adds the app bar, the sync
|
||||||
|
/// banner and the date row. Either way the action row is photo / Claude /
|
||||||
|
/// log, and the field never moves between states.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:diet_guard_app/models/food_suggestion.dart';
|
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/screens/log_meal_actions.dart';
|
import 'package:diet_guard_app/screens/log_meal_actions.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_fill_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_claude_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/screens/log_meal_due_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_future_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_kuchnia_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_logged_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_nav_mixin.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
||||||
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
import 'package:diet_guard_app/services/foodbank_service.dart';
|
import 'package:diet_guard_app/services/foodbank_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_feedback.dart';
|
import 'package:diet_guard_app/services/log_feedback.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_photo_source.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
||||||
import 'package:diet_guard_app/widgets/fill_all_row.dart';
|
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/log_meal_actions_row.dart';
|
|
||||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/meal_action_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/sync_health_banner.dart';
|
import 'package:diet_guard_app/widgets/sync_health_banner.dart';
|
||||||
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Lets the user log one food item, with food-bank autocomplete and
|
/// Lets the user log one food item, with food-bank autocomplete.
|
||||||
/// today's slot status.
|
|
||||||
class LogMealScreen extends StatefulWidget {
|
class LogMealScreen extends StatefulWidget {
|
||||||
/// Creates a [LogMealScreen].
|
/// Creates a [LogMealScreen].
|
||||||
const LogMealScreen({super.key, this.httpClient});
|
const LogMealScreen({super.key, this.httpClient, this.relay, this.photos});
|
||||||
|
|
||||||
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
|
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
|
||||||
/// Production leaves this null so [GitHubClient] builds a real one.
|
|
||||||
final http.Client? httpClient;
|
final http.Client? httpClient;
|
||||||
|
|
||||||
|
/// Where the sparkle button sends; the app-wide [claudeRelay] when null.
|
||||||
|
final ClaudeRelayClient? relay;
|
||||||
|
|
||||||
|
/// Where photos come from; the camera/gallery picker when null.
|
||||||
|
final MealPhotoSource? photos;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<LogMealScreen> createState() => _LogMealScreenState();
|
State<LogMealScreen> createState() => _LogMealScreenState();
|
||||||
}
|
}
|
||||||
@ -46,20 +57,28 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
with
|
with
|
||||||
WidgetsBindingObserver,
|
WidgetsBindingObserver,
|
||||||
LogMealSyncMixin<LogMealScreen>,
|
LogMealSyncMixin<LogMealScreen>,
|
||||||
|
LogMealDueMixin<LogMealScreen>,
|
||||||
|
LogMealLoggedMixin<LogMealScreen>,
|
||||||
LogMealNavMixin<LogMealScreen>,
|
LogMealNavMixin<LogMealScreen>,
|
||||||
LogMealKuchniaMixin<LogMealScreen>,
|
|
||||||
LogMealFutureMixin<LogMealScreen>,
|
LogMealFutureMixin<LogMealScreen>,
|
||||||
LogMealFillMixin<LogMealScreen> {
|
LogMealClaudeMixin<LogMealScreen> {
|
||||||
@override
|
@override
|
||||||
http.Client? get syncHttpClient => widget.httpClient;
|
http.Client? get syncHttpClient => widget.httpClient;
|
||||||
|
@override
|
||||||
|
ClaudeRelayClient get relay => widget.relay ?? claudeRelay;
|
||||||
|
@override
|
||||||
|
late final MealPhotoSource photoSource =
|
||||||
|
widget.photos ?? ImagePickerPhotoSource();
|
||||||
|
|
||||||
final TextEditingController _descController = TextEditingController();
|
final TextEditingController _descController = TextEditingController();
|
||||||
final MacroControllers _macros = MacroControllers();
|
final MacroControllers _macros = MacroControllers();
|
||||||
List<FoodSuggestion> _suggestions = const [];
|
|
||||||
@override
|
@override
|
||||||
int? selectedSlot;
|
TextEditingController get claudeDesc => _descController;
|
||||||
|
@override
|
||||||
|
MacroControllers get claudeMacros => _macros;
|
||||||
|
List<FoodSuggestion> _suggestions = const [];
|
||||||
String _source = 'manual';
|
String _source = 'manual';
|
||||||
String? _status;
|
CueState? _cue; // painted as a tinted icon, never as text
|
||||||
TodayProgress? _progress;
|
TodayProgress? _progress;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@ -68,39 +87,29 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
_descController.addListener(_onDescChanged);
|
_descController.addListener(_onDescChanged);
|
||||||
_macros.addListenerToAll(_onMacroEdited);
|
_macros.addListenerToAll(_onMacroEdited);
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
|
||||||
unawaited(refreshSlots());
|
|
||||||
unawaited(_onDescChanged());
|
unawaited(_onDescChanged());
|
||||||
// Read health before the first sync finishes, so a device that stalled in
|
// Health first, so a device that stalled earlier says so before a tick.
|
||||||
// a previous session says so immediately rather than only after a tick.
|
|
||||||
unawaited(refreshSyncHealth());
|
unawaited(refreshSyncHealth());
|
||||||
unawaited(autoSync());
|
startOpenChain();
|
||||||
// After autoSync so a dish already logged on the PC is known before the
|
|
||||||
// queue is built, and guarded so this costs at most one walk per day.
|
|
||||||
unawaited(loadTodaysDelivery());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
WidgetsBinding.instance.removeObserver(this);
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
|
disposeClaude();
|
||||||
|
restoreStatusBar();
|
||||||
_descController.dispose();
|
_descController.dispose();
|
||||||
_macros.dispose();
|
_macros.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _onMacroEdited() {
|
void _onMacroEdited() {
|
||||||
if (_source == 'food bank') {
|
if (_source == 'food bank') setState(() => _source = 'manual');
|
||||||
setState(() => _source = 'manual');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-runs the food-bank search and dismisses the previous progress card.
|
/// Re-runs the food-bank search and dismisses the previous progress card,
|
||||||
///
|
/// only while the field is non-empty: [_onLogMeal]'s own `clear()` fires
|
||||||
/// The card is cleared only when the field is non-empty because
|
/// this listener too, and would otherwise race it and null the new card.
|
||||||
/// [_onLogMeal]'s own `clear()` fires this listener too: without the guard
|
|
||||||
/// the two async chains race and the clear can null the card right after
|
|
||||||
/// [_onLogMeal] set it, so it never appears on device (in-memory test
|
|
||||||
/// stores resolve fast enough to hide this).
|
|
||||||
Future<void> _onDescChanged() async {
|
Future<void> _onDescChanged() async {
|
||||||
final matches = await FoodBankService.instance.search(_descController.text);
|
final matches = await FoodBankService.instance.search(_descController.text);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
@ -110,18 +119,6 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
|
||||||
TextEditingController get descController => _descController;
|
|
||||||
@override
|
|
||||||
MacroControllers get macroControllers => _macros;
|
|
||||||
@override
|
|
||||||
void onDishPrefilled() => setState(() => _source = 'catering');
|
|
||||||
@override
|
|
||||||
void showFillStatus(String message) => setState(() {
|
|
||||||
_status = message;
|
|
||||||
_progress = null;
|
|
||||||
});
|
|
||||||
|
|
||||||
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
||||||
fillControllersFromSuggestion(suggestion, _descController, _macros);
|
fillControllersFromSuggestion(suggestion, _descController, _macros);
|
||||||
setState(() {
|
setState(() {
|
||||||
@ -132,23 +129,14 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
|
|
||||||
Future<void> _onLogMeal() async {
|
Future<void> _onLogMeal() async {
|
||||||
final desc = _descController.text.trim();
|
final desc = _descController.text.trim();
|
||||||
if (desc.isEmpty) {
|
if (desc.isEmpty) return;
|
||||||
setState(() {
|
final target = resolveLogTarget(targetSlot);
|
||||||
_status = 'Type what you ate first.';
|
|
||||||
_progress = null;
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final target = resolveLogTarget(selectedSlot);
|
|
||||||
if (target.error != null) {
|
if (target.error != null) {
|
||||||
setState(() {
|
setState(() => _cue = CueState.next(_cue, CueKind.error, target.error!));
|
||||||
_status = target.error;
|
|
||||||
_progress = null;
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// On the tap, before the write/sync: waiting for them is just latency.
|
LogFeedback.mealLogged(); // on the tap, before the write
|
||||||
LogFeedback.mealLogged();
|
unawaited(withdrawClaude()); // else Claude would log it a second time
|
||||||
final entry = await LogStorageService.instance.logMeal(
|
final entry = await LogStorageService.instance.logMeal(
|
||||||
desc,
|
desc,
|
||||||
nutritionFromControllers(_macros, _source),
|
nutritionFromControllers(_macros, _source),
|
||||||
@ -162,87 +150,99 @@ class _LogMealScreenState extends State<LogMealScreen>
|
|||||||
_macros.clear();
|
_macros.clear();
|
||||||
setState(() {
|
setState(() {
|
||||||
_source = 'manual';
|
_source = 'manual';
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
photo = null; // else a stale photo keeps the sparkle lit
|
||||||
|
claudeState = ClaudeButtonState.idle;
|
||||||
});
|
});
|
||||||
await refreshSlots();
|
await refreshSlots();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
// The second `prefillNextDish` caller. Without it every dish after the
|
showLogged([LoggedMeal(entry, LoggedOrigin.local)]);
|
||||||
// first stays queued behind another tap and the "N more to log" line
|
|
||||||
// becomes a dead letter -- the exact regression the PC gate once shipped.
|
|
||||||
advanceQueueAfterLog(desc);
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_status = queueStatusLine;
|
_cue = null;
|
||||||
_progress = buildTodayProgress(log, logged: entry);
|
_progress = buildTodayProgress(log, logged: entry);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
if (!slotsLoaded) return const Scaffold();
|
||||||
|
final due = dueMode;
|
||||||
|
// Dimmed while Claude works, but never moved: nothing is added around it.
|
||||||
|
final busy = claudeState == ClaudeButtonState.sending;
|
||||||
|
// Hard rule: nothing sits under the keyboard, so the extras collapse.
|
||||||
|
final typing = MediaQuery.viewInsetsOf(context).bottom > 0;
|
||||||
|
final dim = busy || claudeState == ClaudeButtonState.queued;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: due
|
||||||
title: const Text('Diet Guard'),
|
? null
|
||||||
actions: [
|
: AppBar(
|
||||||
...logMealAppBarActions(
|
actions: logMealAppBarActions(
|
||||||
onFoodBank: onOpenFoodBank,
|
onFoodBank: onOpenFoodBank,
|
||||||
onHistory: onOpenHistory,
|
onHistory: onOpenHistory,
|
||||||
onCalendar: onOpenCalendar,
|
onCalendar: onOpenCalendar,
|
||||||
onSettings: onOpenSettings,
|
onSettings: onOpenSettings,
|
||||||
onBody: onOpenBody,
|
onBody: onOpenBody,
|
||||||
|
leading: buildDateActions(context),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
body: SafeArea(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
padding: const EdgeInsets.all(AppSpacing.md),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
if (!due) SyncHealthBanner(status: syncHealth),
|
||||||
|
buildSlotRow(),
|
||||||
|
Opacity(
|
||||||
|
opacity: dim ? 0.5 : 1,
|
||||||
|
child: IgnorePointer(
|
||||||
|
ignoring: busy,
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
IconField(
|
||||||
|
controller: _descController,
|
||||||
|
icon: Icons.fastfood,
|
||||||
|
semanticLabel: 'What did you eat?',
|
||||||
|
onChanged: (_) => setState(() {}),
|
||||||
|
),
|
||||||
|
AutocompleteSuggestionList(
|
||||||
|
suggestions: _suggestions,
|
||||||
|
onSelected: _onSuggestionSelected,
|
||||||
|
compact: true,
|
||||||
|
compactLimit: due ? 2 : 3,
|
||||||
|
reserveHeight: due,
|
||||||
|
),
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
MacroInputRow(controllers: _macros, compact: true),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
MealActionRow(
|
||||||
|
claude: claudeState,
|
||||||
|
photoAttached: photo != null,
|
||||||
|
canSend: canSend,
|
||||||
|
canLog: _descController.text.trim().isNotEmpty,
|
||||||
|
onPhoto: () => unawaited(attachPhoto(PhotoOrigin.camera)),
|
||||||
|
onGallery: () => unawaited(attachPhoto(PhotoOrigin.gallery)),
|
||||||
|
onRemovePhoto: removePhoto,
|
||||||
|
onSend: sendToClaude,
|
||||||
|
onLog: _onLogMeal,
|
||||||
|
),
|
||||||
|
if (!typing)
|
||||||
|
for (final meal in loggedRows)
|
||||||
|
LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)),
|
||||||
|
if (_cue != null) ...[
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
_cue!.widget,
|
||||||
|
],
|
||||||
|
if (_progress != null && !due && !typing) ...[
|
||||||
|
const SizedBox(height: AppSpacing.sm),
|
||||||
|
TodayProgressCard(progress: _progress!),
|
||||||
|
],
|
||||||
|
],
|
||||||
),
|
),
|
||||||
],
|
|
||||||
),
|
|
||||||
body: SingleChildScrollView(
|
|
||||||
padding: const EdgeInsets.all(AppSpacing.md),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
SyncHealthBanner(status: syncHealth),
|
|
||||||
buildWhenRow(context),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
buildSlotRow(
|
|
||||||
loggedSlots: loggedSlots,
|
|
||||||
selectedSlot: selectedSlot,
|
|
||||||
onTodaySlotSelected: (slot) =>
|
|
||||||
setState(() => selectedSlot = slot),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
TextField(
|
|
||||||
controller: _descController,
|
|
||||||
decoration: const InputDecoration(labelText: 'What did you eat?'),
|
|
||||||
),
|
|
||||||
AutocompleteSuggestionList(
|
|
||||||
suggestions: _suggestions,
|
|
||||||
onSelected: _onSuggestionSelected,
|
|
||||||
compact: true,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
MacroInputRow(controllers: _macros, compact: true),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
LogMealActionsRow(
|
|
||||||
onLoadDelivery: loadDeliveryAndReport,
|
|
||||||
onLog: _onLogMeal,
|
|
||||||
deliveryBusy: deliveryBusy,
|
|
||||||
dishesQueued: dishesStillQueued,
|
|
||||||
),
|
|
||||||
const SizedBox(height: AppSpacing.sm),
|
|
||||||
FillAllRow(
|
|
||||||
onFill: onFillAll,
|
|
||||||
onCancel: onFillCancel,
|
|
||||||
busy: fillFlow.busy || deliveryBusy,
|
|
||||||
armedCount: fillFlow.armedCount,
|
|
||||||
),
|
|
||||||
// Mutually exclusive: _status carries a validation complaint,
|
|
||||||
// _progress the post-log summary. A successful log clears one
|
|
||||||
// and sets the other, so the two never stack.
|
|
||||||
if (_status != null) ...[
|
|
||||||
const SizedBox(height: AppSpacing.sm),
|
|
||||||
Text(_status!),
|
|
||||||
],
|
|
||||||
if (_progress != null) ...[
|
|
||||||
const SizedBox(height: AppSpacing.sm),
|
|
||||||
TodayProgressCard(progress: _progress!),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
|
||||||
import 'package:diet_guard_app/services/background_tasks.dart';
|
import 'package:diet_guard_app/services/background_tasks.dart';
|
||||||
import 'package:diet_guard_app/services/due_slot_check.dart';
|
import 'package:diet_guard_app/services/due_slot_check.dart';
|
||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
@ -9,12 +8,12 @@ import 'package:diet_guard_app/services/foodbank_service.dart';
|
|||||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||||
import 'package:diet_guard_app/services/health_steps.dart';
|
import 'package:diet_guard_app/services/health_steps.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/sync_attempt.dart';
|
||||||
import 'package:diet_guard_app/services/sync_health.dart';
|
import 'package:diet_guard_app/services/sync_health.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Background-sync and lifecycle behaviour for [LogMealScreen]'s state.
|
/// Background-sync and lifecycle behaviour for [LogMealScreen]'s state.
|
||||||
///
|
///
|
||||||
@ -35,12 +34,6 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
/// The slots that already carry a logged meal today.
|
/// The slots that already carry a logged meal today.
|
||||||
Set<int> loggedSlots = {};
|
Set<int> loggedSlots = {};
|
||||||
|
|
||||||
/// The slot the screen is currently logging for.
|
|
||||||
///
|
|
||||||
/// Owned by the screen's own state; declared here so
|
|
||||||
/// [onScheduleMayHaveChanged] can re-derive it when the schedule changes.
|
|
||||||
abstract int? selectedSlot;
|
|
||||||
|
|
||||||
/// The screen's injected HTTP client, or null to use the default.
|
/// The screen's injected HTTP client, or null to use the default.
|
||||||
///
|
///
|
||||||
/// Declared abstract so the mixin stays independent of the widget's own
|
/// Declared abstract so the mixin stays independent of the widget's own
|
||||||
@ -76,6 +69,7 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
Future<void> autoSync() async {
|
Future<void> autoSync() async {
|
||||||
if (autoSyncing) return;
|
if (autoSyncing) return;
|
||||||
autoSyncing = true;
|
autoSyncing = true;
|
||||||
|
bool? landed; // null until the sync itself ran
|
||||||
try {
|
try {
|
||||||
final settings = await SyncSettings.load();
|
final settings = await SyncSettings.load();
|
||||||
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
||||||
@ -95,17 +89,19 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final client = createGitHubClient(settings, httpClient: syncHttpClient);
|
final client = createGitHubClient(settings, httpClient: syncHttpClient);
|
||||||
try {
|
landed = await attemptSync(() async {
|
||||||
// Foreground only (this mixin is UI), and never prompts: fresh
|
try {
|
||||||
// Health Connect steps ride along in this tick's body.json.
|
// Foreground only (this mixin is UI), and never prompts: fresh
|
||||||
await refreshSteps();
|
// Health Connect steps ride along in this tick's body.json.
|
||||||
await runSync(await syncBackend(client));
|
await refreshSteps();
|
||||||
await SyncHealth.recordSuccess();
|
await runSync(await syncBackend(client));
|
||||||
} finally {
|
} finally {
|
||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
|
});
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
await refreshSlots();
|
// Outside attemptSync: a refresh error is no sync failure.
|
||||||
|
if (landed) await refreshSlots();
|
||||||
await refreshSyncHealth();
|
await refreshSyncHealth();
|
||||||
} on Object catch (error, stackTrace) {
|
} on Object catch (error, stackTrace) {
|
||||||
// Best-effort, but never silent: this swallowed the reason a desktop
|
// Best-effort, but never silent: this swallowed the reason a desktop
|
||||||
@ -118,7 +114,9 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
error: error,
|
error: error,
|
||||||
stackTrace: stackTrace,
|
stackTrace: stackTrace,
|
||||||
);
|
);
|
||||||
await SyncHealth.recordFailure();
|
// attemptSync already recorded the sync's own outcome; only a failure
|
||||||
|
// before it (loading settings) is one here.
|
||||||
|
if (landed == null) await SyncHealth.recordFailure();
|
||||||
if (mounted) await refreshSyncHealth();
|
if (mounted) await refreshSyncHealth();
|
||||||
} finally {
|
} finally {
|
||||||
autoSyncing = false;
|
autoSyncing = false;
|
||||||
@ -174,21 +172,12 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
|||||||
setState(() => loggedSlots = logged);
|
setState(() => loggedSlots = logged);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rebuilds the slot row after the settings screen pops.
|
/// Re-derives the due slots after the settings screen pops.
|
||||||
///
|
///
|
||||||
/// The meal-schedule editor lives in settings, and [SlotSelectorRow] reads
|
/// The meal-schedule editor lives in settings, and which slots are due (and
|
||||||
/// `MealScheduleService.current` at build time, so refreshing is enough to
|
/// so whether the screen is in due mode) reads `MealScheduleService.current`
|
||||||
/// re-derive the row -- but the selected slot also has to be recomputed,
|
/// at refresh time. Found on the phone: without this the settings preview
|
||||||
/// since the minute it referred to may no longer be a checkpoint at all.
|
/// and the overdue reminder both updated while the screen behind them kept
|
||||||
///
|
/// the old checkpoints until the app was restarted.
|
||||||
/// Found on the phone: without this the settings preview and the overdue
|
Future<void> onScheduleMayHaveChanged() => refreshSlots();
|
||||||
/// reminder both updated while the row behind them kept the old four
|
|
||||||
/// checkpoints until the app was restarted.
|
|
||||||
Future<void> onScheduleMayHaveChanged() async {
|
|
||||||
await refreshSlots();
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,11 +7,18 @@
|
|||||||
part of 'settings_screen.dart';
|
part of 'settings_screen.dart';
|
||||||
|
|
||||||
mixin _SettingsKcalGoal on State<SettingsScreen> {
|
mixin _SettingsKcalGoal on State<SettingsScreen> {
|
||||||
String? _status;
|
/// The latest outcome as an icon cue; null until something happened.
|
||||||
|
Widget? _status;
|
||||||
|
|
||||||
void _showMessage(String message) {
|
void _showCue(CueKind kind, String semanticLabel) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _status = message);
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: kind,
|
||||||
|
semanticLabel: semanticLabel,
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Timer? _kcalGoalDebounce;
|
Timer? _kcalGoalDebounce;
|
||||||
@ -50,13 +57,13 @@ mixin _SettingsKcalGoal on State<SettingsScreen> {
|
|||||||
() => Permission.ignoreBatteryOptimizations.request();
|
() => Permission.ignoreBatteryOptimizations.request();
|
||||||
try {
|
try {
|
||||||
final status = await request();
|
final status = await request();
|
||||||
_showMessage(
|
if (status.isGranted) {
|
||||||
status.isGranted
|
_showCue(CueKind.ok, 'Battery optimization exemption granted.');
|
||||||
? 'Battery optimization exemption granted.'
|
} else {
|
||||||
: 'Exemption not granted -- notifications may be delayed.',
|
_showCue(CueKind.warn, 'Exemption not granted.');
|
||||||
);
|
}
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
_showMessage('Could not request exemption: $e');
|
_showCue(CueKind.error, 'Could not request exemption: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -15,24 +15,43 @@
|
|||||||
/// encrypted either.
|
/// encrypted either.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show WaitWatch;
|
||||||
import 'package:diet_guard_app/services/kuchnia_client.dart';
|
import 'package:diet_guard_app/services/kuchnia_client.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// What a delivery fetch reports: a cue [kind], a spoken [label] (never
|
||||||
|
/// painted) and, when dishes were banked, their [count] (painted as a number).
|
||||||
|
class FetchOutcome {
|
||||||
|
/// Creates an outcome.
|
||||||
|
const FetchOutcome(this.kind, this.label, {this.count});
|
||||||
|
|
||||||
|
/// Icon/colour of the cue.
|
||||||
|
final CueKind kind;
|
||||||
|
|
||||||
|
/// Spoken description; never painted.
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// Dishes banked, shown as a bare number next to the cue.
|
||||||
|
final int? count;
|
||||||
|
}
|
||||||
|
|
||||||
/// Fetches today's delivery and reports what was banked.
|
/// Fetches today's delivery and reports what was banked.
|
||||||
///
|
///
|
||||||
/// Deliberately says "banked", not "logged": a delivered meal is not an eaten
|
/// Deliberately "banked", not "logged": the explicit fetch only fills the
|
||||||
/// meal, so the dishes land in the food bank and the user still taps to log
|
/// food bank; logging is the log screen's auto-log (`kuchnia_autolog.dart`).
|
||||||
/// each one. Top-level so the settings screen can pass it without growing.
|
/// Top-level so the settings screen can pass it without growing.
|
||||||
Future<String> fetchTodaysDelivery() async {
|
Future<FetchOutcome> fetchTodaysDelivery() async {
|
||||||
final result = await refreshDelivery(DateTime.now());
|
final result = await refreshDelivery(DateTime.now());
|
||||||
if (!result.ok) return result.reason!;
|
if (!result.ok) return FetchOutcome(CueKind.error, result.reason!);
|
||||||
if (result.dishes.isEmpty) return 'No delivery found for today.';
|
if (result.dishes.isEmpty) {
|
||||||
|
return const FetchOutcome(CueKind.warn, 'No delivery found for today.');
|
||||||
|
}
|
||||||
final count = result.dishes.length;
|
final count = result.dishes.length;
|
||||||
return '$count ${count == 1 ? 'dish' : 'dishes'} added to your food bank. '
|
return FetchOutcome(CueKind.ok, '$count dishes added', count: count);
|
||||||
'Log them from the meal screen when you eat them.';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Credential fields plus, on Android, a "fetch today's delivery" action.
|
/// Credential fields plus, on Android, a "fetch today's delivery" action.
|
||||||
@ -43,18 +62,14 @@ class KuchniaSettingsSection extends StatefulWidget {
|
|||||||
/// button is replaced by a one-line explanation rather than silently
|
/// button is replaced by a one-line explanation rather than silently
|
||||||
/// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a
|
/// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a
|
||||||
/// widget test can drive the section without a network or a platform check.
|
/// widget test can drive the section without a network or a platform check.
|
||||||
const KuchniaSettingsSection({
|
const KuchniaSettingsSection({this.canFetch, this.onFetch, super.key});
|
||||||
this.canFetch,
|
|
||||||
this.onFetch,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Whether this platform can reach the catering panel; null means ask.
|
/// Whether this platform can reach the catering panel; null means ask.
|
||||||
final bool? canFetch;
|
final bool? canFetch;
|
||||||
|
|
||||||
/// Fetches today's delivery and returns a status line; null means the real
|
/// Fetches today's delivery and returns a status line; null means the real
|
||||||
/// one.
|
/// one.
|
||||||
final Future<String> Function()? onFetch;
|
final Future<FetchOutcome> Function()? onFetch;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
|
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
|
||||||
@ -69,7 +84,7 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
|||||||
);
|
);
|
||||||
bool _obscured = true;
|
bool _obscured = true;
|
||||||
bool _busy = false;
|
bool _busy = false;
|
||||||
String? _status;
|
Widget? _status;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
@ -85,7 +100,13 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
|||||||
_password.text,
|
_password.text,
|
||||||
);
|
);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _status = 'Saved. It will sync to your other devices.');
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: CueKind.ok,
|
||||||
|
semanticLabel: 'Saved. It will sync to your other devices.',
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _fetch() async {
|
Future<void> _fetch() async {
|
||||||
@ -93,62 +114,65 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
|||||||
_busy = true;
|
_busy = true;
|
||||||
_status = null;
|
_status = null;
|
||||||
});
|
});
|
||||||
final message = await (widget.onFetch ?? fetchTodaysDelivery)();
|
final outcome = await (widget.onFetch ?? fetchTodaysDelivery)();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_busy = false;
|
_busy = false;
|
||||||
_status = message;
|
_status = Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
spacing: AppSpacing.sm,
|
||||||
|
children: [
|
||||||
|
StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: outcome.kind,
|
||||||
|
semanticLabel: outcome.label,
|
||||||
|
),
|
||||||
|
if (outcome.count != null) Text('${outcome.count}'),
|
||||||
|
],
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
|
||||||
final canFetch = widget.canFetch ?? kuchniaFetchSupported;
|
final canFetch = widget.canFetch ?? kuchniaFetchSupported;
|
||||||
// The section owns its own leading divider so the settings screen needs a
|
// The section owns its own leading divider so the settings screen needs a
|
||||||
// single line for it -- that file sits on the repo's 250-line ceiling.
|
// single line for it -- that file sits on the repo's 250-line ceiling.
|
||||||
|
// No heading or blurb: the delivery truck on the fetch button names it.
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
const Divider(),
|
const Divider(),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text('Kuchnia Wikinga', style: theme.textTheme.titleMedium),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
"Your catering panel login, so this device can look up the day's "
|
|
||||||
'delivered dishes and their macros. Stored and synced in plain '
|
|
||||||
'text, like the rest of your synced data.',
|
|
||||||
style: theme.textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
ConstrainedBox(
|
ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: Icons.alternate_email,
|
||||||
|
semanticLabel: 'Panel e-mail',
|
||||||
controller: _username,
|
controller: _username,
|
||||||
keyboardType: TextInputType.emailAddress,
|
keyboardType: TextInputType.emailAddress,
|
||||||
autocorrect: false,
|
autocorrect: false,
|
||||||
decoration: const InputDecoration(labelText: 'Panel e-mail'),
|
|
||||||
onSubmitted: (_) => _save(),
|
onSubmitted: (_) => _save(),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
ConstrainedBox(
|
ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: Icons.key,
|
||||||
|
semanticLabel: 'Panel password',
|
||||||
controller: _password,
|
controller: _password,
|
||||||
obscureText: _obscured,
|
obscure: _obscured,
|
||||||
autocorrect: false,
|
autocorrect: false,
|
||||||
enableSuggestions: false,
|
|
||||||
decoration: InputDecoration(
|
|
||||||
labelText: 'Panel password',
|
|
||||||
suffixIcon: IconButton(
|
|
||||||
icon: Icon(_obscured ? Icons.visibility : Icons.visibility_off),
|
|
||||||
tooltip: _obscured ? 'Show password' : 'Hide password',
|
|
||||||
onPressed: () => setState(() => _obscured = !_obscured),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
onSubmitted: (_) => _save(),
|
onSubmitted: (_) => _save(),
|
||||||
|
suffix: IconButton(
|
||||||
|
icon: Icon(
|
||||||
|
_obscured ? Icons.visibility : Icons.visibility_off,
|
||||||
|
semanticLabel: _obscured ? 'Show password' : 'Hide password',
|
||||||
|
),
|
||||||
|
onPressed: () => setState(() => _obscured = !_obscured),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
@ -156,29 +180,30 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
|||||||
spacing: 8,
|
spacing: 8,
|
||||||
runSpacing: 8,
|
runSpacing: 8,
|
||||||
children: [
|
children: [
|
||||||
FilledButton(onPressed: _save, child: const Text('Save login')),
|
IconButton.filled(
|
||||||
if (canFetch)
|
onPressed: _save,
|
||||||
OutlinedButton.icon(
|
icon: const Icon(Icons.check, semanticLabel: 'Save login'),
|
||||||
onPressed: _busy ? null : _fetch,
|
),
|
||||||
icon: const Icon(Icons.restaurant),
|
// Browser builds show the button greyed out: the panel blocks
|
||||||
label: Text(
|
// browser requests, and the disabled state is the cue.
|
||||||
_busy ? 'Fetching…' : "Fetch today's delivery",
|
IconButton.outlined(
|
||||||
),
|
onPressed: canFetch && !_busy ? _fetch : null,
|
||||||
),
|
icon: _busy
|
||||||
|
? const WaitWatch(
|
||||||
|
operation: 'kuchnia.sync',
|
||||||
|
child: SizedBox.square(
|
||||||
|
dimension: 20,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: const Icon(
|
||||||
|
Icons.local_shipping_outlined,
|
||||||
|
semanticLabel: "Fetch today's delivery",
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (!canFetch) ...[
|
if (_status != null) ...[const SizedBox(height: 8), _status!],
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'Android only — the catering panel blocks browser requests. Your '
|
|
||||||
'login still syncs to your phone from here.',
|
|
||||||
style: theme.textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
if (_status != null) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(_status!, style: theme.textTheme.bodyMedium),
|
|
||||||
],
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,6 +6,8 @@ library;
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show E2ePassphraseButton;
|
||||||
import 'package:diet_guard_app/models/meal_schedule.dart';
|
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||||
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
|
||||||
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
|
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
|
||||||
@ -15,14 +17,18 @@ import 'package:diet_guard_app/services/firebase_backend.dart';
|
|||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
|
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_e2e.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/data_backup_row.dart';
|
import 'package:diet_guard_app/widgets/data_backup_row.dart';
|
||||||
import 'package:diet_guard_app/widgets/log_sound_tile.dart';
|
import 'package:diet_guard_app/widgets/log_sound_tile.dart';
|
||||||
import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
|
import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:kuhy_credit/kuhy_credit.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:permission_handler/permission_handler.dart';
|
import 'package:permission_handler/permission_handler.dart';
|
||||||
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
|
|
||||||
@ -149,30 +155,26 @@ class _SettingsScreenState extends State<SettingsScreen>
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Settings')),
|
// No title: the gear that opened this screen already names it.
|
||||||
// Capped at the prose width: on the ~1366px desktop window the
|
appBar: AppBar(),
|
||||||
// paragraphs below ran ~180 chars/line, twice tokens.md rule 21's limit.
|
// Capped at the prose width so fields do not span a ~1366px window.
|
||||||
body: Center(
|
body: Center(
|
||||||
child: ConstrainedBox(
|
child: ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||||
child: ListView(
|
child: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
Text('Nutrition', style: Theme.of(context).textTheme.titleMedium),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
// A four-digit number: capped so the field does not read as a
|
// A four-digit number: capped so the field does not read as a
|
||||||
// layout error by spanning the whole column.
|
// layout error by spanning the whole column.
|
||||||
ConstrainedBox(
|
ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: MacroKind.kcal.icon,
|
||||||
|
iconColor: MacroKind.kcal.color,
|
||||||
|
semanticLabel: 'Daily kcal goal',
|
||||||
controller: _kcalGoalController,
|
controller: _kcalGoalController,
|
||||||
keyboardType: TextInputType.number,
|
keyboardType: TextInputType.number,
|
||||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||||
decoration: const InputDecoration(
|
|
||||||
labelText: 'Daily kcal goal',
|
|
||||||
helperText: 'Shown in the history day summary',
|
|
||||||
suffixText: 'kcal',
|
|
||||||
),
|
|
||||||
onChanged: _onKcalGoalChanged,
|
onChanged: _onKcalGoalChanged,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@ -186,15 +188,30 @@ class _SettingsScreenState extends State<SettingsScreen>
|
|||||||
const Divider(),
|
const Divider(),
|
||||||
ListTile(
|
ListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Sync settings'),
|
leading: const Icon(
|
||||||
subtitle: const Text('Firebase sync'),
|
Icons.cloud_sync_outlined,
|
||||||
|
semanticLabel: 'Sync settings',
|
||||||
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => unawaited(_openSyncSettings()),
|
onTap: () => unawaited(_openSyncSettings()),
|
||||||
),
|
),
|
||||||
|
// End-to-end encryption passphrase: closed lock while the last
|
||||||
|
// sync found no usable key, so nothing syncs until it is set.
|
||||||
|
ValueListenableBuilder<bool>(
|
||||||
|
valueListenable: syncLocked,
|
||||||
|
builder: (_, locked, _) => ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: E2ePassphraseButton(locked: locked),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// Legacy mirror: muted tint marks it as the secondary path.
|
||||||
ListTile(
|
ListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Advanced sync (GitHub)'),
|
leading: Icon(
|
||||||
subtitle: const Text('Cutover mirror — not recommended'),
|
Icons.code,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Advanced sync (GitHub)',
|
||||||
|
),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: () => unawaited(_openGitHubMirror()),
|
onTap: () => unawaited(_openGitHubMirror()),
|
||||||
),
|
),
|
||||||
@ -203,43 +220,32 @@ class _SettingsScreenState extends State<SettingsScreen>
|
|||||||
.dailyKcalGoal
|
.dailyKcalGoal
|
||||||
.toString(),
|
.toString(),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
|
||||||
const Divider(),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'Notifications',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
_isAndroid
|
|
||||||
? 'A background check nags you every ~15 min if a '
|
|
||||||
'meal slot is overdue. Aggressive OEM battery '
|
|
||||||
'optimization (MIUI, some Samsung configs) can '
|
|
||||||
'delay this well past 15 min -- request an '
|
|
||||||
'exemption for reliable nagging.'
|
|
||||||
: 'A check runs every 5 min while this window is open and '
|
|
||||||
'notifies you about an overdue meal slot. A browser '
|
|
||||||
'cannot run anything once the window is closed -- on '
|
|
||||||
'the PC the real backstop is the diet_guard gate, '
|
|
||||||
'which locks the screen instead.',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
|
||||||
// Battery-optimization exemption is Android-only, and
|
// Battery-optimization exemption is Android-only, and
|
||||||
// `permission_handler` has no web implementation at all;
|
// `permission_handler` has no web implementation at all;
|
||||||
// the row would throw rather than degrade in the browser.
|
// the row would throw rather than degrade in the browser.
|
||||||
if (_isAndroid) ...[
|
if (_isAndroid) ...[
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 24),
|
||||||
OutlinedButton.icon(
|
const Divider(),
|
||||||
onPressed: _requestBatteryExemption,
|
const SizedBox(height: 8),
|
||||||
icon: const Icon(Icons.battery_alert),
|
Align(
|
||||||
label: const Text('Disable battery optimization'),
|
alignment: Alignment.centerLeft,
|
||||||
|
child: IconButton.outlined(
|
||||||
|
onPressed: _requestBatteryExemption,
|
||||||
|
icon: const Icon(
|
||||||
|
Icons.battery_alert,
|
||||||
|
semanticLabel: 'Disable battery optimization',
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
if (_status != null) ...[
|
if (_status != null) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
|
Align(alignment: Alignment.centerLeft, child: _status),
|
||||||
],
|
],
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
const Divider(),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
const Align(alignment: Alignment.centerLeft, child: KuhyCredit()),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -22,13 +22,6 @@ export 'package:diet_guard_app/models/workout_session.dart';
|
|||||||
/// Formula names, in display order.
|
/// Formula names, in display order.
|
||||||
const List<String> activityFormulas = ['MET', 'ACSM', 'Per-km'];
|
const List<String> activityFormulas = ['MET', 'ACSM', 'Per-km'];
|
||||||
|
|
||||||
/// The methods explained, shown under the Activity card.
|
|
||||||
const String methodsNote =
|
|
||||||
'MET = standard activity values x your weight x time. '
|
|
||||||
'ACSM = American College of Sports Medicine running/walking equation '
|
|
||||||
'from your speed. Per-km = ~0.9 kcal per kg per km running, ~0.5 '
|
|
||||||
'walking. All are energy above resting.';
|
|
||||||
|
|
||||||
/// Measured activity averages at most the last two full weeks.
|
/// Measured activity averages at most the last two full weeks.
|
||||||
const int maxWindowDays = 14;
|
const int maxWindowDays = 14;
|
||||||
|
|
||||||
|
|||||||
@ -15,6 +15,7 @@ import 'package:diet_guard_app/services/github_client_factory.dart';
|
|||||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_attempt.dart';
|
||||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||||
import 'package:diet_guard_app/services/sync_health.dart';
|
import 'package:diet_guard_app/services/sync_health.dart';
|
||||||
import 'package:diet_guard_app/services/sync_service.dart';
|
import 'package:diet_guard_app/services/sync_service.dart';
|
||||||
@ -90,21 +91,14 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
|
|||||||
return true; // nothing to push; don't retry
|
return true; // nothing to push; don't retry
|
||||||
}
|
}
|
||||||
final client = createGitHubClient(settings, httpClient: httpClient);
|
final client = createGitHubClient(settings, httpClient: httpClient);
|
||||||
try {
|
// Never silent: attemptSync records the outcome, the only signal that a
|
||||||
await runSync(await syncBackend(client));
|
// background push failed. False -> WorkManager retries with backoff.
|
||||||
await SyncHealth.recordSuccess();
|
final landed = await attemptSync(() async {
|
||||||
return true;
|
try {
|
||||||
} on Exception catch (error, stackTrace) {
|
await runSync(await syncBackend(client));
|
||||||
// Never silent: this is the only signal that a background push failed.
|
} finally {
|
||||||
log(
|
client.close();
|
||||||
'diet_guard background sync failed',
|
}
|
||||||
level: 1000,
|
});
|
||||||
error: error,
|
return landed;
|
||||||
stackTrace: stackTrace,
|
|
||||||
);
|
|
||||||
await SyncHealth.recordFailure();
|
|
||||||
return false; // offline / transient error -> retry with backoff
|
|
||||||
} finally {
|
|
||||||
client.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -31,16 +31,6 @@ const List<(double, String)> _bmiBands = [
|
|||||||
];
|
];
|
||||||
const String _topBand = 'obese class III';
|
const String _topBand = 'obese class III';
|
||||||
|
|
||||||
/// BMI Prime explained, shown under the numbers on both surfaces.
|
|
||||||
const String bmiPrimeNote =
|
|
||||||
'BMI Prime = BMI / 25: 1.00 is the top of the healthy range, '
|
|
||||||
'so 1.02 means 2% above it.';
|
|
||||||
|
|
||||||
/// Trefethen's BMI explained, shown under the numbers on both surfaces.
|
|
||||||
const String trefethenNote =
|
|
||||||
"Trefethen's new BMI = 1.3 x kg / m^2.5: corrects classic BMI, which "
|
|
||||||
'over-reads tall people and under-reads short ones.';
|
|
||||||
|
|
||||||
/// The lean-mass formula the calorie table switches to with a body fat %.
|
/// The lean-mass formula the calorie table switches to with a body fat %.
|
||||||
const String katchMcArdle = 'Katch-McArdle';
|
const String katchMcArdle = 'Katch-McArdle';
|
||||||
|
|
||||||
|
|||||||
156
app/lib/services/claude_relay_client.dart
Normal file
156
app/lib/services/claude_relay_client.dart
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
/// The phone's side of the Claude relay: what the sparkle button sends and
|
||||||
|
/// what comes back.
|
||||||
|
///
|
||||||
|
/// The screen only talks to this interface; `claude_relay_firebase.dart` is the
|
||||||
|
/// real transport (Firebase RTDB, end-to-end encrypted) and
|
||||||
|
/// `claude_relay_fake.dart` the test double. The wire is
|
||||||
|
/// `docs/DOCS-claude-relay.md` plus `tests/fixtures/claude_relay_contract.json`.
|
||||||
|
///
|
||||||
|
/// A `Stream`, not a `Future`: the PC may be off, so a request can sit
|
||||||
|
/// [ClaudeRelayQueued] for hours before the same stream delivers
|
||||||
|
/// [ClaudeRelayLogged]. Terminal events end the stream; [ClaudeRelayQueued]
|
||||||
|
/// does not.
|
||||||
|
///
|
||||||
|
/// **The request id is a ULID** (`rtdb_relay` never serves another key shape)
|
||||||
|
/// and **the entry id is derived from it**: `uuid5(namespace, rid)`, computed
|
||||||
|
/// here by [claudeEntryId] exactly as the PC does. So the phone knows the id
|
||||||
|
/// of the entry before Claude has answered, a logged result is checked against
|
||||||
|
/// it, and undo is a tombstone on that id.
|
||||||
|
///
|
||||||
|
/// **Photos are transient input.** `photoJpeg` lives in memory for one send:
|
||||||
|
/// it is never stored on the phone, never put on a `FoodEntry`, and never part
|
||||||
|
/// of a synced meal record (`repo_invariants_photo_test.dart` enforces it).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:math';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// The UUID namespace the PC derives entry ids in (`entry_id_namespace` in the
|
||||||
|
/// contract fixture).
|
||||||
|
const claudeEntryNamespace = '5d9c1a40-6f0e-5c3e-9b57-d1e7a3c0b2f4';
|
||||||
|
|
||||||
|
/// The id of the entry the PC logs for request [requestId].
|
||||||
|
String claudeEntryId(String requestId) =>
|
||||||
|
const Uuid().v5(claudeEntryNamespace, requestId);
|
||||||
|
|
||||||
|
const _crockford = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
||||||
|
|
||||||
|
/// A fresh ULID: 48 bits of [now] in ms, then 80 random bits, 26 characters of
|
||||||
|
/// Crockford base32. [random] is injectable for tests.
|
||||||
|
String newRequestId({DateTime? now, Random? random}) {
|
||||||
|
final rng = random ?? Random.secure();
|
||||||
|
var ms = (now ?? DateTime.now()).millisecondsSinceEpoch;
|
||||||
|
final out = List<String>.filled(26, '0');
|
||||||
|
for (var i = 9; i >= 0; i--) {
|
||||||
|
out[i] = _crockford[ms % 32];
|
||||||
|
ms ~/= 32;
|
||||||
|
}
|
||||||
|
for (var i = 10; i < 26; i++) {
|
||||||
|
out[i] = _crockford[rng.nextInt(32)];
|
||||||
|
}
|
||||||
|
return out.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the PC picks the slot: the oldest due slot, or the nearest to
|
||||||
|
/// [ClaudeRelayRequest.slotMinute].
|
||||||
|
enum ClaudeRelayMode {
|
||||||
|
/// The phone is in due mode.
|
||||||
|
due,
|
||||||
|
|
||||||
|
/// Nothing is due.
|
||||||
|
normal,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One send: the text and/or photo, and the slot the meal belongs to.
|
||||||
|
class ClaudeRelayRequest {
|
||||||
|
/// Creates a request; at least one of [text] and [photoJpeg] is non-empty.
|
||||||
|
const ClaudeRelayRequest({
|
||||||
|
required this.requestId,
|
||||||
|
required this.slotMinute,
|
||||||
|
this.mode = ClaudeRelayMode.normal,
|
||||||
|
this.text = '',
|
||||||
|
this.photoJpeg,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// A ULID (see [newRequestId]); the entry id is [claudeEntryId] of it.
|
||||||
|
final String requestId;
|
||||||
|
|
||||||
|
/// The slot minute the phone would log against now (`client_slot_min`).
|
||||||
|
final int slotMinute;
|
||||||
|
|
||||||
|
/// Whether the phone is in due mode.
|
||||||
|
final ClaudeRelayMode mode;
|
||||||
|
|
||||||
|
/// What the user typed, trimmed; may be empty when a photo is attached.
|
||||||
|
final String text;
|
||||||
|
|
||||||
|
/// The photo as a JPEG of at most 1024 px, or null.
|
||||||
|
final Uint8List? photoJpeg;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the relay reports about one [ClaudeRelayRequest].
|
||||||
|
sealed class ClaudeRelayEvent {
|
||||||
|
const ClaudeRelayEvent();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The PC is offline; the request is stored and will run later (not terminal).
|
||||||
|
final class ClaudeRelayQueued extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayQueued();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claude logged the meal (terminal). `entry.id == claudeEntryId(rid)`.
|
||||||
|
final class ClaudeRelayLogged extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event for [entry].
|
||||||
|
const ClaudeRelayLogged(this.entry);
|
||||||
|
|
||||||
|
/// The entry the worker wrote.
|
||||||
|
final FoodEntry entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sync is locked (no passphrase), so nothing can be sent (terminal).
|
||||||
|
final class ClaudeRelayLocked extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayLocked();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The send failed (terminal); [reason] is for logs, never painted.
|
||||||
|
final class ClaudeRelayFailed extends ClaudeRelayEvent {
|
||||||
|
/// Creates the event.
|
||||||
|
const ClaudeRelayFailed(this.reason);
|
||||||
|
|
||||||
|
/// Why it failed.
|
||||||
|
final String reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends a meal to Claude through the relay.
|
||||||
|
abstract interface class ClaudeRelayClient {
|
||||||
|
/// Sends [request]; the stream carries zero or more [ClaudeRelayQueued]
|
||||||
|
/// then one terminal event, and never throws (failures are events).
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request);
|
||||||
|
|
||||||
|
/// Withdraws [requestId] if no worker has claimed it yet; true when it is
|
||||||
|
/// gone. False means it was already claimed (or the call failed), and the
|
||||||
|
/// meal will be logged: the stream keeps listening so the row still shows.
|
||||||
|
Future<bool> cancel(String requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stand-in until a transport is wired: every send fails closed.
|
||||||
|
class UnconfiguredClaudeRelayClient implements ClaudeRelayClient {
|
||||||
|
/// Creates the stand-in.
|
||||||
|
const UnconfiguredClaudeRelayClient();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) =>
|
||||||
|
Stream.value(const ClaudeRelayFailed('relay not configured'));
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> cancel(String requestId) async => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client the screen uses unless it is handed one; `main.dart` assigns the
|
||||||
|
/// real transport.
|
||||||
|
ClaudeRelayClient claudeRelay = const UnconfiguredClaudeRelayClient();
|
||||||
49
app/lib/services/claude_relay_fake.dart
Normal file
49
app/lib/services/claude_relay_fake.dart
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
/// A controllable [ClaudeRelayClient] for tests and the unwired app.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
|
||||||
|
/// Records every request and lets the test emit the events by hand.
|
||||||
|
///
|
||||||
|
/// [emit] pushes to the most recent send's stream; a terminal event closes it,
|
||||||
|
/// as a real client's would.
|
||||||
|
class FakeClaudeRelayClient implements ClaudeRelayClient {
|
||||||
|
/// Every request sent, oldest first.
|
||||||
|
final List<ClaudeRelayRequest> sent = [];
|
||||||
|
|
||||||
|
/// Events replayed on each send before the stream waits for [emit].
|
||||||
|
final List<ClaudeRelayEvent> script = [];
|
||||||
|
|
||||||
|
/// Request ids passed to [cancel], oldest first.
|
||||||
|
final List<String> cancelled = [];
|
||||||
|
|
||||||
|
/// What [cancel] answers: true = withdrawn before any claim.
|
||||||
|
bool cancelResult = true;
|
||||||
|
|
||||||
|
StreamController<ClaudeRelayEvent>? _open;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) {
|
||||||
|
sent.add(request);
|
||||||
|
final controller = StreamController<ClaudeRelayEvent>();
|
||||||
|
_open = controller;
|
||||||
|
script.forEach(emit);
|
||||||
|
return controller.stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivers [event] to the open stream; a terminal one closes it.
|
||||||
|
void emit(ClaudeRelayEvent event) {
|
||||||
|
final controller = _open;
|
||||||
|
if (controller == null || controller.isClosed) return;
|
||||||
|
controller.add(event);
|
||||||
|
if (event is! ClaudeRelayQueued) unawaited(controller.close());
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> cancel(String requestId) async {
|
||||||
|
cancelled.add(requestId);
|
||||||
|
return cancelResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
201
app/lib/services/claude_relay_firebase.dart
Normal file
201
app/lib/services/claude_relay_firebase.dart
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
/// The real [ClaudeRelayClient]: requests and answers through Firebase RTDB,
|
||||||
|
/// end-to-end encrypted, served by the PC's `claude-worker`.
|
||||||
|
///
|
||||||
|
/// One send: seal the request with the existing E2E key (header
|
||||||
|
/// `diet-guard-sync/e2e`, the key the log sync already uses), PUT it under
|
||||||
|
/// `requests/<ULID>/req`, then watch the node. No claim after
|
||||||
|
/// [claimWindow] means the PC is offline: [ClaudeRelayQueued], and the same
|
||||||
|
/// stream keeps waiting. The worker's sealed `result` becomes
|
||||||
|
/// [ClaudeRelayLogged] or [ClaudeRelayFailed], and the phone then deletes the
|
||||||
|
/// request node as `docs/DOCS-claude-relay.md` asks.
|
||||||
|
///
|
||||||
|
/// **Fail closed, visibly.** A locked key is [ClaudeRelayLocked]; a request
|
||||||
|
/// that breaks the contract, a transport that keeps failing, a result that
|
||||||
|
/// does not open or carries an entry id the phone did not derive, and a wait
|
||||||
|
/// past [maxWait] are all [ClaudeRelayFailed]. Nothing is ever shown as
|
||||||
|
/// logged unless a valid sealed result says so.
|
||||||
|
///
|
||||||
|
/// Polling, not a stream: the node's child keys (no values, so the photo is
|
||||||
|
/// never re-read) are listed every second, then every 5 s once the wait is
|
||||||
|
/// long. The phone is a foreground client here; a queued request that outlives
|
||||||
|
/// the screen reaches the log through the normal sync instead.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_rtdb.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_wire.dart';
|
||||||
|
import 'package:diet_guard_app/services/firebase_backend.dart';
|
||||||
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_e2e.dart';
|
||||||
|
|
||||||
|
const _fastPoll = Duration(seconds: 1);
|
||||||
|
const _slowPoll = Duration(seconds: 5);
|
||||||
|
const _slowAfter = Duration(seconds: 30);
|
||||||
|
const _maxPollFailures = 3;
|
||||||
|
|
||||||
|
/// [ClaudeRelayClient] over RTDB.
|
||||||
|
class RtdbClaudeRelay implements ClaudeRelayClient {
|
||||||
|
/// Creates the client; every dependency is injectable for tests.
|
||||||
|
RtdbClaudeRelay({
|
||||||
|
required this.openNodes,
|
||||||
|
required this.openCipher,
|
||||||
|
required this.deviceId,
|
||||||
|
DateTime Function()? now,
|
||||||
|
Future<void> Function(Duration)? delay,
|
||||||
|
this.claimWindow = const Duration(seconds: 3),
|
||||||
|
this.maxWait = const Duration(minutes: 15),
|
||||||
|
}) : _now = now ?? DateTime.now,
|
||||||
|
_delay = delay ?? Future<void>.delayed;
|
||||||
|
|
||||||
|
/// The app's real transport: Firebase session, E2E key from the keystore.
|
||||||
|
///
|
||||||
|
/// Everything resolves at send time, so building it in `main` costs nothing
|
||||||
|
/// and a device that signs in later just works.
|
||||||
|
factory RtdbClaudeRelay.firebase() {
|
||||||
|
FirebaseRestClient? client;
|
||||||
|
Future<FirebaseRestClient> session() async => client ??=
|
||||||
|
await openFirebase() ??
|
||||||
|
(throw const RelayTransportError('not signed in to Firebase'));
|
||||||
|
return RtdbClaudeRelay(
|
||||||
|
openNodes: () async {
|
||||||
|
final auth = (await session()).auth;
|
||||||
|
return RtdbNodes(
|
||||||
|
databaseUrl: kProject.databaseUrl,
|
||||||
|
idToken: auth.idToken,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
openCipher: () => session().then(openDietGuardCipher),
|
||||||
|
deviceId: () => currentSyncDeviceId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the node access, throwing [RelayTransportError] when unavailable.
|
||||||
|
final Future<RelayNodes> Function() openNodes;
|
||||||
|
|
||||||
|
/// Opens the E2E cipher, throwing [SyncLockedException] when locked.
|
||||||
|
final Future<E2eCipher> Function() openCipher;
|
||||||
|
|
||||||
|
/// This phone's sync device id, sent as `dev`.
|
||||||
|
final String Function() deviceId;
|
||||||
|
|
||||||
|
/// How long an unclaimed request waits before it reads as queued.
|
||||||
|
final Duration claimWindow;
|
||||||
|
|
||||||
|
/// How long one send waits for an answer before it fails.
|
||||||
|
final Duration maxWait;
|
||||||
|
|
||||||
|
final DateTime Function() _now;
|
||||||
|
final Future<void> Function(Duration) _delay;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<ClaudeRelayEvent> send(ClaudeRelayRequest request) async* {
|
||||||
|
final problem = relayBodyProblem(relayBody(request));
|
||||||
|
if (problem != null) {
|
||||||
|
yield ClaudeRelayFailed('bad request: $problem');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final RelayNodes nodes;
|
||||||
|
final E2eCipher cipher;
|
||||||
|
try {
|
||||||
|
cipher = await openCipher();
|
||||||
|
nodes = await openNodes();
|
||||||
|
final unit = await sealRequest(
|
||||||
|
cipher,
|
||||||
|
request,
|
||||||
|
device: deviceId(),
|
||||||
|
nowMs: _now().millisecondsSinceEpoch,
|
||||||
|
);
|
||||||
|
await nodes.put('${requestNode(request.requestId)}/req', unit);
|
||||||
|
} on SyncLockedException {
|
||||||
|
yield const ClaudeRelayLocked();
|
||||||
|
return;
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
log(
|
||||||
|
'claude relay send failed',
|
||||||
|
level: 1000,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
yield const ClaudeRelayFailed('could not send');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
yield* _await(nodes, cipher, request.requestId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Stream<ClaudeRelayEvent> _await(
|
||||||
|
RelayNodes nodes,
|
||||||
|
E2eCipher cipher,
|
||||||
|
String rid,
|
||||||
|
) async* {
|
||||||
|
final node = requestNode(rid);
|
||||||
|
final started = _now();
|
||||||
|
var queued = false;
|
||||||
|
var failures = 0;
|
||||||
|
while (true) {
|
||||||
|
final waited = _now().difference(started);
|
||||||
|
if (waited > maxWait) {
|
||||||
|
yield const ClaudeRelayFailed('no answer in time');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final keys = await nodes.keys(node);
|
||||||
|
failures = 0;
|
||||||
|
if (keys.contains('result')) {
|
||||||
|
final result = await openResult(
|
||||||
|
cipher,
|
||||||
|
rid,
|
||||||
|
await nodes.get('$node/result'),
|
||||||
|
);
|
||||||
|
await _tidy(nodes, node);
|
||||||
|
yield result;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (keys.isEmpty) {
|
||||||
|
yield const ClaudeRelayFailed('request vanished');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!queued && !keys.contains('claim') && waited >= claimWindow) {
|
||||||
|
queued = true;
|
||||||
|
yield const ClaudeRelayQueued();
|
||||||
|
}
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
log(
|
||||||
|
'claude relay poll failed',
|
||||||
|
level: 900,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
if (++failures >= _maxPollFailures) {
|
||||||
|
yield const ClaudeRelayFailed('connection lost');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await _delay(waited < _slowAfter ? _fastPoll : _slowPoll);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the answered request node. Best effort: the worker also sweeps
|
||||||
|
/// answered nodes after 24 h, so a failure costs nothing but a few bytes.
|
||||||
|
Future<void> _tidy(RelayNodes nodes, String node) async {
|
||||||
|
try {
|
||||||
|
await nodes.delete(node);
|
||||||
|
} on Object catch (error) {
|
||||||
|
log('claude relay cleanup failed', level: 900, error: error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> cancel(String requestId) async {
|
||||||
|
try {
|
||||||
|
return await (await openNodes()).deleteUnclaimed(requestNode(requestId));
|
||||||
|
} on Object catch (error) {
|
||||||
|
log('claude relay cancel failed', level: 900, error: error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
150
app/lib/services/claude_relay_rtdb.dart
Normal file
150
app/lib/services/claude_relay_rtdb.dart
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
/// Raw Realtime Database nodes for the relay, over REST.
|
||||||
|
///
|
||||||
|
/// The sync client (`FirebaseRestClient`) stores text blobs as string leaves;
|
||||||
|
/// the relay's units are JSON objects with a server-time sibling, so it needs
|
||||||
|
/// the node itself. Plain HTTPS like the sync client, so it works on Android
|
||||||
|
/// and in the browser-hosted desktop app alike.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
/// A relay call failed on the network or was refused. The message never holds
|
||||||
|
/// a URL: its query carries the ID token.
|
||||||
|
class RelayTransportError implements Exception {
|
||||||
|
/// Creates the error.
|
||||||
|
const RelayTransportError(this.message);
|
||||||
|
|
||||||
|
/// What went wrong, safe to log.
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'RelayTransportError: $message';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The four node operations the relay needs.
|
||||||
|
abstract interface class RelayNodes {
|
||||||
|
/// The JSON value at [path], or null when absent.
|
||||||
|
Future<Object?> get(String path);
|
||||||
|
|
||||||
|
/// The child keys of [path] (no values), empty when absent.
|
||||||
|
Future<Set<String>> keys(String path);
|
||||||
|
|
||||||
|
/// Replaces the node at [path] with [value].
|
||||||
|
Future<void> put(String path, Object value);
|
||||||
|
|
||||||
|
/// Deletes the node at [path].
|
||||||
|
Future<void> delete(String path);
|
||||||
|
|
||||||
|
/// Deletes [path] only while it holds neither a `claim` nor a `result`,
|
||||||
|
/// atomically: the delete carries the node's ETag, so a worker claiming it
|
||||||
|
/// in between turns the delete into a refusal. True when it is gone.
|
||||||
|
Future<bool> deleteUnclaimed(String path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [RelayNodes] over the Realtime Database REST API.
|
||||||
|
class RtdbNodes implements RelayNodes {
|
||||||
|
/// Creates the client; [idToken] mints the token each request carries.
|
||||||
|
RtdbNodes({
|
||||||
|
required String databaseUrl,
|
||||||
|
required this.idToken,
|
||||||
|
http.Client? client,
|
||||||
|
String namespace = '',
|
||||||
|
}) : _base = databaseUrl.endsWith('/')
|
||||||
|
? databaseUrl.substring(0, databaseUrl.length - 1)
|
||||||
|
: databaseUrl,
|
||||||
|
_prefix = namespace.isEmpty ? '' : '$namespace/',
|
||||||
|
_http = client ?? http.Client();
|
||||||
|
|
||||||
|
/// Supplies a fresh Firebase ID token.
|
||||||
|
final Future<String> Function() idToken;
|
||||||
|
|
||||||
|
final String _base;
|
||||||
|
final String _prefix;
|
||||||
|
final http.Client _http;
|
||||||
|
|
||||||
|
Future<Uri> _uri(String path, [Map<String, String> query = const {}]) async =>
|
||||||
|
Uri.parse(
|
||||||
|
'$_base/$_prefix$path.json',
|
||||||
|
).replace(queryParameters: {'auth': await idToken(), ...query});
|
||||||
|
|
||||||
|
Future<http.Response> _send(
|
||||||
|
String what,
|
||||||
|
Future<http.Response> Function(Uri uri) call,
|
||||||
|
String path, [
|
||||||
|
Map<String, String> query = const {},
|
||||||
|
]) async {
|
||||||
|
try {
|
||||||
|
return await call(await _uri(path, query));
|
||||||
|
} on http.ClientException catch (error) {
|
||||||
|
throw RelayTransportError('network error $what: ${error.message}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Never _refuse(String what, http.Response res) =>
|
||||||
|
throw RelayTransportError('$what refused: HTTP ${res.statusCode}');
|
||||||
|
|
||||||
|
bool _ok(http.Response res) => res.statusCode >= 200 && res.statusCode < 300;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Object?> get(String path) async {
|
||||||
|
final res = await _send('reading', _http.get, path);
|
||||||
|
if (!_ok(res)) _refuse('reading', res);
|
||||||
|
return jsonDecode(res.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Set<String>> keys(String path) async {
|
||||||
|
final res = await _send('listing', _http.get, path, {'shallow': 'true'});
|
||||||
|
if (!_ok(res)) _refuse('listing', res);
|
||||||
|
final decoded = jsonDecode(res.body);
|
||||||
|
return decoded is Map ? decoded.keys.cast<String>().toSet() : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> put(String path, Object value) async {
|
||||||
|
final res = await _send(
|
||||||
|
'writing',
|
||||||
|
(uri) => _http.put(uri, body: jsonEncode(value)),
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
if (!_ok(res)) _refuse('writing', res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> delete(String path) async {
|
||||||
|
final res = await _send('deleting', _http.delete, path);
|
||||||
|
if (!_ok(res)) _refuse('deleting', res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> deleteUnclaimed(String path) async {
|
||||||
|
// `X-Firebase-ETag` makes the read return the node's ETag; a claim or a
|
||||||
|
// result written afterwards changes it, and `if-match` then answers 412.
|
||||||
|
// A full read, not a shallow one: the ETag of a shallow answer is not
|
||||||
|
// guaranteed to cover the children, and this path is rare.
|
||||||
|
final read = await _send(
|
||||||
|
'reading',
|
||||||
|
(uri) => _http.get(uri, headers: {'X-Firebase-ETag': 'true'}),
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
if (!_ok(read)) _refuse('reading', read);
|
||||||
|
final node = jsonDecode(read.body);
|
||||||
|
if (node == null) return true;
|
||||||
|
if (node is Map &&
|
||||||
|
(node.containsKey('claim') || node.containsKey('result'))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final etag = read.headers['etag'];
|
||||||
|
if (etag == null) return false;
|
||||||
|
final res = await _send(
|
||||||
|
'deleting',
|
||||||
|
(uri) => _http.delete(uri, headers: {'if-match': etag}),
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
if (res.statusCode == 412) return false;
|
||||||
|
if (!_ok(res)) _refuse('deleting', res);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
144
app/lib/services/claude_relay_wire.dart
Normal file
144
app/lib/services/claude_relay_wire.dart
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
/// The relay's wire format: sealing a request, opening a result.
|
||||||
|
///
|
||||||
|
/// Mirrors `docs/DOCS-claude-relay.md` sections 1 to 3 and is gated by
|
||||||
|
/// `tests/fixtures/claude_relay_contract.json`. A unit is
|
||||||
|
/// `{"_e2e": <blob>, <clear siblings>}`; the blob is crdt_sync's [E2eCipher]
|
||||||
|
/// over compact JSON with the unit's full path as AAD, so a blob copied to
|
||||||
|
/// another path does not open. Both the request (photo included) and the
|
||||||
|
/// result are sealed: no food text or image is ever in clear.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/services/claude_relay_client.dart';
|
||||||
|
|
||||||
|
/// The relay's root `R`; its header is the existing `diet-guard-sync/e2e`.
|
||||||
|
const relayRoot = 'diet-guard-sync/claude-e2e';
|
||||||
|
|
||||||
|
/// Largest base64 photo the worker accepts, in characters.
|
||||||
|
const relayPhotoB64Max = 600000;
|
||||||
|
|
||||||
|
/// Longest description the worker accepts, in characters after trimming.
|
||||||
|
const relayTextMax = 2000;
|
||||||
|
|
||||||
|
/// The node of request [rid].
|
||||||
|
String requestNode(String rid) => '$relayRoot/requests/$rid';
|
||||||
|
|
||||||
|
/// Returns why [body] breaks the contract, or null when it is valid.
|
||||||
|
///
|
||||||
|
/// The same rules the worker enforces (`bad_request`), checked here first so a
|
||||||
|
/// request that can only fail never leaves the phone.
|
||||||
|
String? relayBodyProblem(Map<String, Object?> body) {
|
||||||
|
final text = body['text'];
|
||||||
|
final photo = body['photo_jpeg_b64'];
|
||||||
|
if (text == null && photo == null) return 'nothing to estimate';
|
||||||
|
if (text != null) {
|
||||||
|
if (text is! String) return 'text is not a string';
|
||||||
|
final length = text.trim().runes.length;
|
||||||
|
if (length < 1 || length > relayTextMax) return 'text length';
|
||||||
|
}
|
||||||
|
if (photo != null) {
|
||||||
|
if (photo is! String || photo.length > relayPhotoB64Max) {
|
||||||
|
return 'photo size';
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final bytes = base64.decode(photo);
|
||||||
|
if (bytes.length < 2 || bytes[0] != 0xFF || bytes[1] != 0xD8) {
|
||||||
|
return 'photo is not a jpeg';
|
||||||
|
}
|
||||||
|
} on FormatException {
|
||||||
|
return 'photo is not base64';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final slot = body['client_slot_min'];
|
||||||
|
if (slot is! int || slot < 0 || slot > 1439) return 'slot';
|
||||||
|
if (body['mode'] != 'due' && body['mode'] != 'normal') return 'mode';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The request's `body` object.
|
||||||
|
Map<String, Object?> relayBody(ClaudeRelayRequest request) => {
|
||||||
|
if (request.text.trim().isNotEmpty) 'text': request.text.trim(),
|
||||||
|
if (request.photoJpeg != null)
|
||||||
|
'photo_jpeg_b64': base64.encode(request.photoJpeg!),
|
||||||
|
'client_slot_min': request.slotMinute,
|
||||||
|
'mode': request.mode.name,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The sealed `req` unit for [request], ready to PUT.
|
||||||
|
///
|
||||||
|
/// `created` is the server's clock, not the phone's: it drives the worker's
|
||||||
|
/// 24 h expiry, and a phone clock can be wrong.
|
||||||
|
Future<Map<String, Object?>> sealRequest(
|
||||||
|
E2eCipher cipher,
|
||||||
|
ClaudeRelayRequest request, {
|
||||||
|
required String device,
|
||||||
|
required int nowMs,
|
||||||
|
}) async {
|
||||||
|
final plain = {
|
||||||
|
'kind': 'meal',
|
||||||
|
'dev': device,
|
||||||
|
'sent_at': nowMs,
|
||||||
|
'body': relayBody(request),
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
'_e2e': await cipher.seal(
|
||||||
|
jsonEncode(plain),
|
||||||
|
path: '${requestNode(request.requestId)}/req',
|
||||||
|
),
|
||||||
|
'created': {'.sv': 'timestamp'},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the `result` unit of [rid] into the event the screen shows.
|
||||||
|
///
|
||||||
|
/// Fail closed: anything that is not exactly a logged meal for this request,
|
||||||
|
/// with the entry id the phone derived itself, is a [ClaudeRelayFailed].
|
||||||
|
Future<ClaudeRelayEvent> openResult(
|
||||||
|
E2eCipher cipher,
|
||||||
|
String rid,
|
||||||
|
Object? node,
|
||||||
|
) async {
|
||||||
|
try {
|
||||||
|
if (node is! Map || node['_e2e'] is! String) {
|
||||||
|
return const ClaudeRelayFailed('result is not a sealed unit');
|
||||||
|
}
|
||||||
|
final plain =
|
||||||
|
jsonDecode(
|
||||||
|
await cipher.open(
|
||||||
|
node['_e2e'] as String,
|
||||||
|
path: '${requestNode(rid)}/result',
|
||||||
|
),
|
||||||
|
)
|
||||||
|
as Map<String, dynamic>;
|
||||||
|
if (plain['id'] != rid) return const ClaudeRelayFailed('result id');
|
||||||
|
if (plain['ok'] != true || plain['status'] != 'logged') {
|
||||||
|
return ClaudeRelayFailed('${plain['error_code'] ?? 'error'}');
|
||||||
|
}
|
||||||
|
if (plain['entry_id'] != claudeEntryId(rid)) {
|
||||||
|
return const ClaudeRelayFailed('entry id mismatch');
|
||||||
|
}
|
||||||
|
return ClaudeRelayLogged(
|
||||||
|
FoodEntry(
|
||||||
|
id: plain['entry_id'] as String,
|
||||||
|
time: plain['time'] as String,
|
||||||
|
desc: plain['desc'] as String,
|
||||||
|
grams: (plain['grams'] as num).toDouble(),
|
||||||
|
kcal: (plain['kcal'] as num).toDouble(),
|
||||||
|
proteinG: (plain['protein_g'] as num).toDouble(),
|
||||||
|
carbsG: (plain['carbs_g'] as num).toDouble(),
|
||||||
|
fatG: (plain['fat_g'] as num).toDouble(),
|
||||||
|
source: 'claude',
|
||||||
|
slotMinute: plain['slot_min'] as int?,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} on E2eDecryptError {
|
||||||
|
return const ClaudeRelayFailed('result did not open');
|
||||||
|
} on Object {
|
||||||
|
// A wrong type or a missing field in a result is a bad answer, not a
|
||||||
|
// crash; the meal is not shown as logged.
|
||||||
|
return const ClaudeRelayFailed('result is malformed');
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,10 +6,10 @@
|
|||||||
/// is never deleted or overwritten, each id is its own record, and two
|
/// is never deleted or overwritten, each id is its own record, and two
|
||||||
/// devices that mint a key at the same moment both keep both.
|
/// devices that mint a key at the same moment both keep both.
|
||||||
///
|
///
|
||||||
/// NOTE: the synced copy sits in Firebase RTDB in plaintext, so Firebase can
|
/// The synced copy is end-to-end encrypted under the shared crdt-sync
|
||||||
/// read these keys (and therefore the sealed login in any export it could get
|
/// passphrase (`sync_e2e.dart`), on `diet-guard-sync/devices-e2e`. The old
|
||||||
/// hold of) until crdt E2E lands. `export_keys` must move under that
|
/// plaintext `diet-guard-sync/devices/<id>/export_keys.json` nodes are
|
||||||
/// encryption too: `~/src/utils/TODO-crdt-e2e-encryption.md`.
|
/// copied over once and then neither read nor written by this app.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|||||||
@ -8,6 +8,7 @@ import 'package:diet_guard_app/services/export_keyring_sync.dart';
|
|||||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||||
import 'package:diet_guard_app/services/github_client_factory.dart';
|
import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_e2e.dart';
|
||||||
import 'package:diet_guard_app/services/sync_settings.dart';
|
import 'package:diet_guard_app/services/sync_settings.dart';
|
||||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||||
|
|
||||||
@ -31,7 +32,7 @@ Future<void> pullExportKeys() async {
|
|||||||
final client = createGitHubClient(await SyncSettings.load());
|
final client = createGitHubClient(await SyncSettings.load());
|
||||||
try {
|
try {
|
||||||
await syncExportKeys(
|
await syncExportKeys(
|
||||||
await syncBackend(client),
|
await openDietGuardStore(await syncBackend(client)),
|
||||||
keyring: defaultKeyring(),
|
keyring: defaultKeyring(),
|
||||||
devicesDir: syncDevicesDir,
|
devicesDir: syncDevicesDir,
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,8 +1,9 @@
|
|||||||
/// The `export_keys` document: the keyring as a crdt_sync log.
|
/// The `export_keys` document: the keyring as a crdt_sync log.
|
||||||
///
|
///
|
||||||
/// One record per key id, never deleted, so the merge is a plain union and
|
/// One record per key id, never deleted, so the merge is a plain union and
|
||||||
/// concurrent mints on two devices both survive. See `export_keyring.dart`
|
/// concurrent mints on two devices both survive. [syncExportKeys] must be
|
||||||
/// for the plaintext-at-Firebase caveat.
|
/// handed the end-to-end encrypted store (`sync_e2e.dart`): these are the
|
||||||
|
/// keys that open every export.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
@ -70,6 +71,7 @@ Future<void> syncExportKeys(
|
|||||||
deviceId: id,
|
deviceId: id,
|
||||||
legacyDeviceId: deviceId == null ? legacySyncDeviceId : null,
|
legacyDeviceId: deviceId == null ? legacySyncDeviceId : null,
|
||||||
pathPrefix: devicesDir,
|
pathPrefix: devicesDir,
|
||||||
|
revsPath: syncRevsDir,
|
||||||
localLog: _toLog(await keyring.all(), id),
|
localLog: _toLog(await keyring.all(), id),
|
||||||
encode: (log) => jsonEncode({
|
encode: (log) => jsonEncode({
|
||||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||||
|
|||||||
107
app/lib/services/kuchnia_autolog.dart
Normal file
107
app/lib/services/kuchnia_autolog.dart
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
/// Logs the delivered catering dishes of the due slots, without a tap.
|
||||||
|
///
|
||||||
|
/// kuhy overrode the old "delivered is not eaten, so never log unattended"
|
||||||
|
/// rule on 2026-11-17 ("LOG EVEN WITHOUT TAP"). The screen calls [logDue] when
|
||||||
|
/// it opens or resumes with a slot due; the plan is the fill-all plan
|
||||||
|
/// (`assignSlots` by the caterer's `mealPriority`, `fillPlan` over occupied
|
||||||
|
/// slots) minus the confirm tap, restricted to the due slots.
|
||||||
|
///
|
||||||
|
/// **Ids are deterministic** so a repeat open and every other device collapse
|
||||||
|
/// to one entry on merge: UUID v5 over the RFC 4122 URL namespace of
|
||||||
|
/// `kuchnia:<delivery date YYYY-MM-DD>:<dish key>`. The shared fixture
|
||||||
|
/// `tests/fixtures/kuchnia_autolog_ids.json` pins them for both languages.
|
||||||
|
/// An undone dish keeps its tombstone, so it is never logged a second time.
|
||||||
|
///
|
||||||
|
/// The fetch is a third-party login, so the day's dishes are cached in memory
|
||||||
|
/// and a failed or empty fetch is retried at most every [retryAfter].
|
||||||
|
/// `KuchniaQueueService.refreshOnce` cannot serve here: after the first clean
|
||||||
|
/// fetch of the day it returns nothing, and slots that fall due later would
|
||||||
|
/// never see their dish.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/models/kuchnia_dish.dart';
|
||||||
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_fill.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_import.dart';
|
||||||
|
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
import 'package:flutter/foundation.dart' show visibleForTesting;
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
/// The id of the entry that logs [dish] for [deliveryDate] (`YYYY-MM-DD`).
|
||||||
|
String kuchniaAutologId(String deliveryDate, KuchniaDish dish) => const Uuid()
|
||||||
|
.v5(Namespace.url.value, 'kuchnia:$deliveryDate:${dish.autologKey}');
|
||||||
|
|
||||||
|
/// Logs delivered dishes for due slots. One per process is plenty.
|
||||||
|
class KuchniaAutoLog {
|
||||||
|
/// Creates the service; every dependency is injectable for tests.
|
||||||
|
KuchniaAutoLog({
|
||||||
|
DeliveryFetch? fetch,
|
||||||
|
DateTime Function()? now,
|
||||||
|
this.retryAfter = const Duration(minutes: 10),
|
||||||
|
}) : _fetch = fetch ?? refreshDelivery,
|
||||||
|
_now = now ?? DateTime.now;
|
||||||
|
|
||||||
|
/// The process-wide instance the screen uses.
|
||||||
|
static KuchniaAutoLog instance = KuchniaAutoLog();
|
||||||
|
|
||||||
|
/// Minimum gap between fetches that found nothing or failed.
|
||||||
|
final Duration retryAfter;
|
||||||
|
|
||||||
|
final DeliveryFetch _fetch;
|
||||||
|
final DateTime Function() _now;
|
||||||
|
String? _cachedDay;
|
||||||
|
List<KuchniaDish> _cachedDishes = const [];
|
||||||
|
DateTime? _lastEmptyFetch;
|
||||||
|
Future<List<FoodEntry>>? _inFlight;
|
||||||
|
|
||||||
|
/// Forgets the cache, so the next call fetches again (tests, day change).
|
||||||
|
@visibleForTesting
|
||||||
|
void reset() {
|
||||||
|
_cachedDay = null;
|
||||||
|
_cachedDishes = const [];
|
||||||
|
_lastEmptyFetch = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs the dishes assigned to [dueSlots]; returns the entries it wrote.
|
||||||
|
///
|
||||||
|
/// Single-flight: a second call while one runs joins it, so an open and a
|
||||||
|
/// resume racing each other cannot interleave two read-modify-writes.
|
||||||
|
Future<List<FoodEntry>> logDue(List<int> dueSlots) =>
|
||||||
|
_inFlight ??= _run(dueSlots).whenComplete(() => _inFlight = null);
|
||||||
|
|
||||||
|
Future<List<FoodEntry>> _run(List<int> dueSlots) async {
|
||||||
|
if (dueSlots.isEmpty) return const [];
|
||||||
|
final today = _now();
|
||||||
|
final dayKey = localDateKey(today);
|
||||||
|
final dishes = await _dishesFor(today, dayKey);
|
||||||
|
if (dishes.isEmpty) return const [];
|
||||||
|
final store = LogStorageService.instance;
|
||||||
|
final slots = daySlots(MealScheduleService.history.forDay(dayKey));
|
||||||
|
final plan = fillPlan(
|
||||||
|
assignSlots(dishes, slots),
|
||||||
|
await loggedSlotsOn(store, today),
|
||||||
|
).where((item) => dueSlots.contains(item.slot)).toList();
|
||||||
|
String idFor(SlottedDish item) => kuchniaAutologId(dayKey, item.dish);
|
||||||
|
final written = await logDishes(plan, storage: store, idFor: idFor);
|
||||||
|
return [for (final item in written) ?await store.findEntry(idFor(item))];
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<List<KuchniaDish>> _dishesFor(DateTime today, String dayKey) async {
|
||||||
|
if (_cachedDay == dayKey) return _cachedDishes;
|
||||||
|
final last = _lastEmptyFetch;
|
||||||
|
if (last != null && _now().difference(last) < retryAfter) return const [];
|
||||||
|
final result = await _fetch(today);
|
||||||
|
if (result.ok && result.dishes.isNotEmpty) {
|
||||||
|
_cachedDay = dayKey;
|
||||||
|
return _cachedDishes = result.dishes;
|
||||||
|
}
|
||||||
|
_lastEmptyFetch = _now();
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,10 +3,12 @@
|
|||||||
/// The Dart mirror of `diet_guard/_kuchnia_log.py`'s `fill_plan` and
|
/// The Dart mirror of `diet_guard/_kuchnia_log.py`'s `fill_plan` and
|
||||||
/// `log_dishes`. KEEP IN SYNC, gated by the shared parity fixture.
|
/// `log_dishes`. KEEP IN SYNC, gated by the shared parity fixture.
|
||||||
///
|
///
|
||||||
/// **Nothing here runs without an explicit confirm tap.** A delivered meal is
|
/// **Delivered counts as eaten (override, 2026-11-17).** The old rule was "a
|
||||||
/// not an eaten meal: logging unattended would let the delivery note satisfy
|
/// delivered meal is not an eaten meal, so nothing logs without a confirm
|
||||||
/// the very checkpoints the gate exists to enforce. [logDishes] is only ever
|
/// tap". kuhy overrode it ("LOG EVEN WITHOUT TAP"): [logDishes] is now also
|
||||||
/// reached from the second tap of `FillAllFlow`.
|
/// reached unattended from `kuchnia_autolog.dart`, which logs the dishes of the
|
||||||
|
/// slots that are due when the app opens. Every such entry has a deterministic
|
||||||
|
/// id and shows an undo row, so a skipped or binned meal is one tap to remove.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_entry.dart';
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
@ -15,6 +17,7 @@ import 'package:diet_guard_app/models/local_time.dart';
|
|||||||
import 'package:diet_guard_app/models/nutrition.dart';
|
import 'package:diet_guard_app/models/nutrition.dart';
|
||||||
import 'package:diet_guard_app/models/slot.dart';
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
|
|
||||||
@ -98,25 +101,34 @@ Future<Set<int>> loggedSlotsOn(LogStorageService store, DateTime day) async {
|
|||||||
/// (a "Log for later" date, strictly after today) each dish is stamped at its
|
/// (a "Log for later" date, strictly after today) each dish is stamped at its
|
||||||
/// slot's time on that day; without it, now -- as a manual log is.
|
/// slot's time on that day; without it, now -- as a manual log is.
|
||||||
///
|
///
|
||||||
|
/// [idFor] gives each dish a deterministic entry id (see
|
||||||
|
/// `kuchniaAutologId`); a dish whose id is already in the log is skipped.
|
||||||
|
///
|
||||||
/// Returns the dishes actually written, in order.
|
/// Returns the dishes actually written, in order.
|
||||||
Future<List<SlottedDish>> logDishes(
|
Future<List<SlottedDish>> logDishes(
|
||||||
List<SlottedDish> chosen, {
|
List<SlottedDish> chosen, {
|
||||||
LogStorageService? storage,
|
LogStorageService? storage,
|
||||||
DateTime? day,
|
DateTime? day,
|
||||||
|
String Function(SlottedDish item)? idFor,
|
||||||
}) async {
|
}) async {
|
||||||
final store = storage ?? LogStorageService.instance;
|
final store = storage ?? LogStorageService.instance;
|
||||||
final seen = {
|
final seen = {
|
||||||
for (final entry in await dayEntries(store, day))
|
for (final entry in await dayEntries(store, day))
|
||||||
_dedupKey(entry.desc, entry.slotMinute),
|
_dedupKey(entry.desc, entry.slotMinute),
|
||||||
};
|
};
|
||||||
|
// Tombstones included: an undone auto-logged dish must stay undone.
|
||||||
|
final knownIds = idFor == null ? const <String>{} : await store.allEntryIds();
|
||||||
final written = <SlottedDish>[];
|
final written = <SlottedDish>[];
|
||||||
for (final item in chosen) {
|
for (final item in chosen) {
|
||||||
|
final id = idFor?.call(item);
|
||||||
|
if (id != null && knownIds.contains(id)) continue;
|
||||||
final key = _dedupKey(item.dish.name, item.slot);
|
final key = _dedupKey(item.dish.name, item.slot);
|
||||||
if (!seen.add(key)) continue;
|
if (!seen.add(key)) continue;
|
||||||
await store.logMeal(
|
await store.logMeal(
|
||||||
item.dish.name,
|
item.dish.name,
|
||||||
dishNutrition(item.dish),
|
dishNutrition(item.dish),
|
||||||
slotMinute: item.slot,
|
slotMinute: item.slot,
|
||||||
|
id: id,
|
||||||
when: day == null
|
when: day == null
|
||||||
? null
|
? null
|
||||||
: DateTime(
|
: DateTime(
|
||||||
|
|||||||
@ -4,12 +4,10 @@
|
|||||||
/// fail-closed boundary: every [KuchniaError] is turned into a reason string
|
/// fail-closed boundary: every [KuchniaError] is turned into a reason string
|
||||||
/// here, so no caller can be broken by a catering outage.
|
/// here, so no caller can be broken by a catering outage.
|
||||||
///
|
///
|
||||||
/// **Nothing is ever logged from here.** A delivered meal is not an eaten
|
/// **Nothing is logged from here: this only banks.** Dishes land in the
|
||||||
/// meal: dishes land in the *curated* bank and the user still taps to log
|
/// *curated* bank. Logging them is `kuchnia_autolog.dart`'s job, which kuhy
|
||||||
/// each one. If the import logged automatically, the gate would satisfy its
|
/// allowed without a tap on 2026-11-17 ("LOG EVEN WITHOUT TAP"; it was
|
||||||
/// own checkpoint from a delivery note, and the log would record what the
|
/// "delivered is not eaten" before), under deterministic ids with an undo.
|
||||||
/// courier dropped off rather than what was eaten -- skipped, shared and
|
|
||||||
/// binned meals included.
|
|
||||||
///
|
///
|
||||||
/// Imports go **only** to the curated bank. The derived bank is rebuilt from
|
/// Imports go **only** to the curated bank. The derived bank is rebuilt from
|
||||||
/// the log on every meal, so anything written there would vanish at the next
|
/// the log on every meal, so anything written there would vanish at the next
|
||||||
|
|||||||
@ -74,6 +74,15 @@ bool energyIsConsistent(double kcal, double protein, double carbs, double fat) {
|
|||||||
return (derived - kcal).abs() <= kuchniaEnergyTolerance * kcal;
|
return (derived - kcal).abs() <= kuchniaEnergyTolerance * kcal;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The panel's meal id as a string, or '' when absent or not a string/int.
|
||||||
|
///
|
||||||
|
/// A bool is not an id; Dart's `is int` already excludes it, matching Python.
|
||||||
|
String _mealId(Object? raw) {
|
||||||
|
if (raw is int) return raw.toString();
|
||||||
|
if (raw is String) return raw.trim();
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
/// Builds one dish, or null when the entry is unusable.
|
/// Builds one dish, or null when the entry is unusable.
|
||||||
///
|
///
|
||||||
/// [fallbackPriority] is the 1-based payload position, used when
|
/// [fallbackPriority] is the 1-based payload position, used when
|
||||||
@ -113,6 +122,7 @@ KuchniaDish? parseMeal(Object? meal, int fallbackPriority) {
|
|||||||
grams: grams,
|
grams: grams,
|
||||||
priority: priority,
|
priority: priority,
|
||||||
slotLabel: rawLabel is String ? rawLabel.trim() : '',
|
slotLabel: rawLabel is String ? rawLabel.trim() : '',
|
||||||
|
dishId: _mealId(meal['deliveryMealId']),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
/// The day's delivered dishes, offered to the log form one at a time.
|
/// The day's delivered dishes, offered to the log form one at a time.
|
||||||
///
|
///
|
||||||
/// **A delivered meal is not an eaten meal.** This queue only ever *prefills*
|
/// **Since 2026-11-17 the log screen no longer prefills from this queue**: a
|
||||||
/// the form; the user still taps to log each dish. Nothing here writes a log
|
/// delivered dish logs itself when its slot is due (`kuchnia_autolog.dart`;
|
||||||
/// entry, and nothing here may start doing so -- the gate would then satisfy
|
/// kuhy overrode "delivered is not eaten", "LOG EVEN WITHOUT TAP"). What
|
||||||
/// its own checkpoint from a delivery note, and the log would record what the
|
/// remains here is the offer/mark bookkeeping and the fetched-today marker.
|
||||||
/// courier dropped off rather than what was eaten.
|
/// The queue itself still writes no log entry.
|
||||||
///
|
///
|
||||||
/// Two things are load-bearing:
|
/// Two things are load-bearing:
|
||||||
///
|
///
|
||||||
|
|||||||
55
app/lib/services/log_entry_lookup.dart
Normal file
55
app/lib/services/log_entry_lookup.dart
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
/// Id lookups over the food log, tombstones included.
|
||||||
|
///
|
||||||
|
/// Split out of `log_storage_service.dart` for the repo's 250-line cap.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/food_entry.dart';
|
||||||
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||||
|
|
||||||
|
/// Returns the entry with [id] anywhere in [log], deleted or not, else null.
|
||||||
|
///
|
||||||
|
/// Tombstones count on purpose: an entry the user undid must keep blocking
|
||||||
|
/// its own id, or a repeat open would log it again.
|
||||||
|
FoodEntry? findEntryById(DayLog log, String id) {
|
||||||
|
for (final entries in log.values) {
|
||||||
|
for (final entry in entries) {
|
||||||
|
if (entry.id == id) return entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Id-keyed writes and reads on [LogStorageService].
|
||||||
|
extension LogEntryLookup on LogStorageService {
|
||||||
|
/// The entry with [id], deleted or not, else null.
|
||||||
|
Future<FoodEntry?> findEntry(String id) async =>
|
||||||
|
findEntryById(await readLog(), id);
|
||||||
|
|
||||||
|
/// Every id in the log, tombstones included.
|
||||||
|
Future<Set<String>> allEntryIds() async => {
|
||||||
|
for (final entries in (await readLog()).values)
|
||||||
|
for (final entry in entries) ?entry.id,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Adds [entry] unless one with its id exists (live or tombstoned), and
|
||||||
|
/// returns whichever copy the log holds.
|
||||||
|
///
|
||||||
|
/// For an entry another device wrote under an id chosen here, such as a
|
||||||
|
/// Claude-logged meal: the sync merge delivers the same record, so this only
|
||||||
|
/// shows it a tick earlier and can never double it.
|
||||||
|
Future<FoodEntry> addIfAbsent(FoodEntry entry) async {
|
||||||
|
final log = await readLog();
|
||||||
|
final id = entry.id;
|
||||||
|
if (id != null) {
|
||||||
|
final existing = findEntryById(log, id);
|
||||||
|
if (existing != null) return existing;
|
||||||
|
}
|
||||||
|
final dayKey = entry.time.length >= 10
|
||||||
|
? entry.time.substring(0, 10)
|
||||||
|
: localDateKey(DateTime.now());
|
||||||
|
log.putIfAbsent(dayKey, () => []).add(entry);
|
||||||
|
await writeLog(log);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -10,6 +10,7 @@ import 'package:diet_guard_app/models/nutrition.dart';
|
|||||||
import 'package:diet_guard_app/models/slot.dart';
|
import 'package:diet_guard_app/models/slot.dart';
|
||||||
import 'package:diet_guard_app/services/document_store.dart';
|
import 'package:diet_guard_app/services/document_store.dart';
|
||||||
import 'package:diet_guard_app/services/document_store_factory.dart';
|
import 'package:diet_guard_app/services/document_store_factory.dart';
|
||||||
|
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
@ -39,10 +40,8 @@ class LogStorageService {
|
|||||||
|
|
||||||
final DocumentStore _store;
|
final DocumentStore _store;
|
||||||
|
|
||||||
/// Initializes the singleton against the platform document store: files in
|
/// Initializes the singleton against the platform document store (files on
|
||||||
/// the app's documents directory on Android (phone-sandboxed; no
|
/// Android, IndexedDB in the browser-hosted desktop app).
|
||||||
/// external-storage permission needed), IndexedDB in the browser-hosted
|
|
||||||
/// desktop app.
|
|
||||||
static Future<LogStorageService> init() async {
|
static Future<LogStorageService> init() async {
|
||||||
if (_instance != null) return _instance!;
|
if (_instance != null) return _instance!;
|
||||||
final svc = LogStorageService._(await openDocumentStore());
|
final svc = LogStorageService._(await openDocumentStore());
|
||||||
@ -88,8 +87,7 @@ class LogStorageService {
|
|||||||
|
|
||||||
/// Persists the full log to the store, mirroring `_state._write_log`.
|
/// Persists the full log to the store, mirroring `_state._write_log`.
|
||||||
///
|
///
|
||||||
/// Atomicity against a concurrent reader is the store's job (see
|
/// Atomicity against a concurrent reader is the store's job.
|
||||||
/// `FileDocumentStore.write`'s temp-file-and-rename), not this method's.
|
|
||||||
Future<void> writeLog(DayLog log) async {
|
Future<void> writeLog(DayLog log) async {
|
||||||
final encoded = <String, Object?>{
|
final encoded = <String, Object?>{
|
||||||
for (final mapEntry in log.entries)
|
for (final mapEntry in log.entries)
|
||||||
@ -98,27 +96,34 @@ class LogStorageService {
|
|||||||
await _store.write(documentName, jsonEncode(encoded));
|
await _store.write(documentName, jsonEncode(encoded));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Appends a signed-on-PC-eventually entry for [desc] to [when]'s day (or
|
/// Appends an entry for [desc] to [when]'s day (today's when null).
|
||||||
/// today's, when [when] is null).
|
|
||||||
///
|
///
|
||||||
/// Mirrors `_state.log_meal`: always assigns a fresh `id`, never computes
|
/// Mirrors `_state.log_meal`: never computes an `hmac` (the phone never
|
||||||
/// an `hmac` (the phone never holds the shared key -- the PC re-signs on
|
/// holds the key; the PC re-signs on merge). [when] pre-logs a future
|
||||||
/// merge, see Milestone 3). [when] lets a caller pre-log a meal against a
|
/// date/slot and must not be in the past. [slotMinute] is a minute of day
|
||||||
/// future date/slot; must not be in the past. [slotMinute] is the slot's
|
/// (`slotForLog`'s result), never an hour.
|
||||||
/// minute of day (`slotForLog`'s result), never an hour.
|
///
|
||||||
|
/// A caller-chosen [id] makes the write idempotent: an entry already
|
||||||
|
/// carrying it (live or tombstoned) is returned and nothing is written.
|
||||||
Future<FoodEntry> logMeal(
|
Future<FoodEntry> logMeal(
|
||||||
String desc,
|
String desc,
|
||||||
Nutrition nutrition, {
|
Nutrition nutrition, {
|
||||||
int? slotMinute,
|
int? slotMinute,
|
||||||
List<MealComponent>? components,
|
List<MealComponent>? components,
|
||||||
DateTime? when,
|
DateTime? when,
|
||||||
|
String? id,
|
||||||
}) async {
|
}) async {
|
||||||
if (when != null && when.isBefore(DateTime.now())) {
|
if (when != null && when.isBefore(DateTime.now())) {
|
||||||
throw ArgumentError.value(when, 'when', 'cannot log a meal in the past');
|
throw ArgumentError.value(when, 'when', 'cannot log a meal in the past');
|
||||||
}
|
}
|
||||||
final now = when ?? DateTime.now();
|
final now = when ?? DateTime.now();
|
||||||
|
final log = await readLog();
|
||||||
|
if (id != null) {
|
||||||
|
final existing = findEntryById(log, id);
|
||||||
|
if (existing != null) return existing;
|
||||||
|
}
|
||||||
final entry = FoodEntry(
|
final entry = FoodEntry(
|
||||||
id: const Uuid().v4(),
|
id: id ?? const Uuid().v4(),
|
||||||
time: isoLocalSeconds(now),
|
time: isoLocalSeconds(now),
|
||||||
desc: desc,
|
desc: desc,
|
||||||
grams: nutrition.grams,
|
grams: nutrition.grams,
|
||||||
@ -130,7 +135,6 @@ class LogStorageService {
|
|||||||
slotMinute: slotMinute,
|
slotMinute: slotMinute,
|
||||||
components: components,
|
components: components,
|
||||||
);
|
);
|
||||||
final log = await readLog();
|
|
||||||
log.putIfAbsent(localDateKey(now), () => []).add(entry);
|
log.putIfAbsent(localDateKey(now), () => []).add(entry);
|
||||||
await writeLog(log);
|
await writeLog(log);
|
||||||
return entry;
|
return entry;
|
||||||
@ -165,9 +169,6 @@ class LogStorageService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns every non-tombstoned entry across all days, newest first.
|
/// Returns every non-tombstoned entry across all days, newest first.
|
||||||
///
|
|
||||||
/// Backs the history screen -- the only place that needs to see more than
|
|
||||||
/// "today".
|
|
||||||
Future<List<FoodEntry>> allEntriesNewestFirst() async {
|
Future<List<FoodEntry>> allEntriesNewestFirst() async {
|
||||||
final log = await readLog();
|
final log = await readLog();
|
||||||
final entries =
|
final entries =
|
||||||
@ -183,7 +184,7 @@ class LogStorageService {
|
|||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns today's total calories, mirrors `_state.today_total_kcal`.
|
/// Today's total calories, mirrors `_state.today_total_kcal`.
|
||||||
Future<double> todayTotalKcal() async {
|
Future<double> todayTotalKcal() async {
|
||||||
final entries = await todayEntries();
|
final entries = await todayEntries();
|
||||||
var total = 0.0;
|
var total = 0.0;
|
||||||
|
|||||||
8
app/lib/services/meal_photo_cleanup.dart
Normal file
8
app/lib/services/meal_photo_cleanup.dart
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
/// Deletes the cache file `image_picker` leaves behind.
|
||||||
|
///
|
||||||
|
/// `dart:io` stays behind the platform seam (see `repo_invariants_test.dart`):
|
||||||
|
/// the io half deletes, the web half has no file to delete.
|
||||||
|
library;
|
||||||
|
|
||||||
|
export 'meal_photo_cleanup_io.dart'
|
||||||
|
if (dart.library.js_interop) 'meal_photo_cleanup_web.dart';
|
||||||
11
app/lib/services/meal_photo_cleanup_io.dart
Normal file
11
app/lib/services/meal_photo_cleanup_io.dart
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// Deletes the picked file at [path]; a failure is not worth a crash.
|
||||||
|
Future<void> discardPickedFile(String path) async {
|
||||||
|
try {
|
||||||
|
await File(path).delete();
|
||||||
|
} on FileSystemException {
|
||||||
|
// Already gone, or not ours to delete: the bytes were read, which is all
|
||||||
|
// that mattered.
|
||||||
|
}
|
||||||
|
}
|
||||||
2
app/lib/services/meal_photo_cleanup_web.dart
Normal file
2
app/lib/services/meal_photo_cleanup_web.dart
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/// Web has no cache file: the picker returns an in-memory blob.
|
||||||
|
Future<void> discardPickedFile(String path) async {}
|
||||||
76
app/lib/services/meal_photo_source.dart
Normal file
76
app/lib/services/meal_photo_source.dart
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
/// Where a meal photo comes from. A photo is transient input to Claude: the
|
||||||
|
/// bytes live in memory for one send and are never stored, put on a
|
||||||
|
/// `FoodEntry` or synced.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/meal_photo_cleanup.dart';
|
||||||
|
import 'package:flutter/foundation.dart' show kIsWeb, visibleForTesting;
|
||||||
|
import 'package:image_picker/image_picker.dart';
|
||||||
|
import 'package:permission_handler/permission_handler.dart';
|
||||||
|
|
||||||
|
/// Which picker the user asked for.
|
||||||
|
enum PhotoOrigin {
|
||||||
|
/// Take a new photo (a tap on the photo button).
|
||||||
|
camera,
|
||||||
|
|
||||||
|
/// Choose an existing one (a long press).
|
||||||
|
gallery,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands back a photo as JPEG bytes, or null when the user backed out.
|
||||||
|
abstract interface class MealPhotoSource {
|
||||||
|
/// Picks one photo from [origin].
|
||||||
|
Future<Uint8List?> pick(PhotoOrigin origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The longest edge the photo is scaled to before it leaves the phone.
|
||||||
|
const mealPhotoMaxEdge = 1024.0;
|
||||||
|
|
||||||
|
/// [MealPhotoSource] on `image_picker`.
|
||||||
|
class ImagePickerPhotoSource implements MealPhotoSource {
|
||||||
|
/// Creates the source; the three seams default to the real plugins.
|
||||||
|
ImagePickerPhotoSource({
|
||||||
|
@visibleForTesting Future<XFile?> Function(ImageSource source)? pickFile,
|
||||||
|
@visibleForTesting Future<bool> Function()? requestCamera,
|
||||||
|
@visibleForTesting Future<void> Function(String path)? discard,
|
||||||
|
}) : _pickFile = pickFile ?? _pickWithPlugin,
|
||||||
|
_requestCamera = requestCamera ?? _requestCameraPermission,
|
||||||
|
_discard = discard ?? discardPickedFile;
|
||||||
|
|
||||||
|
final Future<XFile?> Function(ImageSource source) _pickFile;
|
||||||
|
final Future<bool> Function() _requestCamera;
|
||||||
|
final Future<void> Function(String path) _discard;
|
||||||
|
|
||||||
|
static Future<XFile?> _pickWithPlugin(ImageSource source) =>
|
||||||
|
ImagePicker().pickImage(
|
||||||
|
source: source,
|
||||||
|
maxWidth: mealPhotoMaxEdge,
|
||||||
|
maxHeight: mealPhotoMaxEdge,
|
||||||
|
imageQuality: 85,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// `permission_handler` has no web implementation; the browser asks for
|
||||||
|
/// the camera itself when the picker opens.
|
||||||
|
static Future<bool> _requestCameraPermission() async {
|
||||||
|
if (kIsWeb) return true;
|
||||||
|
return (await Permission.camera.request()).isGranted;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Uint8List?> pick(PhotoOrigin origin) async {
|
||||||
|
// The runtime permission comes first: launching the camera intent without
|
||||||
|
// it fails on Android, and the failure names nothing.
|
||||||
|
if (origin == PhotoOrigin.camera && !await _requestCamera()) return null;
|
||||||
|
final file = await _pickFile(
|
||||||
|
origin == PhotoOrigin.camera ? ImageSource.camera : ImageSource.gallery,
|
||||||
|
);
|
||||||
|
if (file == null) return null;
|
||||||
|
final bytes = await file.readAsBytes();
|
||||||
|
// The plugin leaves the scaled JPEG in the app cache; the bytes are all
|
||||||
|
// that is needed, so the file goes the moment they are read.
|
||||||
|
await _discard(file.path);
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -20,8 +20,9 @@ abstract class NotificationBackend {
|
|||||||
/// of the app.
|
/// of the app.
|
||||||
Future<bool?> requestPermission();
|
Future<bool?> requestPermission();
|
||||||
|
|
||||||
/// Posts (or replaces) the notification for [slot].
|
/// Posts (or replaces) the notification for [slot], titled with the slot's
|
||||||
Future<void> show(int slot, String title, String body);
|
/// clock time and carrying no body text.
|
||||||
|
Future<void> show(int slot, String title);
|
||||||
|
|
||||||
/// Removes the notification for [slot], if one is showing.
|
/// Removes the notification for [slot], if one is showing.
|
||||||
Future<void> cancel(int slot);
|
Future<void> cancel(int slot);
|
||||||
|
|||||||
@ -15,7 +15,8 @@ class LocalNotificationsBackend implements NotificationBackend {
|
|||||||
final FlutterLocalNotificationsPlugin plugin;
|
final FlutterLocalNotificationsPlugin plugin;
|
||||||
|
|
||||||
static const _channelId = 'diet_guard_due_slot';
|
static const _channelId = 'diet_guard_due_slot';
|
||||||
static const _channelName = 'Meal reminders';
|
// The app's proper name, same as the launcher label (no descriptive text).
|
||||||
|
static const _channelName = 'DietGuard';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> initialize() async {
|
Future<void> initialize() async {
|
||||||
@ -23,6 +24,20 @@ class LocalNotificationsBackend implements NotificationBackend {
|
|||||||
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
|
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
|
||||||
);
|
);
|
||||||
await plugin.initialize(settings: settings);
|
await plugin.initialize(settings: settings);
|
||||||
|
|
||||||
|
// Re-create the channel so Android renames it if an install still shows
|
||||||
|
// the old "Meal reminders" label.
|
||||||
|
await plugin
|
||||||
|
.resolvePlatformSpecificImplementation<
|
||||||
|
AndroidFlutterLocalNotificationsPlugin
|
||||||
|
>()
|
||||||
|
?.createNotificationChannel(
|
||||||
|
const AndroidNotificationChannel(
|
||||||
|
_channelId,
|
||||||
|
_channelName,
|
||||||
|
importance: Importance.high,
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Requests Android 13+'s runtime `POST_NOTIFICATIONS` permission.
|
/// Requests Android 13+'s runtime `POST_NOTIFICATIONS` permission.
|
||||||
@ -47,7 +62,7 @@ class LocalNotificationsBackend implements NotificationBackend {
|
|||||||
Future.value();
|
Future.value();
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> show(int slot, String title, String body) async {
|
Future<void> show(int slot, String title) async {
|
||||||
const details = NotificationDetails(
|
const details = NotificationDetails(
|
||||||
android: AndroidNotificationDetails(
|
android: AndroidNotificationDetails(
|
||||||
_channelId,
|
_channelId,
|
||||||
@ -56,12 +71,7 @@ class LocalNotificationsBackend implements NotificationBackend {
|
|||||||
priority: Priority.high,
|
priority: Priority.high,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
await plugin.show(
|
await plugin.show(id: slot, title: title, notificationDetails: details);
|
||||||
id: slot,
|
|
||||||
title: title,
|
|
||||||
body: body,
|
|
||||||
notificationDetails: details,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
|
|||||||
@ -36,13 +36,13 @@ class WebNotificationBackend implements NotificationBackend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> show(int slot, String title, String body) async {
|
Future<void> show(int slot, String title) async {
|
||||||
// Posting without permission throws; a silent no-op matches this
|
// Posting without permission throws; a silent no-op matches this
|
||||||
// service's degrade-quietly stance everywhere else.
|
// service's degrade-quietly stance everywhere else.
|
||||||
if (!_granted) return;
|
if (!_granted) return;
|
||||||
_shown[slot] = web.Notification(
|
_shown[slot] = web.Notification(
|
||||||
title,
|
title,
|
||||||
web.NotificationOptions(body: body, tag: 'diet_guard_slot_$slot'),
|
web.NotificationOptions(tag: 'diet_guard_slot_$slot'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -86,11 +86,9 @@ class NotificationService {
|
|||||||
await _backend.cancel(id);
|
await _backend.cancel(id);
|
||||||
}
|
}
|
||||||
for (final slot in due) {
|
for (final slot in due) {
|
||||||
await _backend.show(
|
// The title is only the overdue slot's clock time (a number from the
|
||||||
slot,
|
// user's own schedule); the launcher icon is the second channel.
|
||||||
'Meal not logged',
|
await _backend.show(slot, slotLabel(slot));
|
||||||
"You haven't logged your ${slotLabel(slot)} meal yet.",
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
42
app/lib/services/sync_attempt.dart
Normal file
42
app/lib/services/sync_attempt.dart
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
/// Runs one sync and records its outcome for the "not syncing" banner.
|
||||||
|
///
|
||||||
|
/// The banner said "Not syncing" on a phone whose sync looked fine, and the
|
||||||
|
/// release build keeps no log that could say why (see `sync_health.dart`).
|
||||||
|
/// So a failure here also goes to the board through the app-wide reporter:
|
||||||
|
/// the next one files its own ticket with the exception that caused it.
|
||||||
|
/// Inside a WorkManager isolate no reporter is installed, so a background
|
||||||
|
/// failure is only recorded, not filed.
|
||||||
|
///
|
||||||
|
/// Only the sync itself is timed in: screen refreshes after a landed sync
|
||||||
|
/// run outside, so their errors never mark a working sync as failed.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart' show AppErrors;
|
||||||
|
import 'package:diet_guard_app/services/sync_health.dart';
|
||||||
|
|
||||||
|
/// Runs [sync]; records success, or failure plus a `sync.failed` report.
|
||||||
|
///
|
||||||
|
/// Returns whether the sync landed. Never throws.
|
||||||
|
Future<bool> attemptSync(Future<void> Function() sync) async {
|
||||||
|
try {
|
||||||
|
await sync();
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
log(
|
||||||
|
'diet_guard sync failed',
|
||||||
|
level: 1000,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
AppErrors.instance?.reporter.report(
|
||||||
|
'sync.failed',
|
||||||
|
error,
|
||||||
|
stack: stackTrace,
|
||||||
|
);
|
||||||
|
await SyncHealth.recordFailure();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
await SyncHealth.recordSuccess();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@ -14,16 +14,24 @@ import 'package:diet_guard_app/services/wake_alarm_weights.dart';
|
|||||||
|
|
||||||
/// Runs the Body sync against [client], under [devicesDir].
|
/// Runs the Body sync against [client], under [devicesDir].
|
||||||
///
|
///
|
||||||
|
/// [wakeAlarm] is wake-alarm's own encrypted store; null (locked, or not
|
||||||
|
/// opened) skips the weigh-in ingest and nothing else.
|
||||||
|
///
|
||||||
/// No-ops when [BodyService] is uninitialised (a widget test, or an isolate
|
/// No-ops when [BodyService] is uninitialised (a widget test, or an isolate
|
||||||
/// that never loaded it), so it can neither publish nor clobber anything.
|
/// that never loaded it), so it can neither publish nor clobber anything.
|
||||||
Future<void> syncBody(RemoteStore client, {required String devicesDir}) async {
|
Future<void> syncBody(
|
||||||
|
RemoteStore client, {
|
||||||
|
required String devicesDir,
|
||||||
|
RemoteStore? wakeAlarm,
|
||||||
|
}) async {
|
||||||
if (!BodyService.isInitialized) return;
|
if (!BodyService.isInitialized) return;
|
||||||
await ingestWakeAlarmWeights(client);
|
if (wakeAlarm != null) await ingestWakeAlarmWeights(wakeAlarm);
|
||||||
final merged = await syncLog(
|
final merged = await syncLog(
|
||||||
client: client,
|
client: client,
|
||||||
deviceId: currentSyncDeviceId,
|
deviceId: currentSyncDeviceId,
|
||||||
legacyDeviceId: legacySyncDeviceId,
|
legacyDeviceId: legacySyncDeviceId,
|
||||||
pathPrefix: devicesDir,
|
pathPrefix: devicesDir,
|
||||||
|
revsPath: syncRevsDir,
|
||||||
localLog: bodyToLog(BodyService.instance.document),
|
localLog: bodyToLog(BodyService.instance.document),
|
||||||
encode: encodeBodyForPush,
|
encode: encodeBodyForPush,
|
||||||
decode: parseRemoteBody,
|
decode: parseRemoteBody,
|
||||||
|
|||||||
@ -5,8 +5,14 @@ import 'package:diet_guard_app/services/github_client_factory.dart';
|
|||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'package:uuid/uuid.dart';
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
/// Where every device's synced files live on the remote.
|
/// Where every device's synced files live on the remote: the end-to-end
|
||||||
const syncDevicesDir = 'diet-guard-sync/devices';
|
/// encrypted twin of the old plaintext `diet-guard-sync/devices` (see
|
||||||
|
/// `sync_e2e.dart`; `E2eLayout.of` derives the same names).
|
||||||
|
const syncDevicesDir = 'diet-guard-sync/devices-e2e';
|
||||||
|
|
||||||
|
/// Where peers publish their (keyed) revisions, apart from the old
|
||||||
|
/// plaintext `diet-guard-sync/revs` the E2E copy fingerprints.
|
||||||
|
const syncRevsDir = 'diet-guard-sync/revs-e2e';
|
||||||
|
|
||||||
/// SharedPreferences key holding this install's device id.
|
/// SharedPreferences key holding this install's device id.
|
||||||
///
|
///
|
||||||
|
|||||||
102
app/lib/services/sync_e2e.dart
Normal file
102
app/lib/services/sync_e2e.dart
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
/// End-to-end encryption of everything this app syncs.
|
||||||
|
///
|
||||||
|
/// Every blob under `diet-guard-sync/devices-e2e` (food log, banks, budget,
|
||||||
|
/// catering credential, Body, export keyring) is sealed with a key derived
|
||||||
|
/// from the shared crdt-sync passphrase kept in the OS keystore; Firebase and
|
||||||
|
/// the GitHub mirror only see record ids, tombstones and clocks. The
|
||||||
|
/// wake-alarm weigh-ins live on their own prefix with their own header, so
|
||||||
|
/// they get a second store over the same backend.
|
||||||
|
///
|
||||||
|
/// Fail closed: without a usable key nothing is pulled or pushed. The old
|
||||||
|
/// plaintext `diet-guard-sync/devices` is copied over on open (picking up
|
||||||
|
/// writes from builds not yet migrated) and never written or deleted here.
|
||||||
|
/// Mirrors `diet_guard/_sync_e2e.py`.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
|
||||||
|
show openEncryptedStoreFromKeystore;
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
/// The plaintext prefix every pre-E2E build wrote; only the copy reads it.
|
||||||
|
const legacyDevicesDir = 'diet-guard-sync/devices';
|
||||||
|
|
||||||
|
/// Where the wake-alarm app published before E2E.
|
||||||
|
const legacyWakeAlarmDir = 'wake-alarm-sync/devices';
|
||||||
|
|
||||||
|
/// Argon2id cost for a header this device creates; only tests lower it.
|
||||||
|
@visibleForTesting
|
||||||
|
Argon2Params e2eArgon2Params = Argon2Params.recommended;
|
||||||
|
|
||||||
|
/// Whether the last open found no usable key, for the lock button.
|
||||||
|
final ValueNotifier<bool> syncLocked = ValueNotifier<bool>(false);
|
||||||
|
|
||||||
|
/// Thrown instead of syncing when end-to-end encryption has no usable key.
|
||||||
|
class SyncLockedException implements Exception {
|
||||||
|
/// Creates the exception for [reason].
|
||||||
|
const SyncLockedException(this.reason);
|
||||||
|
|
||||||
|
/// Why the store is locked.
|
||||||
|
final E2eLockReason reason;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'sync locked (${reason.name})';
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<E2eState> _open(RemoteStore backend, String oldPrefix) =>
|
||||||
|
openEncryptedStoreFromKeystore(
|
||||||
|
store: backend,
|
||||||
|
oldPrefix: oldPrefix,
|
||||||
|
params: e2eArgon2Params,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// The encrypted diet_guard store over [backend], the outermost store.
|
||||||
|
///
|
||||||
|
/// Throws [SyncLockedException] when locked, so no caller can fall through
|
||||||
|
/// to a plaintext sync.
|
||||||
|
Future<RemoteStore> openDietGuardStore(RemoteStore backend) async {
|
||||||
|
final state = await _open(backend, legacyDevicesDir);
|
||||||
|
syncLocked.value = state is! E2eReady;
|
||||||
|
if (state is E2eReady) return state.store;
|
||||||
|
throw SyncLockedException(
|
||||||
|
state is E2eLocked ? state.reason : E2eLockReason.badHeader,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cipher of the diet_guard E2E key, for units outside the log sync (the
|
||||||
|
/// Claude relay seals its requests with it).
|
||||||
|
///
|
||||||
|
/// Throws [SyncLockedException] when there is no usable key, same as
|
||||||
|
/// [openDietGuardStore]. The relay lives under `diet-guard-sync/claude-e2e`,
|
||||||
|
/// whose header path is the existing `diet-guard-sync/e2e`: one passphrase,
|
||||||
|
/// one salt, one key.
|
||||||
|
Future<E2eCipher> openDietGuardCipher(RemoteStore backend) async {
|
||||||
|
final state = await _open(backend, legacyDevicesDir);
|
||||||
|
syncLocked.value = state is! E2eReady;
|
||||||
|
if (state is E2eReady) return state.store.key.cipher(acceptPlaintext: false);
|
||||||
|
throw SyncLockedException(
|
||||||
|
state is E2eLocked ? state.reason : E2eLockReason.badHeader,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The encrypted wake-alarm store over [backend], or null when locked or
|
||||||
|
/// unreachable.
|
||||||
|
///
|
||||||
|
/// Its weigh-ins are optional input to the diet sync, so nothing here may
|
||||||
|
/// fail the tick: a lock or a transport error skips only the ingest.
|
||||||
|
Future<RemoteStore?> openWakeAlarmStore(RemoteStore backend) async {
|
||||||
|
try {
|
||||||
|
final state = await _open(backend, legacyWakeAlarmDir);
|
||||||
|
return state is E2eReady ? state.store : null;
|
||||||
|
} on Object catch (error, stackTrace) {
|
||||||
|
log(
|
||||||
|
'wake-alarm store unavailable; skipping weigh-ins',
|
||||||
|
level: 900,
|
||||||
|
error: error,
|
||||||
|
stackTrace: stackTrace,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -53,8 +53,7 @@ abstract final class SyncHealth {
|
|||||||
_recordFailure(SyncFailureKind.unconfigured);
|
_recordFailure(SyncFailureKind.unconfigured);
|
||||||
|
|
||||||
/// Marks a tick that had a backend but failed to publish.
|
/// Marks a tick that had a backend but failed to publish.
|
||||||
static Future<void> recordFailure() =>
|
static Future<void> recordFailure() => _recordFailure(SyncFailureKind.failed);
|
||||||
_recordFailure(SyncFailureKind.failed);
|
|
||||||
|
|
||||||
static Future<void> _recordFailure(SyncFailureKind kind) =>
|
static Future<void> _recordFailure(SyncFailureKind kind) =>
|
||||||
_withPrefs((prefs) => prefs.setString(_kFailureKind, kind.name));
|
_withPrefs((prefs) => prefs.setString(_kFailureKind, kind.name));
|
||||||
@ -155,6 +154,16 @@ class SyncHealthStatus {
|
|||||||
return 'Not syncing since ${_ago(since)}. Meals stay on this device.';
|
return 'Not syncing since ${_ago(since)}. Meals stay on this device.';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Compact elapsed time (`5h`, `2d`) for a numeral beside the banner's
|
||||||
|
/// glyph; null when it has not been at least an hour or never succeeded.
|
||||||
|
String? get agoShort {
|
||||||
|
final last = lastSuccess;
|
||||||
|
if (last == null) return null;
|
||||||
|
final since = now.difference(last);
|
||||||
|
if (since < const Duration(hours: 1)) return null;
|
||||||
|
return since.inDays >= 1 ? '${since.inDays}d' : '${since.inHours}h';
|
||||||
|
}
|
||||||
|
|
||||||
static String _ago(Duration since) {
|
static String _ago(Duration since) {
|
||||||
if (since.inDays >= 1) {
|
if (since.inDays >= 1) {
|
||||||
return '${since.inDays}d ago';
|
return '${since.inDays}d ago';
|
||||||
|
|||||||
@ -24,6 +24,7 @@ import 'package:diet_guard_app/services/log_storage_service.dart';
|
|||||||
import 'package:diet_guard_app/services/sync_body.dart';
|
import 'package:diet_guard_app/services/sync_body.dart';
|
||||||
import 'package:diet_guard_app/services/sync_budget_local.dart';
|
import 'package:diet_guard_app/services/sync_budget_local.dart';
|
||||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||||
|
import 'package:diet_guard_app/services/sync_e2e.dart';
|
||||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||||
import 'package:diet_guard_app/services/sync_merge_kuchnia.dart';
|
import 'package:diet_guard_app/services/sync_merge_kuchnia.dart';
|
||||||
import 'package:diet_guard_app/services/sync_state_factory.dart';
|
import 'package:diet_guard_app/services/sync_state_factory.dart';
|
||||||
@ -32,10 +33,19 @@ const String _devicesDir = syncDevicesDir;
|
|||||||
|
|
||||||
/// Runs one full sync tick: pull, merge, persist, push.
|
/// Runs one full sync tick: pull, merge, persist, push.
|
||||||
///
|
///
|
||||||
|
/// [backend] is the outermost raw store (the Firebase/GitHub mirror);
|
||||||
|
/// everything goes through its end-to-end encrypted view, and a locked
|
||||||
|
/// device throws [SyncLockedException] before a single read or write.
|
||||||
|
///
|
||||||
/// Returns the merged log as it now sits on disk locally. Propagates any
|
/// Returns the merged log as it now sits on disk locally. Propagates any
|
||||||
/// [GitHubSyncError] from the client for the caller (auto-sync / the manual
|
/// [GitHubSyncError] from the client for the caller (auto-sync / the manual
|
||||||
/// "Sync now" action) to decide how to report.
|
/// "Sync now" action) to decide how to report.
|
||||||
Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
|
Future<DayLog> runSync(
|
||||||
|
RemoteStore backend, {
|
||||||
|
SyncStateStore? stateStore,
|
||||||
|
}) async {
|
||||||
|
final client = await openDietGuardStore(backend);
|
||||||
|
final wakeAlarm = await openWakeAlarmStore(backend);
|
||||||
final logService = LogStorageService.instance;
|
final logService = LogStorageService.instance;
|
||||||
final local = await logService.readLog();
|
final local = await logService.readLog();
|
||||||
|
|
||||||
@ -44,6 +54,7 @@ Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
|
|||||||
deviceId: currentSyncDeviceId,
|
deviceId: currentSyncDeviceId,
|
||||||
legacyDeviceId: legacySyncDeviceId,
|
legacyDeviceId: legacySyncDeviceId,
|
||||||
pathPrefix: _devicesDir,
|
pathPrefix: _devicesDir,
|
||||||
|
revsPath: syncRevsDir,
|
||||||
localLog: dayLogToLog(local),
|
localLog: dayLogToLog(local),
|
||||||
encode: encodeLogForPush,
|
encode: encodeLogForPush,
|
||||||
decode: parseRemoteLog,
|
decode: parseRemoteLog,
|
||||||
@ -65,7 +76,7 @@ Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
|
|||||||
await _syncManualBank(client);
|
await _syncManualBank(client);
|
||||||
await _syncKuchniaCredential(client);
|
await _syncKuchniaCredential(client);
|
||||||
await _syncExportKeys(client);
|
await _syncExportKeys(client);
|
||||||
await syncBody(client, devicesDir: _devicesDir);
|
await syncBody(client, devicesDir: _devicesDir, wakeAlarm: wakeAlarm);
|
||||||
return merged;
|
return merged;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -80,6 +91,7 @@ Future<void> _syncFoodBank(RemoteStore client) async {
|
|||||||
deviceId: currentSyncDeviceId,
|
deviceId: currentSyncDeviceId,
|
||||||
legacyDeviceId: legacySyncDeviceId,
|
legacyDeviceId: legacySyncDeviceId,
|
||||||
pathPrefix: _devicesDir,
|
pathPrefix: _devicesDir,
|
||||||
|
revsPath: syncRevsDir,
|
||||||
localLog: foodBankToLog(await FoodBankService.instance.readBank()),
|
localLog: foodBankToLog(await FoodBankService.instance.readBank()),
|
||||||
encode: encodeFoodBankForPush,
|
encode: encodeFoodBankForPush,
|
||||||
decode: parseRemoteFoodBank,
|
decode: parseRemoteFoodBank,
|
||||||
@ -102,6 +114,7 @@ Future<void> _syncManualBank(RemoteStore client) async {
|
|||||||
deviceId: currentSyncDeviceId,
|
deviceId: currentSyncDeviceId,
|
||||||
legacyDeviceId: legacySyncDeviceId,
|
legacyDeviceId: legacySyncDeviceId,
|
||||||
pathPrefix: _devicesDir,
|
pathPrefix: _devicesDir,
|
||||||
|
revsPath: syncRevsDir,
|
||||||
localLog: manualBankToLog(local),
|
localLog: manualBankToLog(local),
|
||||||
encode: encodeManualBankForPush,
|
encode: encodeManualBankForPush,
|
||||||
decode: parseRemoteManualBank,
|
decode: parseRemoteManualBank,
|
||||||
@ -118,6 +131,7 @@ Future<void> _syncBudget(RemoteStore client) async {
|
|||||||
deviceId: currentSyncDeviceId,
|
deviceId: currentSyncDeviceId,
|
||||||
legacyDeviceId: legacySyncDeviceId,
|
legacyDeviceId: legacySyncDeviceId,
|
||||||
pathPrefix: _devicesDir,
|
pathPrefix: _devicesDir,
|
||||||
|
revsPath: syncRevsDir,
|
||||||
localLog: localBudgetLog(),
|
localLog: localBudgetLog(),
|
||||||
encode: encodeBudgetForPush,
|
encode: encodeBudgetForPush,
|
||||||
decode: parseRemoteBudget,
|
decode: parseRemoteBudget,
|
||||||
@ -149,8 +163,7 @@ Future<void> _syncExportKeys(RemoteStore client) async {
|
|||||||
///
|
///
|
||||||
/// The phone runs its own catering importer, so it cannot fetch anything until
|
/// The phone runs its own catering importer, so it cannot fetch anything until
|
||||||
/// the panel password reaches it -- that is the whole reason this credential
|
/// the panel password reaches it -- that is the whole reason this credential
|
||||||
/// syncs at all. It is plaintext on the wire, like the rest of the synced
|
/// syncs at all. Sealed end-to-end like the rest of the synced state.
|
||||||
/// state; see `sync_merge_kuchnia.dart`.
|
|
||||||
///
|
///
|
||||||
/// A device that has no credential contributes an empty log, so it neither
|
/// A device that has no credential contributes an empty log, so it neither
|
||||||
/// blocks nor clobbers a peer's real value -- it relays it. Mirrors
|
/// blocks nor clobbers a peer's real value -- it relays it. Mirrors
|
||||||
@ -162,6 +175,7 @@ Future<void> _syncKuchniaCredential(RemoteStore client) async {
|
|||||||
deviceId: currentSyncDeviceId,
|
deviceId: currentSyncDeviceId,
|
||||||
legacyDeviceId: legacySyncDeviceId,
|
legacyDeviceId: legacySyncDeviceId,
|
||||||
pathPrefix: _devicesDir,
|
pathPrefix: _devicesDir,
|
||||||
|
revsPath: syncRevsDir,
|
||||||
localLog: credentialToLog(
|
localLog: credentialToLog(
|
||||||
KuchniaCredentialService.username,
|
KuchniaCredentialService.username,
|
||||||
KuchniaCredentialService.password,
|
KuchniaCredentialService.password,
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
/// Morning weigh-ins from the wake-alarm app, as Body weight candidates.
|
/// Morning weigh-ins from the wake-alarm app, as Body weight candidates.
|
||||||
///
|
///
|
||||||
/// The wake-alarm phone app publishes
|
/// The wake-alarm phone app publishes
|
||||||
/// `wake-alarm-sync/devices/<id>/alarm.json`: a crdt_sync Log whose
|
/// `wake-alarm-sync/devices-e2e/<id>/alarm.json` (end-to-end encrypted, read
|
||||||
|
/// through wake-alarm's own `EncryptingStore`): a crdt_sync Log whose
|
||||||
/// `alarm` record carries `fields[name] = [value, hlc]`. Two fields hold
|
/// `alarm` record carries `fields[name] = [value, hlc]`. Two fields hold
|
||||||
/// weights:
|
/// weights:
|
||||||
///
|
///
|
||||||
@ -25,7 +26,7 @@ import 'package:diet_guard_app/services/body_service.dart';
|
|||||||
import 'package:diet_guard_app/services/sync_merge_body.dart';
|
import 'package:diet_guard_app/services/sync_merge_body.dart';
|
||||||
|
|
||||||
/// Where the wake-alarm app publishes, one directory per device.
|
/// Where the wake-alarm app publishes, one directory per device.
|
||||||
const wakeAlarmDevicesDir = 'wake-alarm-sync/devices';
|
const wakeAlarmDevicesDir = 'wake-alarm-sync/devices-e2e';
|
||||||
|
|
||||||
const _latestField = 'latest_weight_kg';
|
const _latestField = 'latest_weight_kg';
|
||||||
const _sessionsField = 'morning_sessions';
|
const _sessionsField = 'morning_sessions';
|
||||||
|
|||||||
246
app/lib/ui/cues.dart
Normal file
246
app/lib/ui/cues.dart
Normal file
@ -0,0 +1,246 @@
|
|||||||
|
/// Text-free status cues: tinted icon + shake + haptic instead of sentences.
|
||||||
|
///
|
||||||
|
/// Every cue carries its meaning twice (icon shape AND colour) and exposes
|
||||||
|
/// the old sentence only as a screen-reader label, never as visible text.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
export 'package:diet_guard_app/ui/icon_field.dart';
|
||||||
|
|
||||||
|
/// What a [StatusCue] reports.
|
||||||
|
enum CueKind {
|
||||||
|
/// Something worked.
|
||||||
|
ok(Icons.check_circle),
|
||||||
|
|
||||||
|
/// Neutral information.
|
||||||
|
info(Icons.info),
|
||||||
|
|
||||||
|
/// Caution, e.g. nothing to do or only partly done.
|
||||||
|
warn(Icons.warning_amber_rounded),
|
||||||
|
|
||||||
|
/// Something failed or the input was rejected.
|
||||||
|
error(Icons.error);
|
||||||
|
|
||||||
|
const CueKind(this.icon);
|
||||||
|
|
||||||
|
/// Default glyph for this kind.
|
||||||
|
final IconData icon;
|
||||||
|
|
||||||
|
/// Tint for this kind from the active theme.
|
||||||
|
Color tint(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final status =
|
||||||
|
Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark;
|
||||||
|
return switch (this) {
|
||||||
|
CueKind.ok => status.success,
|
||||||
|
CueKind.info => scheme.onSurfaceVariant,
|
||||||
|
CueKind.warn => status.warning,
|
||||||
|
CueKind.error => scheme.error,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tinted icon chip that replaces a status sentence.
|
||||||
|
///
|
||||||
|
/// [CueKind.error] shakes (~3 swings, skipped when the platform asks for
|
||||||
|
/// reduced motion) and fires a heavy haptic; [CueKind.ok] fires a light one.
|
||||||
|
/// [semanticLabel] is announced as a live region and is never painted.
|
||||||
|
class StatusCue extends StatefulWidget {
|
||||||
|
/// Creates a cue of [kind]; [icon] overrides the kind's default glyph.
|
||||||
|
const StatusCue({
|
||||||
|
required this.kind,
|
||||||
|
required this.semanticLabel,
|
||||||
|
this.icon,
|
||||||
|
this.count,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Meaning of the cue.
|
||||||
|
final CueKind kind;
|
||||||
|
|
||||||
|
/// Spoken description (screen readers, tests); never painted.
|
||||||
|
final String semanticLabel;
|
||||||
|
|
||||||
|
/// Optional glyph replacing [CueKind.icon].
|
||||||
|
final IconData? icon;
|
||||||
|
|
||||||
|
/// Optional numeral painted beside the glyph (e.g. dishes logged).
|
||||||
|
final int? count;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<StatusCue> createState() => _StatusCueState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _StatusCueState extends State<StatusCue>
|
||||||
|
with SingleTickerProviderStateMixin {
|
||||||
|
late final AnimationController _shake = AnimationController(
|
||||||
|
vsync: this,
|
||||||
|
duration: AppDuration.slow * 2,
|
||||||
|
);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
unawaited(_announce());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _announce() async {
|
||||||
|
switch (widget.kind) {
|
||||||
|
case CueKind.error:
|
||||||
|
await HapticFeedback.heavyImpact();
|
||||||
|
if (mounted && !MediaQuery.disableAnimationsOf(context)) {
|
||||||
|
await _shake.forward();
|
||||||
|
}
|
||||||
|
case CueKind.ok:
|
||||||
|
await HapticFeedback.lightImpact();
|
||||||
|
case CueKind.info || CueKind.warn:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_shake.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final tint = widget.kind.tint(context);
|
||||||
|
return Semantics(
|
||||||
|
liveRegion: true,
|
||||||
|
label: widget.semanticLabel,
|
||||||
|
child: ExcludeSemantics(
|
||||||
|
child: AnimatedBuilder(
|
||||||
|
animation: _shake,
|
||||||
|
builder: (context, child) => Transform.translate(
|
||||||
|
offset: Offset(math.sin(_shake.value * 6 * math.pi) * 8, 0),
|
||||||
|
child: child,
|
||||||
|
),
|
||||||
|
child: DecoratedBox(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: tint.withValues(alpha: 0.16),
|
||||||
|
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||||
|
border: Border.all(color: tint),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(AppSpacing.sm),
|
||||||
|
child: _GlyphCount(
|
||||||
|
widget.icon ?? widget.kind.icon,
|
||||||
|
tint,
|
||||||
|
widget.count,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows an icon-only snackbar; [onUndo] adds an undo arrow inside it.
|
||||||
|
///
|
||||||
|
/// `SnackBarAction` can only carry text, so the undo is an [IconButton].
|
||||||
|
void showCueSnack(
|
||||||
|
BuildContext context, {
|
||||||
|
required CueKind kind,
|
||||||
|
required String semanticLabel,
|
||||||
|
IconData? icon,
|
||||||
|
int? count,
|
||||||
|
VoidCallback? onUndo,
|
||||||
|
}) {
|
||||||
|
final messenger = ScaffoldMessenger.of(context)..hideCurrentSnackBar();
|
||||||
|
final tint = kind.tint(context);
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Semantics(
|
||||||
|
liveRegion: true,
|
||||||
|
label: semanticLabel,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
ExcludeSemantics(
|
||||||
|
child: _GlyphCount(icon ?? kind.icon, tint, count),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
if (onUndo != null)
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.undo, semanticLabel: 'Undo'),
|
||||||
|
onPressed: () {
|
||||||
|
messenger.hideCurrentSnackBar();
|
||||||
|
onUndo();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A status to show: `label` is only spoken; the `kind` glyph and the
|
||||||
|
/// `count` numeral (null = glyph only) are what is painted.
|
||||||
|
typedef CountCue = ({String label, CueKind kind, int? count});
|
||||||
|
|
||||||
|
/// One screen's current status cue; [seq] re-keys the widget so an identical
|
||||||
|
/// consecutive status still shakes/pulses again.
|
||||||
|
@immutable
|
||||||
|
class CueState {
|
||||||
|
/// Creates the successor of [previous] carrying [kind] and [label].
|
||||||
|
CueState.next(CueState? previous, this.kind, this.label, [this.count])
|
||||||
|
: seq = (previous?.seq ?? 0) + 1;
|
||||||
|
|
||||||
|
/// Meaning.
|
||||||
|
final CueKind kind;
|
||||||
|
|
||||||
|
/// Spoken description; never painted.
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// Optional numeral painted beside the glyph.
|
||||||
|
final int? count;
|
||||||
|
|
||||||
|
/// Monotonic counter used as the widget key.
|
||||||
|
final int seq;
|
||||||
|
|
||||||
|
/// The left-aligned cue widget for this state.
|
||||||
|
Widget get widget => Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: StatusCue(
|
||||||
|
key: ValueKey(seq),
|
||||||
|
kind: kind,
|
||||||
|
semanticLabel: label,
|
||||||
|
count: count,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tinted glyph, followed by [count] when there is one.
|
||||||
|
class _GlyphCount extends StatelessWidget {
|
||||||
|
const _GlyphCount(this.icon, this.tint, this.count);
|
||||||
|
|
||||||
|
final IconData icon;
|
||||||
|
final Color tint;
|
||||||
|
final int? count;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final n = count;
|
||||||
|
if (n == null) return Icon(icon, color: tint);
|
||||||
|
return Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(icon, color: tint),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
Text(
|
||||||
|
'$n',
|
||||||
|
style: TextStyle(color: tint, fontWeight: FontWeight.w700),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
134
app/lib/ui/icon_field.dart
Normal file
134
app/lib/ui/icon_field.dart
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
/// An icon-captioned text field: the glyph is painted, the words are only a
|
||||||
|
/// spoken label (see [IconField]).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// A bordered text field whose caption is an icon plus a spoken label.
|
||||||
|
///
|
||||||
|
/// Replaces `InputDecoration(labelText: ...)`: the glyph is painted, the
|
||||||
|
/// words exist only for screen readers, tests and flutter-web-drive.
|
||||||
|
class IconField extends StatelessWidget {
|
||||||
|
/// Creates a field captioned by [icon].
|
||||||
|
const IconField({
|
||||||
|
required this.icon,
|
||||||
|
required this.semanticLabel,
|
||||||
|
this.controller,
|
||||||
|
this.keyboardType,
|
||||||
|
this.obscure = false,
|
||||||
|
this.suffix,
|
||||||
|
this.onChanged,
|
||||||
|
this.dense = false,
|
||||||
|
this.fieldKey,
|
||||||
|
this.iconColor,
|
||||||
|
this.inputFormatters,
|
||||||
|
this.onSubmitted,
|
||||||
|
this.autofocus = false,
|
||||||
|
this.autocorrect = true,
|
||||||
|
this.fontSize,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Input formatters, e.g. digits only.
|
||||||
|
final List<TextInputFormatter>? inputFormatters;
|
||||||
|
|
||||||
|
/// Called when the user submits from the keyboard.
|
||||||
|
final ValueChanged<String>? onSubmitted;
|
||||||
|
|
||||||
|
/// Whether the field grabs focus when it first appears.
|
||||||
|
final bool autofocus;
|
||||||
|
|
||||||
|
/// Whether the keyboard may autocorrect (false for e-mails and secrets).
|
||||||
|
final bool autocorrect;
|
||||||
|
|
||||||
|
/// Text size of the typed value; the theme's when null.
|
||||||
|
final double? fontSize;
|
||||||
|
|
||||||
|
/// Painted caption.
|
||||||
|
final IconData icon;
|
||||||
|
|
||||||
|
/// Tint of [icon]; the theme's default when null.
|
||||||
|
final Color? iconColor;
|
||||||
|
|
||||||
|
/// Spoken caption; never painted.
|
||||||
|
final String semanticLabel;
|
||||||
|
|
||||||
|
/// Backing controller.
|
||||||
|
final TextEditingController? controller;
|
||||||
|
|
||||||
|
/// Keyboard type.
|
||||||
|
final TextInputType? keyboardType;
|
||||||
|
|
||||||
|
/// Hides the typed characters.
|
||||||
|
final bool obscure;
|
||||||
|
|
||||||
|
/// Trailing widget, e.g. a visibility toggle.
|
||||||
|
final Widget? suffix;
|
||||||
|
|
||||||
|
/// Change callback.
|
||||||
|
final ValueChanged<String>? onChanged;
|
||||||
|
|
||||||
|
/// Compact vertical padding.
|
||||||
|
final bool dense;
|
||||||
|
|
||||||
|
/// Key given to the inner [TextField].
|
||||||
|
final Key? fieldKey;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
// MergeSemantics folds the spoken label into the TextField's own node:
|
||||||
|
// a bare `Semantics(textField: true)` wrapper produced a second,
|
||||||
|
// disabled textbox beside the real one, so drivers tapped the dead one.
|
||||||
|
return MergeSemantics(
|
||||||
|
child: Semantics(
|
||||||
|
label: semanticLabel,
|
||||||
|
child: TextField(
|
||||||
|
key: fieldKey,
|
||||||
|
controller: controller,
|
||||||
|
keyboardType: keyboardType,
|
||||||
|
obscureText: obscure,
|
||||||
|
onChanged: onChanged,
|
||||||
|
onSubmitted: onSubmitted,
|
||||||
|
inputFormatters: inputFormatters,
|
||||||
|
autofocus: autofocus,
|
||||||
|
autocorrect: autocorrect,
|
||||||
|
style: fontSize == null ? null : TextStyle(fontSize: fontSize),
|
||||||
|
enableSuggestions: autocorrect,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
prefixIcon: ExcludeSemantics(child: Icon(icon, color: iconColor)),
|
||||||
|
prefixIconConstraints: dense
|
||||||
|
? const BoxConstraints(minWidth: 32, minHeight: 32)
|
||||||
|
: null,
|
||||||
|
suffixIcon: suffix,
|
||||||
|
isDense: dense,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gives [child] a spoken name without painting any text.
|
||||||
|
///
|
||||||
|
/// Wraps `Semantics(label:)`; keeping the string on a `semanticLabel:` line
|
||||||
|
/// lets line-based text scanners recognise it as accessibility metadata even
|
||||||
|
/// after the formatter splits `Semantics(` from its arguments.
|
||||||
|
class SpokenLabel extends StatelessWidget {
|
||||||
|
/// Creates a labelled wrapper around [child].
|
||||||
|
const SpokenLabel({
|
||||||
|
required this.semanticLabel,
|
||||||
|
required this.child,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Spoken name; never painted.
|
||||||
|
final String semanticLabel;
|
||||||
|
|
||||||
|
/// The widget being named.
|
||||||
|
final Widget child;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) =>
|
||||||
|
Semantics(label: semanticLabel, container: true, child: child);
|
||||||
|
}
|
||||||
80
app/lib/ui/macro_kind.dart
Normal file
80
app/lib/ui/macro_kind.dart
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
/// Shape + colour vocabulary for the nutrition fields, so a field or figure
|
||||||
|
/// is recognised by its glyph instead of a "P"/"C"/"F"/"kcal" word.
|
||||||
|
///
|
||||||
|
/// Protein is a green circle, carbs an amber triangle, fat a blue square;
|
||||||
|
/// colour never carries the meaning alone (shape does too).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// One nutrition field and its non-text identity.
|
||||||
|
enum MacroKind {
|
||||||
|
/// Reference weight the typed macros are stated for.
|
||||||
|
perGrams(Icons.scale, Color(0xFFAAA09A), 'per (g)', 'per'),
|
||||||
|
|
||||||
|
/// Energy.
|
||||||
|
kcal(Icons.bolt, Color(0xFFE08A3C), 'kcal', 'kcal'),
|
||||||
|
|
||||||
|
/// Protein.
|
||||||
|
protein(Icons.circle, Color(0xFF8A9A3C), 'protein g', 'P'),
|
||||||
|
|
||||||
|
/// Carbohydrate.
|
||||||
|
carbs(Icons.change_history, Color(0xFFE0A63C), 'carbs g', 'C'),
|
||||||
|
|
||||||
|
/// Fat.
|
||||||
|
fat(Icons.square, Color(0xFF6C9BD1), 'fat g', 'F'),
|
||||||
|
|
||||||
|
/// Portion weight actually eaten.
|
||||||
|
eaten(Icons.rice_bowl, Color(0xFFAAA09A), 'eaten (g)', 'eaten');
|
||||||
|
|
||||||
|
const MacroKind(this.icon, this.color, this._long, this._short);
|
||||||
|
|
||||||
|
/// Painted glyph.
|
||||||
|
final IconData icon;
|
||||||
|
|
||||||
|
/// Glyph tint.
|
||||||
|
final Color color;
|
||||||
|
|
||||||
|
final String _long;
|
||||||
|
final String _short;
|
||||||
|
|
||||||
|
/// Spoken name; the long form unless [compact].
|
||||||
|
String semanticLabel({required bool compact}) => compact ? _short : _long;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A glyph + number pair, e.g. a green circle and `12`.
|
||||||
|
class MacroFigure extends StatelessWidget {
|
||||||
|
/// Creates a figure for [kind] showing [grams] (or [value] verbatim).
|
||||||
|
const MacroFigure({
|
||||||
|
required this.kind,
|
||||||
|
required this.value,
|
||||||
|
this.size = 12,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Which nutrient.
|
||||||
|
final MacroKind kind;
|
||||||
|
|
||||||
|
/// The number to show, already formatted.
|
||||||
|
final String value;
|
||||||
|
|
||||||
|
/// Glyph size.
|
||||||
|
final double size;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
kind.icon,
|
||||||
|
color: kind.color,
|
||||||
|
size: size,
|
||||||
|
semanticLabel: kind.semanticLabel(compact: false),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 3),
|
||||||
|
Text(value),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
33
app/lib/ui/source_icon.dart
Normal file
33
app/lib/ui/source_icon.dart
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
/// Glyph for where a log entry came from, replacing the stored source word
|
||||||
|
/// (`manual`, `food bank`, `catering`) that used to be printed on screen.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Icon for a stored entry `source` value; unknown values get a neutral dot.
|
||||||
|
IconData sourceIcon(String source) => switch (source) {
|
||||||
|
'manual' => Icons.edit,
|
||||||
|
'food bank' => Icons.restaurant_menu,
|
||||||
|
'catering' => Icons.local_shipping,
|
||||||
|
_ => Icons.circle_outlined,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A small painted [sourceIcon] that still speaks the stored source value.
|
||||||
|
class SourceMark extends StatelessWidget {
|
||||||
|
/// Creates a mark for [source].
|
||||||
|
const SourceMark(this.source, {this.size = 14, super.key});
|
||||||
|
|
||||||
|
/// Stored source value.
|
||||||
|
final String source;
|
||||||
|
|
||||||
|
/// Glyph size.
|
||||||
|
final double size;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Icon(
|
||||||
|
sourceIcon(source),
|
||||||
|
size: size,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: source,
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -6,7 +6,7 @@
|
|||||||
/// hand-picked, not algorithmically derived from one seed color.
|
/// hand-picked, not algorithmically derived from one seed color.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Builds the app's single dark `ThemeData` from the shared token set.
|
/// Builds the app's single dark `ThemeData` from the shared token set.
|
||||||
ThemeData buildAppTheme() {
|
ThemeData buildAppTheme() {
|
||||||
@ -195,6 +195,9 @@ abstract final class AppWidth {
|
|||||||
/// value reads as a layout error rather than an affordance.
|
/// value reads as a layout error rather than an affordance.
|
||||||
static const double field = 420;
|
static const double field = 420;
|
||||||
|
|
||||||
|
/// 440px — cap for a date/time picker dialog (7 day columns + year wheel).
|
||||||
|
static const double picker = 440;
|
||||||
|
|
||||||
/// Viewport height below which the layout should switch to its compact form.
|
/// Viewport height below which the layout should switch to its compact form.
|
||||||
///
|
///
|
||||||
/// 700px, i.e. 768 minus typical window chrome: the supported floor is a
|
/// 700px, i.e. 768 minus typical window chrome: the supported floor is a
|
||||||
|
|||||||
@ -2,12 +2,13 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_suggestion.dart';
|
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// A tappable list of [FoodSuggestion]s, each filling the form on tap.
|
/// A tappable list of [FoodSuggestion]s, each filling the form on tap.
|
||||||
///
|
///
|
||||||
/// When [compact] is true, only the top 3 suggestions render as compact
|
/// When [compact] is true, only the top [compactLimit] suggestions render as
|
||||||
/// single-line rows, with a "N more" button opening the full list in a
|
/// compact single-line rows, with a "N more" button opening the full list in a
|
||||||
/// bottom sheet so nothing becomes unreachable.
|
/// bottom sheet so nothing becomes unreachable.
|
||||||
class AutocompleteSuggestionList extends StatelessWidget {
|
class AutocompleteSuggestionList extends StatelessWidget {
|
||||||
/// Creates an [AutocompleteSuggestionList] for [suggestions].
|
/// Creates an [AutocompleteSuggestionList] for [suggestions].
|
||||||
@ -15,6 +16,8 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
required this.suggestions,
|
required this.suggestions,
|
||||||
required this.onSelected,
|
required this.onSelected,
|
||||||
this.compact = false,
|
this.compact = false,
|
||||||
|
this.compactLimit = 3,
|
||||||
|
this.reserveHeight = false,
|
||||||
super.key,
|
super.key,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -28,7 +31,16 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
/// of the full unbounded list.
|
/// of the full unbounded list.
|
||||||
final bool compact;
|
final bool compact;
|
||||||
|
|
||||||
static const int _compactLimit = 3;
|
/// How many rows a compact list shows before its "more" button.
|
||||||
|
final int compactLimit;
|
||||||
|
|
||||||
|
/// Whether a compact list always occupies [dueBlockHeight], empty or full,
|
||||||
|
/// so nothing below it shifts as suggestions come and go (due mode).
|
||||||
|
final bool reserveHeight;
|
||||||
|
|
||||||
|
/// Height of the block that holds a compact list of two rows plus the
|
||||||
|
/// "more" button; due mode reserves it so nothing below shifts.
|
||||||
|
static const double dueBlockHeight = 120;
|
||||||
|
|
||||||
Future<void> _showMore(BuildContext context) async {
|
Future<void> _showMore(BuildContext context) async {
|
||||||
await showModalBottomSheet<void>(
|
await showModalBottomSheet<void>(
|
||||||
@ -47,6 +59,15 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final list = _list(context);
|
||||||
|
if (!reserveHeight) return list;
|
||||||
|
return SizedBox(
|
||||||
|
height: dueBlockHeight,
|
||||||
|
child: Align(alignment: Alignment.topLeft, child: list),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _list(BuildContext context) {
|
||||||
if (suggestions.isEmpty) return const SizedBox.shrink();
|
if (suggestions.isEmpty) return const SizedBox.shrink();
|
||||||
if (!compact) {
|
if (!compact) {
|
||||||
return ListView.builder(
|
return ListView.builder(
|
||||||
@ -57,15 +78,19 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
return ListTile(
|
return ListTile(
|
||||||
dense: true,
|
dense: true,
|
||||||
title: Text(suggestion.name),
|
title: Text(suggestion.name),
|
||||||
subtitle: Text(
|
subtitle: Align(
|
||||||
'${suggestion.nutrition.kcal.toStringAsFixed(0)} kcal',
|
alignment: Alignment.centerLeft,
|
||||||
|
child: MacroFigure(
|
||||||
|
kind: MacroKind.kcal,
|
||||||
|
value: suggestion.nutrition.kcal.toStringAsFixed(0),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
onTap: () => onSelected(suggestion),
|
onTap: () => onSelected(suggestion),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final shown = suggestions.take(_compactLimit).toList();
|
final shown = suggestions.take(compactLimit).toList();
|
||||||
final remaining = suggestions.length - shown.length;
|
final remaining = suggestions.length - shown.length;
|
||||||
return Column(
|
return Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
@ -76,17 +101,34 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
|||||||
onTap: () => onSelected(suggestion),
|
onTap: () => onSelected(suggestion),
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
child: Text(
|
child: Row(
|
||||||
'${suggestion.name} · '
|
children: [
|
||||||
'${suggestion.nutrition.kcal.toStringAsFixed(0)} kcal',
|
Flexible(
|
||||||
overflow: TextOverflow.ellipsis,
|
child: Text(
|
||||||
|
suggestion.name,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
MacroFigure(
|
||||||
|
kind: MacroKind.kcal,
|
||||||
|
value: suggestion.nutrition.kcal.toStringAsFixed(0),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (remaining > 0)
|
if (remaining > 0)
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => _showMore(context),
|
onPressed: () => _showMore(context),
|
||||||
child: Text('$remaining more'),
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
const Icon(Icons.more_horiz, semanticLabel: 'More'),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Text('+$remaining'),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -2,23 +2,23 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/period_average.dart';
|
import 'package:diet_guard_app/models/period_average.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Displays this week's and this month's average kcal/day and their bands.
|
/// Displays this week's and this month's average kcal/day and their bands.
|
||||||
///
|
///
|
||||||
/// Mirrors `_calendar_view.py`'s `averages_text`: "Avg/day (to yesterday):
|
/// Mirrors `_calendar_view.py`'s `averages_text`, minus the words: each period
|
||||||
/// week NNNN kcal (band) · month NNNN kcal (band)".
|
/// is a calendar glyph, the average as a number, and the band as a tinted
|
||||||
|
/// icon (check = under, warning = slightly over, error = very over, dash =
|
||||||
|
/// no data) so colour is never the only channel.
|
||||||
///
|
///
|
||||||
/// Both periods stop at yesterday, so this line does not swing every time a
|
/// Both periods stop at yesterday, so this line does not swing every time a
|
||||||
/// meal is logged today -- it answers "how has this week gone", not "how am I
|
/// meal is logged today -- it answers "how has this week gone", not "how am I
|
||||||
/// doing right now", which is what the Today progress card is for.
|
/// doing right now", which is what the Today progress card is for.
|
||||||
class AverageSummaryRow extends StatelessWidget {
|
class AverageSummaryRow extends StatelessWidget {
|
||||||
/// Creates an [AverageSummaryRow].
|
/// Creates an [AverageSummaryRow].
|
||||||
const AverageSummaryRow({
|
const AverageSummaryRow({required this.week, required this.month, super.key});
|
||||||
required this.week,
|
|
||||||
required this.month,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// The current ISO week's average, through yesterday.
|
/// The current ISO week's average, through yesterday.
|
||||||
final PeriodAverage week;
|
final PeriodAverage week;
|
||||||
@ -26,18 +26,72 @@ class AverageSummaryRow extends StatelessWidget {
|
|||||||
/// The current calendar month's average, through yesterday.
|
/// The current calendar month's average, through yesterday.
|
||||||
final PeriodAverage month;
|
final PeriodAverage month;
|
||||||
|
|
||||||
static String _part(PeriodAverage period) {
|
|
||||||
final avg = period.avgKcal;
|
|
||||||
if (avg == null) return bandLabel(period.band);
|
|
||||||
return '${avg.round()} kcal (${bandLabel(period.band)})';
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Text(
|
return Row(
|
||||||
'Avg/day (to yesterday): week ${_part(week)} · month ${_part(month)}',
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
textAlign: TextAlign.center,
|
children: [
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
_PeriodFigure(
|
||||||
|
period: week,
|
||||||
|
icon: Icons.calendar_view_week,
|
||||||
|
semanticLabel: 'week',
|
||||||
|
),
|
||||||
|
const SizedBox(width: 24),
|
||||||
|
_PeriodFigure(
|
||||||
|
period: month,
|
||||||
|
icon: Icons.calendar_view_month,
|
||||||
|
semanticLabel: 'month',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PeriodFigure extends StatelessWidget {
|
||||||
|
const _PeriodFigure({
|
||||||
|
required this.period,
|
||||||
|
required this.icon,
|
||||||
|
required this.semanticLabel,
|
||||||
|
});
|
||||||
|
|
||||||
|
final PeriodAverage period;
|
||||||
|
final IconData icon;
|
||||||
|
final String semanticLabel;
|
||||||
|
|
||||||
|
(CueKind, IconData) get _band => switch (period.band) {
|
||||||
|
null => (CueKind.info, Icons.remove_circle_outline),
|
||||||
|
AverageBand.under => (CueKind.ok, Icons.check_circle),
|
||||||
|
AverageBand.slightlyOver => (CueKind.warn, Icons.warning_amber_rounded),
|
||||||
|
AverageBand.veryOver => (CueKind.error, Icons.error),
|
||||||
|
};
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final (kind, bandIcon) = _band;
|
||||||
|
final avg = period.avgKcal;
|
||||||
|
final style = Theme.of(context).textTheme.bodySmall;
|
||||||
|
return Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(icon, size: 16, semanticLabel: semanticLabel),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Icon(
|
||||||
|
bandIcon,
|
||||||
|
size: 16,
|
||||||
|
color: kind.tint(context),
|
||||||
|
semanticLabel: bandLabel(period.band),
|
||||||
|
),
|
||||||
|
if (avg != null) ...[
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Icon(
|
||||||
|
MacroKind.kcal.icon,
|
||||||
|
size: 14,
|
||||||
|
color: MacroKind.kcal.color,
|
||||||
|
semanticLabel: 'kcal',
|
||||||
|
),
|
||||||
|
Text('${avg.round()}', style: style),
|
||||||
|
],
|
||||||
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,9 +2,13 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/services/activity_kcal.dart';
|
import 'package:diet_guard_app/services/activity_kcal.dart';
|
||||||
import 'package:diet_guard_app/services/body_steps.dart';
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/widgets/body/formula_figure.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/workout_kind_icon.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// How many of the newest sessions to list.
|
/// How many of the newest sessions to list.
|
||||||
const int activityListLimit = 10;
|
const int activityListLimit = 10;
|
||||||
@ -55,48 +59,118 @@ class ActivityCard extends StatelessWidget {
|
|||||||
final lastDay = steps.isEmpty
|
final lastDay = steps.isEmpty
|
||||||
? null
|
? null
|
||||||
: steps.keys.reduce((a, b) => a.compareTo(b) > 0 ? a : b);
|
: steps.keys.reduce((a, b) => a.compareTo(b) > 0 ? a : b);
|
||||||
|
final muted = Theme.of(context).colorScheme.onSurfaceVariant;
|
||||||
return BodySection(
|
return BodySection(
|
||||||
title: 'Activity',
|
semanticLabel: 'Activity',
|
||||||
children: [
|
children: [
|
||||||
if (sessions == null && steps.isEmpty)
|
if (sessions == null && steps.isEmpty)
|
||||||
const BodyNote('No activity data yet -- published by the PC.'),
|
const StatusCue(
|
||||||
|
kind: CueKind.info,
|
||||||
|
icon: Icons.directions_run,
|
||||||
|
semanticLabel: 'No activity data yet -- published by the PC.',
|
||||||
|
),
|
||||||
if (means != null) ...[
|
if (means != null) ...[
|
||||||
BodyNote('Mean daily exercise, last $window full days:'),
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.date_range,
|
||||||
|
size: 18,
|
||||||
|
color: muted,
|
||||||
|
semanticLabel: 'Mean daily exercise, last $window full days:',
|
||||||
|
),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
Text('$window'),
|
||||||
|
],
|
||||||
|
),
|
||||||
for (final name in activityFormulas)
|
for (final name in activityFormulas)
|
||||||
BodyStatRow(name, '${whole(means[name] ?? 0)} kcal/day'),
|
_FormulaRow(name, whole(means[name] ?? 0)),
|
||||||
],
|
],
|
||||||
if (lastDay != null && stepKcal != null)
|
if (lastDay != null && stepKcal != null)
|
||||||
BodyNote(
|
Padding(
|
||||||
'Steps outside workouts: ${steps[lastDay]} on $lastDay; above '
|
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs),
|
||||||
'$stepBaseline/day they add ${whole(stepKcal)} kcal/day '
|
child: Row(
|
||||||
'(included above).',
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.directions_walk,
|
||||||
|
size: 18,
|
||||||
|
color: muted,
|
||||||
|
semanticLabel: 'Steps outside workouts',
|
||||||
|
),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
Text('${steps[lastDay]} $lastDay'),
|
||||||
|
const Spacer(),
|
||||||
|
Icon(Icons.add, size: 16, color: muted),
|
||||||
|
MacroFigure(
|
||||||
|
kind: MacroKind.kcal,
|
||||||
|
value: whole(stepKcal),
|
||||||
|
size: 16,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
if (onConnectSteps != null)
|
if (onConnectSteps != null)
|
||||||
Align(
|
Align(
|
||||||
alignment: Alignment.centerLeft,
|
alignment: Alignment.centerLeft,
|
||||||
child: OutlinedButton.icon(
|
child: OutlinedButton(
|
||||||
icon: const Icon(Icons.directions_walk),
|
|
||||||
label: const Text('Connect Health Connect steps'),
|
|
||||||
onPressed: onConnectSteps,
|
onPressed: onConnectSteps,
|
||||||
|
child: const Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.directions_walk,
|
||||||
|
semanticLabel: 'Connect Health Connect steps',
|
||||||
|
),
|
||||||
|
Icon(Icons.link),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (sessions != null && kg == null)
|
if (sessions != null && kg == null)
|
||||||
const BodyNote('Enter your weight to estimate exercise kcal.'),
|
const StatusCue(
|
||||||
|
kind: CueKind.warn,
|
||||||
|
icon: Icons.monitor_weight,
|
||||||
|
semanticLabel: 'Enter your weight to estimate exercise kcal.',
|
||||||
|
),
|
||||||
if (sessions != null && kg != null) ...[
|
if (sessions != null && kg != null) ...[
|
||||||
const Divider(),
|
const Divider(),
|
||||||
if (newest.isEmpty)
|
if (newest.isEmpty)
|
||||||
const BodyNote('No workouts in the last 28 days.'),
|
const StatusCue(
|
||||||
|
kind: CueKind.info,
|
||||||
|
icon: Icons.event_busy,
|
||||||
|
semanticLabel: 'No workouts in the last 28 days.',
|
||||||
|
),
|
||||||
for (final session in newest.take(activityListLimit))
|
for (final session in newest.take(activityListLimit))
|
||||||
_SessionTile(result: sessionKcal(session, kg)),
|
_SessionTile(result: sessionKcal(session, kg)),
|
||||||
if (newest.isNotEmpty)
|
|
||||||
const BodyNote('~ = no distance, MET estimate used instead.'),
|
|
||||||
const BodyNote(methodsNote),
|
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A formula's glyph on the left, its kcal figure on the right.
|
||||||
|
class _FormulaRow extends StatelessWidget {
|
||||||
|
const _FormulaRow(this.name, this.value);
|
||||||
|
|
||||||
|
final String name;
|
||||||
|
final String value;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: FormulaGlyph(name),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
MacroFigure(kind: MacroKind.kcal, value: value, size: 16),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
class _SessionTile extends StatelessWidget {
|
class _SessionTile extends StatelessWidget {
|
||||||
const _SessionTile({required this.result});
|
const _SessionTile({required this.result});
|
||||||
|
|
||||||
@ -106,22 +180,67 @@ class _SessionTile extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final session = result.session;
|
final session = result.session;
|
||||||
final km = session.km;
|
final km = session.km;
|
||||||
final distance = km == null ? '' : ', ${oneDecimal(km)} km';
|
final muted = Theme.of(context).colorScheme.onSurfaceVariant;
|
||||||
final kcal = [
|
return Padding(
|
||||||
for (final name in activityFormulas)
|
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs),
|
||||||
_formulaKcal(name, result.kcal[name]!, result.fallback.contains(name)),
|
child: Column(
|
||||||
].join(' · ');
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
return ListTile(
|
children: [
|
||||||
dense: true,
|
Row(
|
||||||
contentPadding: EdgeInsets.zero,
|
children: [
|
||||||
title: Text('${session.day} ${session.label}'),
|
Text(session.day),
|
||||||
subtitle: Text(
|
const SizedBox(width: AppSpacing.sm),
|
||||||
'${whole(session.minutes)} min$distance\n$kcal kcal',
|
Icon(
|
||||||
|
kindIcon(session.kind),
|
||||||
|
size: 16,
|
||||||
|
color: muted,
|
||||||
|
semanticLabel: session.label,
|
||||||
|
),
|
||||||
|
if (session.source == 'manual') ...[
|
||||||
|
const SizedBox(width: AppSpacing.sm),
|
||||||
|
Flexible(child: Text(session.label)),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.timer_outlined,
|
||||||
|
size: 16,
|
||||||
|
color: muted,
|
||||||
|
semanticLabel: 'minutes',
|
||||||
|
),
|
||||||
|
Text(' ${whole(session.minutes)}'),
|
||||||
|
if (km != null) ...[
|
||||||
|
const SizedBox(width: AppSpacing.md),
|
||||||
|
Icon(Icons.route, size: 16, color: muted, semanticLabel: 'km'),
|
||||||
|
Text(' ${oneDecimal(km)}'),
|
||||||
|
],
|
||||||
|
const SizedBox(width: AppSpacing.md),
|
||||||
|
Icon(
|
||||||
|
MacroKind.kcal.icon,
|
||||||
|
size: 16,
|
||||||
|
color: MacroKind.kcal.color,
|
||||||
|
semanticLabel: 'kcal',
|
||||||
|
),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
Expanded(
|
||||||
|
child: Wrap(
|
||||||
|
spacing: AppSpacing.sm,
|
||||||
|
children: [
|
||||||
|
for (final name in activityFormulas)
|
||||||
|
FormulaFigure(
|
||||||
|
name,
|
||||||
|
whole(result.kcal[name]!),
|
||||||
|
fallback: result.fallback.contains(name),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
isThreeLine: true,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String _formulaKcal(String name, double kcal, bool fallback) =>
|
|
||||||
'$name ${whole(kcal)}${fallback ? '~' : ''}';
|
|
||||||
|
|||||||
@ -1,52 +1,74 @@
|
|||||||
/// A titled card, the building block of every Body screen section.
|
/// A card, the building block of every Body screen section, plus the
|
||||||
|
/// icon-led stat rows the cards are made of. No headings: the overview tile
|
||||||
|
/// that opened the sheet already says what it is.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/services/body_calc.dart';
|
import 'package:diet_guard_app/services/body_calc.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// A card with a title row and [children] stacked below it.
|
/// A card with [children] stacked in it; [semanticLabel] names it for screen
|
||||||
|
/// readers and tests and is never painted.
|
||||||
class BodySection extends StatelessWidget {
|
class BodySection extends StatelessWidget {
|
||||||
/// Creates a section.
|
/// Creates a section.
|
||||||
const BodySection({
|
const BodySection({
|
||||||
required this.title,
|
required this.semanticLabel,
|
||||||
required this.children,
|
required this.children,
|
||||||
super.key,
|
super.key,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Section heading.
|
/// Spoken name of the section.
|
||||||
final String title;
|
final String semanticLabel;
|
||||||
|
|
||||||
/// Section content.
|
/// Section content.
|
||||||
final List<Widget> children;
|
final List<Widget> children;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
return Semantics(
|
||||||
return Card(
|
container: true,
|
||||||
margin: const EdgeInsets.only(bottom: AppSpacing.md),
|
label: semanticLabel,
|
||||||
child: Padding(
|
child: Card(
|
||||||
padding: const EdgeInsets.all(AppSpacing.md),
|
margin: const EdgeInsets.only(bottom: AppSpacing.md),
|
||||||
child: Column(
|
child: Padding(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
padding: const EdgeInsets.all(AppSpacing.md),
|
||||||
children: [
|
child: Column(
|
||||||
Text(title, style: theme.textTheme.titleMedium),
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
const SizedBox(height: AppSpacing.sm),
|
children: children,
|
||||||
...children,
|
),
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A label on the left, a value on the right; one line of a stats card.
|
/// One line of a stats card: a leading mark on the left, a value on the right.
|
||||||
|
///
|
||||||
|
/// The mark is either a formula name ([BodyStatRow.named]: a proper noun such
|
||||||
|
/// as Devine or ACSM, shown as is) or an icon ([BodyStatRow.icon]).
|
||||||
class BodyStatRow extends StatelessWidget {
|
class BodyStatRow extends StatelessWidget {
|
||||||
/// Creates a row.
|
/// A row led by a formula's proper name.
|
||||||
const BodyStatRow(this.label, this.value, {this.color, super.key});
|
const BodyStatRow.named(this.name, this.value, {this.color, super.key})
|
||||||
|
: icon = null,
|
||||||
|
semanticLabel = null;
|
||||||
|
|
||||||
/// What the value is.
|
/// A row led by [icon], spoken as [semanticLabel].
|
||||||
final String label;
|
const BodyStatRow.icon(
|
||||||
|
IconData this.icon,
|
||||||
|
String this.semanticLabel,
|
||||||
|
this.value, {
|
||||||
|
this.color,
|
||||||
|
super.key,
|
||||||
|
}) : name = null;
|
||||||
|
|
||||||
|
/// Proper-noun lead, or null when an icon leads.
|
||||||
|
final String? name;
|
||||||
|
|
||||||
|
/// Icon lead, or null when a name leads.
|
||||||
|
final IconData? icon;
|
||||||
|
|
||||||
|
/// Spoken description of [icon].
|
||||||
|
final String? semanticLabel;
|
||||||
|
|
||||||
/// The formatted value.
|
/// The formatted value.
|
||||||
final String value;
|
final String value;
|
||||||
@ -56,11 +78,19 @@ class BodyStatRow extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final lead = icon;
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2),
|
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
Expanded(child: Text(label)),
|
Expanded(
|
||||||
|
child: lead == null
|
||||||
|
? Text(name!)
|
||||||
|
: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: Icon(lead, size: 20, semanticLabel: semanticLabel),
|
||||||
|
),
|
||||||
|
),
|
||||||
Text(
|
Text(
|
||||||
value,
|
value,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
@ -74,28 +104,8 @@ class BodyStatRow extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A muted one-line explanation (missing data, notes).
|
/// `74.99` -> `"75.0 kg"`, null -> a dash. Half-up, like the PC.
|
||||||
class BodyNote extends StatelessWidget {
|
String formatKg(double? kg) => kg == null ? '—' : '${oneDecimal(kg)} kg';
|
||||||
/// Creates a note.
|
|
||||||
const BodyNote(this.text, {super.key});
|
|
||||||
|
|
||||||
/// The note.
|
|
||||||
final String text;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final theme = Theme.of(context);
|
|
||||||
return Text(
|
|
||||||
text,
|
|
||||||
style: theme.textTheme.bodySmall?.copyWith(
|
|
||||||
color: theme.colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `74.99` -> `"75.0 kg"`, null -> `"n/a"`. Half-up, like the PC.
|
|
||||||
String formatKg(double? kg) => kg == null ? 'n/a' : '${oneDecimal(kg)} kg';
|
|
||||||
|
|
||||||
/// [value] to one decimal, rounded half-up like the PC prints it.
|
/// [value] to one decimal, rounded half-up like the PC prints it.
|
||||||
String oneDecimal(double value) => halfUp(value, 1).toStringAsFixed(1);
|
String oneDecimal(double value) => halfUp(value, 1).toStringAsFixed(1);
|
||||||
|
|||||||
@ -2,8 +2,25 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/services/body_calc.dart';
|
import 'package:diet_guard_app/services/body_calc.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// The BMI band as glyph + colour (never colour alone): a green check inside
|
||||||
|
/// the healthy range, an amber or red arrow towards the side it is off by.
|
||||||
|
(IconData, CueKind) bmiBandCue(String category) {
|
||||||
|
if (category == 'normal') return (Icons.check_circle, CueKind.ok);
|
||||||
|
if (category.contains('thinness')) {
|
||||||
|
return (Icons.trending_down, CueKind.warn);
|
||||||
|
}
|
||||||
|
if (category.startsWith('overweight')) {
|
||||||
|
return (Icons.trending_up, CueKind.warn);
|
||||||
|
}
|
||||||
|
if (category.startsWith('obese')) return (Icons.trending_up, CueKind.error);
|
||||||
|
return (Icons.help_outline, CueKind.info);
|
||||||
|
}
|
||||||
|
|
||||||
/// BMI, BMI Prime, Trefethen's BMI and the WHO category.
|
/// BMI, BMI Prime, Trefethen's BMI and the WHO category.
|
||||||
class BmiCard extends StatelessWidget {
|
class BmiCard extends StatelessWidget {
|
||||||
@ -17,30 +34,40 @@ class BmiCard extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final report = bmiReport(bio);
|
final report = bmiReport(bio);
|
||||||
final (low, high) = healthyRange(bio);
|
final (low, high) = healthyRange(bio);
|
||||||
final normal = report.category == 'normal';
|
final (icon, kind) = bmiBandCue(report.category);
|
||||||
|
final tint = kind.tint(context);
|
||||||
return BodySection(
|
return BodySection(
|
||||||
title: 'BMI',
|
semanticLabel: 'BMI',
|
||||||
children: [
|
children: [
|
||||||
BodyStatRow(
|
Row(
|
||||||
'BMI',
|
children: [
|
||||||
oneDecimal(report.bmi),
|
Icon(icon, color: tint, semanticLabel: report.category),
|
||||||
color: normal ? null : Theme.of(context).colorScheme.error,
|
const SizedBox(width: AppSpacing.sm),
|
||||||
|
Text(
|
||||||
|
oneDecimal(report.bmi),
|
||||||
|
style: Theme.of(
|
||||||
|
context,
|
||||||
|
).textTheme.headlineMedium?.copyWith(color: tint),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
BodyStatRow('Category', report.category),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
BodyStatRow('BMI Prime', halfUp(report.prime, 2).toStringAsFixed(2)),
|
BodyStatRow.named(
|
||||||
BodyStatRow('Trefethen (new BMI)', oneDecimal(report.trefethen)),
|
'BMI Prime',
|
||||||
BodyStatRow(
|
halfUp(report.prime, 2).toStringAsFixed(2),
|
||||||
|
),
|
||||||
|
BodyStatRow.named('Trefethen', oneDecimal(report.trefethen)),
|
||||||
|
BodyStatRow.icon(
|
||||||
|
Icons.favorite,
|
||||||
'Healthy weight for your height (BMI 18.5-24.9)',
|
'Healthy weight for your height (BMI 18.5-24.9)',
|
||||||
'${oneDecimal(low)}-${oneDecimal(high)} kg',
|
'${oneDecimal(low)}-${oneDecimal(high)} kg',
|
||||||
),
|
),
|
||||||
const BodyNote(bmiPrimeNote),
|
|
||||||
const BodyNote(trefethenNote),
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every ideal-weight formula; `n/a` where one is undefined.
|
/// Every ideal-weight formula; a dash where one is undefined.
|
||||||
class IdealWeightCard extends StatelessWidget {
|
class IdealWeightCard extends StatelessWidget {
|
||||||
/// Creates the card for [bio].
|
/// Creates the card for [bio].
|
||||||
const IdealWeightCard({required this.bio, super.key});
|
const IdealWeightCard({required this.bio, super.key});
|
||||||
@ -51,25 +78,25 @@ class IdealWeightCard extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final formulas = idealWeights(bio);
|
final formulas = idealWeights(bio);
|
||||||
final undefined = formulas.any((f) => f.value == null);
|
|
||||||
final summary = idealSummary(formulas);
|
final summary = idealSummary(formulas);
|
||||||
return BodySection(
|
return BodySection(
|
||||||
title: 'Ideal weight',
|
semanticLabel: 'Ideal weight',
|
||||||
children: [
|
children: [
|
||||||
for (final formula in formulas)
|
for (final formula in formulas)
|
||||||
BodyStatRow(formula.name, formatKg(formula.value)),
|
BodyStatRow.named(formula.name, formatKg(formula.value)),
|
||||||
if (summary != null) ...[
|
if (summary != null) ...[
|
||||||
const Divider(),
|
const Divider(),
|
||||||
BodyStatRow('Average of all', formatKg(summary.$1)),
|
BodyStatRow.icon(
|
||||||
BodyStatRow(
|
Icons.functions,
|
||||||
|
'Average of all',
|
||||||
|
formatKg(summary.$1),
|
||||||
|
),
|
||||||
|
BodyStatRow.icon(
|
||||||
|
Icons.swap_horiz,
|
||||||
'Ideal range',
|
'Ideal range',
|
||||||
'${oneDecimal(summary.$2)}-${oneDecimal(summary.$3)} kg',
|
'${oneDecimal(summary.$2)}-${oneDecimal(summary.$3)} kg',
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
if (undefined)
|
|
||||||
const BodyNote(
|
|
||||||
'Devine, Robinson and Miller are undefined below 152.4 cm.',
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -89,14 +116,29 @@ class BmrCard extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return BodySection(
|
return BodySection(
|
||||||
title: 'Resting metabolism (BMR)',
|
semanticLabel: 'Resting metabolism (BMR)',
|
||||||
children: [
|
children: [
|
||||||
for (final formula in bmrFormulas(bio, bodyFatPct))
|
for (final formula in bmrFormulas(bio, bodyFatPct))
|
||||||
BodyStatRow(
|
Padding(
|
||||||
formula.name,
|
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2),
|
||||||
formula.value == null
|
child: Row(
|
||||||
? 'n/a -- log a body-fat %'
|
children: [
|
||||||
: '${whole(formula.value!)} kcal',
|
Expanded(child: Text(formula.name)),
|
||||||
|
if (formula.value == null)
|
||||||
|
Icon(
|
||||||
|
Icons.percent,
|
||||||
|
size: 18,
|
||||||
|
color: CueKind.warn.tint(context),
|
||||||
|
semanticLabel: 'n/a -- log a body-fat %',
|
||||||
|
)
|
||||||
|
else
|
||||||
|
MacroFigure(
|
||||||
|
kind: MacroKind.kcal,
|
||||||
|
value: whole(formula.value!),
|
||||||
|
size: 16,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,22 +1,34 @@
|
|||||||
/// The Body screen's overview: two-column metric tiles that fit one phone
|
/// The Body screen's overview: two-column icon tiles that fit one phone
|
||||||
/// screen. Tapping a tile opens the section's full card in a bottom sheet.
|
/// screen. Tapping a tile opens the section's full card in a bottom sheet.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// One tile: a section [title], an optional headline [value], and the
|
/// One tile: a big [icon] (spoken as [semanticLabel]), an optional headline
|
||||||
/// [builder] of the full card shown in the sheet.
|
/// [value] and the [builder] of the full card shown in the sheet.
|
||||||
class BodyTileSpec {
|
class BodyTileSpec {
|
||||||
/// Creates a tile spec.
|
/// Creates a tile spec.
|
||||||
const BodyTileSpec({required this.title, required this.builder, this.value});
|
const BodyTileSpec({
|
||||||
|
required this.semanticLabel,
|
||||||
|
required this.icon,
|
||||||
|
required this.builder,
|
||||||
|
this.value,
|
||||||
|
this.valueIcon,
|
||||||
|
});
|
||||||
|
|
||||||
/// Section name, the same text the full card carries.
|
/// Spoken name of the section; never painted.
|
||||||
final String title;
|
final String semanticLabel;
|
||||||
|
|
||||||
|
/// The section's glyph.
|
||||||
|
final IconData icon;
|
||||||
|
|
||||||
/// Headline number for the tile (null when the section has none).
|
/// Headline number for the tile (null when the section has none).
|
||||||
final String? value;
|
final String? value;
|
||||||
|
|
||||||
|
/// Small glyph in front of [value] (e.g. a bolt for kcal).
|
||||||
|
final IconData? valueIcon;
|
||||||
|
|
||||||
/// Builds the full card for the sheet.
|
/// Builds the full card for the sheet.
|
||||||
final WidgetBuilder builder;
|
final WidgetBuilder builder;
|
||||||
}
|
}
|
||||||
@ -76,33 +88,58 @@ class _Tile extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
|
final value = spec.value;
|
||||||
|
final valueIcon = spec.valueIcon;
|
||||||
return Card(
|
return Card(
|
||||||
margin: EdgeInsets.zero,
|
margin: EdgeInsets.zero,
|
||||||
child: InkWell(
|
child: Semantics(
|
||||||
onTap: () => _open(context),
|
button: true,
|
||||||
borderRadius: BorderRadius.circular(AppRadius.md),
|
label: spec.semanticLabel,
|
||||||
child: Padding(
|
child: InkWell(
|
||||||
padding: const EdgeInsets.all(AppSpacing.sm),
|
onTap: () => _open(context),
|
||||||
child: Column(
|
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
child: Padding(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
padding: const EdgeInsets.all(AppSpacing.sm),
|
||||||
children: [
|
child: Row(
|
||||||
Text(
|
children: [
|
||||||
spec.title,
|
ExcludeSemantics(
|
||||||
maxLines: 2,
|
child: Icon(
|
||||||
overflow: TextOverflow.ellipsis,
|
spec.icon,
|
||||||
style: theme.textTheme.bodyMedium,
|
size: 36,
|
||||||
),
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
if (spec.value != null)
|
|
||||||
Text(
|
|
||||||
spec.value!,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: theme.textTheme.titleMedium?.copyWith(
|
|
||||||
color: theme.colorScheme.primary,
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
// The whole space beside the glyph goes to the value; it
|
||||||
|
// scales down instead of ellipsizing ("70.0 kg" must show).
|
||||||
|
Expanded(
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerRight,
|
||||||
|
child: FittedBox(
|
||||||
|
fit: BoxFit.scaleDown,
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
if (valueIcon != null)
|
||||||
|
Icon(
|
||||||
|
valueIcon,
|
||||||
|
size: 18,
|
||||||
|
color: theme.colorScheme.primary,
|
||||||
|
),
|
||||||
|
if (value != null)
|
||||||
|
Text(
|
||||||
|
value,
|
||||||
|
maxLines: 1,
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
color: theme.colorScheme.primary,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
230
app/lib/widgets/body/dated_value_card.dart
Normal file
230
app/lib/widgets/body/dated_value_card.dart
Normal file
@ -0,0 +1,230 @@
|
|||||||
|
/// Dated-value entry card: save or delete any day, undo a delete, and chart
|
||||||
|
/// the history. Shared by weight and body fat (see `weight_card.dart`).
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/weight_chart.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Enters/deletes a day's value and charts the history.
|
||||||
|
class DatedValueCard extends StatefulWidget {
|
||||||
|
/// Creates the card.
|
||||||
|
const DatedValueCard({
|
||||||
|
required this.semanticLabel,
|
||||||
|
required this.fieldSemanticLabel,
|
||||||
|
required this.icon,
|
||||||
|
required this.unit,
|
||||||
|
required this.min,
|
||||||
|
required this.max,
|
||||||
|
required this.latest,
|
||||||
|
required this.series,
|
||||||
|
required this.onSave,
|
||||||
|
required this.onDelete,
|
||||||
|
required this.onChanged,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Spoken name of the card; never painted.
|
||||||
|
final String semanticLabel;
|
||||||
|
|
||||||
|
/// Spoken name of the input; never painted.
|
||||||
|
final String fieldSemanticLabel;
|
||||||
|
|
||||||
|
/// Glyph captioning the input.
|
||||||
|
final IconData icon;
|
||||||
|
|
||||||
|
/// Unit suffix (`kg`, `%`).
|
||||||
|
final String unit;
|
||||||
|
|
||||||
|
/// Smallest accepted value.
|
||||||
|
final double min;
|
||||||
|
|
||||||
|
/// Largest accepted value.
|
||||||
|
final double max;
|
||||||
|
|
||||||
|
/// Newest `(day, value)`, or null.
|
||||||
|
final (String, double)? latest;
|
||||||
|
|
||||||
|
/// Every live `(day, value)`, oldest first.
|
||||||
|
final List<(String, double)> series;
|
||||||
|
|
||||||
|
/// Writes a value for a day.
|
||||||
|
final Future<void> Function(String day, double value) onSave;
|
||||||
|
|
||||||
|
/// Deletes a day.
|
||||||
|
final Future<void> Function(String day) onDelete;
|
||||||
|
|
||||||
|
/// Called once a value has been written or deleted.
|
||||||
|
final VoidCallback onChanged;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<DatedValueCard> createState() => _DatedValueCardState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DatedValueCardState extends State<DatedValueCard> {
|
||||||
|
final _value = TextEditingController();
|
||||||
|
String _day = localDateKey(DateTime.now());
|
||||||
|
Widget? _status;
|
||||||
|
(String, double)? _undo;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_value.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
String _fmt(double value) => '${oneDecimal(value)} ${widget.unit}';
|
||||||
|
|
||||||
|
Future<void> _pickDay() async {
|
||||||
|
final picked = await pickDate(
|
||||||
|
context: context,
|
||||||
|
firstDate: DateTime(2000),
|
||||||
|
lastDate: DateTime.now(),
|
||||||
|
initialDate: DateTime.parse(_day),
|
||||||
|
);
|
||||||
|
if (picked == null || !mounted) return;
|
||||||
|
setState(() => _day = localDateKey(picked));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _save() async {
|
||||||
|
final value = double.tryParse(_value.text.replaceAll(',', '.'));
|
||||||
|
if (value == null || value < widget.min || value > widget.max) {
|
||||||
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: CueKind.error,
|
||||||
|
icon: widget.icon,
|
||||||
|
semanticLabel:
|
||||||
|
'${widget.semanticLabel} must be ${whole(widget.min)}-'
|
||||||
|
'${whole(widget.max)} ${widget.unit}.',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await widget.onSave(_day, value);
|
||||||
|
if (!mounted) return;
|
||||||
|
_value.clear();
|
||||||
|
setState(() {
|
||||||
|
_undo = null;
|
||||||
|
_status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: CueKind.ok,
|
||||||
|
semanticLabel: 'Saved ${_fmt(value)} for $_day.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
widget.onChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes at once; the undo arrow restores the value that was there.
|
||||||
|
Future<void> _delete() async {
|
||||||
|
final day = _day;
|
||||||
|
final removed = [
|
||||||
|
for (final point in widget.series)
|
||||||
|
if (point.$1 == day) point,
|
||||||
|
];
|
||||||
|
await widget.onDelete(day);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_undo = removed.isEmpty ? null : removed.first;
|
||||||
|
_status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: CueKind.ok,
|
||||||
|
icon: Icons.delete_outline,
|
||||||
|
semanticLabel: 'Deleted $day.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
widget.onChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _restore() async {
|
||||||
|
final undo = _undo;
|
||||||
|
if (undo == null) return;
|
||||||
|
await widget.onSave(undo.$1, undo.$2);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_undo = null;
|
||||||
|
_status = null;
|
||||||
|
});
|
||||||
|
widget.onChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final latest = widget.latest;
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final undo = _undo;
|
||||||
|
return BodySection(
|
||||||
|
semanticLabel: widget.semanticLabel,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
const Icon(Icons.update, size: 18, semanticLabel: 'Latest'),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
if (latest == null)
|
||||||
|
Icon(Icons.block, size: 18, color: scheme.outline)
|
||||||
|
else
|
||||||
|
// Scales down instead of clipping on a narrow sheet.
|
||||||
|
Flexible(
|
||||||
|
child: FittedBox(
|
||||||
|
fit: BoxFit.scaleDown,
|
||||||
|
child: Text('${_fmt(latest.$2)} ${latest.$1}', maxLines: 1),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: IconField(
|
||||||
|
icon: widget.icon,
|
||||||
|
semanticLabel: widget.fieldSemanticLabel,
|
||||||
|
controller: _value,
|
||||||
|
keyboardType: const TextInputType.numberWithOptions(
|
||||||
|
decimal: true,
|
||||||
|
),
|
||||||
|
inputFormatters: [
|
||||||
|
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: _pickDay,
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [const Icon(Icons.event, size: 18), Text(' $_day')],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
if (_status != null) _status! else const SizedBox.shrink(),
|
||||||
|
if (undo != null)
|
||||||
|
IconButton(
|
||||||
|
onPressed: _restore,
|
||||||
|
icon: const Icon(Icons.undo, semanticLabel: 'Undo'),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(
|
||||||
|
Icons.delete_outline,
|
||||||
|
semanticLabel: 'Delete this day',
|
||||||
|
),
|
||||||
|
onPressed: _delete,
|
||||||
|
),
|
||||||
|
IconButton.filled(
|
||||||
|
onPressed: _save,
|
||||||
|
icon: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
WeightChart(series: widget.series),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
65
app/lib/widgets/body/formula_figure.dart
Normal file
65
app/lib/widgets/body/formula_figure.dart
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
/// A kcal formula shown as a glyph + number; its proper name is only the
|
||||||
|
/// glyph's spoken label.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/activity_kcal.dart';
|
||||||
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// One distinct glyph per entry of [activityFormulas].
|
||||||
|
const Map<String, IconData> formulaIcons = {
|
||||||
|
'MET': Icons.speed,
|
||||||
|
'ACSM': Icons.functions,
|
||||||
|
'Per-km': Icons.straighten,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The glyph for formula [name], spoken as the formula's proper name.
|
||||||
|
class FormulaGlyph extends StatelessWidget {
|
||||||
|
/// Creates a glyph for [name].
|
||||||
|
const FormulaGlyph(this.name, {this.size = 16, super.key});
|
||||||
|
|
||||||
|
/// The formula's proper name (a key of [formulaIcons]).
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
/// Glyph size.
|
||||||
|
final double size;
|
||||||
|
|
||||||
|
// The proper name is spoken only: a tooltip paints on long-press.
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Icon(
|
||||||
|
formulaIcons[name],
|
||||||
|
size: size,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: name,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Glyph + number (a trailing `~` marks a figure that reuses the MET value).
|
||||||
|
class FormulaFigure extends StatelessWidget {
|
||||||
|
/// Creates a figure.
|
||||||
|
const FormulaFigure(
|
||||||
|
this.name,
|
||||||
|
this.value, {
|
||||||
|
this.fallback = false,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The formula's proper name.
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
/// The formatted kcal number.
|
||||||
|
final String value;
|
||||||
|
|
||||||
|
/// Whether the figure is a fallback to the MET value.
|
||||||
|
final bool fallback;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
FormulaGlyph(name),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
Text(fallback ? '$value~' : value),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,6 +1,7 @@
|
|||||||
/// The Body screen's top line: "To [lose] [0.5] [kg] / [week] on
|
/// The Body screen's top line as marks instead of a sentence: direction
|
||||||
/// [Moderate] eat 2019 kcal". Every bracket is tappable and opens a picker;
|
/// arrow, amount, unit, per-period calendar, activity glyph, then a bolt and
|
||||||
/// the choice is saved (and synced) immediately. Informational only.
|
/// the daily kcal answer. Every mark is tappable and opens a picker; the
|
||||||
|
/// choice is saved (and synced) immediately. Informational only.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
@ -9,12 +10,15 @@ import 'package:diet_guard_app/services/body_calc.dart';
|
|||||||
import 'package:diet_guard_app/services/body_energy.dart';
|
import 'package:diet_guard_app/services/body_energy.dart';
|
||||||
import 'package:diet_guard_app/services/body_prefs.dart';
|
import 'package:diet_guard_app/services/body_prefs.dart';
|
||||||
import 'package:diet_guard_app/services/body_service.dart';
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/goal_icons.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/goal_pickers.dart';
|
import 'package:diet_guard_app/widgets/body/goal_pickers.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// The goal sentence and its answer.
|
/// The goal row and its answer.
|
||||||
class GoalCard extends StatefulWidget {
|
class GoalCard extends StatefulWidget {
|
||||||
/// Creates the card.
|
/// Creates the card.
|
||||||
const GoalCard({
|
const GoalCard({
|
||||||
@ -47,26 +51,59 @@ class _GoalCardState extends State<GoalCard> {
|
|||||||
await setGoal(BodyService.instance, picked);
|
await setGoal(BodyService.instance, picked);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _choice(String text, Future<Goal?> Function(BuildContext, Goal) p) {
|
/// A bordered, tappable mark spoken as [spoken]; [child] is its look.
|
||||||
|
Widget _choice(
|
||||||
|
String spoken,
|
||||||
|
Widget child,
|
||||||
|
Future<Goal?> Function(BuildContext, Goal) picker,
|
||||||
|
) {
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
return InkWell(
|
return Semantics(
|
||||||
onTap: () => unawaited(_pick(p)),
|
button: true,
|
||||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
label: spoken,
|
||||||
child: Padding(
|
child: InkWell(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xs),
|
onTap: () => unawaited(_pick(picker)),
|
||||||
child: Text(
|
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||||
text,
|
child: Container(
|
||||||
style: TextStyle(
|
padding: const EdgeInsets.symmetric(
|
||||||
color: scheme.primary,
|
horizontal: AppSpacing.sm,
|
||||||
fontWeight: FontWeight.w600,
|
vertical: AppSpacing.xs,
|
||||||
decoration: TextDecoration.underline,
|
),
|
||||||
decorationColor: scheme.primary,
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||||
|
border: Border.all(color: scheme.outline),
|
||||||
|
),
|
||||||
|
child: ExcludeSemantics(
|
||||||
|
child: DefaultTextStyle.merge(
|
||||||
|
style: TextStyle(
|
||||||
|
color: scheme.primary,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
child: IconTheme.merge(
|
||||||
|
data: IconThemeData(color: scheme.primary),
|
||||||
|
child: child,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Widget _iconChoice(
|
||||||
|
String spoken,
|
||||||
|
IconData icon,
|
||||||
|
Future<Goal?> Function(BuildContext, Goal) picker, {
|
||||||
|
String? caption,
|
||||||
|
}) => _choice(
|
||||||
|
spoken,
|
||||||
|
Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [Icon(icon), if (caption != null) Text(caption)],
|
||||||
|
),
|
||||||
|
picker,
|
||||||
|
);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
@ -76,51 +113,81 @@ class _GoalCardState extends State<GoalCard> {
|
|||||||
final tdee = target.tdee;
|
final tdee = target.tdee;
|
||||||
final maintain = _goal.direction == 'maintain';
|
final maintain = _goal.direction == 'maintain';
|
||||||
return BodySection(
|
return BodySection(
|
||||||
title: 'Daily calorie target',
|
semanticLabel: 'Daily calorie target',
|
||||||
children: [
|
children: [
|
||||||
Wrap(
|
Wrap(
|
||||||
crossAxisAlignment: WrapCrossAlignment.center,
|
crossAxisAlignment: WrapCrossAlignment.center,
|
||||||
runSpacing: AppSpacing.xs,
|
spacing: AppSpacing.sm,
|
||||||
|
runSpacing: AppSpacing.sm,
|
||||||
children: [
|
children: [
|
||||||
const Text('To'),
|
_iconChoice(
|
||||||
_choice(_goal.direction, pickDirection),
|
_goal.direction,
|
||||||
|
directionIcon(_goal.direction),
|
||||||
|
pickDirection,
|
||||||
|
),
|
||||||
if (!maintain) ...[
|
if (!maintain) ...[
|
||||||
_choice(formatG(_goal.amount), pickAmount),
|
_choice(
|
||||||
_choice(_goal.weightUnit, pickWeightUnit),
|
formatG(_goal.amount),
|
||||||
const Text('/'),
|
Text(formatG(_goal.amount)),
|
||||||
_choice(_goal.timeUnit, pickTimeUnit),
|
pickAmount,
|
||||||
],
|
),
|
||||||
const Text('on'),
|
_choice(_goal.weightUnit, Text(_goal.weightUnit), pickWeightUnit),
|
||||||
_choice(activityLabel(_goal.activity), pickActivity),
|
_iconChoice(
|
||||||
if (kcal != null) ...[
|
_goal.timeUnit,
|
||||||
const Text('eat '),
|
timeUnitIcon(_goal.timeUnit),
|
||||||
Text(
|
pickTimeUnit,
|
||||||
'$kcal',
|
|
||||||
style: theme.textTheme.headlineMedium?.copyWith(
|
|
||||||
color: theme.colorScheme.primary,
|
|
||||||
fontWeight: FontWeight.w700,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
const Text(' kcal'),
|
|
||||||
],
|
],
|
||||||
|
_iconChoice(
|
||||||
|
activityLabel(_goal.activity),
|
||||||
|
activityIcon(_goal.activity),
|
||||||
|
pickActivity,
|
||||||
|
caption: activityCaption(_goal.activity),
|
||||||
|
),
|
||||||
|
if (kcal != null)
|
||||||
|
Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(MacroKind.kcal.icon, color: theme.colorScheme.primary),
|
||||||
|
Text(
|
||||||
|
'$kcal',
|
||||||
|
style: theme.textTheme.headlineMedium?.copyWith(
|
||||||
|
color: theme.colorScheme.primary,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
if (kcal == null)
|
if (kcal == null)
|
||||||
const BodyNote('no workouts published yet (the PC publishes them).'),
|
const StatusCue(
|
||||||
|
kind: CueKind.warn,
|
||||||
|
icon: Icons.directions_run,
|
||||||
|
semanticLabel: 'no workouts published yet (the PC publishes them).',
|
||||||
|
),
|
||||||
if (target.belowFloor)
|
if (target.belowFloor)
|
||||||
Text(
|
const StatusCue(
|
||||||
'That is below the $minTargetKcal kcal floor.',
|
kind: CueKind.error,
|
||||||
style: TextStyle(color: theme.colorScheme.error),
|
icon: Icons.vertical_align_bottom,
|
||||||
|
semanticLabel: 'That is below the $minTargetKcal kcal floor.',
|
||||||
),
|
),
|
||||||
if (tdee != null)
|
if (tdee != null)
|
||||||
BodyNote(
|
Row(
|
||||||
'Maintenance ${whole(tdee)} kcal (${target.bmrName} resting '
|
children: [
|
||||||
'burn x activity); 1 kg of fat = ${formatG(kcalPerKg)} kcal.',
|
Icon(
|
||||||
|
Icons.balance,
|
||||||
|
size: 18,
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Maintenance',
|
||||||
|
),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
MacroFigure(kind: MacroKind.kcal, value: whole(tdee), size: 16),
|
||||||
|
const SizedBox(width: AppSpacing.sm),
|
||||||
|
Text(target.bmrName),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
const BodyNote(
|
|
||||||
'Informational only — the budget is never changed from here.',
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
45
app/lib/widgets/body/goal_icons.dart
Normal file
45
app/lib/widgets/body/goal_icons.dart
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
/// Glyphs for the goal's enumerations (direction, time unit, activity), so
|
||||||
|
/// the goal reads as a row of icons and numbers instead of a sentence.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/body_energy.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/body/formula_figure.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Lose = down arrow, maintain = level bar, gain = up arrow.
|
||||||
|
IconData directionIcon(String direction) => switch (direction) {
|
||||||
|
'lose' => Icons.south,
|
||||||
|
'gain' => Icons.north,
|
||||||
|
_ => Icons.drag_handle,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Day / week / month / year as calendar views of growing span.
|
||||||
|
IconData timeUnitIcon(String unit) => switch (unit) {
|
||||||
|
'day' => Icons.calendar_view_day,
|
||||||
|
'week' => Icons.calendar_view_week,
|
||||||
|
'month' => Icons.calendar_view_month,
|
||||||
|
_ => Icons.event_repeat,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The five levels ramp from a chair to a barbell; a measured choice wears
|
||||||
|
/// its formula's glyph (the same one the Activity sheet shows next to kcal).
|
||||||
|
IconData activityIcon(String key) => switch (key) {
|
||||||
|
'sedentary' => Icons.chair,
|
||||||
|
'light' => Icons.directions_walk,
|
||||||
|
'moderate' => Icons.directions_bike,
|
||||||
|
'very' => Icons.directions_run,
|
||||||
|
'extra' => Icons.fitness_center,
|
||||||
|
_ when key.startsWith(measuredPrefix) =>
|
||||||
|
formulaIcons[key.substring(measuredPrefix.length)] ?? Icons.speed,
|
||||||
|
_ => Icons.speed,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Numeric caption under an activity icon: the TDEE multiplier of a level.
|
||||||
|
/// Null for a measured formula (its glyph names it; the proper name is only
|
||||||
|
/// spoken) and for an unknown key.
|
||||||
|
String? activityCaption(String key) {
|
||||||
|
for (final level in activityLevels) {
|
||||||
|
if (level.key == key) return formatG(level.factor);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@ -1,71 +1,141 @@
|
|||||||
/// The pickers behind each tappable word of the goal sentence.
|
/// The pickers behind each tappable mark of the goal row.
|
||||||
///
|
///
|
||||||
/// Each returns the edited [Goal], or null when dismissed.
|
/// Each returns the edited [Goal], or null when dismissed. Options are icons
|
||||||
|
/// (plus a number or proper name where one exists); the spoken name of every
|
||||||
|
/// option is its semantic label.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/services/body_energy.dart';
|
import 'package:diet_guard_app/services/body_energy.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/widgets/body/goal_icons.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// One choice in a picker sheet.
|
||||||
|
typedef PickerOption = ({
|
||||||
|
String value,
|
||||||
|
String spoken,
|
||||||
|
IconData icon,
|
||||||
|
String? caption,
|
||||||
|
});
|
||||||
|
|
||||||
Future<String?> _sheet(
|
Future<String?> _sheet(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
String title,
|
List<PickerOption> options,
|
||||||
List<(String, String, String?)> options,
|
|
||||||
String selected,
|
String selected,
|
||||||
) => showModalBottomSheet<String>(
|
) => showModalBottomSheet<String>(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => SafeArea(
|
builder: (context) => SafeArea(
|
||||||
child: ListView(
|
child: Padding(
|
||||||
shrinkWrap: true,
|
padding: const EdgeInsets.all(AppSpacing.md),
|
||||||
children: [
|
child: Wrap(
|
||||||
ListTile(title: Text(title)),
|
spacing: AppSpacing.sm,
|
||||||
for (final (value, label, subtitle) in options)
|
runSpacing: AppSpacing.sm,
|
||||||
ListTile(
|
children: [
|
||||||
title: Text(label),
|
for (final option in options)
|
||||||
subtitle: subtitle == null ? null : Text(subtitle),
|
_OptionButton(
|
||||||
selected: value == selected,
|
option: option,
|
||||||
trailing: value == selected ? const Icon(Icons.check) : null,
|
selected: option.value == selected,
|
||||||
onTap: () => Navigator.of(context).pop(value),
|
onTap: () => Navigator.of(context).pop(option.value),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
class _OptionButton extends StatelessWidget {
|
||||||
|
const _OptionButton({
|
||||||
|
required this.option,
|
||||||
|
required this.selected,
|
||||||
|
required this.onTap,
|
||||||
|
});
|
||||||
|
|
||||||
|
final PickerOption option;
|
||||||
|
final bool selected;
|
||||||
|
final VoidCallback onTap;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final tint = selected ? scheme.primary : scheme.onSurfaceVariant;
|
||||||
|
return Semantics(
|
||||||
|
button: true,
|
||||||
|
selected: selected,
|
||||||
|
label: option.spoken,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: onTap,
|
||||||
|
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||||
|
child: Container(
|
||||||
|
width: 72,
|
||||||
|
padding: const EdgeInsets.all(AppSpacing.sm),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||||
|
border: Border.all(
|
||||||
|
color: selected ? scheme.primary : scheme.outline,
|
||||||
|
),
|
||||||
|
color: selected ? scheme.primary.withValues(alpha: 0.16) : null,
|
||||||
|
),
|
||||||
|
child: ExcludeSemantics(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(option.icon, color: tint, size: 28),
|
||||||
|
if (option.caption != null)
|
||||||
|
Text(
|
||||||
|
option.caption!,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(color: tint),
|
||||||
|
),
|
||||||
|
if (selected)
|
||||||
|
Icon(Icons.check, size: 14, color: scheme.primary),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Lose / maintain / gain.
|
/// Lose / maintain / gain.
|
||||||
Future<Goal?> pickDirection(BuildContext context, Goal goal) async {
|
Future<Goal?> pickDirection(BuildContext context, Goal goal) async {
|
||||||
final value = await _sheet(context, 'Direction', [
|
final value = await _sheet(context, [
|
||||||
for (final d in directions) (d, d, null),
|
for (final d in directions)
|
||||||
|
(value: d, spoken: d, icon: directionIcon(d), caption: null),
|
||||||
], goal.direction);
|
], goal.direction);
|
||||||
return value == null ? null : goal.copyWith(direction: value);
|
return value == null ? null : goal.copyWith(direction: value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Kilograms, pounds, grams or stones.
|
/// Kilograms, pounds, grams or stones (the unit symbols are the captions).
|
||||||
Future<Goal?> pickWeightUnit(BuildContext context, Goal goal) async {
|
Future<Goal?> pickWeightUnit(BuildContext context, Goal goal) async {
|
||||||
final value = await _sheet(context, 'Weight unit', [
|
final value = await _sheet(context, [
|
||||||
for (final u in weightUnits.keys) (u, u, null),
|
for (final u in weightUnits.keys)
|
||||||
|
(value: u, spoken: u, icon: Icons.scale, caption: u),
|
||||||
], goal.weightUnit);
|
], goal.weightUnit);
|
||||||
return value == null ? null : goal.copyWith(weightUnit: value);
|
return value == null ? null : goal.copyWith(weightUnit: value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Per day, week, month or year.
|
/// Per day, week, month or year.
|
||||||
Future<Goal?> pickTimeUnit(BuildContext context, Goal goal) async {
|
Future<Goal?> pickTimeUnit(BuildContext context, Goal goal) async {
|
||||||
final value = await _sheet(context, 'Per', [
|
final value = await _sheet(context, [
|
||||||
for (final u in timeUnits.keys) (u, u, null),
|
for (final u in timeUnits.keys)
|
||||||
|
(value: u, spoken: u, icon: timeUnitIcon(u), caption: null),
|
||||||
], goal.timeUnit);
|
], goal.timeUnit);
|
||||||
return value == null ? null : goal.copyWith(timeUnit: value);
|
return value == null ? null : goal.copyWith(timeUnit: value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The five levels, then the three measured formulas.
|
/// The five levels, then the three measured formulas.
|
||||||
Future<Goal?> pickActivity(BuildContext context, Goal goal) async {
|
Future<Goal?> pickActivity(BuildContext context, Goal goal) async {
|
||||||
final meaning = {for (final l in activityLevels) l.key: l.meaning};
|
final value = await _sheet(context, [
|
||||||
final value = await _sheet(context, 'Activity', [
|
|
||||||
for (final key in activityChoices)
|
for (final key in activityChoices)
|
||||||
(
|
(
|
||||||
key,
|
value: key,
|
||||||
activityLabel(key),
|
spoken: activityLabel(key),
|
||||||
meaning[key] ?? 'BMR x 1.2 + your real workouts and steps',
|
icon: activityIcon(key),
|
||||||
|
caption: activityCaption(key),
|
||||||
),
|
),
|
||||||
], goal.activity);
|
], goal.activity);
|
||||||
return value == null ? null : goal.copyWith(activity: value);
|
return value == null ? null : goal.copyWith(activity: value);
|
||||||
@ -95,6 +165,7 @@ class _AmountDialogState extends State<_AmountDialog> {
|
|||||||
late final _controller = TextEditingController(
|
late final _controller = TextEditingController(
|
||||||
text: formatG(widget.goal.amount),
|
text: formatG(widget.goal.amount),
|
||||||
);
|
);
|
||||||
|
bool _rejected = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
@ -104,14 +175,17 @@ class _AmountDialogState extends State<_AmountDialog> {
|
|||||||
|
|
||||||
void _submit() {
|
void _submit() {
|
||||||
final typed = double.tryParse(_controller.text.replaceAll(',', '.'));
|
final typed = double.tryParse(_controller.text.replaceAll(',', '.'));
|
||||||
if (typed != null && typed >= 0) Navigator.of(context).pop(typed);
|
if (typed != null && typed >= 0) {
|
||||||
|
Navigator.of(context).pop(typed);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() => _rejected = true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final goal = widget.goal;
|
final goal = widget.goal;
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
title: Text('How much (${goal.weightUnit} / ${goal.timeUnit})'),
|
|
||||||
content: Column(
|
content: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
@ -126,23 +200,29 @@ class _AmountDialogState extends State<_AmountDialog> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.edit,
|
||||||
|
semanticLabel: 'Other amount',
|
||||||
controller: _controller,
|
controller: _controller,
|
||||||
decoration: const InputDecoration(labelText: 'Other amount'),
|
|
||||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
inputFormatters: [
|
inputFormatters: [
|
||||||
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
||||||
],
|
],
|
||||||
onSubmitted: (_) => _submit(),
|
onSubmitted: (_) => _submit(),
|
||||||
),
|
),
|
||||||
|
if (_rejected)
|
||||||
|
const StatusCue(kind: CueKind.error, semanticLabel: 'not a number'),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
IconButton(
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
child: const Text('Cancel'),
|
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||||
|
),
|
||||||
|
IconButton.filled(
|
||||||
|
onPressed: _submit,
|
||||||
|
icon: const Icon(Icons.check, semanticLabel: 'OK'),
|
||||||
),
|
),
|
||||||
FilledButton(onPressed: _submit, child: const Text('OK')),
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,10 +3,12 @@ library;
|
|||||||
|
|
||||||
import 'package:diet_guard_app/models/local_time.dart';
|
import 'package:diet_guard_app/models/local_time.dart';
|
||||||
import 'package:diet_guard_app/services/body_service.dart';
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Edits the profile; calls [onSaved] after a successful save.
|
/// Edits the profile; calls [onSaved] after a successful save.
|
||||||
class ProfileCard extends StatefulWidget {
|
class ProfileCard extends StatefulWidget {
|
||||||
@ -24,7 +26,7 @@ class _ProfileCardState extends State<ProfileCard> {
|
|||||||
final _height = TextEditingController();
|
final _height = TextEditingController();
|
||||||
String? _birth;
|
String? _birth;
|
||||||
String? _sex;
|
String? _sex;
|
||||||
String? _status;
|
Widget? _status;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@ -45,7 +47,7 @@ class _ProfileCardState extends State<ProfileCard> {
|
|||||||
Future<void> _pickBirth() async {
|
Future<void> _pickBirth() async {
|
||||||
final now = DateTime.now();
|
final now = DateTime.now();
|
||||||
final initial = DateTime.tryParse(_birth ?? '') ?? DateTime(now.year - 30);
|
final initial = DateTime.tryParse(_birth ?? '') ?? DateTime(now.year - 30);
|
||||||
final picked = await showDatePicker(
|
final picked = await pickDate(
|
||||||
context: context,
|
context: context,
|
||||||
firstDate: DateTime(1900),
|
firstDate: DateTime(1900),
|
||||||
lastDate: now,
|
lastDate: now,
|
||||||
@ -59,7 +61,14 @@ class _ProfileCardState extends State<ProfileCard> {
|
|||||||
Future<void> _save() async {
|
Future<void> _save() async {
|
||||||
final height = double.tryParse(_height.text.replaceAll(',', '.'));
|
final height = double.tryParse(_height.text.replaceAll(',', '.'));
|
||||||
if (height == null || height < 50 || height > 260) {
|
if (height == null || height < 50 || height > 260) {
|
||||||
setState(() => _status = 'Height must be 50-260 cm.');
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: CueKind.error,
|
||||||
|
icon: Icons.height,
|
||||||
|
semanticLabel: 'Height must be 50-260 cm.',
|
||||||
|
),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await BodyService.instance.setProfile(
|
await BodyService.instance.setProfile(
|
||||||
@ -68,28 +77,45 @@ class _ProfileCardState extends State<ProfileCard> {
|
|||||||
sex: _sex,
|
sex: _sex,
|
||||||
);
|
);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _status = 'Saved.');
|
setState(
|
||||||
|
() => _status = StatusCue(
|
||||||
|
key: UniqueKey(),
|
||||||
|
kind: CueKind.ok,
|
||||||
|
semanticLabel: 'Saved.',
|
||||||
|
),
|
||||||
|
);
|
||||||
widget.onSaved();
|
widget.onSaved();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final birth = _birth;
|
||||||
|
final status = _status;
|
||||||
return BodySection(
|
return BodySection(
|
||||||
title: 'Profile',
|
semanticLabel: 'Profile',
|
||||||
children: [
|
children: [
|
||||||
Row(
|
Align(
|
||||||
children: [
|
alignment: Alignment.centerLeft,
|
||||||
Expanded(child: Text('Born: ${_birth ?? 'not set'}')),
|
child: TextButton(
|
||||||
TextButton.icon(
|
onPressed: _pickBirth,
|
||||||
icon: const Icon(Icons.cake),
|
child: Row(
|
||||||
label: const Text('Birth date'),
|
mainAxisSize: MainAxisSize.min,
|
||||||
onPressed: _pickBirth,
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.cake,
|
||||||
|
color: birth == null ? scheme.error : null,
|
||||||
|
semanticLabel: 'Birth date',
|
||||||
|
),
|
||||||
|
if (birth != null) Text(' $birth'),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
],
|
),
|
||||||
),
|
),
|
||||||
TextField(
|
IconField(
|
||||||
|
icon: Icons.height,
|
||||||
|
semanticLabel: 'Height (cm)',
|
||||||
controller: _height,
|
controller: _height,
|
||||||
decoration: const InputDecoration(labelText: 'Height (cm)'),
|
|
||||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
inputFormatters: [
|
inputFormatters: [
|
||||||
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
||||||
@ -97,9 +123,16 @@ class _ProfileCardState extends State<ProfileCard> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
SegmentedButton<String>(
|
SegmentedButton<String>(
|
||||||
|
showSelectedIcon: false,
|
||||||
segments: const [
|
segments: const [
|
||||||
ButtonSegment(value: 'm', label: Text('Male')),
|
ButtonSegment(
|
||||||
ButtonSegment(value: 'f', label: Text('Female')),
|
value: 'm',
|
||||||
|
icon: Icon(Icons.male, semanticLabel: 'Male'),
|
||||||
|
),
|
||||||
|
ButtonSegment(
|
||||||
|
value: 'f',
|
||||||
|
icon: Icon(Icons.female, semanticLabel: 'Female'),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
selected: {?_sex},
|
selected: {?_sex},
|
||||||
emptySelectionAllowed: true,
|
emptySelectionAllowed: true,
|
||||||
@ -109,8 +142,11 @@ class _ProfileCardState extends State<ProfileCard> {
|
|||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Expanded(child: BodyNote(_status ?? 'Syncs to the PC.')),
|
if (status != null) Expanded(child: status) else const Spacer(),
|
||||||
FilledButton(onPressed: _save, child: const Text('Save profile')),
|
IconButton.filled(
|
||||||
|
onPressed: _save,
|
||||||
|
icon: const Icon(Icons.check, semanticLabel: 'Save profile'),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@ -4,11 +4,14 @@
|
|||||||
/// day overrides it (a planned feast on Saturday too).
|
/// day overrides it (a planned feast on Saturday too).
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/services/body_energy.dart';
|
||||||
import 'package:diet_guard_app/services/week_plan.dart';
|
import 'package:diet_guard_app/services/week_plan.dart';
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// The planner.
|
/// The planner.
|
||||||
class WeekPlanCard extends StatefulWidget {
|
class WeekPlanCard extends StatefulWidget {
|
||||||
@ -53,8 +56,7 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final target = int.tryParse(_target.text) ?? widget.defaultTarget;
|
final target = int.tryParse(_target.text) ?? widget.defaultTarget;
|
||||||
final typed = <int, int>{
|
final typed = <int, int>{
|
||||||
for (var i = 0; i < 7; i++)
|
for (var i = 0; i < 7; i++) i: ?int.tryParse(_days[i].text),
|
||||||
i: ?int.tryParse(_days[i].text),
|
|
||||||
};
|
};
|
||||||
final plan = planWeek(
|
final plan = planWeek(
|
||||||
widget.today ?? DateTime.now(),
|
widget.today ?? DateTime.now(),
|
||||||
@ -64,41 +66,39 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
|
|||||||
);
|
);
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
return BodySection(
|
return BodySection(
|
||||||
title: 'Week planner (info only)',
|
semanticLabel: 'Week planner',
|
||||||
children: [
|
children: [
|
||||||
TextField(
|
SpokenLabel(
|
||||||
controller: _target,
|
semanticLabel: 'Weekly average target (kcal/day)',
|
||||||
decoration: InputDecoration(
|
child: TextField(
|
||||||
labelText: 'Weekly average target (kcal/day)',
|
controller: _target,
|
||||||
hintText: '${widget.defaultTarget}',
|
decoration: InputDecoration(
|
||||||
|
prefixIcon: ExcludeSemantics(
|
||||||
|
child: Icon(MacroKind.kcal.icon, color: MacroKind.kcal.color),
|
||||||
|
),
|
||||||
|
hintText: '${widget.defaultTarget}',
|
||||||
|
),
|
||||||
|
keyboardType: TextInputType.number,
|
||||||
|
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||||
|
onChanged: (_) => setState(() {}),
|
||||||
),
|
),
|
||||||
keyboardType: TextInputType.number,
|
|
||||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
|
||||||
onChanged: (_) => setState(() {}),
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
for (var i = 0; i < 7; i++)
|
for (var i = 0; i < 7; i++)
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
SizedBox(width: 48, child: Text(plan.days[i].weekday)),
|
// Day of month, not a weekday word: rows run Monday..Sunday.
|
||||||
|
SizedBox(width: 32, child: Text(plan.days[i].day.substring(8))),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: _DayFigure(plan.days[i], belowFloor: plan.belowFloor),
|
||||||
'${plan.days[i].kcal} kcal ${_sourceLabel(plan.days[i])}',
|
|
||||||
style: TextStyle(
|
|
||||||
color: plan.days[i].source == 'plan' && plan.belowFloor
|
|
||||||
? scheme.error
|
|
||||||
: null,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: 96,
|
width: 96,
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: Icons.rice_bowl,
|
||||||
|
semanticLabel: 'ate…',
|
||||||
controller: _days[i],
|
controller: _days[i],
|
||||||
decoration: const InputDecoration(
|
dense: true,
|
||||||
hintText: 'ate…',
|
|
||||||
isDense: true,
|
|
||||||
),
|
|
||||||
keyboardType: TextInputType.number,
|
keyboardType: TextInputType.number,
|
||||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||||
onChanged: (_) => setState(() {}),
|
onChanged: (_) => setState(() {}),
|
||||||
@ -107,26 +107,86 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: AppSpacing.sm),
|
const SizedBox(height: AppSpacing.sm),
|
||||||
BodyNote(_summary(plan)),
|
_Summary(plan, scheme),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String _sourceLabel(DayPlan day) => switch (day.source) {
|
/// A day's kcal with a glyph for where the number came from.
|
||||||
'typed' => '(typed)',
|
class _DayFigure extends StatelessWidget {
|
||||||
'logged' => '(logged)',
|
const _DayFigure(this.day, {required this.belowFloor});
|
||||||
'unlogged' => '(not logged -- type it)',
|
|
||||||
_ => '(plan)',
|
|
||||||
};
|
|
||||||
|
|
||||||
String _summary(WeekPlan plan) {
|
final DayPlan day;
|
||||||
final per = plan.perRemaining;
|
final bool belowFloor;
|
||||||
if (per == null) {
|
|
||||||
return 'Every day is known: week average '
|
@override
|
||||||
'${whole(plan.weekAvg)} kcal.';
|
Widget build(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final (icon, spoken) = switch (day.source) {
|
||||||
|
'typed' => (Icons.edit, '(typed)'),
|
||||||
|
'logged' => (Icons.check, '(logged)'),
|
||||||
|
'unlogged' => (Icons.help_outline, '(not logged -- type it)'),
|
||||||
|
_ => (Icons.insights, '(plan)'),
|
||||||
|
};
|
||||||
|
final bad = day.source == 'plan' && belowFloor;
|
||||||
|
final unlogged = day.source == 'unlogged';
|
||||||
|
final tint = bad
|
||||||
|
? scheme.error
|
||||||
|
: unlogged
|
||||||
|
? CueKind.warn.tint(context)
|
||||||
|
: null;
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
MacroFigure(kind: MacroKind.kcal, value: '${day.kcal}', size: 16),
|
||||||
|
const SizedBox(width: AppSpacing.sm),
|
||||||
|
Icon(icon, size: 16, color: tint, semanticLabel: spoken),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What to eat on the open days, or the finished week's average.
|
||||||
|
class _Summary extends StatelessWidget {
|
||||||
|
const _Summary(this.plan, this.scheme);
|
||||||
|
|
||||||
|
final WeekPlan plan;
|
||||||
|
final ColorScheme scheme;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final per = plan.perRemaining;
|
||||||
|
if (per == null) {
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.check_circle,
|
||||||
|
color: CueKind.ok.tint(context),
|
||||||
|
semanticLabel: 'Every day is known: week average',
|
||||||
|
),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
MacroFigure(kind: MacroKind.kcal, value: whole(plan.weekAvg)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
const Icon(Icons.restaurant, size: 18, semanticLabel: 'Eat'),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
MacroFigure(kind: MacroKind.kcal, value: '$per'),
|
||||||
|
const SizedBox(width: AppSpacing.md),
|
||||||
|
const Icon(Icons.flag_outlined, size: 18, semanticLabel: 'average'),
|
||||||
|
const SizedBox(width: AppSpacing.xs),
|
||||||
|
Text('${plan.targetAvg}'),
|
||||||
|
if (plan.belowFloor) ...[
|
||||||
|
const SizedBox(width: AppSpacing.md),
|
||||||
|
const StatusCue(
|
||||||
|
kind: CueKind.error,
|
||||||
|
icon: Icons.vertical_align_bottom,
|
||||||
|
semanticLabel: 'below the $minTargetKcal kcal floor',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
}
|
}
|
||||||
final floor = plan.belowFloor ? ' -- below the 1200 kcal floor!' : '';
|
|
||||||
return 'Eat $per kcal on each open day to average '
|
|
||||||
'${plan.targetAvg}$floor';
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,12 +5,11 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/body_document.dart';
|
import 'package:diet_guard_app/models/body_document.dart';
|
||||||
import 'package:diet_guard_app/models/local_time.dart';
|
|
||||||
import 'package:diet_guard_app/services/body_service.dart';
|
import 'package:diet_guard_app/services/body_service.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
import 'package:diet_guard_app/widgets/body/dated_value_card.dart';
|
||||||
import 'package:diet_guard_app/widgets/body/weight_chart.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
export 'package:diet_guard_app/widgets/body/dated_value_card.dart';
|
||||||
|
|
||||||
/// Weight: 20-400 kg; wake-alarm weigh-ins land here too.
|
/// Weight: 20-400 kg; wake-alarm weigh-ins land here too.
|
||||||
class WeightCard extends StatelessWidget {
|
class WeightCard extends StatelessWidget {
|
||||||
@ -24,12 +23,12 @@ class WeightCard extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final body = BodyService.instance;
|
final body = BodyService.instance;
|
||||||
return DatedValueCard(
|
return DatedValueCard(
|
||||||
title: 'Weight',
|
semanticLabel: 'Weight',
|
||||||
fieldLabel: 'Weight (kg)',
|
fieldSemanticLabel: 'Weight (kg)',
|
||||||
|
icon: Icons.monitor_weight,
|
||||||
unit: 'kg',
|
unit: 'kg',
|
||||||
min: 20,
|
min: 20,
|
||||||
max: 400,
|
max: 400,
|
||||||
hint: 'Morning weigh-ins from wake-alarm appear here.',
|
|
||||||
latest: body.latestWeight,
|
latest: body.latestWeight,
|
||||||
series: body.weightSeries,
|
series: body.weightSeries,
|
||||||
onSave: body.setWeight,
|
onSave: body.setWeight,
|
||||||
@ -51,12 +50,12 @@ class BodyFatCard extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final body = BodyService.instance;
|
final body = BodyService.instance;
|
||||||
return DatedValueCard(
|
return DatedValueCard(
|
||||||
title: 'Body fat',
|
semanticLabel: 'Body fat',
|
||||||
fieldLabel: 'Body fat (%)',
|
fieldSemanticLabel: 'Body fat (%)',
|
||||||
|
icon: Icons.percent,
|
||||||
unit: '%',
|
unit: '%',
|
||||||
min: minBodyFat,
|
min: minBodyFat,
|
||||||
max: maxBodyFat,
|
max: maxBodyFat,
|
||||||
hint: 'With a body fat %, targets use the lean-mass (Katch-McArdle) BMR.',
|
|
||||||
latest: body.latestBodyFat,
|
latest: body.latestBodyFat,
|
||||||
series: body.bodyFatSeries,
|
series: body.bodyFatSeries,
|
||||||
onSave: body.setBodyFat,
|
onSave: body.setBodyFat,
|
||||||
@ -65,150 +64,3 @@ class BodyFatCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Enters/deletes a day's value and charts the history.
|
|
||||||
class DatedValueCard extends StatefulWidget {
|
|
||||||
/// Creates the card.
|
|
||||||
const DatedValueCard({
|
|
||||||
required this.title,
|
|
||||||
required this.fieldLabel,
|
|
||||||
required this.unit,
|
|
||||||
required this.min,
|
|
||||||
required this.max,
|
|
||||||
required this.hint,
|
|
||||||
required this.latest,
|
|
||||||
required this.series,
|
|
||||||
required this.onSave,
|
|
||||||
required this.onDelete,
|
|
||||||
required this.onChanged,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Section heading.
|
|
||||||
final String title;
|
|
||||||
|
|
||||||
/// Input label.
|
|
||||||
final String fieldLabel;
|
|
||||||
|
|
||||||
/// Unit suffix (`kg`, `%`).
|
|
||||||
final String unit;
|
|
||||||
|
|
||||||
/// Smallest accepted value.
|
|
||||||
final double min;
|
|
||||||
|
|
||||||
/// Largest accepted value.
|
|
||||||
final double max;
|
|
||||||
|
|
||||||
/// Note shown until something is saved.
|
|
||||||
final String hint;
|
|
||||||
|
|
||||||
/// Newest `(day, value)`, or null.
|
|
||||||
final (String, double)? latest;
|
|
||||||
|
|
||||||
/// Every live `(day, value)`, oldest first.
|
|
||||||
final List<(String, double)> series;
|
|
||||||
|
|
||||||
/// Writes a value for a day.
|
|
||||||
final Future<void> Function(String day, double value) onSave;
|
|
||||||
|
|
||||||
/// Deletes a day.
|
|
||||||
final Future<void> Function(String day) onDelete;
|
|
||||||
|
|
||||||
/// Called once a value has been written or deleted.
|
|
||||||
final VoidCallback onChanged;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<DatedValueCard> createState() => _DatedValueCardState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _DatedValueCardState extends State<DatedValueCard> {
|
|
||||||
final _value = TextEditingController();
|
|
||||||
String _day = localDateKey(DateTime.now());
|
|
||||||
String? _status;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_value.dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
String _fmt(double value) => '${oneDecimal(value)} ${widget.unit}';
|
|
||||||
|
|
||||||
Future<void> _pickDay() async {
|
|
||||||
final picked = await showDatePicker(
|
|
||||||
context: context,
|
|
||||||
firstDate: DateTime(2000),
|
|
||||||
lastDate: DateTime.now(),
|
|
||||||
initialDate: DateTime.parse(_day),
|
|
||||||
);
|
|
||||||
if (picked == null || !mounted) return;
|
|
||||||
setState(() => _day = localDateKey(picked));
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _save() async {
|
|
||||||
final value = double.tryParse(_value.text.replaceAll(',', '.'));
|
|
||||||
if (value == null || value < widget.min || value > widget.max) {
|
|
||||||
setState(
|
|
||||||
() => _status =
|
|
||||||
'${widget.title} must be ${whole(widget.min)}-'
|
|
||||||
'${whole(widget.max)} ${widget.unit}.',
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await widget.onSave(_day, value);
|
|
||||||
if (!mounted) return;
|
|
||||||
_value.clear();
|
|
||||||
setState(() => _status = 'Saved ${_fmt(value)} for $_day.');
|
|
||||||
widget.onChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _delete() async {
|
|
||||||
await widget.onDelete(_day);
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() => _status = 'Deleted $_day.');
|
|
||||||
widget.onChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final latest = widget.latest;
|
|
||||||
return BodySection(
|
|
||||||
title: widget.title,
|
|
||||||
children: [
|
|
||||||
BodyStatRow(
|
|
||||||
'Latest',
|
|
||||||
latest == null ? 'none yet' : '${_fmt(latest.$2)} (${latest.$1})',
|
|
||||||
),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: TextField(
|
|
||||||
controller: _value,
|
|
||||||
decoration: InputDecoration(labelText: widget.fieldLabel),
|
|
||||||
keyboardType: const TextInputType.numberWithOptions(
|
|
||||||
decimal: true,
|
|
||||||
),
|
|
||||||
inputFormatters: [
|
|
||||||
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
TextButton(onPressed: _pickDay, child: Text(_day)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(child: BodyNote(_status ?? widget.hint)),
|
|
||||||
IconButton(
|
|
||||||
icon: const Icon(Icons.delete_outline),
|
|
||||||
tooltip: 'Delete this day',
|
|
||||||
onPressed: _delete,
|
|
||||||
),
|
|
||||||
FilledButton(onPressed: _save, child: const Text('Save')),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
WeightChart(series: widget.series),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -4,11 +4,12 @@
|
|||||||
/// drawn to scale rather than evenly spaced.
|
/// drawn to scale rather than evenly spaced.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:fl_chart/fl_chart.dart';
|
import 'package:fl_chart/fl_chart.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Selectable chart ranges, `(label, days)`; null days = everything.
|
/// Selectable chart ranges, `(spoken name, days)`; null days = everything.
|
||||||
const List<(String, int?)> weightChartRanges = [
|
const List<(String, int?)> weightChartRanges = [
|
||||||
('30d', 30),
|
('30d', 30),
|
||||||
('90d', 90),
|
('90d', 90),
|
||||||
@ -61,11 +62,19 @@ class _WeightChartState extends State<WeightChart> {
|
|||||||
Wrap(
|
Wrap(
|
||||||
spacing: AppSpacing.sm,
|
spacing: AppSpacing.sm,
|
||||||
children: [
|
children: [
|
||||||
for (final (label, days) in weightChartRanges)
|
for (final (spoken, days) in weightChartRanges)
|
||||||
ChoiceChip(
|
SpokenLabel(
|
||||||
label: Text(label),
|
semanticLabel: spoken,
|
||||||
selected: _days == days,
|
child: ChoiceChip(
|
||||||
onSelected: (_) => setState(() => _days = days),
|
// Days as a bare numeral; "everything" as the infinity glyph.
|
||||||
|
label: ExcludeSemantics(
|
||||||
|
child: days == null
|
||||||
|
? const Icon(Icons.all_inclusive, size: 18)
|
||||||
|
: Text('$days'),
|
||||||
|
),
|
||||||
|
selected: _days == days,
|
||||||
|
onSelected: (_) => setState(() => _days = days),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -73,7 +82,14 @@ class _WeightChartState extends State<WeightChart> {
|
|||||||
SizedBox(
|
SizedBox(
|
||||||
height: 200,
|
height: 200,
|
||||||
child: points.length < 2
|
child: points.length < 2
|
||||||
? const Center(child: Text('Need two readings for a graph.'))
|
? Center(
|
||||||
|
child: Icon(
|
||||||
|
Icons.show_chart,
|
||||||
|
size: 64,
|
||||||
|
color: Theme.of(context).colorScheme.outline,
|
||||||
|
semanticLabel: 'Need two readings for a graph.',
|
||||||
|
),
|
||||||
|
)
|
||||||
: _chart(context, points),
|
: _chart(context, points),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
13
app/lib/widgets/body/workout_kind_icon.dart
Normal file
13
app/lib/widgets/body/workout_kind_icon.dart
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
/// Returns the activity-type icon for [kind].
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Activity kind icons used by _SessionTile (in `activity_card.dart`).
|
||||||
|
IconData kindIcon(String kind) => switch (kind) {
|
||||||
|
'run' => Icons.directions_run,
|
||||||
|
'walk' => Icons.directions_walk,
|
||||||
|
'cycle' => Icons.directions_bike,
|
||||||
|
'strength' => Icons.fitness_center,
|
||||||
|
_ => Icons.sports,
|
||||||
|
};
|
||||||
@ -5,8 +5,8 @@ import 'dart:async';
|
|||||||
|
|
||||||
import 'package:data_transfer_flutter/data_transfer_flutter.dart';
|
import 'package:data_transfer_flutter/data_transfer_flutter.dart';
|
||||||
import 'package:diet_guard_app/services/data_export.dart';
|
import 'package:diet_guard_app/services/data_export.dart';
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Suggested file name, identical on every platform.
|
/// Suggested file name, identical on every platform.
|
||||||
const exportFileName = 'diet-guard-export.json';
|
const exportFileName = 'diet-guard-export.json';
|
||||||
|
|||||||
@ -3,7 +3,7 @@ library;
|
|||||||
|
|
||||||
import 'package:diet_guard_app/models/day_status.dart';
|
import 'package:diet_guard_app/models/day_status.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Monthly calendar widget that colors each day by its [DayStatus].
|
/// Monthly calendar widget that colors each day by its [DayStatus].
|
||||||
///
|
///
|
||||||
@ -46,23 +46,6 @@ class DayStatusCalendar extends StatelessWidget {
|
|||||||
/// outside the displayed month is never tappable regardless.
|
/// outside the displayed month is never tappable regardless.
|
||||||
final void Function(DateTime day)? onDaySelected;
|
final void Function(DateTime day)? onDaySelected;
|
||||||
|
|
||||||
static const _weekHeaders = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
|
|
||||||
|
|
||||||
static const _monthNames = [
|
|
||||||
'January',
|
|
||||||
'February',
|
|
||||||
'March',
|
|
||||||
'April',
|
|
||||||
'May',
|
|
||||||
'June',
|
|
||||||
'July',
|
|
||||||
'August',
|
|
||||||
'September',
|
|
||||||
'October',
|
|
||||||
'November',
|
|
||||||
'December',
|
|
||||||
];
|
|
||||||
|
|
||||||
String _dateKey(int year, int m, int day) =>
|
String _dateKey(int year, int m, int day) =>
|
||||||
'$year-${m.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}';
|
'$year-${m.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}';
|
||||||
|
|
||||||
@ -129,13 +112,18 @@ class DayStatusCalendar extends StatelessWidget {
|
|||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
children: [
|
children: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(Icons.chevron_left, color: scheme.onSurfaceVariant),
|
icon: Icon(
|
||||||
|
Icons.chevron_left,
|
||||||
|
color: scheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Previous month',
|
||||||
|
),
|
||||||
visualDensity: VisualDensity.compact,
|
visualDensity: VisualDensity.compact,
|
||||||
padding: EdgeInsets.zero,
|
padding: EdgeInsets.zero,
|
||||||
onPressed: onPrevMonth,
|
onPressed: onPrevMonth,
|
||||||
),
|
),
|
||||||
|
// Numeric month/year: a month name would be written chrome.
|
||||||
Text(
|
Text(
|
||||||
'${_monthNames[m - 1]} $year',
|
'${m.toString().padLeft(2, '0')} · $year',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: scheme.onSurface,
|
color: scheme.onSurface,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.bold,
|
||||||
@ -143,7 +131,11 @@ class DayStatusCalendar extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(Icons.chevron_right, color: scheme.onSurfaceVariant),
|
icon: Icon(
|
||||||
|
Icons.chevron_right,
|
||||||
|
color: scheme.onSurfaceVariant,
|
||||||
|
semanticLabel: 'Next month',
|
||||||
|
),
|
||||||
visualDensity: VisualDensity.compact,
|
visualDensity: VisualDensity.compact,
|
||||||
padding: EdgeInsets.zero,
|
padding: EdgeInsets.zero,
|
||||||
onPressed: onNextMonth,
|
onPressed: onNextMonth,
|
||||||
@ -153,25 +145,23 @@ class DayStatusCalendar extends StatelessWidget {
|
|||||||
const SizedBox(height: AppSpacing.xs + 2),
|
const SizedBox(height: AppSpacing.xs + 2),
|
||||||
Row(
|
Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||||
children: _weekHeaders
|
// Weekday names are gone: seven dots mark the Monday-first
|
||||||
.map(
|
// columns, the two weekend ones in the accent colour.
|
||||||
(h) => SizedBox(
|
children: [
|
||||||
width: 30,
|
for (var col = 0; col < 7; col++)
|
||||||
child: Text(
|
SizedBox(
|
||||||
h,
|
width: 30,
|
||||||
textAlign: TextAlign.center,
|
child: Center(
|
||||||
// Two-letter day abbreviations are UI chrome (like a
|
child: Icon(
|
||||||
// badge/tag), deliberately kept below the 16px body
|
Icons.circle,
|
||||||
// floor rather than forced to grow past their slot.
|
size: col >= 5 ? 8 : 5,
|
||||||
style: TextStyle(
|
color: col >= 5
|
||||||
color: scheme.onSurfaceVariant,
|
? scheme.primary
|
||||||
fontSize: AppTextSize.label - 2,
|
: scheme.onSurfaceVariant,
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
),
|
||||||
.toList(),
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: AppSpacing.xs),
|
const SizedBox(height: AppSpacing.xs),
|
||||||
...List.generate(rows, (row) {
|
...List.generate(rows, (row) {
|
||||||
@ -218,9 +208,10 @@ class DayStatusCalendar extends StatelessWidget {
|
|||||||
// and no semantics for a screen reader. InkWell is a focus
|
// and no semantics for a screen reader. InkWell is a focus
|
||||||
// stop and is activated by Enter/Space.
|
// stop and is activated by Enter/Space.
|
||||||
final date = DateTime(year, m, day);
|
final date = DateTime(year, m, day);
|
||||||
|
final semanticLabel = 'View $day/$m/$year';
|
||||||
return Semantics(
|
return Semantics(
|
||||||
button: true,
|
button: true,
|
||||||
label: 'View $day/$m/$year',
|
label: semanticLabel,
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
onTap: () => onDaySelected!(date),
|
onTap: () => onDaySelected!(date),
|
||||||
customBorder: const CircleBorder(),
|
customBorder: const CircleBorder(),
|
||||||
|
|||||||
@ -1,77 +0,0 @@
|
|||||||
/// The log form's "Fill all with catering" row: one button, plus Cancel while
|
|
||||||
/// a proposal is armed.
|
|
||||||
///
|
|
||||||
/// Its own row rather than a third control in [LogMealActionsRow]: that row is
|
|
||||||
/// already full on a narrow phone, and "✓ Confirm (N)" must stay legible.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:diet_guard_app/services/kuchnia_client.dart';
|
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
/// Resting label, mirroring the PC gate's "🍱 Fill all".
|
|
||||||
const fillAllLabel = '🍱 Fill all with catering';
|
|
||||||
|
|
||||||
/// Fill-all button; relabels to "✓ Confirm (N)" once a proposal is armed.
|
|
||||||
class FillAllRow extends StatelessWidget {
|
|
||||||
/// Creates the row.
|
|
||||||
const FillAllRow({
|
|
||||||
required this.onFill,
|
|
||||||
required this.onCancel,
|
|
||||||
this.busy = false,
|
|
||||||
this.armedCount = 0,
|
|
||||||
this.canFetchDelivery,
|
|
||||||
super.key,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// First tap proposes, second tap confirms.
|
|
||||||
final Future<void> Function() onFill;
|
|
||||||
|
|
||||||
/// Disarms a proposal without writing anything.
|
|
||||||
final VoidCallback onCancel;
|
|
||||||
|
|
||||||
/// Disables both controls while a fetch or the confirm's writes run.
|
|
||||||
final bool busy;
|
|
||||||
|
|
||||||
/// How many dishes the armed proposal would log; 0 when none is armed.
|
|
||||||
final int armedCount;
|
|
||||||
|
|
||||||
/// Whether the platform can fetch at all. Defaults to
|
|
||||||
/// [kuchniaFetchSupported] -- false on web, where the caterer's panel blocks
|
|
||||||
/// browser requests -- so the row is hidden there, like the delivery button.
|
|
||||||
final bool? canFetchDelivery;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (!(canFetchDelivery ?? kuchniaFetchSupported)) {
|
|
||||||
return const SizedBox.shrink();
|
|
||||||
}
|
|
||||||
final armed = armedCount > 0;
|
|
||||||
return Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: OutlinedButton(
|
|
||||||
onPressed: busy ? null : onFill,
|
|
||||||
child: FittedBox(
|
|
||||||
fit: BoxFit.scaleDown,
|
|
||||||
child: Text(_label(armed), maxLines: 1),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (armed) ...[
|
|
||||||
const SizedBox(width: AppSpacing.sm),
|
|
||||||
TextButton(
|
|
||||||
onPressed: busy ? null : onCancel,
|
|
||||||
child: const Text('Cancel'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
String _label(bool armed) {
|
|
||||||
if (busy) return 'Working…';
|
|
||||||
if (armed) return '✓ Confirm ($armedCount)';
|
|
||||||
return fillAllLabel;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
124
app/lib/widgets/filters/filter_chrome.dart
Normal file
124
app/lib/widgets/filters/filter_chrome.dart
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
/// Icon-only chrome shared by the history and food-bank filter sheets: the
|
||||||
|
/// clear control, the apply bar and the sort chooser. Each control paints a
|
||||||
|
/// glyph and speaks its old caption only through its semantic label.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
|
/// Top row of a filter sheet: one clear-everything icon, right-aligned.
|
||||||
|
class FilterSheetHeader extends StatelessWidget {
|
||||||
|
/// Creates a header whose clear icon calls [onClear].
|
||||||
|
const FilterSheetHeader({required this.onClear, super.key});
|
||||||
|
|
||||||
|
/// Called when the clear icon is pressed.
|
||||||
|
final VoidCallback onClear;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 4, 8, 0),
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerRight,
|
||||||
|
child: IconButton(
|
||||||
|
icon: const Icon(Icons.filter_list_off, semanticLabel: 'Clear all'),
|
||||||
|
onPressed: onClear,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bottom bar of a filter sheet: one full-width check button.
|
||||||
|
class FilterApplyBar extends StatelessWidget {
|
||||||
|
/// Creates an apply bar that calls [onApply].
|
||||||
|
const FilterApplyBar({required this.onApply, super.key});
|
||||||
|
|
||||||
|
/// Called when the check is pressed.
|
||||||
|
final VoidCallback onApply;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Padding(
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
child: SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: ElevatedButton(
|
||||||
|
onPressed: onApply,
|
||||||
|
child: const Icon(Icons.check, semanticLabel: 'Apply'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One choice in a [SortChoiceRow]: a glyph, its tint and its spoken name.
|
||||||
|
class SortOption<T> {
|
||||||
|
/// Creates an option selecting [value].
|
||||||
|
const SortOption(this.value, this.icon, this.semanticLabel, {this.color});
|
||||||
|
|
||||||
|
/// The value reported when chosen.
|
||||||
|
final T value;
|
||||||
|
|
||||||
|
/// Painted glyph.
|
||||||
|
final IconData icon;
|
||||||
|
|
||||||
|
/// Spoken name; never painted.
|
||||||
|
final String semanticLabel;
|
||||||
|
|
||||||
|
/// Glyph tint; the theme default when null.
|
||||||
|
final Color? color;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Icon chips for the sort field plus an arrow for the direction.
|
||||||
|
class SortChoiceRow<T> extends StatelessWidget {
|
||||||
|
/// Creates a chooser over [options] with [selected] active.
|
||||||
|
const SortChoiceRow({
|
||||||
|
required this.options,
|
||||||
|
required this.selected,
|
||||||
|
required this.ascending,
|
||||||
|
required this.onChanged,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Choices in display order.
|
||||||
|
final List<SortOption<T>> options;
|
||||||
|
|
||||||
|
/// The active choice.
|
||||||
|
final T selected;
|
||||||
|
|
||||||
|
/// Whether the sort runs ascending.
|
||||||
|
final bool ascending;
|
||||||
|
|
||||||
|
/// Called with the new field and direction.
|
||||||
|
final void Function({required T field, required bool asc}) onChanged;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 4,
|
||||||
|
children: [
|
||||||
|
for (final o in options)
|
||||||
|
ChoiceChip(
|
||||||
|
label: Icon(
|
||||||
|
o.icon,
|
||||||
|
size: 18,
|
||||||
|
color: o.color,
|
||||||
|
semanticLabel: o.semanticLabel,
|
||||||
|
),
|
||||||
|
selected: selected == o.value,
|
||||||
|
onSelected: (_) => onChanged(field: o.value, asc: ascending),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(
|
||||||
|
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
||||||
|
semanticLabel: ascending ? 'Ascending' : 'Descending',
|
||||||
|
),
|
||||||
|
onPressed: () => onChanged(field: selected, asc: !ascending),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,9 +6,11 @@
|
|||||||
/// screen owns the other's controls.
|
/// screen owns the other's controls.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// The free-text "search by name" field in the filter sheet.
|
/// The free-text search-by-name field in the filter sheet.
|
||||||
///
|
///
|
||||||
/// Stateful only to own its [TextEditingController]; the query itself lives in
|
/// Stateful only to own its [TextEditingController]; the query itself lives in
|
||||||
/// the screen's [HistoryFilter].
|
/// the screen's [HistoryFilter].
|
||||||
@ -44,13 +46,11 @@ class NameSearchFieldState extends State<NameSearchField> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return TextField(
|
return IconField(
|
||||||
|
icon: Icons.search,
|
||||||
|
semanticLabel: 'Search by name',
|
||||||
controller: _controller,
|
controller: _controller,
|
||||||
decoration: const InputDecoration(
|
dense: true,
|
||||||
labelText: 'Search by name',
|
|
||||||
prefixIcon: Icon(Icons.search),
|
|
||||||
isDense: true,
|
|
||||||
),
|
|
||||||
onChanged: widget.onChanged,
|
onChanged: widget.onChanged,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -112,7 +112,7 @@ class SliderSelectedLabel extends StatelessWidget {
|
|||||||
class FilterRangeRow extends StatelessWidget {
|
class FilterRangeRow extends StatelessWidget {
|
||||||
/// Creates a range row bounded by [maxValue].
|
/// Creates a range row bounded by [maxValue].
|
||||||
const FilterRangeRow({
|
const FilterRangeRow({
|
||||||
required this.label,
|
required this.kind,
|
||||||
required this.sliderKey,
|
required this.sliderKey,
|
||||||
required this.maxValue,
|
required this.maxValue,
|
||||||
required this.min,
|
required this.min,
|
||||||
@ -123,8 +123,8 @@ class FilterRangeRow extends StatelessWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Section heading, e.g. `Protein range (g)`.
|
/// Which nutrient this range filters; its glyph heads the row.
|
||||||
final String label;
|
final MacroKind kind;
|
||||||
|
|
||||||
/// Widget key on the slider itself, so tests can drive one row.
|
/// Widget key on the slider itself, so tests can drive one row.
|
||||||
final Key sliderKey;
|
final Key sliderKey;
|
||||||
@ -158,7 +158,14 @@ class FilterRangeRow extends StatelessWidget {
|
|||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
Text(label, style: Theme.of(context).textTheme.labelLarge),
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: Icon(
|
||||||
|
kind.icon,
|
||||||
|
color: kind.color,
|
||||||
|
semanticLabel: kind.semanticLabel(compact: false),
|
||||||
|
),
|
||||||
|
),
|
||||||
if (showEndpointLabels)
|
if (showEndpointLabels)
|
||||||
SliderEndpointLabels(lo: '0', hi: '${maxValue.round()}$unit'),
|
SliderEndpointLabels(lo: '0', hi: '${maxValue.round()}$unit'),
|
||||||
RangeSlider(
|
RangeSlider(
|
||||||
|
|||||||
@ -4,7 +4,9 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Prompts for a new manually-curated food bank entry.
|
/// Prompts for a new manually-curated food bank entry.
|
||||||
///
|
///
|
||||||
@ -53,49 +55,50 @@ class AddEntryDialogState extends State<AddEntryDialog> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _field(String label, TextEditingController ctrl) => Padding(
|
Widget _field(MacroKind kind, TextEditingController ctrl) => Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 8),
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: kind.icon,
|
||||||
|
iconColor: kind.color,
|
||||||
|
semanticLabel: kind.semanticLabel(compact: false),
|
||||||
controller: ctrl,
|
controller: ctrl,
|
||||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
decoration: InputDecoration(labelText: label, isDense: true),
|
dense: true,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
title: const Text('Add to food bank'),
|
|
||||||
content: SingleChildScrollView(
|
content: SingleChildScrollView(
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 8),
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
child: TextField(
|
child: IconField(
|
||||||
|
icon: Icons.restaurant,
|
||||||
|
semanticLabel: 'Name',
|
||||||
controller: _name,
|
controller: _name,
|
||||||
decoration: const InputDecoration(
|
dense: true,
|
||||||
labelText: 'Name',
|
|
||||||
isDense: true,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
_field('Reference grams', _grams),
|
_field(MacroKind.perGrams, _grams),
|
||||||
_field('Kcal', _kcal),
|
_field(MacroKind.kcal, _kcal),
|
||||||
_field('Protein (g)', _protein),
|
_field(MacroKind.protein, _protein),
|
||||||
_field('Carbs (g)', _carbs),
|
_field(MacroKind.carbs, _carbs),
|
||||||
_field('Fat (g)', _fat),
|
_field(MacroKind.fat, _fat),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
IconButton(
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
child: const Text('Cancel'),
|
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||||
),
|
),
|
||||||
ElevatedButton(
|
ElevatedButton(
|
||||||
onPressed: _save,
|
onPressed: _save,
|
||||||
child: const Text('Save to bank'),
|
child: const Icon(Icons.check, semanticLabel: 'Save to bank'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -4,9 +4,12 @@
|
|||||||
/// range rows come from `widgets/filters/`, shared with the history sheet.
|
/// range rows come from `widgets/filters/`, shared with the history sheet.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'package:diet_guard_app/ui/cues.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:diet_guard_app/widgets/filters/filter_chrome.dart';
|
||||||
import 'package:diet_guard_app/widgets/filters/filter_fields.dart';
|
import 'package:diet_guard_app/widgets/filters/filter_fields.dart';
|
||||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// The draggable bottom sheet that edits the food bank's filter and sort order.
|
/// The draggable bottom sheet that edits the food bank's filter and sort order.
|
||||||
///
|
///
|
||||||
@ -63,6 +66,35 @@ class FbFilterSheet extends StatelessWidget {
|
|||||||
/// Called when the user clears every criterion.
|
/// Called when the user clears every criterion.
|
||||||
final VoidCallback onClear;
|
final VoidCallback onClear;
|
||||||
|
|
||||||
|
static final List<SortOption<FbSortField>> _sortOptions = [
|
||||||
|
const SortOption(FbSortField.count, Icons.repeat, 'Usage count'),
|
||||||
|
const SortOption(FbSortField.name, Icons.sort_by_alpha, 'Name'),
|
||||||
|
SortOption(
|
||||||
|
FbSortField.kcal,
|
||||||
|
MacroKind.kcal.icon,
|
||||||
|
'Kcal',
|
||||||
|
color: MacroKind.kcal.color,
|
||||||
|
),
|
||||||
|
SortOption(
|
||||||
|
FbSortField.protein,
|
||||||
|
MacroKind.protein.icon,
|
||||||
|
'Protein',
|
||||||
|
color: MacroKind.protein.color,
|
||||||
|
),
|
||||||
|
SortOption(
|
||||||
|
FbSortField.carbs,
|
||||||
|
MacroKind.carbs.icon,
|
||||||
|
'Carbs',
|
||||||
|
color: MacroKind.carbs.color,
|
||||||
|
),
|
||||||
|
SortOption(
|
||||||
|
FbSortField.fat,
|
||||||
|
MacroKind.fat.icon,
|
||||||
|
'Fat',
|
||||||
|
color: MacroKind.fat.color,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return DraggableScrollableSheet(
|
return DraggableScrollableSheet(
|
||||||
@ -71,35 +103,17 @@ class FbFilterSheet extends StatelessWidget {
|
|||||||
maxChildSize: 0.95,
|
maxChildSize: 0.95,
|
||||||
builder: (context, scroll) => Column(
|
builder: (context, scroll) => Column(
|
||||||
children: [
|
children: [
|
||||||
Padding(
|
FilterSheetHeader(onClear: onClear),
|
||||||
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
'Filter & Sort',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
TextButton(
|
|
||||||
onPressed: onClear,
|
|
||||||
child: const Text('Clear all'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const Divider(),
|
const Divider(),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: ListView(
|
child: ListView(
|
||||||
controller: scroll,
|
controller: scroll,
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
TextField(
|
IconField(
|
||||||
decoration: const InputDecoration(
|
icon: Icons.search,
|
||||||
labelText: 'Search by name',
|
semanticLabel: 'Search by name',
|
||||||
prefixIcon: Icon(Icons.search),
|
dense: true,
|
||||||
isDense: true,
|
|
||||||
),
|
|
||||||
controller: TextEditingController(text: filter.nameQuery)
|
controller: TextEditingController(text: filter.nameQuery)
|
||||||
..selection = TextSelection.collapsed(
|
..selection = TextSelection.collapsed(
|
||||||
offset: filter.nameQuery.length,
|
offset: filter.nameQuery.length,
|
||||||
@ -111,7 +125,7 @@ class FbFilterSheet extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
FilterRangeRow(
|
FilterRangeRow(
|
||||||
label: 'Kcal range',
|
kind: MacroKind.kcal,
|
||||||
sliderKey: const Key('fb-kcal-range-slider'),
|
sliderKey: const Key('fb-kcal-range-slider'),
|
||||||
maxValue: maxKcal,
|
maxValue: maxKcal,
|
||||||
min: filter.minKcal,
|
min: filter.minKcal,
|
||||||
@ -124,7 +138,7 @@ class FbFilterSheet extends StatelessWidget {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
FilterRangeRow(
|
FilterRangeRow(
|
||||||
label: 'Protein range (g)',
|
kind: MacroKind.protein,
|
||||||
sliderKey: const Key('fb-protein-range-slider'),
|
sliderKey: const Key('fb-protein-range-slider'),
|
||||||
maxValue: maxProtein,
|
maxValue: maxProtein,
|
||||||
min: filter.minProtein,
|
min: filter.minProtein,
|
||||||
@ -138,7 +152,7 @@ class FbFilterSheet extends StatelessWidget {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
FilterRangeRow(
|
FilterRangeRow(
|
||||||
label: 'Carbs range (g)',
|
kind: MacroKind.carbs,
|
||||||
sliderKey: const Key('fb-carbs-range-slider'),
|
sliderKey: const Key('fb-carbs-range-slider'),
|
||||||
maxValue: maxCarbs,
|
maxValue: maxCarbs,
|
||||||
min: filter.minCarbs,
|
min: filter.minCarbs,
|
||||||
@ -152,7 +166,7 @@ class FbFilterSheet extends StatelessWidget {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
FilterRangeRow(
|
FilterRangeRow(
|
||||||
label: 'Fat range (g)',
|
kind: MacroKind.fat,
|
||||||
sliderKey: const Key('fb-fat-range-slider'),
|
sliderKey: const Key('fb-fat-range-slider'),
|
||||||
maxValue: maxFat,
|
maxValue: maxFat,
|
||||||
min: filter.minFat,
|
min: filter.minFat,
|
||||||
@ -165,74 +179,16 @@ class FbFilterSheet extends StatelessWidget {
|
|||||||
onFilterChanged(filter);
|
onFilterChanged(filter);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
Text(
|
SortChoiceRow<FbSortField>(
|
||||||
'Sort by',
|
options: _sortOptions,
|
||||||
style: Theme.of(context).textTheme.labelLarge,
|
selected: sortField,
|
||||||
),
|
ascending: ascending,
|
||||||
const SizedBox(height: 4),
|
onChanged: onSortChanged,
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: DropdownButton<FbSortField>(
|
|
||||||
isExpanded: true,
|
|
||||||
value: sortField,
|
|
||||||
items: const [
|
|
||||||
DropdownMenuItem(
|
|
||||||
value: FbSortField.count,
|
|
||||||
child: Text('Usage count'),
|
|
||||||
),
|
|
||||||
DropdownMenuItem(
|
|
||||||
value: FbSortField.name,
|
|
||||||
child: Text('Name'),
|
|
||||||
),
|
|
||||||
DropdownMenuItem(
|
|
||||||
value: FbSortField.kcal,
|
|
||||||
child: Text('Kcal'),
|
|
||||||
),
|
|
||||||
DropdownMenuItem(
|
|
||||||
value: FbSortField.protein,
|
|
||||||
child: Text('Protein'),
|
|
||||||
),
|
|
||||||
DropdownMenuItem(
|
|
||||||
value: FbSortField.carbs,
|
|
||||||
child: Text('Carbs'),
|
|
||||||
),
|
|
||||||
DropdownMenuItem(
|
|
||||||
value: FbSortField.fat,
|
|
||||||
child: Text('Fat'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
onChanged: (v) {
|
|
||||||
if (v != null) {
|
|
||||||
onSortChanged(field: v, asc: ascending);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
IconButton(
|
|
||||||
icon: Icon(
|
|
||||||
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
|
||||||
),
|
|
||||||
tooltip: ascending ? 'Ascending' : 'Descending',
|
|
||||||
onPressed: () =>
|
|
||||||
onSortChanged(field: sortField, asc: !ascending),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Padding(
|
FilterApplyBar(onApply: onApply),
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: SizedBox(
|
|
||||||
width: double.infinity,
|
|
||||||
child: ElevatedButton(
|
|
||||||
onPressed: onApply,
|
|
||||||
child: const Text('Apply'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@ -2,9 +2,13 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// One banked food: its name, macros, and how often it has been logged.
|
/// One banked food: its name, macros, and how often it has been logged.
|
||||||
|
///
|
||||||
|
/// Macros are glyph + number pairs; the reference weight carries the scale
|
||||||
|
/// glyph, the use count keeps its `×N` numeral.
|
||||||
class RecordTile extends StatelessWidget {
|
class RecordTile extends StatelessWidget {
|
||||||
/// Creates a [RecordTile] for [record].
|
/// Creates a [RecordTile] for [record].
|
||||||
const RecordTile(this.record, {super.key});
|
const RecordTile(this.record, {super.key});
|
||||||
@ -14,19 +18,23 @@ class RecordTile extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final macros =
|
String n(double v) => v.toStringAsFixed(0);
|
||||||
'P ${record.proteinG.toStringAsFixed(0)} g '
|
|
||||||
'C ${record.carbsG.toStringAsFixed(0)} g '
|
|
||||||
'F ${record.fatG.toStringAsFixed(0)} g';
|
|
||||||
final per = record.grams > 0
|
|
||||||
? ' per ${record.grams.toStringAsFixed(0)} g'
|
|
||||||
: '';
|
|
||||||
return ListTile(
|
return ListTile(
|
||||||
title: Text(record.desc),
|
title: Text(record.desc),
|
||||||
subtitle: Text('${record.kcal.toStringAsFixed(0)} kcal$per · $macros'),
|
subtitle: Wrap(
|
||||||
|
spacing: 12,
|
||||||
|
children: [
|
||||||
|
MacroFigure(kind: MacroKind.kcal, value: n(record.kcal)),
|
||||||
|
if (record.grams > 0)
|
||||||
|
MacroFigure(kind: MacroKind.perGrams, value: '${n(record.grams)}g'),
|
||||||
|
MacroFigure(kind: MacroKind.protein, value: '${n(record.proteinG)}g'),
|
||||||
|
MacroFigure(kind: MacroKind.carbs, value: '${n(record.carbsG)}g'),
|
||||||
|
MacroFigure(kind: MacroKind.fat, value: '${n(record.fatG)}g'),
|
||||||
|
],
|
||||||
|
),
|
||||||
trailing: record.count > 0
|
trailing: record.count > 0
|
||||||
? Text(
|
? Text(
|
||||||
'×${record.count.toStringAsFixed(0)}',
|
'×${n(record.count)}',
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
style: Theme.of(context).textTheme.bodySmall,
|
||||||
)
|
)
|
||||||
: null,
|
: null,
|
||||||
|
|||||||
@ -4,8 +4,9 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||||
|
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||||
import 'package:diet_guard_app/ui/theme.dart';
|
import 'package:diet_guard_app/ui/theme.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:material_ui/material_ui.dart';
|
||||||
|
|
||||||
/// Tiles per row.
|
/// Tiles per row.
|
||||||
const int fbGridColumns = 3;
|
const int fbGridColumns = 3;
|
||||||
@ -59,11 +60,13 @@ class FbTile extends StatelessWidget {
|
|||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Align(
|
||||||
'${record.kcal.toStringAsFixed(0)} kcal',
|
alignment: Alignment.centerLeft,
|
||||||
maxLines: 1,
|
child: MacroFigure(
|
||||||
overflow: TextOverflow.ellipsis,
|
kind: MacroKind.kcal,
|
||||||
style: theme.textTheme.bodySmall,
|
value: record.kcal.toStringAsFixed(0),
|
||||||
|
size: 14,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (record.count > 0)
|
if (record.count > 0)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user