mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-28 22:59:05 +01:00
Compare commits
No commits in common. "main" and "v1.0.121" have entirely different histories.
62
.github/workflows/dependency-freshness.yml
vendored
Normal file
62
.github/workflows/dependency-freshness.yml
vendored
Normal file
@ -0,0 +1,62 @@
|
||||
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
|
||||
33
.github/workflows/file-length.yml
vendored
Normal file
33
.github/workflows/file-length.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
name: file-length
|
||||
|
||||
# The 250-line cap, enforced on push as well as at commit time. The local
|
||||
# pre-commit hook can be skipped (a fresh clone that never ran `pre-commit
|
||||
# install` has no hooks at all), so the cap needs a second gate that no one
|
||||
# can forget to install.
|
||||
#
|
||||
# Deliberately a SEPARATE workflow from release-apk.yml: a file that grew too
|
||||
# long should fail lint, not block publishing an APK.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
file-length:
|
||||
name: file length <= 250 lines
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The gate and its exemption list live in the shared utils repo so every
|
||||
# repo enforces the same cap. Checking it out beats vendoring a copy
|
||||
# here, which is exactly how a gate and a survey start disagreeing.
|
||||
- name: Check out the shared gate
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: kuhyx/utils
|
||||
path: .utils
|
||||
|
||||
- name: Enforce the cap
|
||||
run: bash .utils/scripts/check_file_length.sh --all
|
||||
20
.github/workflows/pre-commit.yml
vendored
20
.github/workflows/pre-commit.yml
vendored
@ -17,16 +17,22 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- group: mypy
|
||||
hooks: mypy
|
||||
skip: ""
|
||||
- group: pylint
|
||||
hooks: pylint
|
||||
skip: ""
|
||||
- group: rest
|
||||
hooks: ""
|
||||
skip: "dependency-freshness"
|
||||
skip: mypy,pylint
|
||||
name: pre-commit (${{ matrix.group }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The file-length and md-naming hooks delegate to the shared gates in
|
||||
# kuhyx/utils, which a runner does not have at $HOME/src/utils. Only
|
||||
# the rest group runs them.
|
||||
# The file-length, md-naming and dependency-freshness hooks delegate to
|
||||
# the shared gates in kuhyx/utils, which a runner does not have at
|
||||
# $HOME/src/utils. Only the rest group runs them.
|
||||
- name: Check out the shared gates
|
||||
if: matrix.group == 'rest'
|
||||
uses: actions/checkout@v4
|
||||
@ -53,9 +59,9 @@ jobs:
|
||||
# mypy and pylint bring their own hook environments, so they need only
|
||||
# pre-commit. The rest group's language: system patch-targets hook
|
||||
# imports diet_guard and every patched module (requests, gatelock,
|
||||
# crdt_sync, freedays, mcp, pydantic) -- so it keeps the full
|
||||
# requirements.txt. That install used to run in the one job, with plain
|
||||
# pip, for ~24 s.
|
||||
# crdt_sync, freedays, mcp, pydantic), and dependency-freshness needs
|
||||
# pyyaml and packaging -- so it keeps the full requirements.txt. That
|
||||
# install used to run in the one job, with plain pip, for ~24 s.
|
||||
- name: Install pre-commit and the system hooks' imports
|
||||
run: |
|
||||
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
|
||||
with:
|
||||
flutter-version: 3.50.1
|
||||
flutter-version: 3.47.7
|
||||
channel: stable
|
||||
cache: true
|
||||
|
||||
@ -108,9 +108,7 @@ jobs:
|
||||
run: |
|
||||
flutter build apk --release \
|
||||
--build-name="${{ steps.ver.outputs.semver }}" \
|
||||
--build-number="${{ steps.vc.outputs.code }}" \
|
||||
--dart-define=APP_BUILD="${{ steps.vc.outputs.code }}" \
|
||||
--dart-define=APP_VERSION="${{ steps.ver.outputs.semver }}"
|
||||
--build-number="${{ steps.vc.outputs.code }}"
|
||||
|
||||
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
||||
# the debug key if key.properties is misplaced, producing a green build
|
||||
|
||||
@ -9,7 +9,6 @@ default_language_version:
|
||||
default_stages: [pre-commit]
|
||||
fail_fast: false
|
||||
|
||||
default_install_hook_types: [pre-commit, pre-push, post-commit, post-merge, post-rewrite]
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.6.0
|
||||
@ -25,6 +24,11 @@ repos:
|
||||
- id: check-merge-conflict
|
||||
- id: detect-private-key
|
||||
- id: debug-statements
|
||||
- id: name-tests-test
|
||||
args: [--pytest-test-first]
|
||||
# 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.
|
||||
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$
|
||||
- id: check-ast
|
||||
- id: mixed-line-ending
|
||||
args: [--fix=lf]
|
||||
@ -52,133 +56,100 @@ repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.15.2
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
|
||||
types_or: [python, pyi]
|
||||
- id: ruff-format
|
||||
types_or: [python, pyi]
|
||||
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v1.13.0
|
||||
hooks:
|
||||
- id: mypy
|
||||
args:
|
||||
- --ignore-missing-imports
|
||||
- --no-error-summary
|
||||
- --disable-error-code=no-untyped-def
|
||||
- --disable-error-code=no-untyped-call
|
||||
- --disable-error-code=var-annotated
|
||||
- --disable-error-code=no-any-unimported
|
||||
- --disable-error-code=type-arg
|
||||
- --disable-error-code=no-any-return
|
||||
- --disable-error-code=misc
|
||||
- --disable-error-code=unused-ignore
|
||||
- --disable-error-code=unreachable
|
||||
- --disable-error-code=assignment
|
||||
- --disable-error-code=no-redef
|
||||
- --disable-error-code=attr-defined
|
||||
- --disable-error-code=arg-type
|
||||
- --disable-error-code=union-attr
|
||||
- --disable-error-code=call-overload
|
||||
- --disable-error-code=return-value
|
||||
- --disable-error-code=redundant-cast
|
||||
- --disable-error-code=empty-body
|
||||
- --disable-error-code=list-item
|
||||
additional_dependencies:
|
||||
- types-requests
|
||||
|
||||
- repo: https://github.com/pylint-dev/pylint
|
||||
rev: v3.3.2
|
||||
hooks:
|
||||
- id: pylint
|
||||
args:
|
||||
- --rcfile=pyproject.toml
|
||||
- --fail-under=10
|
||||
- --jobs=4
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
- requests
|
||||
# Kept in step with pyproject.toml: pip refuses two different
|
||||
# direct URLs for one distribution, so any pin that drifts from
|
||||
# the manifest becomes an unresolvable hook environment rather
|
||||
# than merely an old one.
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.10.0#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
|
||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
|
||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.3.0#subdirectory=sickdays
|
||||
- mcp>=2,<3
|
||||
- pydantic
|
||||
- defusedxml==0.7.1
|
||||
# Test suites intentionally use patterns (protected-access, magic-value
|
||||
# comparisons) that don't belong in the source-code 10/10 gate.
|
||||
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
||||
|
||||
- repo: https://github.com/PyCQA/bandit
|
||||
rev: 1.7.10
|
||||
hooks:
|
||||
- id: bandit
|
||||
args:
|
||||
- -c
|
||||
- pyproject.toml
|
||||
- --severity-level=high
|
||||
- --confidence-level=medium
|
||||
- --skip=B113
|
||||
additional_dependencies: ["bandit[toml]"]
|
||||
exclude: ^(tests/|.*test.*\.py$)
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
# Split into <60 s steps (run in this order); no-arg ci_mirror.sh is the CI form.
|
||||
- id: ci-mirror-venv
|
||||
name: CI mirror 1 (clean venv)
|
||||
entry: bash scripts/ci_mirror.sh venv
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-precommit
|
||||
name: CI mirror 2 (pre-commit --all-files)
|
||||
entry: bash scripts/ci_mirror.sh precommit
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-pytest
|
||||
name: CI mirror 3 (pytest, xvfb, 100% cov)
|
||||
entry: bash scripts/ci_mirror.sh pytest
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-1
|
||||
name: CI mirror 5 (flutter test 1/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 0/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-2
|
||||
name: CI mirror 6 (flutter test 2/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 1/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-3
|
||||
name: CI mirror 7 (flutter test 3/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 2/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-4
|
||||
name: CI mirror 8 (flutter test 4/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 3/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-5
|
||||
name: CI mirror 9 (flutter test 5/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 4/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-6
|
||||
name: CI mirror 10 (flutter test 6/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 5/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-7
|
||||
name: CI mirror 11 (flutter test 7/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 6/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-8
|
||||
name: CI mirror 12 (flutter test 8/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 7/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-9
|
||||
name: CI mirror 13 (flutter test 9/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 8/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-10
|
||||
name: CI mirror 14 (flutter test 10/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 9/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-11
|
||||
name: CI mirror 15 (flutter test 11/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 10/12
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
- id: ci-mirror-flutter-test-12
|
||||
name: CI mirror 16 (flutter test 12/12)
|
||||
entry: bash scripts/ci_mirror.sh flutter-test --shard 11/12
|
||||
- id: ci-mirror
|
||||
name: CI mirror (clean-venv pytest + pre-commit --all-files)
|
||||
entry: bash scripts/ci_mirror.sh
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
stages: [manual]
|
||||
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.3.0
|
||||
hooks:
|
||||
- id: codespell
|
||||
args:
|
||||
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||
# Devine: the 1974 ideal-body-weight formula's author, not "define".
|
||||
- --ignore-words-list=devine
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
# Fails a commit that still points crdt_sync at a local path. Local
|
||||
@ -199,6 +170,29 @@ repos:
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
require_serial: true
|
||||
- id: shellcheck
|
||||
name: shellcheck
|
||||
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
|
||||
language: system
|
||||
types: [shell]
|
||||
# A PKGBUILD is a makepkg manifest, not a standalone script: it has no
|
||||
# shebang (SC2148) and its variables are read by makepkg rather than by
|
||||
# the file itself (SC2034). namcap is what actually lints these.
|
||||
exclude: '^packaging/aur/PKGBUILD$'
|
||||
# The shared 250-line cap. Checks only the files in the commit, so an
|
||||
# unrelated commit never breaks; exits 1 rather than warning. No
|
||||
# baseline and no allowlist -- those are suppressions. The exemption
|
||||
# list (generated/vendored/data files) lives with the checker in
|
||||
# ~/src/utils/file_length/config.py so the gate and the survey cannot
|
||||
# disagree.
|
||||
#
|
||||
# Deliberately unfiltered: no types_or and no files. The cap applies to
|
||||
# Dart and prose too, and a type filter here is what would silently
|
||||
# exempt the whole Flutter app and every .md.
|
||||
- id: file-length
|
||||
name: file length <= 250 lines
|
||||
entry: scripts/check_file_length.sh
|
||||
language: system
|
||||
|
||||
# unittest.mock.patch fails OPEN: once a refactor moves a name, a patch
|
||||
# target that still imports redirects nothing, the test passes, and the
|
||||
@ -206,7 +200,7 @@ repos:
|
||||
# patch target statically so a stale path fails the commit instead.
|
||||
- id: patch-targets
|
||||
name: test patch targets resolve
|
||||
entry: python3 scripts/check_patch_targets.py diet_guard
|
||||
entry: python3 scripts/check_patch_targets.py
|
||||
language: system
|
||||
pass_filenames: false
|
||||
files: ^diet_guard/
|
||||
@ -221,30 +215,6 @@ repos:
|
||||
language: system
|
||||
files: \.(md|markdown)$
|
||||
|
||||
- id: todo-closer
|
||||
name: close Todo trailer tasks
|
||||
entry: scripts/todo_hooks.sh closer
|
||||
language: system
|
||||
stages: [post-commit]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
|
||||
- id: todo-import-pr-merge
|
||||
name: import PR Todo sections (pull)
|
||||
entry: scripts/todo_hooks.sh import-pr post-merge
|
||||
language: system
|
||||
stages: [post-merge]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
|
||||
- id: todo-import-pr-rewrite
|
||||
name: import PR Todo sections (pull --rebase)
|
||||
entry: scripts/todo_hooks.sh import-pr post-rewrite
|
||||
language: system
|
||||
stages: [post-rewrite]
|
||||
always_run: true
|
||||
pass_filenames: false
|
||||
|
||||
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
||||
# so the question is mechanically answerable at all.
|
||||
#
|
||||
|
||||
138
AGENTS.md
138
AGENTS.md
@ -1,57 +1,51 @@
|
||||
# CLAUDE.md — diet_guard
|
||||
|
||||
A log-to-unlock gate. Every ~15 min `diet-guard-gate.timer` checks whether a meal slot (08:00,
|
||||
12:00, 16:00, 20:00 by default — the schedule is user-configurable, see below) elapsed unlogged; if
|
||||
so it opens a fullscreen Tk window that blocks the desktop until the user logs what they ate. It
|
||||
also tracks a daily calorie/macro budget, seeded from biometrics at `init` and freely editable
|
||||
afterward on either device. A History tab (`_gatelock_calendar.py`) and the phone's Calendar screen
|
||||
show adherence, streaks, a YTD tally and weekly/monthly averages, all derived from `_daystatus.py` /
|
||||
`day_status_service.dart` and `_averages.py` / `average_service.dart`.
|
||||
A log-to-unlock gate. Every ~15 min `diet-guard-gate.timer` checks whether a
|
||||
meal slot (08:00, 12:00, 16:00, 20:00 by default — the schedule is
|
||||
user-configurable, see below) elapsed unlogged; if so it opens a
|
||||
fullscreen Tk window that blocks the desktop until the user logs what they
|
||||
ate. It also tracks a daily calorie/macro budget, seeded from biometrics at
|
||||
`init` and freely editable afterward on either device. A History tab
|
||||
(`_gatelock_calendar.py`) and the phone's Calendar screen show adherence,
|
||||
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 catch-up rule).
|
||||
`docs/DOCS-design.md` holds the original spec (slot timing, the Tue/Wed/Thu
|
||||
catch-up rule).
|
||||
|
||||
## Commands
|
||||
|
||||
- One sync tick: `python -m diet_guard sync`
|
||||
- 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`
|
||||
- "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`
|
||||
- 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-changed: `scripts/test_changed.sh` (maps py and app/ dart changes to their tests, no coverage)
|
||||
- lint: n/a: dropped (kuhy, 2026-11-27)
|
||||
- coverage: n/a: dropped (kuhy, 2026-11-27)
|
||||
- deploy: `bash scripts/deploy.sh` (pull ~/src/diet-guard, system-Python install, desktop app; health-checked)
|
||||
- coverage-gaps: n/a: dropped (kuhy, 2026-11-27)
|
||||
- lint: `pre-commit run --all-files`
|
||||
- coverage: `python -m pytest -n auto -p no:sugar -q` (writes coverage.lcov)
|
||||
- coverage-gaps: `coverage-gaps coverage.lcov`
|
||||
|
||||
## Scheduling
|
||||
|
||||
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15:00`, `Persistent=true`), not
|
||||
boot-relative — a boot-relative timer collided with fullscreen games grabbing input.
|
||||
`diet-guard-gate.service` is `Type=oneshot` and exits 0 at once when no lock is due (free/sick day:
|
||||
[docs/DOCS-sick-days.md](docs/DOCS-sick-days.md)). Needs `DISPLAY`/`XAUTHORITY`; see the unit file
|
||||
and `wait_for_display()`.
|
||||
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15:00`,
|
||||
`Persistent=true`), not boot-relative — a boot-relative timer collided with
|
||||
fullscreen games grabbing input. `diet-guard-gate.service` is `Type=oneshot`
|
||||
and exits 0 at once when no lock is due (free/sick day: [docs/DOCS-sick-days.md](docs/DOCS-sick-days.md)).
|
||||
Needs `DISPLAY`/`XAUTHORITY`; see the unit file and `wait_for_display()`.
|
||||
|
||||
## Cross-device sync
|
||||
|
||||
A sync tick pulls every other device's log from `kuhyx/syncs` (`diet-guard-sync/`, dumb file storage
|
||||
via the REST Contents API), merges (`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
|
||||
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food bank, pushes back.
|
||||
A sync tick pulls every other device's log from `kuhyx/syncs`
|
||||
(`diet-guard-sync/`, dumb file storage via the REST Contents API), merges
|
||||
(`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
|
||||
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food
|
||||
bank, pushes back.
|
||||
|
||||
**End-to-end encrypted** (since 2026-11-12, `_sync_e2e.py` / `app/lib/services/sync_e2e.dart`):
|
||||
everything lives on `diet-guard-sync/devices-e2e` (revs `revs-e2e`, header `diet-guard-sync/e2e`),
|
||||
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.
|
||||
**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
|
||||
`gate_is_due()` first and pulls *only* when a lock is otherwise due, so a
|
||||
@ -115,18 +109,19 @@ moments state actually changes here.
|
||||
|
||||
## Production dependency installation
|
||||
|
||||
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new non-stdlib dependency must
|
||||
go into system Python's user site-packages:
|
||||
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new
|
||||
non-stdlib dependency must go into system Python's user site-packages:
|
||||
|
||||
```bash
|
||||
/usr/bin/python3 -m pip install --user --break-system-packages -e .
|
||||
```
|
||||
|
||||
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv. Installing only into `.venv`
|
||||
caused a 3-day production outage (2026-06-19).
|
||||
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv.
|
||||
Installing only into `.venv` caused a 3-day production outage (2026-06-19).
|
||||
|
||||
Run `install.sh` from a **durable** clone (`~/src/diet-guard`), never a scratch dir — it does `pip
|
||||
install -e`, so the clone must persist for `git pull` to reach the running service.
|
||||
Run `install.sh` from a **durable** clone (`~/src/diet-guard`), never a scratch
|
||||
dir — it does `pip install -e`, so the clone must persist for `git pull` to
|
||||
reach the running service.
|
||||
|
||||
## Operational gotchas
|
||||
|
||||
@ -143,7 +138,6 @@ install -e`, so the clone must persist for `git pull` to reach the running servi
|
||||
`test_budget_history.py`; it syncs as `hist:<YYYY-MM-DD>` fields on the
|
||||
existing `budget` record, so devices predating the feature relay them
|
||||
untouched.
|
||||
- **Offline first**: save locally before any network call; store fetched data on disk (`kuchnia_delivery.json`, both devices).
|
||||
- **Body data persists and syncs** (profile, weight log, PC workouts) as
|
||||
`body.json`; its tables are informational. [docs/DOCS-body.md](docs/DOCS-body.md).
|
||||
- **PC and phone share one source of truth for everything**: food log, budget,
|
||||
@ -162,14 +156,16 @@ install -e`, so the clone must persist for `git pull` to reach the running servi
|
||||
|
||||
## The companion app's desktop target is a web build
|
||||
|
||||
`app/` builds for **Android** and **web** only. There is no `app/linux/` — Flutter's GTK embedder
|
||||
manages ~20fps at 3840x2160 where the same Dart in Chrome sustains ~144fps
|
||||
(`~/src/todo/docs/DOCS-desktop-performance-findings.md`). The desktop app is the web build served by
|
||||
`bin/diet_guard_desktop.dart` in a Chrome `--app` window.
|
||||
`app/` builds for **Android** and **web** only. There is no `app/linux/` —
|
||||
Flutter's GTK embedder manages ~20fps at 3840x2160 where the same Dart in
|
||||
Chrome sustains ~144fps (`~/src/todo/docs/DOCS-desktop-performance-findings.md`). The
|
||||
desktop app is the web build served by `bin/diet_guard_desktop.dart` in a
|
||||
Chrome `--app` window.
|
||||
|
||||
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io` only in `*_io.dart`
|
||||
seams and `lib/desktop/`, port 8732 and the `diet-guard-desktop` Chrome profile pinned (IndexedDB is
|
||||
keyed by origin, so changing either hides the entire local food log).
|
||||
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io`
|
||||
only in `*_io.dart` seams and `lib/desktop/`, port 8732 and the
|
||||
`diet-guard-desktop` Chrome profile pinned (IndexedDB is keyed by origin, so
|
||||
changing either hides the entire local food log).
|
||||
|
||||
- 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
|
||||
@ -182,17 +178,19 @@ keyed by origin, so changing either hides the entire local food log).
|
||||
|
||||
## The meal schedule
|
||||
|
||||
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and how many meals fall
|
||||
between them; interior slots round to the 15-min grid. Default `(480, 1200, 4)` is the old hardcoded
|
||||
08/12/16/20. The load-bearing 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
|
||||
satisfaction), the forward-only history, and the two edit surfaces are in
|
||||
[docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) — read it before touching `_slots.py` /
|
||||
`_slot_wire.py` / `slot.dart`.
|
||||
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and
|
||||
how many meals fall between them; interior slots round to the 15-min grid.
|
||||
Default `(480, 1200, 4)` is the old hardcoded 08/12/16/20. The load-bearing
|
||||
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 satisfaction), the forward-only history, and the two edit
|
||||
surfaces are in [docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) —
|
||||
read it before touching `_slots.py` / `_slot_wire.py` / `slot.dart`.
|
||||
|
||||
## Averages (`_averages.py` / `average_service.dart`)
|
||||
|
||||
Three load-bearing rules; changing any silently changes what "under budget" means:
|
||||
Three load-bearing rules; changing any silently changes what "under budget"
|
||||
means:
|
||||
|
||||
- **Denominator is logged days, not elapsed days.** An unlogged day is not a
|
||||
zero-kcal day.
|
||||
@ -202,9 +200,10 @@ Three load-bearing rules; changing any silently changes what "under budget" mean
|
||||
week" is empty on a Monday, and reports `no logged days yet` rather than a
|
||||
fake average.
|
||||
|
||||
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` / `kOverBudgetYellowCeiling` **by
|
||||
import, not by copy**. The MCP `get_averages` tool drops `avg_budget` (budget secrecy on the network
|
||||
only); the CLI, gate and phone show both.
|
||||
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` /
|
||||
`kOverBudgetYellowCeiling` **by import, not by copy**. The MCP `get_averages`
|
||||
tool drops `avg_budget` (budget secrecy on the network only); the CLI, gate and
|
||||
phone show both.
|
||||
|
||||
## Do NOT
|
||||
|
||||
@ -218,18 +217,18 @@ only); the CLI, gate and phone show both.
|
||||
(`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
|
||||
can never be satisfied, i.e. a permanent lock. Integer `//` and `~/` only.
|
||||
- Don't re-add the meal builder, "repeat last meal" or the reward prompt
|
||||
(removed deliberately, `app/test/repo_invariants_test.dart`). A meal photo is
|
||||
transient input to Claude only (2026-11-17): never stored, on a `FoodEntry`
|
||||
or synced; the invariants test asserts no image bytes reach a record.
|
||||
- Don't re-add the meal builder, "repeat last meal", the reward prompt, or
|
||||
**meal photos** — all removed deliberately, enforced by
|
||||
`app/test/repo_invariants_test.dart`. Photos also took `image_picker`, the
|
||||
blob stores, the `/blobs/` route and the `CAMERA` permission; re-adding them
|
||||
means syncing image blobs too.
|
||||
- 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
|
||||
format.
|
||||
- Catering logs itself since 2026-11-17 (kuhy overrode "delivered ≠ eaten":
|
||||
"LOG EVEN WITHOUT TAP"): v5 ids `kuchnia:<date>:<dishId>`, undo tombstones.
|
||||
Don't let its Python and Dart halves drift (shared fixtures) or make the
|
||||
synced password machine-local. [docs](docs/DOCS-kuchnia-wikinga.md),
|
||||
[phone](docs/DOCS-kuchnia-wikinga-phone.md).
|
||||
- Don't let the catering import log unattended (delivered ≠ eaten), don't let
|
||||
its Python and Dart halves drift (one shared fixture gates them), and don't
|
||||
make the synced password machine-local — the phone could not then fetch.
|
||||
[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 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
|
||||
@ -241,7 +240,8 @@ only); the CLI, gate and phone show both.
|
||||
## Flutter/Dart AI rules
|
||||
|
||||
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
||||
via `~/.claude/CLAUDE.md`. Re-fetch periodically. Split across five files for the 250-line cap._
|
||||
via `~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically.
|
||||
Split across five files to stay under the 250-line cap._
|
||||
|
||||
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
|
||||
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)
|
||||
|
||||
@ -1,20 +0,0 @@
|
||||
# diet-guard dopamine-ux: context
|
||||
|
||||
## context you would otherwise rediscover
|
||||
|
||||
- This app has **no `design_system` dependency** — `app/lib/ui/theme.dart` is a
|
||||
hand-transcription of the shared tokens (values are byte-identical, names in
|
||||
comments). Motion tokens from prompt 01 must be **transcribed into that local
|
||||
theme file**, matching the existing convention. Do not add the dependency here;
|
||||
that is a separate, larger refactor.
|
||||
- Capability baseline, verified 2026-08-16: **no audio package, no `assets:`
|
||||
block, no `vibration` package, no VIBRATE permission.** The only existing
|
||||
audio-adjacent thing is the `diet_guard_due_slot` notification channel
|
||||
(`app/lib/services/notification_backend_io.dart` ~:17-18, :52-55) at
|
||||
`Importance.high` with no explicit sound/vibration override — leave it alone.
|
||||
- The app already computes both a **logging streak** and an **adherence streak**
|
||||
(`_daystatus.py:144`/`:153` on the Python side, mirrored in Dart). You are
|
||||
making existing true data feel like something, not inventing a new metric.
|
||||
- diet-guard state lives under XDG (`~/.local/share/diet_guard`), unlike
|
||||
screen-locker's in-repo JSON. Tests isolate it via
|
||||
`~/src/diet-guard/diet_guard/tests/conftest.py:97` `_isolate_state`.
|
||||
@ -1,30 +0,0 @@
|
||||
# Lock order
|
||||
|
||||
When several locks are due at once, gatelock shows the one with the highest
|
||||
rank first. Each lower lock waits, with no window, until every higher lock has
|
||||
been cleared. kuhy fixed this order on 2026-11-21:
|
||||
|
||||
| Order | Lock | gatelock app | Rank | Repo |
|
||||
|---|---|---|---|---|
|
||||
| 1 | workout | screen_locker | 200 | screen-locker |
|
||||
| 2 | book | book_guard | 175 | book-guard |
|
||||
| 3 | tutor | tutor_gate | 150 | tutor |
|
||||
| 4 | diet | diet_guard | 130 | diet-guard |
|
||||
| 5 | focus | focus_guard | 128 | focus-guard |
|
||||
| 6 | leetcode | leetcode_guard | 125 | leetcode-guard |
|
||||
|
||||
LeetCode goes last. Each rank is a literal in its own repo, not a
|
||||
`gatelock.RANK_*` constant, so changing one does not need a gatelock release.
|
||||
Every repo keeps a copy of this file, and its tests fail when its own number
|
||||
differs from its row here. Change the rank, this table and the copies in the
|
||||
other repos together.
|
||||
|
||||
Not in the table:
|
||||
|
||||
- The wake alarm (300) outranks everything.
|
||||
- The evening chain (`gatelock.evening_chain`) runs its rungs one at a time,
|
||||
in the order book, tutor, LeetCode. Its book rung locks at 150, which ties
|
||||
the tutor. Ranks only order locks that are due at the same moment.
|
||||
- All of these lock with a global grab and VT switching disabled, so no
|
||||
higher rank is ever a weaker lock. `gatelock/scripts/verify_all_lockers.py`
|
||||
checks this order on a private X server.
|
||||
@ -87,15 +87,6 @@ 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
|
||||
(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
|
||||
|
||||
```bash
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- Sync (github_client.dart) needs raw socket access. -->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<!-- HapticFeedback on a successful meal log (log_meal_screen.dart). -->
|
||||
<uses-permission android:name="android.permission.VIBRATE"/>
|
||||
<!-- Android 13+ requires runtime opt-in to post notifications; requested
|
||||
at launch via NotificationService.requestPermission(). -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
@ -19,12 +17,6 @@
|
||||
only, foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, so the
|
||||
WorkManager isolate never reads Health Connect. -->
|
||||
<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
|
||||
check is a 15-minute WorkManager periodic task, not exact alarms
|
||||
(more robust against OEM background-kill; +/-15 min is accepted, see
|
||||
|
||||
@ -1,7 +1,4 @@
|
||||
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
|
||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
||||
android.useAndroidX=true
|
||||
# This newDsl flag was added by the Flutter template
|
||||
android.newDsl=false
|
||||
|
||||
@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip
|
||||
|
||||
Binary file not shown.
@ -163,11 +163,6 @@ Future<bool> _launchBrowser(String home, int port) async {
|
||||
// a browser icon instead of diet_guard's.
|
||||
'--class=diet_guard_app',
|
||||
'--no-first-run',
|
||||
// The distro wrapper appends ~/.config/chromium-flags.conf to every launch,
|
||||
// which here carries `--load-extension` for Claude in Chrome. Logged out in
|
||||
// this profile, it opened a claude.ai login tab in a second, normal browser
|
||||
// window on every start. This flag also drops command-line extensions.
|
||||
'--disable-extensions',
|
||||
]);
|
||||
|
||||
final started = DateTime.now();
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
/// 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,7 +19,6 @@ library;
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:diet_guard_app/desktop/error_page.dart' show isNavigation;
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// GitHub's REST API base, which [GitHubProxy] fronts.
|
||||
@ -178,13 +177,8 @@ class GitHubProxy {
|
||||
}
|
||||
|
||||
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
|
||||
..statusCode = response.statusCode
|
||||
..headers.contentType = ContentType.json
|
||||
..add(response.bodyBytes);
|
||||
}
|
||||
|
||||
@ -24,7 +24,6 @@ import 'dart:io';
|
||||
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/error_page.dart';
|
||||
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
||||
import 'package:diet_guard_app/services/desktop_wrapper.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
@ -92,7 +91,6 @@ class WrapperServer {
|
||||
} on Exception {
|
||||
request.response.statusCode = HttpStatus.internalServerError;
|
||||
}
|
||||
paintErrorIcon(request);
|
||||
await request.response.close();
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,21 +3,13 @@
|
||||
library;
|
||||
|
||||
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/services/app_settings_service.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/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/document_store_factory.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/frame_stats.dart';
|
||||
import 'package:diet_guard_app/services/kuchnia_autolog.dart';
|
||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||
import 'package:diet_guard_app/services/kuchnia_queue.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
@ -25,31 +17,13 @@ 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/sync_device_id.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
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
|
||||
// device id falls back to the pre-migration role constant.
|
||||
final deviceId = await initSyncDeviceId();
|
||||
errors.connect(
|
||||
sink: () async => (await openFirebase())?.patchValues,
|
||||
deviceId: () async => deviceId,
|
||||
);
|
||||
await initSyncDeviceId();
|
||||
await LogStorageService.init();
|
||||
await AppSettingsService.init();
|
||||
await BudgetHistoryService.init();
|
||||
@ -58,10 +32,6 @@ Future<void> main() async {
|
||||
await KuchniaCredentialService.init();
|
||||
await BodyService.init();
|
||||
await KuchniaQueueService.init();
|
||||
// Offline first: the day's catering dishes survive a restart.
|
||||
KuchniaAutoLog.instance = KuchniaAutoLog(store: await openDocumentStore());
|
||||
// The sparkle button's transport; until this line it fails closed.
|
||||
claudeRelay = RtdbClaudeRelay.firebase();
|
||||
final notifications = await NotificationService.init();
|
||||
// Deliberately *not* awaited before the first frame: the browser's
|
||||
// `Notification.requestPermission()` does not complete until the user
|
||||
@ -81,25 +51,19 @@ Future<void> main() async {
|
||||
// coverage:ignore-start
|
||||
if (frameStatsEnabled) startFrameStats();
|
||||
// coverage:ignore-end
|
||||
runApp(DietGuardApp(errors: errors));
|
||||
runApp(const DietGuardApp());
|
||||
}
|
||||
|
||||
/// Root widget for the Diet Guard companion app.
|
||||
class DietGuardApp extends StatelessWidget {
|
||||
/// Creates the [DietGuardApp] root widget.
|
||||
const DietGuardApp({this.errors, super.key});
|
||||
|
||||
/// App-wide error reporting; null in widget tests.
|
||||
final AppErrors? errors;
|
||||
const DietGuardApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Diet Guard',
|
||||
theme: buildAppTheme(),
|
||||
navigatorObservers: [
|
||||
if (errors case final errors?) AppErrorsRouteObserver(errors),
|
||||
],
|
||||
home: const LogMealScreen(),
|
||||
);
|
||||
}
|
||||
|
||||
@ -20,35 +20,8 @@ class KuchniaDish {
|
||||
required this.grams,
|
||||
required this.priority,
|
||||
required this.slotLabel,
|
||||
this.dishId = '',
|
||||
});
|
||||
|
||||
/// Rebuilds a dish stored by [toJson]; throws on a malformed record.
|
||||
factory KuchniaDish.fromJson(Map<String, Object?> json) => KuchniaDish(
|
||||
name: json['name']! as String,
|
||||
kcal: (json['kcal']! as num).toDouble(),
|
||||
proteinG: (json['protein_g']! as num).toDouble(),
|
||||
carbsG: (json['carbs_g']! as num).toDouble(),
|
||||
fatG: (json['fat_g']! as num).toDouble(),
|
||||
grams: (json['grams']! as num).toDouble(),
|
||||
priority: json['priority']! as int,
|
||||
slotLabel: json['slot_label']! as String,
|
||||
dishId: json['dish_id'] as String? ?? '',
|
||||
);
|
||||
|
||||
/// The stored form; the keys follow the PC's `kuchnia_delivery.json`.
|
||||
Map<String, Object?> toJson() => {
|
||||
'name': name,
|
||||
'kcal': kcal,
|
||||
'protein_g': proteinG,
|
||||
'carbs_g': carbsG,
|
||||
'fat_g': fatG,
|
||||
'grams': grams,
|
||||
'priority': priority,
|
||||
'slot_label': slotLabel,
|
||||
'dish_id': dishId,
|
||||
};
|
||||
|
||||
/// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...".
|
||||
///
|
||||
/// Not `mealName`, which is the slot label ("Kolacja") and would collapse
|
||||
@ -79,17 +52,6 @@ class KuchniaDish {
|
||||
/// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only.
|
||||
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.
|
||||
///
|
||||
/// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count
|
||||
|
||||
@ -10,28 +10,76 @@ library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:diet_guard_app/screens/body_screen_data.dart';
|
||||
import 'package:diet_guard_app/services/activity_kcal.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
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_prefs.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/health_steps.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/widgets/body/activity_card.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_stats_cards.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_tile_grid.dart';
|
||||
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/week_plan_card.dart';
|
||||
import 'package:diet_guard_app/widgets/body/weight_card.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
export 'package:diet_guard_app/screens/body_screen_data.dart';
|
||||
/// Builds the person from the stored profile and newest weight, or null
|
||||
/// when anything the formulas need is missing.
|
||||
Biometrics? currentBiometrics(BodyService body, DateTime today) {
|
||||
final birth = DateTime.tryParse(body.birth ?? '');
|
||||
final height = body.heightCm;
|
||||
final sex = body.sex;
|
||||
final weight = body.latestWeight;
|
||||
if (birth == null || height == null || sex == null || weight == null) {
|
||||
return null;
|
||||
}
|
||||
return Biometrics(
|
||||
weightKg: weight.$2,
|
||||
heightCm: height,
|
||||
ageYears: ageOn(birth, today).toDouble(),
|
||||
isMale: sex == 'm',
|
||||
);
|
||||
}
|
||||
|
||||
/// Steps outside workouts by day, as stored.
|
||||
Map<String, int> stepsByDay(BodyService body) =>
|
||||
body.document.steps.map((day, entry) => MapEntry(day, entry.n));
|
||||
|
||||
/// Mean daily exercise per formula (steps included), the steps' own share,
|
||||
/// and the number of full days averaged -- like the PC's `_body_view`: the
|
||||
/// two means are null without a person, or without any published workout
|
||||
/// or step count.
|
||||
(Map<String, double>?, double?, int) bodyExercise(
|
||||
BodyService body,
|
||||
Biometrics? bio,
|
||||
DateTime today,
|
||||
) {
|
||||
final sessions = body.sessions;
|
||||
final steps = stepsByDay(body);
|
||||
if (bio == null || (sessions == null && steps.isEmpty)) {
|
||||
return (null, null, 0);
|
||||
}
|
||||
final byDay = steps.map((day, n) => MapEntry(day, stepKcal(n, bio)));
|
||||
final weight = bio.weightKg;
|
||||
final all = sessions ?? const <Session>[];
|
||||
return (
|
||||
dailyExercise(all, weight, today, byDay),
|
||||
extraShare(all, today, byDay),
|
||||
windowDays(all, today, byDay),
|
||||
);
|
||||
}
|
||||
|
||||
/// Sums each day's non-deleted kcal.
|
||||
Map<String, double> kcalByDay(DayLog log) => {
|
||||
for (final entry in log.entries)
|
||||
entry.key: entry.value
|
||||
.where((food) => !food.deleted)
|
||||
.fold<double>(0, (sum, food) => sum + food.kcal),
|
||||
};
|
||||
|
||||
/// The Body screen.
|
||||
class BodyScreen extends StatefulWidget {
|
||||
@ -52,17 +100,7 @@ class _BodyScreenState extends State<BodyScreen> {
|
||||
late final bool _profileAtTop = !BodyService.instance.profileComplete;
|
||||
|
||||
/// Whether the Health Connect button shows: supported and not yet granted.
|
||||
///
|
||||
/// A notifier, not a bool: the Activity sheet stays open while the
|
||||
/// permission is granted, and its button must disappear and its numbers
|
||||
/// refresh without reopening the sheet.
|
||||
final ValueNotifier<bool> _canConnectSteps = ValueNotifier(false);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_canConnectSteps.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
bool _canConnectSteps = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@ -79,8 +117,7 @@ class _BodyScreenState extends State<BodyScreen> {
|
||||
final granted = await source.hasPermission().catchError((_) => false);
|
||||
if (granted) await refreshSteps();
|
||||
if (!mounted) return;
|
||||
_canConnectSteps.value = !granted;
|
||||
setState(() {});
|
||||
setState(() => _canConnectSteps = !granted);
|
||||
}
|
||||
|
||||
Future<void> _connectSteps() async {
|
||||
@ -89,8 +126,7 @@ class _BodyScreenState extends State<BodyScreen> {
|
||||
);
|
||||
if (granted) await refreshSteps();
|
||||
if (!mounted) return;
|
||||
_canConnectSteps.value = !granted;
|
||||
setState(() {});
|
||||
setState(() => _canConnectSteps = !granted);
|
||||
}
|
||||
|
||||
Future<void> _loadLog() async {
|
||||
@ -108,140 +144,70 @@ class _BodyScreenState extends State<BodyScreen> {
|
||||
final body = BodyService.instance;
|
||||
final today = DateTime.now();
|
||||
final bio = currentBiometrics(body, today);
|
||||
final (exercise, _, _) = bodyExercise(body, bio, today);
|
||||
final tiles = _tiles(body, bio, exercise);
|
||||
final sessions = body.sessions;
|
||||
final weight = body.latestWeight?.$2;
|
||||
final (exercise, stepsKcal, window) = bodyExercise(body, bio, today);
|
||||
final bodyFat = body.latestBodyFat?.$2;
|
||||
final profile = ProfileCard(onSaved: _onChanged);
|
||||
return Scaffold(
|
||||
appBar: AppBar(),
|
||||
body: Padding(
|
||||
appBar: AppBar(title: const Text('Body')),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||
child: BodyTileGrid(tiles: tiles),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// The Activity card from the live service state.
|
||||
Widget _activityCard({required bool canConnect}) {
|
||||
final body = BodyService.instance;
|
||||
final (exercise, stepsKcal, window) = bodyExercise(
|
||||
body,
|
||||
currentBiometrics(body, DateTime.now()),
|
||||
DateTime.now(),
|
||||
);
|
||||
return ActivityCard(
|
||||
sessions: body.sessions,
|
||||
weightKg: body.latestWeight?.$2,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (_profileAtTop) profile,
|
||||
if (bio == null)
|
||||
BodySection(
|
||||
title: 'Daily calorie target',
|
||||
children: [BodyNote(_missing(body))],
|
||||
)
|
||||
else
|
||||
GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
|
||||
WeightCard(onChanged: _onChanged),
|
||||
if (bio != null) ...[
|
||||
BmiCard(bio: bio),
|
||||
IdealWeightCard(bio: bio),
|
||||
BmrCard(bio: bio, bodyFatPct: bodyFat),
|
||||
],
|
||||
ActivityCard(
|
||||
sessions: sessions,
|
||||
weightKg: weight,
|
||||
exercise: exercise,
|
||||
steps: stepsByDay(body),
|
||||
stepsKcal: stepsKcal,
|
||||
window: window,
|
||||
onConnectSteps: canConnect ? _connectSteps : null,
|
||||
);
|
||||
}
|
||||
|
||||
/// Every section as a tile: the profile first while it is incomplete, last
|
||||
/// otherwise (decided once, see [_profileAtTop]).
|
||||
List<BodyTileSpec> _tiles(
|
||||
BodyService body,
|
||||
Biometrics? bio,
|
||||
Map<String, double>? exercise,
|
||||
) {
|
||||
final weight = body.latestWeight?.$2;
|
||||
final bodyFat = body.latestBodyFat?.$2;
|
||||
final age = bodyAgeText(body, DateTime.now());
|
||||
final profile = BodyTileSpec(
|
||||
semanticLabel: 'Profile',
|
||||
icon: Icons.person,
|
||||
value: age,
|
||||
valueIcon: age == null ? null : Icons.cake,
|
||||
builder: (_) => ProfileCard(onSaved: _onChanged),
|
||||
);
|
||||
final goal = bio == null
|
||||
? null
|
||||
: goalTarget(
|
||||
savedGoal(body),
|
||||
tableBmr(bio, bodyFat).value!,
|
||||
tableBmr(bio, bodyFat).name,
|
||||
exercise,
|
||||
).kcal;
|
||||
return [
|
||||
if (_profileAtTop) profile,
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Daily calorie target',
|
||||
icon: Icons.flag,
|
||||
value: goal == null ? null : '$goal',
|
||||
valueIcon: goal == null ? null : MacroKind.kcal.icon,
|
||||
builder: (_) => bio == null
|
||||
? BodySection(
|
||||
semanticLabel: 'Daily calorie target',
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
for (final icon in bodyMissingIcons(body))
|
||||
StatusCue(
|
||||
kind: CueKind.warn,
|
||||
icon: icon,
|
||||
semanticLabel: bodyMissingNote(body),
|
||||
onConnectSteps: _canConnectSteps ? _connectSteps : null,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
: GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
|
||||
),
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Weight',
|
||||
icon: Icons.monitor_weight,
|
||||
value: weight == null ? null : formatKg(weight),
|
||||
builder: (_) => WeightCard(onChanged: _onChanged),
|
||||
),
|
||||
if (bio != null) ...[
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'BMI',
|
||||
icon: Icons.accessibility_new,
|
||||
value: oneDecimal(bmiReport(bio).bmi),
|
||||
builder: (_) => BmiCard(bio: bio),
|
||||
),
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Ideal weight',
|
||||
icon: Icons.balance,
|
||||
builder: (_) => IdealWeightCard(bio: bio),
|
||||
),
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Resting metabolism (BMR)',
|
||||
icon: Icons.bedtime,
|
||||
value: whole(tableBmr(bio, bodyFat).value!),
|
||||
valueIcon: MacroKind.kcal.icon,
|
||||
builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat),
|
||||
),
|
||||
],
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Activity',
|
||||
icon: Icons.directions_run,
|
||||
builder: (_) => ValueListenableBuilder<bool>(
|
||||
valueListenable: _canConnectSteps,
|
||||
builder: (_, canConnect, _) => _activityCard(canConnect: canConnect),
|
||||
),
|
||||
),
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Week planner',
|
||||
icon: Icons.calendar_view_week,
|
||||
builder: (_) => WeekPlanCard(
|
||||
WeekPlanCard(
|
||||
defaultTarget: AppSettingsService.dailyKcalGoal,
|
||||
logged: _logged,
|
||||
),
|
||||
),
|
||||
if (!_profileAtTop) profile,
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Body fat',
|
||||
icon: Icons.percent,
|
||||
value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %',
|
||||
builder: (_) => BodyFatCard(onChanged: _onChanged),
|
||||
BodyFatCard(onChanged: _onChanged),
|
||||
BodyNote('Age ${_age(body, today)} · synced with the PC.'),
|
||||
],
|
||||
),
|
||||
];
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _missing(BodyService body) {
|
||||
if (body.latestWeight == null && body.birth == null) {
|
||||
return 'Set your profile and enter your weight to see BMI, ideal '
|
||||
'weight and calorie targets.';
|
||||
}
|
||||
if (body.latestWeight == null) return 'Enter your weight to see the numbers.';
|
||||
return 'Set your profile (birth date, height, sex) to see the numbers.';
|
||||
}
|
||||
|
||||
String _age(BodyService body, DateTime today) {
|
||||
final birth = DateTime.tryParse(body.birth ?? '');
|
||||
return birth == null ? 'unknown' : '${ageOn(birth, today)}';
|
||||
}
|
||||
|
||||
@ -1,88 +0,0 @@
|
||||
/// Pure data helpers behind the Body screen (split out for the 250-line cap).
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/services/activity_kcal.dart';
|
||||
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_steps.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
|
||||
/// when anything the formulas need is missing.
|
||||
Biometrics? currentBiometrics(BodyService body, DateTime today) {
|
||||
final birth = DateTime.tryParse(body.birth ?? '');
|
||||
final height = body.heightCm;
|
||||
final sex = body.sex;
|
||||
final weight = body.latestWeight;
|
||||
if (birth == null || height == null || sex == null || weight == null) {
|
||||
return null;
|
||||
}
|
||||
return Biometrics(
|
||||
weightKg: weight.$2,
|
||||
heightCm: height,
|
||||
ageYears: ageOn(birth, today).toDouble(),
|
||||
isMale: sex == 'm',
|
||||
);
|
||||
}
|
||||
|
||||
/// Steps outside workouts by day, as stored.
|
||||
Map<String, int> stepsByDay(BodyService body) =>
|
||||
body.document.steps.map((day, entry) => MapEntry(day, entry.n));
|
||||
|
||||
/// Mean daily exercise per formula (steps included), the steps' own share,
|
||||
/// and the number of full days averaged -- like the PC's `_body_view`: the
|
||||
/// two means are null without a person, or without any published workout
|
||||
/// or step count.
|
||||
(Map<String, double>?, double?, int) bodyExercise(
|
||||
BodyService body,
|
||||
Biometrics? bio,
|
||||
DateTime today,
|
||||
) {
|
||||
final sessions = body.sessions;
|
||||
final steps = stepsByDay(body);
|
||||
if (bio == null || (sessions == null && steps.isEmpty)) {
|
||||
return (null, null, 0);
|
||||
}
|
||||
final byDay = steps.map((day, n) => MapEntry(day, stepKcal(n, bio)));
|
||||
final weight = bio.weightKg;
|
||||
final all = sessions ?? const <Session>[];
|
||||
return (
|
||||
dailyExercise(all, weight, today, byDay),
|
||||
extraShare(all, today, byDay),
|
||||
windowDays(all, today, byDay),
|
||||
);
|
||||
}
|
||||
|
||||
/// Sums each day's non-deleted kcal.
|
||||
Map<String, double> kcalByDay(DayLog log) => {
|
||||
for (final entry in log.entries)
|
||||
entry.key: entry.value
|
||||
.where((food) => !food.deleted)
|
||||
.fold<double>(0, (sum, food) => sum + food.kcal),
|
||||
};
|
||||
|
||||
/// 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) {
|
||||
if (body.latestWeight == null && body.birth == null) {
|
||||
return 'Set your profile and enter your weight to see BMI, ideal '
|
||||
'weight and calorie targets.';
|
||||
}
|
||||
if (body.latestWeight == null) return 'Enter your weight to see the numbers.';
|
||||
return 'Set your profile (birth date, height, sex) to see the numbers.';
|
||||
}
|
||||
|
||||
/// The age in whole years, or null while no birth date is stored.
|
||||
String? bodyAgeText(BodyService body, DateTime today) {
|
||||
final birth = DateTime.tryParse(body.birth ?? '');
|
||||
return birth == null ? null : '${ageOn(birth, today)}';
|
||||
}
|
||||
@ -9,7 +9,6 @@ library;
|
||||
|
||||
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/period_average.dart';
|
||||
import 'package:diet_guard_app/screens/history_screen.dart';
|
||||
@ -18,13 +17,11 @@ 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/day_status_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/day_status_calendar.dart';
|
||||
import 'package:diet_guard_app/widgets/streak_summary_row.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
/// Screen showing the budget-adherence calendar, streaks, and budget entry.
|
||||
class CalendarScreen extends StatefulWidget {
|
||||
@ -154,10 +151,11 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_loading) {
|
||||
return const Scaffold(body: WaitWatch.centered('calendar.load'));
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
return Scaffold(
|
||||
appBar: AppBar(),
|
||||
appBar: AppBar(title: const Text('Calendar')),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
@ -170,10 +168,11 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
||||
if (_budgetStatus != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: StatusCue(
|
||||
key: ValueKey(_budgetStatus),
|
||||
kind: _budgetError ? CueKind.error : CueKind.ok,
|
||||
semanticLabel: _budgetStatus!,
|
||||
child: Text(
|
||||
_budgetStatus!,
|
||||
style: TextStyle(
|
||||
color: _budgetError ? theme.colorScheme.error : null,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
@ -216,11 +215,7 @@ class _BudgetRow extends StatelessWidget {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
MacroKind.kcal.icon,
|
||||
color: MacroKind.kcal.color,
|
||||
semanticLabel: 'Daily budget (kcal)',
|
||||
),
|
||||
const Text('Daily budget (kcal):'),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(
|
||||
width: 90,
|
||||
@ -235,10 +230,7 @@ class _BudgetRow extends StatelessWidget {
|
||||
const SizedBox(width: 8),
|
||||
FilledButton(
|
||||
onPressed: onEditOrSave,
|
||||
child: Icon(
|
||||
editing ? Icons.check : Icons.edit,
|
||||
semanticLabel: editing ? 'Save' : 'Edit',
|
||||
),
|
||||
child: Text(editing ? 'Save' : 'Edit'),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@ -8,10 +8,9 @@ import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.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/ui/cues.dart';
|
||||
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
|
||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
/// Edit screen for an existing [FoodEntry].
|
||||
@ -36,7 +35,6 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
||||
List<FoodSuggestion> _suggestions = const [];
|
||||
String _source = 'manual';
|
||||
String? _status;
|
||||
int _rejections = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@ -82,7 +80,9 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
||||
}
|
||||
|
||||
Future<void> _onDescChanged() async {
|
||||
final matches = await FoodBankService.instance.search(_descController.text);
|
||||
final matches = await FoodBankService.instance.search(
|
||||
_descController.text,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() => _suggestions = matches);
|
||||
}
|
||||
@ -104,10 +104,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
||||
Future<void> _onSave() async {
|
||||
final desc = _descController.text.trim();
|
||||
if (desc.isEmpty) {
|
||||
setState(() {
|
||||
_status = 'Description cannot be empty.';
|
||||
_rejections++;
|
||||
});
|
||||
setState(() => _status = 'Description cannot be empty.');
|
||||
return;
|
||||
}
|
||||
final nutrition = nutritionForPortion(
|
||||
@ -145,16 +142,17 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(),
|
||||
appBar: AppBar(title: const Text('Edit meal')),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
IconField(
|
||||
icon: Icons.restaurant,
|
||||
semanticLabel: 'What did you eat?',
|
||||
TextField(
|
||||
controller: _descController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'What did you eat?',
|
||||
),
|
||||
),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxHeight: 240),
|
||||
@ -170,20 +168,12 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: _onSave,
|
||||
child: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||
child: const Text('Save'),
|
||||
),
|
||||
),
|
||||
if (_status != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
// New key per rejection so a repeat error shakes again.
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: StatusCue(
|
||||
key: ValueKey(_rejections),
|
||||
kind: CueKind.error,
|
||||
semanticLabel: _status!,
|
||||
),
|
||||
),
|
||||
Text(_status!),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
||||
@ -8,15 +8,12 @@ library;
|
||||
|
||||
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/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_filter.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_tile_grid.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Browses every banked food -- log-derived and manually curated -- with
|
||||
/// filtering, sorting, and an add-entry dialog.
|
||||
@ -132,13 +129,6 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Shows the full macro line for a tapped tile.
|
||||
Future<void> _openDetail(FoodBankRecord record) => showModalBottomSheet<void>(
|
||||
context: context,
|
||||
useSafeArea: true,
|
||||
builder: (_) => SafeArea(child: RecordTile(record)),
|
||||
);
|
||||
|
||||
Future<void> _openAddDialog() async {
|
||||
final result = await showDialog<FoodBankRecord>(
|
||||
context: context,
|
||||
@ -154,16 +144,15 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
final all = _allEntries;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Food Bank'),
|
||||
actions: [
|
||||
if (all != null)
|
||||
Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.filter_list,
|
||||
semanticLabel: 'Filter & sort',
|
||||
),
|
||||
icon: const Icon(Icons.filter_list),
|
||||
tooltip: 'Filter & sort',
|
||||
onPressed: _openFilterSheet,
|
||||
),
|
||||
if (_filter.isActive)
|
||||
@ -184,23 +173,66 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
],
|
||||
),
|
||||
body: all == null
|
||||
? const WaitWatch.centered('food_bank.load')
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _displayed.isEmpty
|
||||
? Center(
|
||||
child: Icon(
|
||||
all.isEmpty ? Icons.restaurant_menu : Icons.filter_list_off,
|
||||
size: 64,
|
||||
color: Theme.of(context).colorScheme.outline,
|
||||
semanticLabel: all.isEmpty
|
||||
? 'Food bank is empty.'
|
||||
child: Text(
|
||||
all.isEmpty
|
||||
? 'Food bank is empty.\n'
|
||||
'Log meals to populate it, or add entries manually.'
|
||||
: 'No entries match the current filter.',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
)
|
||||
: FbTileGrid(records: _displayed, onOpen: _openDetail),
|
||||
: ListView.builder(
|
||||
itemCount: _displayed.length,
|
||||
itemBuilder: (context, i) => RecordTile(_displayed[i]),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: _openAddDialog,
|
||||
child: const Icon(Icons.add, semanticLabel: 'Add manual entry'),
|
||||
tooltip: 'Add manual entry',
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Record tile
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// One banked food: its name, macros, and how often it has been logged.
|
||||
class RecordTile extends StatelessWidget {
|
||||
/// Creates a [RecordTile] for [record].
|
||||
const RecordTile(this.record, {super.key});
|
||||
|
||||
/// The banked record this tile renders.
|
||||
final FoodBankRecord record;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final macros =
|
||||
'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(
|
||||
title: Text(record.desc),
|
||||
subtitle: Text(
|
||||
'${record.kcal.toStringAsFixed(0)} kcal$per · $macros',
|
||||
),
|
||||
trailing: record.count > 0
|
||||
? Text(
|
||||
'×${record.count.toStringAsFixed(0)}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filter sheet
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@ -28,27 +28,54 @@ class _ClientIdSetupDialogState extends State<_ClientIdSetupDialog> {
|
||||
|
||||
@override
|
||||
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(
|
||||
content: IconField(
|
||||
icon: Icons.apps,
|
||||
semanticLabel: 'Client ID',
|
||||
title: const Text('One-time GitHub setup needed'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
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: [
|
||||
IconButton(
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
IconButton.filled(
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final id = _controller.text.trim();
|
||||
if (id.isNotEmpty) Navigator.of(context).pop(id);
|
||||
},
|
||||
icon: const Icon(Icons.arrow_forward, semanticLabel: 'Continue'),
|
||||
child: const Text('Continue'),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@ -21,7 +21,7 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
||||
TextEditingController get _clientIdController;
|
||||
|
||||
bool _busy = false;
|
||||
Widget? _status;
|
||||
String? _status;
|
||||
String _storedToken = '';
|
||||
SyncSettings _currentSettings() {
|
||||
final typed = _tokenController.text.trim();
|
||||
@ -37,18 +37,9 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
||||
clientId: _clientIdController.text.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Shows the outcome as an icon cue; [semanticLabel] is spoken, never
|
||||
/// painted.
|
||||
void _showCue(CueKind kind, String semanticLabel) {
|
||||
void _showMessage(String message) {
|
||||
if (!mounted) return;
|
||||
setState(
|
||||
() => _status = StatusCue(
|
||||
key: UniqueKey(),
|
||||
kind: kind,
|
||||
semanticLabel: semanticLabel,
|
||||
),
|
||||
);
|
||||
setState(() => _status = message);
|
||||
}
|
||||
|
||||
Future<void> _connectGitHub() async {
|
||||
@ -78,12 +69,12 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
||||
_storedToken = token;
|
||||
if (SyncSettings.exposesTokenValue) _tokenController.text = token;
|
||||
});
|
||||
_showCue(CueKind.info, 'Connected — syncing…');
|
||||
_showMessage('Connected — syncing…');
|
||||
await _currentSettings().save();
|
||||
await _syncAfterConnect();
|
||||
}
|
||||
} on Exception catch (e) {
|
||||
_showCue(CueKind.error, 'Could not start device flow: $e');
|
||||
_showMessage('Could not start device flow: $e');
|
||||
} finally {
|
||||
auth.close();
|
||||
}
|
||||
@ -97,10 +88,10 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
_showCue(CueKind.ok, 'Connected and synced.');
|
||||
_showMessage('Connected and synced.');
|
||||
} on Exception catch (e) {
|
||||
await SyncHealth.recordFailure();
|
||||
_showCue(CueKind.error, 'Connected, but sync failed: $e');
|
||||
_showMessage('Connected, but sync failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
@ -111,7 +102,7 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
||||
await _currentSettings().save();
|
||||
if (!mounted) return;
|
||||
setState(() => _busy = false);
|
||||
_showCue(CueKind.ok, 'Saved.');
|
||||
_showMessage('Saved.');
|
||||
}
|
||||
|
||||
Future<void> _testConnection() async {
|
||||
@ -120,13 +111,11 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
||||
final client = createGitHubClient(settings, httpClient: widget.httpClient);
|
||||
try {
|
||||
final ok = await client.canAccessRepo();
|
||||
if (ok) {
|
||||
_showCue(CueKind.ok, 'GitHub connection OK.');
|
||||
} else {
|
||||
_showCue(CueKind.error, 'GitHub connection failed.');
|
||||
}
|
||||
_showMessage(
|
||||
ok ? 'GitHub connection OK.' : 'GitHub connection failed.',
|
||||
);
|
||||
} on Exception catch (e) {
|
||||
_showCue(CueKind.error, 'GitHub connection failed: $e');
|
||||
_showMessage('GitHub connection failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
if (mounted) setState(() => _busy = false);
|
||||
@ -144,10 +133,10 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
|
||||
// *because* the banner told them syncing had stopped, so a successful
|
||||
// run here must dismiss the warning it caused.
|
||||
await SyncHealth.recordSuccess();
|
||||
_showCue(CueKind.ok, 'Synced.');
|
||||
_showMessage('Synced.');
|
||||
} on Exception catch (e) {
|
||||
await SyncHealth.recordFailure();
|
||||
_showCue(CueKind.error, 'Sync failed: $e');
|
||||
_showMessage('Sync failed: $e');
|
||||
} finally {
|
||||
client.close();
|
||||
if (mounted) setState(() => _busy = false);
|
||||
|
||||
@ -8,17 +8,15 @@ library;
|
||||
|
||||
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/github_client_factory.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_settings.dart';
|
||||
import 'package:diet_guard_app/ui/cues.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:http/http.dart' as http;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
part 'github_client_id_dialog.dart';
|
||||
part 'github_mirror_actions.dart';
|
||||
@ -96,87 +94,107 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
|
||||
/// The token as loaded, so a platform that cannot display it (web) still
|
||||
/// round-trips it instead of blanking it on the next save.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// Runs the OAuth device flow and, on success, fills in the token field.
|
||||
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_loading) {
|
||||
return const Scaffold(body: WaitWatch.centered('github_mirror.load'));
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
return Scaffold(
|
||||
// No title and no explanatory paragraph: the code glyph that opened this
|
||||
// screen names it, and the connect button is self-evident.
|
||||
appBar: AppBar(),
|
||||
// Centred and capped at the prose width so fields do not span the
|
||||
// whole window on the desktop surface.
|
||||
appBar: AppBar(title: const Text('Advanced sync (GitHub)')),
|
||||
// Centred and capped at the prose width -- see settings_screen.dart's
|
||||
// note on why: on the desktop surface an uncapped ListView spanned the
|
||||
// full window, so explanatory paragraphs ran far past the readable
|
||||
// line-length limit.
|
||||
body: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
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(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: IconButton.filled(
|
||||
child: FilledButton.icon(
|
||||
onPressed: _connectGitHub,
|
||||
icon: const Icon(
|
||||
Icons.login,
|
||||
semanticLabel: 'Connect GitHub',
|
||||
),
|
||||
icon: const Icon(Icons.login),
|
||||
label: const Text('Connect GitHub'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
IconField(
|
||||
icon: Icons.person_outline,
|
||||
semanticLabel: 'GitHub owner',
|
||||
TextField(
|
||||
controller: _ownerController,
|
||||
decoration: const InputDecoration(labelText: 'GitHub owner'),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
IconField(
|
||||
icon: Icons.folder_outlined,
|
||||
semanticLabel: 'Repo',
|
||||
TextField(
|
||||
controller: _repoController,
|
||||
decoration: const InputDecoration(labelText: 'Repo'),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
IconField(
|
||||
icon: Icons.apps,
|
||||
semanticLabel: 'OAuth App client id',
|
||||
TextField(
|
||||
controller: _clientIdController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'OAuth App client id',
|
||||
helperText: 'Needed for the Connect GitHub button',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
IconField(
|
||||
icon: Icons.key,
|
||||
semanticLabel: 'Personal access token (fallback)',
|
||||
TextField(
|
||||
controller: _tokenController,
|
||||
obscure: true,
|
||||
obscureText: 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),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
IconButton.filled(
|
||||
ElevatedButton(
|
||||
onPressed: _busy ? null : _save,
|
||||
icon: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||
child: const Text('Save'),
|
||||
),
|
||||
// Tests the GitHub connection only (a canAccessRepo call);
|
||||
// it says nothing about Firebase.
|
||||
IconButton.outlined(
|
||||
OutlinedButton(
|
||||
onPressed: _busy ? null : _testConnection,
|
||||
tooltip: 'Test',
|
||||
icon: const Icon(
|
||||
Icons.network_check,
|
||||
semanticLabel: 'Test GitHub connection',
|
||||
// Named for what it actually does: _testConnection builds
|
||||
// a GitHub client and calls canAccessRepo(). It says
|
||||
// nothing about Firebase, and the bare label implied
|
||||
// otherwise.
|
||||
child: const Text('Test GitHub connection'),
|
||||
),
|
||||
),
|
||||
IconButton.filled(
|
||||
ElevatedButton(
|
||||
onPressed: _busy ? null : _syncNow,
|
||||
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'),
|
||||
child: const Text('Sync now'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_status != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Align(alignment: Alignment.centerLeft, child: _status),
|
||||
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
||||
@ -7,7 +7,6 @@ library;
|
||||
|
||||
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/screens/edit_entry_screen.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
@ -15,7 +14,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_grouping.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_list.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Logged meal history: every entry, grouped by day, filterable and sortable.
|
||||
///
|
||||
@ -160,16 +159,15 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
final allEntries = _allEntries;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('History'),
|
||||
actions: [
|
||||
if (allEntries != null)
|
||||
Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.filter_list,
|
||||
semanticLabel: 'Filter & sort',
|
||||
),
|
||||
icon: const Icon(Icons.filter_list),
|
||||
tooltip: 'Filter & sort',
|
||||
onPressed: _openFilterSheet,
|
||||
),
|
||||
if (_filter.isActive)
|
||||
@ -190,14 +188,11 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
],
|
||||
),
|
||||
body: allEntries == null
|
||||
? const WaitWatch.centered('history.load')
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _displayed.isEmpty
|
||||
? Center(
|
||||
child: Icon(
|
||||
allEntries.isEmpty ? Icons.restaurant : Icons.filter_list_off,
|
||||
size: 64,
|
||||
color: Theme.of(context).colorScheme.outline,
|
||||
semanticLabel: allEntries.isEmpty
|
||||
child: Text(
|
||||
allEntries.isEmpty
|
||||
? 'Nothing logged yet.'
|
||||
: 'No entries match the current filter.',
|
||||
),
|
||||
|
||||
@ -2,11 +2,12 @@ import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_progress.dart';
|
||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 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.
|
||||
/// Split out of `log_meal_screen.dart` for the repo's 250-line cap, mirroring
|
||||
/// `log_meal_kuchnia_mixin.dart`'s `fillControllersFromDish`.
|
||||
void fillControllersFromSuggestion(
|
||||
FoodSuggestion suggestion,
|
||||
TextEditingController desc,
|
||||
@ -31,8 +32,7 @@ Nutrition nutritionFromControllers(MacroControllers macros, String source) =>
|
||||
source: source,
|
||||
);
|
||||
|
||||
/// The destination buttons in [LogMealScreen]'s app bar, after [leading]
|
||||
/// (the date picker).
|
||||
/// The five destination buttons in [LogMealScreen]'s app bar.
|
||||
///
|
||||
/// 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
|
||||
@ -43,32 +43,30 @@ List<Widget> logMealAppBarActions({
|
||||
required VoidCallback onCalendar,
|
||||
required VoidCallback onSettings,
|
||||
required VoidCallback onBody,
|
||||
List<Widget> leading = const [],
|
||||
}) => [
|
||||
...leading,
|
||||
IconButton(
|
||||
icon: const Icon(Icons.monitor_weight),
|
||||
tooltip: 'Body',
|
||||
icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'),
|
||||
onPressed: onBody,
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Foods',
|
||||
icon: const Icon(Icons.restaurant_menu, semanticLabel: 'Food bank'),
|
||||
icon: const Icon(Icons.restaurant_menu),
|
||||
tooltip: 'Food bank',
|
||||
onPressed: onFoodBank,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.history),
|
||||
tooltip: 'History',
|
||||
icon: const Icon(Icons.history, semanticLabel: 'History'),
|
||||
onPressed: onHistory,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.calendar_month),
|
||||
tooltip: 'Calendar',
|
||||
icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'),
|
||||
onPressed: onCalendar,
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Sync',
|
||||
icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'),
|
||||
icon: const Icon(Icons.settings),
|
||||
tooltip: 'Sync settings',
|
||||
onPressed: onSettings,
|
||||
),
|
||||
];
|
||||
|
||||
@ -1,137 +0,0 @@
|
||||
/// 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());
|
||||
}
|
||||
@ -1,89 +0,0 @@
|
||||
/// 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));
|
||||
}
|
||||
}
|
||||
105
app/lib/screens/log_meal_fill_mixin.dart
Normal file
105
app/lib/screens/log_meal_fill_mixin.dart
Normal file
@ -0,0 +1,105 @@
|
||||
/// 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,7 +3,10 @@
|
||||
/// 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
|
||||
/// tomorrow.
|
||||
/// tomorrow. Today's own not-yet-due slots keep using the screen's existing
|
||||
/// [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;
|
||||
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
@ -12,9 +15,9 @@ import 'package:diet_guard_app/models/meal_schedule.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/meal_schedule_service.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Adds a future-date meal-log picker to [LogMealScreen]'s state.
|
||||
mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
||||
@ -48,7 +51,7 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
||||
Future<void> _pickFutureDate() async {
|
||||
final today = DateTime.now();
|
||||
final tomorrow = DateTime(today.year, today.month, today.day + 1);
|
||||
final picked = await pickDate(
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
firstDate: tomorrow,
|
||||
lastDate: tomorrow.add(const Duration(days: 365)),
|
||||
@ -81,58 +84,51 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
||||
onLogDateChanged();
|
||||
}
|
||||
|
||||
/// The app bar's date actions: the picker (leftmost icon) and, once a date
|
||||
/// is picked, a way back to today. A picked date tints the picker gold with
|
||||
/// a small dot; no text is painted.
|
||||
List<Widget> buildDateActions(BuildContext context) {
|
||||
/// The "When" row: a "Log for later" button, or the picked date with a
|
||||
/// button to change it and one to clear back to today.
|
||||
Widget buildWhenRow(BuildContext context) {
|
||||
final date = _futureDate;
|
||||
final gold = Theme.of(context).colorScheme.primary;
|
||||
return [
|
||||
IconButton(
|
||||
// Not Icons.calendar_month: the bar's own "Calendar" nav button uses
|
||||
// that, and two on screen make `find.byIcon` ambiguous.
|
||||
icon: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.edit_calendar,
|
||||
color: date == null ? null : gold,
|
||||
semanticLabel: date == null ? 'Log for later' : 'Change date',
|
||||
),
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Icon(Icons.event, size: 18, color: scheme.onSurfaceVariant),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Expanded(child: Text(date == null ? 'Today' : localDateKey(date))),
|
||||
TextButton.icon(
|
||||
// Not Icons.calendar_month: the app bar's own "Calendar" nav button
|
||||
// already uses that, and a second one on screen makes
|
||||
// `find.byIcon` ambiguous for widget tests (and taps) alike.
|
||||
icon: const Icon(Icons.date_range, size: 18),
|
||||
label: Text(date == null ? 'Log for later' : 'Change date'),
|
||||
onPressed: _pickFutureDate,
|
||||
),
|
||||
if (date != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close, semanticLabel: 'Back to today'),
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: 'Back to today',
|
||||
onPressed: resetFutureLog,
|
||||
),
|
||||
];
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// The slot row for a picked future date, else nothing.
|
||||
///
|
||||
/// Today has no slot row any more: the screen derives today's slot (the
|
||||
/// oldest due one, else the nearest). A *future* date has no due slots to
|
||||
/// derive from, so the row survives for exactly that case.
|
||||
Widget buildSlotRow() {
|
||||
/// The slot row to show: [futureDate]'s own (driven by that date's logged
|
||||
/// slots) when a future date is picked, otherwise today's, built from the
|
||||
/// screen's own state and [onTodaySlotSelected].
|
||||
Widget buildSlotRow({
|
||||
required Set<int> loggedSlots,
|
||||
required int? selectedSlot,
|
||||
required ValueChanged<int?> onTodaySlotSelected,
|
||||
}) {
|
||||
final date = _futureDate;
|
||||
if (date == null) return const SizedBox.shrink();
|
||||
if (date == null) {
|
||||
return SlotSelectorRow(
|
||||
now: DateTime.now(),
|
||||
loggedSlots: loggedSlots,
|
||||
selectedSlot: selectedSlot,
|
||||
onSlotSelected: onTodaySlotSelected,
|
||||
);
|
||||
}
|
||||
return SlotSelectorRow(
|
||||
now: DateTime(date.year, date.month, date.day),
|
||||
schedule: _futureSchedule,
|
||||
|
||||
235
app/lib/screens/log_meal_kuchnia_mixin.dart
Normal file
235
app/lib/screens/log_meal_kuchnia_mixin.dart
Normal file
@ -0,0 +1,235 @@
|
||||
/// 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.';
|
||||
}
|
||||
}
|
||||
@ -1,82 +0,0 @@
|
||||
/// 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/history_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:material_ui/material_ui.dart';
|
||||
|
||||
/// The five app-bar destinations reachable from [LogMealScreen].
|
||||
///
|
||||
|
||||
@ -1,11 +1,9 @@
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/models/local_time.dart';
|
||||
import 'package:diet_guard_app/models/slot.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_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/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||
import 'package:diet_guard_app/widgets/today_progress_card.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
@ -16,13 +14,13 @@ double parseMacroField(TextEditingController controller) =>
|
||||
/// Summarises today from the log just written.
|
||||
///
|
||||
/// Takes the already-read [log] rather than re-reading, so the card can
|
||||
/// never disagree with the write that produced it. [logged] is that write:
|
||||
/// the card counts up from the totals without it.
|
||||
TodayProgress buildTodayProgress(DayLog log, {FoodEntry? logged}) {
|
||||
/// never disagree with the write that produced it.
|
||||
TodayProgress buildTodayProgress(DayLog log) {
|
||||
final budget = AppSettingsService.dailyKcalGoal;
|
||||
final today = localDateKey(DateTime.now());
|
||||
final entries = _live(log[today]);
|
||||
final before = logged == null ? log : _without(log, logged.id);
|
||||
final entries = (log[today] ?? const <FoodEntry>[])
|
||||
.where((entry) => !entry.deleted)
|
||||
.toList();
|
||||
final macros = sumMacros(entries);
|
||||
return TodayProgress(
|
||||
consumedKcal: sumKcal(entries),
|
||||
@ -30,28 +28,8 @@ TodayProgress buildTodayProgress(DayLog log, {FoodEntry? logged}) {
|
||||
proteinG: macros.proteinG,
|
||||
carbsG: macros.carbsG,
|
||||
fatG: macros.fatG,
|
||||
adherenceStreak: _streak(log),
|
||||
loggedSlotMinute: logged == null ? null : _slotOf(logged),
|
||||
loggedKcal: logged?.kcal,
|
||||
previousKcal: logged == null ? null : sumKcal(_live(before[today])),
|
||||
previousAdherenceStreak: logged == null ? null : _streak(before),
|
||||
adherenceStreak: adherenceStreak(
|
||||
statusMap(log, schedule: BudgetHistoryService.schedule),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
int _slotOf(FoodEntry entry) =>
|
||||
entry.slotMinute ??
|
||||
slotForLog(DateTime.parse(entry.time), MealScheduleService.current);
|
||||
|
||||
List<FoodEntry> _live(List<FoodEntry>? entries) =>
|
||||
(entries ?? const <FoodEntry>[]).where((entry) => !entry.deleted).toList();
|
||||
|
||||
int _streak(DayLog log) =>
|
||||
adherenceStreak(statusMap(log, schedule: BudgetHistoryService.schedule));
|
||||
|
||||
DayLog _without(DayLog log, String? id) => {
|
||||
for (final MapEntry(:key, :value) in log.entries)
|
||||
key: [
|
||||
for (final entry in value)
|
||||
if (entry.id != id) entry,
|
||||
],
|
||||
};
|
||||
|
||||
@ -1,54 +1,42 @@
|
||||
/// 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."
|
||||
///
|
||||
/// 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;
|
||||
|
||||
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/slot.dart';
|
||||
import 'package:diet_guard_app/screens/log_meal_actions.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_fill_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_kuchnia_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_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/log_feedback.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/ui/cues.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/autocomplete_suggestion_list.dart';
|
||||
import 'package:diet_guard_app/widgets/logged_meal_row.dart';
|
||||
import 'package:diet_guard_app/widgets/fill_all_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/meal_action_row.dart';
|
||||
import 'package:diet_guard_app/widgets/sync_health_banner.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:material_ui/material_ui.dart';
|
||||
|
||||
/// Lets the user log one food item, with food-bank autocomplete.
|
||||
/// Lets the user log one food item, with food-bank autocomplete and
|
||||
/// today's slot status.
|
||||
class LogMealScreen extends StatefulWidget {
|
||||
/// Creates a [LogMealScreen].
|
||||
const LogMealScreen({super.key, this.httpClient, this.relay, this.photos});
|
||||
const LogMealScreen({super.key, this.httpClient});
|
||||
|
||||
/// Injectable HTTP client for auto-sync; tests pass a [MockClient].
|
||||
/// Production leaves this null so [GitHubClient] builds a real one.
|
||||
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
|
||||
State<LogMealScreen> createState() => _LogMealScreenState();
|
||||
}
|
||||
@ -57,28 +45,20 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
with
|
||||
WidgetsBindingObserver,
|
||||
LogMealSyncMixin<LogMealScreen>,
|
||||
LogMealDueMixin<LogMealScreen>,
|
||||
LogMealLoggedMixin<LogMealScreen>,
|
||||
LogMealNavMixin<LogMealScreen>,
|
||||
LogMealKuchniaMixin<LogMealScreen>,
|
||||
LogMealFutureMixin<LogMealScreen>,
|
||||
LogMealClaudeMixin<LogMealScreen> {
|
||||
LogMealFillMixin<LogMealScreen> {
|
||||
@override
|
||||
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 MacroControllers _macros = MacroControllers();
|
||||
@override
|
||||
TextEditingController get claudeDesc => _descController;
|
||||
@override
|
||||
MacroControllers get claudeMacros => _macros;
|
||||
List<FoodSuggestion> _suggestions = const [];
|
||||
@override
|
||||
int? selectedSlot;
|
||||
String _source = 'manual';
|
||||
CueState? _cue; // painted as a tinted icon, never as text
|
||||
String? _status;
|
||||
TodayProgress? _progress;
|
||||
|
||||
@override
|
||||
@ -87,29 +67,39 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_descController.addListener(_onDescChanged);
|
||||
_macros.addListenerToAll(_onMacroEdited);
|
||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
||||
unawaited(refreshSlots());
|
||||
unawaited(_onDescChanged());
|
||||
// Health first, so a device that stalled earlier says so before a tick.
|
||||
// Read health before the first sync finishes, so a device that stalled in
|
||||
// a previous session says so immediately rather than only after a tick.
|
||||
unawaited(refreshSyncHealth());
|
||||
startOpenChain();
|
||||
unawaited(autoSync());
|
||||
// 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
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
disposeClaude();
|
||||
restoreStatusBar();
|
||||
_descController.dispose();
|
||||
_macros.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onMacroEdited() {
|
||||
if (_source == 'food bank') setState(() => _source = 'manual');
|
||||
if (_source == 'food bank') {
|
||||
setState(() => _source = 'manual');
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-runs the food-bank search and dismisses the previous progress card,
|
||||
/// only while the field is non-empty: [_onLogMeal]'s own `clear()` fires
|
||||
/// this listener too, and would otherwise race it and null the new card.
|
||||
/// Re-runs the food-bank search and dismisses the previous progress card.
|
||||
///
|
||||
/// The card is cleared only when the field is non-empty because
|
||||
/// [_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 {
|
||||
final matches = await FoodBankService.instance.search(_descController.text);
|
||||
if (!mounted) return;
|
||||
@ -119,6 +109,18 @@ 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) {
|
||||
fillControllersFromSuggestion(suggestion, _descController, _macros);
|
||||
setState(() {
|
||||
@ -129,15 +131,22 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
|
||||
Future<void> _onLogMeal() async {
|
||||
final desc = _descController.text.trim();
|
||||
if (desc.isEmpty) return;
|
||||
final target = resolveLogTarget(targetSlot);
|
||||
if (target.error != null) {
|
||||
setState(() => _cue = CueState.next(_cue, CueKind.error, target.error!));
|
||||
if (desc.isEmpty) {
|
||||
setState(() {
|
||||
_status = 'Type what you ate first.';
|
||||
_progress = null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
LogFeedback.mealLogged(); // on the tap, before the write
|
||||
unawaited(withdrawClaude()); // else Claude would log it a second time
|
||||
final entry = await LogStorageService.instance.logMeal(
|
||||
final target = resolveLogTarget(selectedSlot);
|
||||
if (target.error != null) {
|
||||
setState(() {
|
||||
_status = target.error;
|
||||
_progress = null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
await LogStorageService.instance.logMeal(
|
||||
desc,
|
||||
nutritionFromControllers(_macros, _source),
|
||||
slotMinute: target.slot,
|
||||
@ -150,101 +159,89 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
_macros.clear();
|
||||
setState(() {
|
||||
_source = 'manual';
|
||||
photo = null; // else a stale photo keeps the sparkle lit
|
||||
claudeState = ClaudeButtonState.idle;
|
||||
selectedSlot = slotForLog(DateTime.now(), MealScheduleService.current);
|
||||
});
|
||||
await refreshSlots();
|
||||
if (!mounted) return;
|
||||
showLogged([LoggedMeal(entry, LoggedOrigin.local)]);
|
||||
// The second `prefillNextDish` caller. Without it every dish after the
|
||||
// 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(() {
|
||||
_cue = null;
|
||||
_progress = buildTodayProgress(log, logged: entry);
|
||||
_status = queueStatusLine;
|
||||
_progress = buildTodayProgress(log);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
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(
|
||||
appBar: due
|
||||
? null
|
||||
: AppBar(
|
||||
actions: logMealAppBarActions(
|
||||
appBar: AppBar(
|
||||
title: const Text('Diet Guard'),
|
||||
actions: [
|
||||
...logMealAppBarActions(
|
||||
onFoodBank: onOpenFoodBank,
|
||||
onHistory: onOpenHistory,
|
||||
onCalendar: onOpenCalendar,
|
||||
onSettings: onOpenSettings,
|
||||
onBody: onOpenBody,
|
||||
leading: buildDateActions(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
body: 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(
|
||||
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,
|
||||
icon: Icons.fastfood,
|
||||
semanticLabel: 'What did you eat?',
|
||||
onChanged: (_) => setState(() {}),
|
||||
decoration: const InputDecoration(labelText: 'What did you eat?'),
|
||||
),
|
||||
AutocompleteSuggestionList(
|
||||
suggestions: _suggestions,
|
||||
onSelected: _onSuggestionSelected,
|
||||
compact: true,
|
||||
compactLimit: due ? 2 : 3,
|
||||
reserveHeight: due,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
const SizedBox(height: 8),
|
||||
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,
|
||||
const SizedBox(height: 8),
|
||||
LogMealActionsRow(
|
||||
onLoadDelivery: loadDeliveryAndReport,
|
||||
onLog: _onLogMeal,
|
||||
deliveryBusy: deliveryBusy,
|
||||
dishesQueued: dishesStillQueued,
|
||||
),
|
||||
if (!typing)
|
||||
for (final meal in loggedRows)
|
||||
LoggedMealRow(meal: meal, onUndo: () => undoLogged(meal)),
|
||||
if (_cue != null) ...[
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
_cue!.widget,
|
||||
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 && !due && !typing) ...[
|
||||
if (_progress != null) ...[
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
TodayProgressCard(progress: _progress!),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
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/due_slot_check.dart';
|
||||
import 'package:diet_guard_app/services/firebase_client.dart';
|
||||
@ -8,12 +9,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/health_steps.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_attempt.dart';
|
||||
import 'package:diet_guard_app/services/meal_schedule_service.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_settings.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
/// Background-sync and lifecycle behaviour for [LogMealScreen]'s state.
|
||||
///
|
||||
@ -34,6 +35,12 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
/// The slots that already carry a logged meal today.
|
||||
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.
|
||||
///
|
||||
/// Declared abstract so the mixin stays independent of the widget's own
|
||||
@ -69,7 +76,6 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
Future<void> autoSync() async {
|
||||
if (autoSyncing) return;
|
||||
autoSyncing = true;
|
||||
bool? landed; // null until the sync itself ran
|
||||
try {
|
||||
final settings = await SyncSettings.load();
|
||||
// Either backend counts. `isConfigured` means "has a GitHub token", so
|
||||
@ -89,19 +95,17 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
return;
|
||||
}
|
||||
final client = createGitHubClient(settings, httpClient: syncHttpClient);
|
||||
landed = await attemptSync(() async {
|
||||
try {
|
||||
// Foreground only (this mixin is UI), and never prompts: fresh
|
||||
// Health Connect steps ride along in this tick's body.json.
|
||||
await refreshSteps();
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
if (!mounted) return;
|
||||
// Outside attemptSync: a refresh error is no sync failure.
|
||||
if (landed) await refreshSlots();
|
||||
await refreshSlots();
|
||||
await refreshSyncHealth();
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Best-effort, but never silent: this swallowed the reason a desktop
|
||||
@ -114,9 +118,7 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
// attemptSync already recorded the sync's own outcome; only a failure
|
||||
// before it (loading settings) is one here.
|
||||
if (landed == null) await SyncHealth.recordFailure();
|
||||
await SyncHealth.recordFailure();
|
||||
if (mounted) await refreshSyncHealth();
|
||||
} finally {
|
||||
autoSyncing = false;
|
||||
@ -172,12 +174,21 @@ mixin LogMealSyncMixin<T extends StatefulWidget> on State<T>
|
||||
setState(() => loggedSlots = logged);
|
||||
}
|
||||
|
||||
/// Re-derives the due slots after the settings screen pops.
|
||||
/// Rebuilds the slot row after the settings screen pops.
|
||||
///
|
||||
/// The meal-schedule editor lives in settings, and which slots are due (and
|
||||
/// so whether the screen is in due mode) reads `MealScheduleService.current`
|
||||
/// at refresh time. Found on the phone: without this the settings preview
|
||||
/// and the overdue reminder both updated while the screen behind them kept
|
||||
/// the old checkpoints until the app was restarted.
|
||||
Future<void> onScheduleMayHaveChanged() => refreshSlots();
|
||||
/// The meal-schedule editor lives in settings, and [SlotSelectorRow] reads
|
||||
/// `MealScheduleService.current` at build time, so refreshing is enough to
|
||||
/// re-derive the row -- but the selected slot also has to be recomputed,
|
||||
/// since the minute it referred to may no longer be a checkpoint at all.
|
||||
///
|
||||
/// Found on the phone: without this the settings preview and the overdue
|
||||
/// 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,18 +7,11 @@
|
||||
part of 'settings_screen.dart';
|
||||
|
||||
mixin _SettingsKcalGoal on State<SettingsScreen> {
|
||||
/// The latest outcome as an icon cue; null until something happened.
|
||||
Widget? _status;
|
||||
String? _status;
|
||||
|
||||
void _showCue(CueKind kind, String semanticLabel) {
|
||||
void _showMessage(String message) {
|
||||
if (!mounted) return;
|
||||
setState(
|
||||
() => _status = StatusCue(
|
||||
key: UniqueKey(),
|
||||
kind: kind,
|
||||
semanticLabel: semanticLabel,
|
||||
),
|
||||
);
|
||||
setState(() => _status = message);
|
||||
}
|
||||
|
||||
Timer? _kcalGoalDebounce;
|
||||
@ -57,13 +50,13 @@ mixin _SettingsKcalGoal on State<SettingsScreen> {
|
||||
() => Permission.ignoreBatteryOptimizations.request();
|
||||
try {
|
||||
final status = await request();
|
||||
if (status.isGranted) {
|
||||
_showCue(CueKind.ok, 'Battery optimization exemption granted.');
|
||||
} else {
|
||||
_showCue(CueKind.warn, 'Exemption not granted.');
|
||||
}
|
||||
_showMessage(
|
||||
status.isGranted
|
||||
? 'Battery optimization exemption granted.'
|
||||
: 'Exemption not granted -- notifications may be delayed.',
|
||||
);
|
||||
} on Exception catch (e) {
|
||||
_showCue(CueKind.error, 'Could not request exemption: $e');
|
||||
_showMessage('Could not request exemption: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,43 +15,24 @@
|
||||
/// encrypted either.
|
||||
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_credential_service.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: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;
|
||||
}
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Fetches today's delivery and reports what was banked.
|
||||
///
|
||||
/// Deliberately "banked", not "logged": the explicit fetch only fills the
|
||||
/// food bank; logging is the log screen's auto-log (`kuchnia_autolog.dart`).
|
||||
/// Top-level so the settings screen can pass it without growing.
|
||||
Future<FetchOutcome> fetchTodaysDelivery() async {
|
||||
/// Deliberately says "banked", not "logged": a delivered meal is not an eaten
|
||||
/// meal, so the dishes land in the food bank and the user still taps to log
|
||||
/// each one. Top-level so the settings screen can pass it without growing.
|
||||
Future<String> fetchTodaysDelivery() async {
|
||||
final result = await refreshDelivery(DateTime.now());
|
||||
if (!result.ok) return FetchOutcome(CueKind.error, result.reason!);
|
||||
if (result.dishes.isEmpty) {
|
||||
return const FetchOutcome(CueKind.warn, 'No delivery found for today.');
|
||||
}
|
||||
if (!result.ok) return result.reason!;
|
||||
if (result.dishes.isEmpty) return 'No delivery found for today.';
|
||||
final count = result.dishes.length;
|
||||
return FetchOutcome(CueKind.ok, '$count dishes added', count: count);
|
||||
return '$count ${count == 1 ? 'dish' : 'dishes'} added to your food bank. '
|
||||
'Log them from the meal screen when you eat them.';
|
||||
}
|
||||
|
||||
/// Credential fields plus, on Android, a "fetch today's delivery" action.
|
||||
@ -62,14 +43,18 @@ class KuchniaSettingsSection extends StatefulWidget {
|
||||
/// button is replaced by a one-line explanation rather than silently
|
||||
/// 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.
|
||||
const KuchniaSettingsSection({this.canFetch, this.onFetch, super.key});
|
||||
const KuchniaSettingsSection({
|
||||
this.canFetch,
|
||||
this.onFetch,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Whether this platform can reach the catering panel; null means ask.
|
||||
final bool? canFetch;
|
||||
|
||||
/// Fetches today's delivery and returns a status line; null means the real
|
||||
/// one.
|
||||
final Future<FetchOutcome> Function()? onFetch;
|
||||
final Future<String> Function()? onFetch;
|
||||
|
||||
@override
|
||||
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
|
||||
@ -84,7 +69,7 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
||||
);
|
||||
bool _obscured = true;
|
||||
bool _busy = false;
|
||||
Widget? _status;
|
||||
String? _status;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
@ -100,13 +85,7 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
||||
_password.text,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(
|
||||
() => _status = StatusCue(
|
||||
key: UniqueKey(),
|
||||
kind: CueKind.ok,
|
||||
semanticLabel: 'Saved. It will sync to your other devices.',
|
||||
),
|
||||
);
|
||||
setState(() => _status = 'Saved. It will sync to your other devices.');
|
||||
}
|
||||
|
||||
Future<void> _fetch() async {
|
||||
@ -114,96 +93,92 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
||||
_busy = true;
|
||||
_status = null;
|
||||
});
|
||||
final outcome = await (widget.onFetch ?? fetchTodaysDelivery)();
|
||||
final message = await (widget.onFetch ?? fetchTodaysDelivery)();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_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}'),
|
||||
],
|
||||
);
|
||||
_status = message;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final canFetch = widget.canFetch ?? kuchniaFetchSupported;
|
||||
// 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.
|
||||
// No heading or blurb: the delivery truck on the fetch button names it.
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 24),
|
||||
const Divider(),
|
||||
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(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||
child: IconField(
|
||||
icon: Icons.alternate_email,
|
||||
semanticLabel: 'Panel e-mail',
|
||||
child: TextField(
|
||||
controller: _username,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
autocorrect: false,
|
||||
decoration: const InputDecoration(labelText: 'Panel e-mail'),
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||
child: IconField(
|
||||
icon: Icons.key,
|
||||
semanticLabel: 'Panel password',
|
||||
child: TextField(
|
||||
controller: _password,
|
||||
obscure: _obscured,
|
||||
obscureText: _obscured,
|
||||
autocorrect: false,
|
||||
onSubmitted: (_) => _save(),
|
||||
suffix: IconButton(
|
||||
icon: Icon(
|
||||
_obscured ? Icons.visibility : Icons.visibility_off,
|
||||
semanticLabel: _obscured ? 'Show password' : 'Hide password',
|
||||
),
|
||||
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(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
IconButton.filled(
|
||||
onPressed: _save,
|
||||
icon: const Icon(Icons.check, semanticLabel: 'Save login'),
|
||||
),
|
||||
// Browser builds show the button greyed out: the panel blocks
|
||||
// browser requests, and the disabled state is the cue.
|
||||
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",
|
||||
FilledButton(onPressed: _save, child: const Text('Save login')),
|
||||
if (canFetch)
|
||||
OutlinedButton.icon(
|
||||
onPressed: _busy ? null : _fetch,
|
||||
icon: const Icon(Icons.restaurant),
|
||||
label: Text(
|
||||
_busy ? 'Fetching…' : "Fetch today's delivery",
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_status != null) ...[const SizedBox(height: 8), _status!],
|
||||
if (!canFetch) ...[
|
||||
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),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,13 +1,16 @@
|
||||
/// App settings: kcal goal, notifications, data export/import, and links to
|
||||
/// the shared Firebase "Sync settings" and the app-local GitHub mirror (its
|
||||
/// connect also runs a real `runSync`, which the shared screen does not).
|
||||
/// App settings: kcal goal, notifications, and links to the two sync
|
||||
/// surfaces.
|
||||
///
|
||||
/// "Sync settings" is the shared `sync_settings_ui` package (Firebase
|
||||
/// only -- diet_guard has no local backup format, so `BackupSlot` is null).
|
||||
/// "Advanced sync (GitHub)" stays app-local ([GitHubMirrorScreen]) because
|
||||
/// connecting it also triggers a real log sync via `runSync`, which the
|
||||
/// shared package's Firebase section does not do -- it only saves settings.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
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/screens/github_mirror_screen.dart';
|
||||
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
|
||||
@ -17,18 +20,12 @@ import 'package:diet_guard_app/services/firebase_backend.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/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/widgets/data_backup_row.dart';
|
||||
import 'package:diet_guard_app/widgets/log_sound_tile.dart';
|
||||
import 'package:diet_guard_app/widgets/meal_schedule_editor.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
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:sync_settings_ui/sync_settings_ui.dart';
|
||||
|
||||
@ -51,7 +48,8 @@ class SettingsScreen extends StatefulWidget {
|
||||
this.firebaseFactory,
|
||||
});
|
||||
|
||||
/// HTTP client for the linked [GitHubMirrorScreen]; tests pass [MockClient].
|
||||
/// Injectable HTTP client for the linked [GitHubMirrorScreen]; tests pass
|
||||
/// a [MockClient].
|
||||
final http.Client? httpClient;
|
||||
|
||||
/// Injectable battery-optimization-exemption request; tests pass a fake.
|
||||
@ -71,10 +69,14 @@ class SettingsScreen extends StatefulWidget {
|
||||
/// Reads the stored Firebase account. Injected for the same reason as
|
||||
/// [googleFirebaseFactory]: the keystore is a platform channel.
|
||||
///
|
||||
/// Backed by [storedAccount], not [loadAccount]: the shared screen reads
|
||||
/// the account back right after a Google sign-in, and [loadAccount]'s
|
||||
/// desktop fallback throws on Android (seen on the phone as "Google sign-in
|
||||
/// failed"). See the keystore-only read in [firebase_backend.dart].
|
||||
/// Deliberately backed by [storedAccount], not [loadAccount]: the shared
|
||||
/// `SyncSettingsScreen` uses this single closure both to display the
|
||||
/// status and to read back the account right after a Google sign-in.
|
||||
/// [loadAccount]'s desktop-wrapper fallback resolves to `file:///` on
|
||||
/// Android and throws -- verified on the phone, where it turned a
|
||||
/// successful sign-in into "Google sign-in failed". `storedAccount` is the
|
||||
/// keystore-only read [firebase_backend.dart] documents for exactly this
|
||||
/// read-back case.
|
||||
final Future<FirebaseAccount?> Function()? accountLoader;
|
||||
|
||||
/// Persists the account. See [accountLoader].
|
||||
@ -150,31 +152,37 @@ class _SettingsScreenState extends State<SettingsScreen>
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
// No title: the gear that opened this screen already names it.
|
||||
appBar: AppBar(),
|
||||
// Capped at the prose width so fields do not span a ~1366px window.
|
||||
appBar: AppBar(title: const Text('Settings')),
|
||||
// Centred and capped at the prose width. On the desktop surface this
|
||||
// ListView spanned the full ~1366px window, so the explanatory
|
||||
// paragraphs below ran ~180 characters per line -- roughly twice the
|
||||
// readable limit (tokens.md rule 21) -- and every field stretched with
|
||||
// them. Invisible on the phone, where the window is already narrow.
|
||||
body: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
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
|
||||
// layout error by spanning the whole column.
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||
child: IconField(
|
||||
icon: MacroKind.kcal.icon,
|
||||
iconColor: MacroKind.kcal.color,
|
||||
semanticLabel: 'Daily kcal goal',
|
||||
child: TextField(
|
||||
controller: _kcalGoalController,
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Daily kcal goal',
|
||||
helperText: 'Shown in the history day summary',
|
||||
suffixText: 'kcal',
|
||||
),
|
||||
onChanged: _onKcalGoalChanged,
|
||||
),
|
||||
),
|
||||
const LogSoundTile(),
|
||||
const SizedBox(height: 16),
|
||||
const SizedBox(height: 24),
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
..._mealScheduleSection(context),
|
||||
@ -183,64 +191,55 @@ class _SettingsScreenState extends State<SettingsScreen>
|
||||
const Divider(),
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: const Icon(
|
||||
Icons.cloud_sync_outlined,
|
||||
semanticLabel: 'Sync settings',
|
||||
),
|
||||
title: const Text('Sync settings'),
|
||||
subtitle: const Text('Firebase sync'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
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(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: Icon(
|
||||
Icons.code,
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
semanticLabel: 'Advanced sync (GitHub)',
|
||||
),
|
||||
title: const Text('Advanced sync (GitHub)'),
|
||||
subtitle: const Text('Cutover mirror — not recommended'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => unawaited(_openGitHubMirror()),
|
||||
),
|
||||
DataBackupRow(
|
||||
onImported: () => _kcalGoalController.text = AppSettingsService
|
||||
.dailyKcalGoal
|
||||
.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
|
||||
// `permission_handler` has no web implementation at all;
|
||||
// the row would throw rather than degrade in the browser.
|
||||
if (_isAndroid) ...[
|
||||
const SizedBox(height: 24),
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: IconButton.outlined(
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _requestBatteryExemption,
|
||||
icon: const Icon(
|
||||
Icons.battery_alert,
|
||||
semanticLabel: 'Disable battery optimization',
|
||||
),
|
||||
),
|
||||
icon: const Icon(Icons.battery_alert),
|
||||
label: const Text('Disable battery optimization'),
|
||||
),
|
||||
],
|
||||
if (_status != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Align(alignment: Alignment.centerLeft, child: _status),
|
||||
Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
const Align(alignment: Alignment.centerLeft, child: KuhyCredit()),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@ -22,6 +22,13 @@ export 'package:diet_guard_app/models/workout_session.dart';
|
||||
/// Formula names, in display order.
|
||||
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.
|
||||
const int maxWindowDays = 14;
|
||||
|
||||
|
||||
@ -33,7 +33,6 @@ class AppSettingsService {
|
||||
final DocumentStore _store;
|
||||
int _dailyKcalGoal = kDefaultDailyKcalGoal;
|
||||
DateTime? _dailyKcalGoalUpdatedAt;
|
||||
bool _soundOnLog = true;
|
||||
|
||||
/// Returns the configured daily kcal goal, or the default when
|
||||
/// uninitialised. This is the budget in force *today*; asking what applied
|
||||
@ -45,19 +44,6 @@ class AppSettingsService {
|
||||
static DateTime? get dailyKcalGoalUpdatedAt =>
|
||||
_instance?._dailyKcalGoalUpdatedAt;
|
||||
|
||||
/// Whether a logged meal plays the confirm cue; on unless turned off.
|
||||
///
|
||||
/// Device-local, deliberately not synced: a phone in a meeting and a PC
|
||||
/// with speakers want different answers.
|
||||
static bool get soundOnLog => _instance?._soundOnLog ?? true;
|
||||
|
||||
/// Persists [on] without touching the budget's edit stamp, which would
|
||||
/// otherwise make this device win the next budget merge.
|
||||
Future<void> setSoundOnLog({required bool on}) async {
|
||||
_soundOnLog = on;
|
||||
await _writeToDisk();
|
||||
}
|
||||
|
||||
/// Initialises the singleton against the platform document store (files on
|
||||
/// Android, IndexedDB in the browser-hosted desktop app).
|
||||
static Future<AppSettingsService> init() async {
|
||||
@ -119,9 +105,6 @@ class AppSettingsService {
|
||||
data['daily_kcal_goal_updated_at'] as String,
|
||||
);
|
||||
}
|
||||
if (data is Map && data['sound_on_log'] is bool) {
|
||||
_soundOnLog = data['sound_on_log'] as bool;
|
||||
}
|
||||
} on Exception {
|
||||
// Ignore parse errors and keep defaults.
|
||||
}
|
||||
@ -177,7 +160,6 @@ class AppSettingsService {
|
||||
'daily_kcal_goal': _dailyKcalGoal,
|
||||
'daily_kcal_goal_updated_at': _dailyKcalGoalUpdatedAt
|
||||
?.toIso8601String(),
|
||||
'sound_on_log': _soundOnLog,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@ -15,7 +15,6 @@ 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/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_device_id.dart';
|
||||
import 'package:diet_guard_app/services/sync_health.dart';
|
||||
import 'package:diet_guard_app/services/sync_service.dart';
|
||||
@ -91,14 +90,21 @@ Future<bool> backgroundSyncPush({http.Client? httpClient}) async {
|
||||
return true; // nothing to push; don't retry
|
||||
}
|
||||
final client = createGitHubClient(settings, httpClient: httpClient);
|
||||
// Never silent: attemptSync records the outcome, the only signal that a
|
||||
// background push failed. False -> WorkManager retries with backoff.
|
||||
final landed = await attemptSync(() async {
|
||||
try {
|
||||
await runSync(await syncBackend(client));
|
||||
await SyncHealth.recordSuccess();
|
||||
return true;
|
||||
} on Exception catch (error, stackTrace) {
|
||||
// Never silent: this is the only signal that a background push failed.
|
||||
log(
|
||||
'diet_guard background sync failed',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
await SyncHealth.recordFailure();
|
||||
return false; // offline / transient error -> retry with backoff
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
return landed;
|
||||
}
|
||||
|
||||
@ -31,6 +31,21 @@ const List<(double, String)> _bmiBands = [
|
||||
];
|
||||
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.';
|
||||
|
||||
/// Broca explained, shown under the ideal-weight list.
|
||||
const String brocaNote =
|
||||
'Broca = height in cm - 100 (1871); it overshoots, so Broca (modified) '
|
||||
'takes 10% off it for men and 15% for women.';
|
||||
|
||||
/// The lean-mass formula the calorie table switches to with a body fat %.
|
||||
const String katchMcArdle = 'Katch-McArdle';
|
||||
|
||||
@ -135,9 +150,8 @@ double? _perInch(
|
||||
|
||||
/// Every ideal-body-weight formula we can evaluate, in kg.
|
||||
///
|
||||
/// Only data-backed ones (Devine, its MetLife refits, Peterson); Broca, its
|
||||
/// derivatives and Hamwi were dropped. The BMI healthy range is
|
||||
/// [healthyRange], shown with BMI; [idealSummary] averages these.
|
||||
/// Only Creff uses age. The BMI healthy range is [healthyRange], shown with
|
||||
/// BMI; [idealSummary] averages these.
|
||||
List<Formula> idealWeights(Biometrics bio) {
|
||||
final h = bio.heightCm;
|
||||
final inches = h / _cmPerInch - _fiveFeetIn;
|
||||
@ -154,6 +168,14 @@ List<Formula> idealWeights(Biometrics bio) {
|
||||
'Miller',
|
||||
_perInch(inches, male ? 56.2 : 53.1, male ? 1.41 : 1.36, defined: ok),
|
||||
),
|
||||
Formula(
|
||||
'Hamwi',
|
||||
_perInch(inches, male ? 48 : 45.5, male ? 2.7 : 2.2, defined: ok),
|
||||
),
|
||||
Formula('Broca', h - 100.0),
|
||||
Formula('Broca (modified)', (h - 100.0) * (male ? 0.9 : 0.85)),
|
||||
Formula('Lorentz', h - 100.0 - (h - 150.0) / (male ? 4.0 : 2.0)),
|
||||
Formula('Creff (age)', (h - 100.0 + bio.ageYears / 10.0) * 0.9),
|
||||
Formula(
|
||||
'Peterson (BMI 22)',
|
||||
2.2 * _targetBmi + 3.5 * _targetBmi * (metres - 1.5),
|
||||
|
||||
@ -1,156 +0,0 @@
|
||||
/// 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();
|
||||
@ -1,49 +0,0 @@
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
@ -1,201 +0,0 @@
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,150 +0,0 @@
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
@ -1,144 +0,0 @@
|
||||
/// 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');
|
||||
}
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
// coverage:ignore-file
|
||||
import 'package:audioplayers/audioplayers.dart';
|
||||
|
||||
AudioPlayer? _player;
|
||||
|
||||
final _mixOverMusicWithoutFocus = AudioContext(
|
||||
android: const AudioContextAndroid(
|
||||
contentType: AndroidContentType.sonification,
|
||||
usageType: AndroidUsageType.assistanceSonification,
|
||||
audioFocus: AndroidAudioFocus.none,
|
||||
),
|
||||
);
|
||||
|
||||
/// Plays the bundled `confirm` cue through the audioplayers plugin.
|
||||
Future<void> playConfirmCueAsset() async {
|
||||
final player = _player ??= AudioPlayer();
|
||||
await player.play(
|
||||
AssetSource('sounds/log_confirm.ogg'),
|
||||
ctx: _mixOverMusicWithoutFocus,
|
||||
mode: PlayerMode.lowLatency,
|
||||
);
|
||||
}
|
||||
@ -1,144 +0,0 @@
|
||||
/// User-owned export and merge-only import of every synced document.
|
||||
///
|
||||
/// Import is `mergeLogs` plus the sync tick's own write-back, so it never
|
||||
/// deletes and a repeat is a no-op. The catering login (a password) travels
|
||||
/// only as an AEAD-sealed `kuchnia` section; see `data_export_kuchnia.dart`.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/body_service.dart';
|
||||
import 'package:diet_guard_app/services/data_export_kuchnia.dart';
|
||||
import 'package:diet_guard_app/services/export_keyring.dart';
|
||||
import 'package:diet_guard_app/services/export_keyring_default.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/sync_budget_local.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge_body.dart';
|
||||
|
||||
/// The `format` marker an export carries.
|
||||
const exportFormat = 'diet_guard_export';
|
||||
|
||||
/// The newest export layout this build reads and writes.
|
||||
const exportVersion = 1;
|
||||
|
||||
class _Document {
|
||||
const _Document(this.key, this.readLocal, this.apply);
|
||||
|
||||
final String key;
|
||||
final Future<Log> Function() readLocal;
|
||||
final Future<void> Function(Log merged) apply;
|
||||
}
|
||||
|
||||
Future<void> _applyFoodLog(Log merged) async {
|
||||
final log = logToDayLog(merged);
|
||||
await LogStorageService.instance.writeLog(log);
|
||||
await FoodBankService.instance.rebuildAndPersist(log);
|
||||
}
|
||||
|
||||
Future<Log> _readBody() async =>
|
||||
BodyService.isInitialized ? bodyToLog(BodyService.instance.document) : {};
|
||||
|
||||
Future<void> _applyBody(Log merged) async {
|
||||
if (merged.isEmpty || !BodyService.isInitialized) return;
|
||||
await BodyService.instance.applyMerged(logToBody(merged));
|
||||
}
|
||||
|
||||
/// Food log first: applying it rebuilds the derived bank merged next.
|
||||
final List<_Document> _documents = [
|
||||
_Document(
|
||||
'food_log',
|
||||
() async => dayLogToLog(await LogStorageService.instance.readLog()),
|
||||
_applyFoodLog,
|
||||
),
|
||||
_Document(
|
||||
'food_bank',
|
||||
() async => foodBankToLog(await FoodBankService.instance.readBank()),
|
||||
(merged) => FoodBankService.instance.writeBank(logToFoodBank(merged)),
|
||||
),
|
||||
_Document(
|
||||
'food_bank_manual',
|
||||
() async =>
|
||||
manualBankToLog(await FoodBankService.instance.readManualBank()),
|
||||
(merged) =>
|
||||
FoodBankService.instance.applyMergedManualBank(logToManualBank(merged)),
|
||||
),
|
||||
_Document('budget', () async => localBudgetLog(), applyBudgetLog),
|
||||
const _Document('body', _readBody, _applyBody),
|
||||
];
|
||||
|
||||
Map<String, Object?> _encodeLog(Log log) => {
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
};
|
||||
|
||||
Log _decodeLog(String key, Object? payload) {
|
||||
if (payload is! Map) throw FormatException('"$key" is not an object');
|
||||
try {
|
||||
return {
|
||||
for (final entry in payload.entries)
|
||||
entry.key as String: Record.fromJson(
|
||||
(entry.value as Map).cast<String, dynamic>(),
|
||||
),
|
||||
};
|
||||
} on Object catch (error) {
|
||||
throw FormatException('"$key" has a malformed record: $error');
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns every synced document as one pretty-printed JSON export.
|
||||
///
|
||||
/// The encrypted login section uses the newest key of [keyring] (default: the
|
||||
/// OS-keystore ring).
|
||||
Future<String> exportAllData({DateTime? now, ExportKeyring? keyring}) async {
|
||||
final documents = <String, Object?>{
|
||||
for (final doc in _documents) doc.key: _encodeLog(await doc.readLocal()),
|
||||
};
|
||||
return const JsonEncoder.withIndent(' ').convert({
|
||||
'format': exportFormat,
|
||||
'version': exportVersion,
|
||||
'exportedAt': (now ?? DateTime.now()).toIso8601String(),
|
||||
'documents': documents,
|
||||
...await kuchniaExportEntries(keyring ?? defaultKeyring()),
|
||||
});
|
||||
}
|
||||
|
||||
/// Merges an [exportAllData] payload into the local store.
|
||||
///
|
||||
/// Parses every document before writing any, so a bad file changes nothing.
|
||||
/// Throws [FormatException] when [text] is not a diet_guard export. A sealed
|
||||
/// login that cannot be opened (unknown key id even after [pullKeys], or
|
||||
/// tampered data) is skipped after the rest merged, then reported as
|
||||
/// [KuchniaImportException]. An existing local login is kept.
|
||||
Future<void> importAllData(
|
||||
String text, {
|
||||
ExportKeyring? keyring,
|
||||
Future<void> Function() pullKeys = pullExportKeys,
|
||||
}) async {
|
||||
final Object? raw;
|
||||
try {
|
||||
raw = jsonDecode(text);
|
||||
} on FormatException {
|
||||
throw const FormatException('not valid JSON');
|
||||
}
|
||||
if (raw is! Map || raw['format'] != exportFormat) {
|
||||
throw const FormatException('not a diet_guard export');
|
||||
}
|
||||
final version = raw['version'];
|
||||
final documents = raw['documents'];
|
||||
if (version is! int || version > exportVersion || documents is! Map) {
|
||||
throw const FormatException('unsupported diet_guard export');
|
||||
}
|
||||
final incoming = <_Document, Log>{
|
||||
for (final doc in _documents)
|
||||
if (documents[doc.key] != null)
|
||||
doc: _decodeLog(doc.key, documents[doc.key]),
|
||||
};
|
||||
final before = {for (final doc in incoming.keys) doc: await doc.readLocal()};
|
||||
for (final MapEntry(key: doc, value: log) in incoming.entries) {
|
||||
final local = mergeLogs(before[doc]!, await doc.readLocal());
|
||||
await doc.apply(mergeLogs(local, log));
|
||||
}
|
||||
await importKuchnia(raw, keyring ?? defaultKeyring(), pullKeys);
|
||||
}
|
||||
@ -1,107 +0,0 @@
|
||||
/// The catering login inside the data export, as an encrypted section.
|
||||
///
|
||||
/// The password is never written in clear: the whole credential document is
|
||||
/// sealed with AES-256-GCM under the newest key of the export keyring (see
|
||||
/// `export_keyring.dart`), and the section names that key by `kid`. If the
|
||||
/// keystore is unavailable the section is omitted and `kuchnia_skipped` says
|
||||
/// so; there is no plaintext fallback.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:diet_guard_app/services/export_crypto.dart';
|
||||
import 'package:diet_guard_app/services/export_keyring.dart';
|
||||
import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
|
||||
|
||||
/// Export key holding the sealed login.
|
||||
const kuchniaKey = 'kuchnia';
|
||||
|
||||
/// Export key explaining why [kuchniaKey] is absent.
|
||||
const kuchniaSkippedKey = 'kuchnia_skipped';
|
||||
|
||||
/// A login in the file could not be restored; the rest of the import did run.
|
||||
class KuchniaImportException implements Exception {
|
||||
/// Creates the exception; [reason] is `unknown_key` or `unreadable`.
|
||||
const KuchniaImportException(this.reason);
|
||||
|
||||
/// Why the section was skipped.
|
||||
final String reason;
|
||||
|
||||
@override
|
||||
String toString() => 'KuchniaImportException: $reason';
|
||||
}
|
||||
|
||||
/// Top-level export entries for the login: the sealed box, or the skip flag.
|
||||
Future<Map<String, Object?>> kuchniaExportEntries(ExportKeyring keyring) async {
|
||||
if (!KuchniaCredentialService.isInitialized ||
|
||||
!KuchniaCredentialService.isConfigured) {
|
||||
return {};
|
||||
}
|
||||
final ExportKey key;
|
||||
try {
|
||||
key = await keyring.ensureNewest();
|
||||
} on Object {
|
||||
return {kuchniaSkippedKey: 'keystore_unavailable'};
|
||||
}
|
||||
final clear = jsonEncode({
|
||||
'username': KuchniaCredentialService.username,
|
||||
'password': KuchniaCredentialService.password,
|
||||
't': KuchniaCredentialService.editedAt,
|
||||
});
|
||||
return {kuchniaKey: await encryptWithKey(clear, key)};
|
||||
}
|
||||
|
||||
/// The key for [kid]; pulls the synced keyring once if it is not held yet.
|
||||
Future<ExportKey?> _findKey(
|
||||
ExportKeyring keyring,
|
||||
String kid,
|
||||
Future<void> Function() pullKeys,
|
||||
) async {
|
||||
final held = await keyring.byId(kid);
|
||||
if (held != null) return held;
|
||||
try {
|
||||
await pullKeys();
|
||||
} on Object {
|
||||
return null;
|
||||
}
|
||||
final pulled = await keyring.byId(kid);
|
||||
return pulled;
|
||||
}
|
||||
|
||||
/// Opens the section from [root] and writes it only into an empty login.
|
||||
///
|
||||
/// Throws [KuchniaImportException] when it is present but cannot be opened.
|
||||
/// A configured local login is never overwritten.
|
||||
Future<void> importKuchnia(
|
||||
Map<dynamic, dynamic> root,
|
||||
ExportKeyring keyring,
|
||||
Future<void> Function() pullKeys,
|
||||
) async {
|
||||
final box = root[kuchniaKey];
|
||||
if (box == null) return;
|
||||
final kid = envelopeKeyId(box);
|
||||
final Map<dynamic, dynamic> doc;
|
||||
try {
|
||||
final key = kid == null ? null : await _findKey(keyring, kid, pullKeys);
|
||||
if (key == null) throw const KuchniaImportException('unknown_key');
|
||||
doc = jsonDecode(await decryptWithKey(box, key)) as Map;
|
||||
} on KuchniaImportException {
|
||||
rethrow;
|
||||
} on Object {
|
||||
throw const KuchniaImportException('unreadable');
|
||||
}
|
||||
final username = doc['username'];
|
||||
final password = doc['password'];
|
||||
if (username is! String || password is! String) {
|
||||
throw const KuchniaImportException('unreadable');
|
||||
}
|
||||
if (!KuchniaCredentialService.isInitialized ||
|
||||
KuchniaCredentialService.isConfigured) {
|
||||
return;
|
||||
}
|
||||
await KuchniaCredentialService.instance.applySynced(
|
||||
username,
|
||||
password,
|
||||
doc['t'] is String ? doc['t'] as String : '',
|
||||
);
|
||||
}
|
||||
@ -1,100 +0,0 @@
|
||||
/// AES-256-GCM sealing for the data export, keyed by an [ExportKey].
|
||||
///
|
||||
/// Pure Dart (`package:cryptography`), no `dart:io`, so it runs on Android and
|
||||
/// in the web build alike. Nothing here falls back to plaintext: any failure
|
||||
/// is an [ExportCryptoException].
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:cryptography/cryptography.dart';
|
||||
import 'package:diet_guard_app/services/export_keyring.dart';
|
||||
|
||||
/// The `enc` marker of the only envelope layout this build reads and writes.
|
||||
const encryptionVersion = 'v2';
|
||||
|
||||
const _nonceBytes = 12;
|
||||
const _macBytes = 16;
|
||||
|
||||
/// Binds a ciphertext to its role and key id, so it cannot be replayed.
|
||||
List<int> _aad(String kid) =>
|
||||
utf8.encode('diet_guard_export:kuchnia:$encryptionVersion:$kid');
|
||||
|
||||
/// Wrong key, tampered or malformed envelope.
|
||||
class ExportCryptoException implements Exception {
|
||||
/// Creates the exception.
|
||||
const ExportCryptoException(this.message);
|
||||
|
||||
/// What was wrong; never contains key material.
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => 'ExportCryptoException: $message';
|
||||
}
|
||||
|
||||
/// Seals [plaintext] under [key] with a fresh random nonce.
|
||||
///
|
||||
/// `ciphertext` is the encrypted bytes followed by the 16-byte GCM tag.
|
||||
Future<Map<String, Object?>> encryptWithKey(
|
||||
String plaintext,
|
||||
ExportKey key,
|
||||
) async {
|
||||
final rng = Random.secure();
|
||||
final nonce = Uint8List.fromList([
|
||||
for (var i = 0; i < _nonceBytes; i++) rng.nextInt(256),
|
||||
]);
|
||||
final box = await AesGcm.with256bits().encrypt(
|
||||
utf8.encode(plaintext),
|
||||
secretKey: SecretKey(key.bytes),
|
||||
nonce: nonce,
|
||||
aad: _aad(key.kid),
|
||||
);
|
||||
return {
|
||||
'enc': encryptionVersion,
|
||||
'alg': 'AES-256-GCM',
|
||||
'kid': key.kid,
|
||||
'nonce': base64Encode(nonce),
|
||||
'ciphertext': base64Encode([...box.cipherText, ...box.mac.bytes]),
|
||||
};
|
||||
}
|
||||
|
||||
/// The key id an envelope was sealed with, or null when it has none.
|
||||
String? envelopeKeyId(Object? envelope) {
|
||||
if (envelope is! Map || envelope['enc'] != encryptionVersion) return null;
|
||||
final kid = envelope['kid'];
|
||||
return kid is String ? kid : null;
|
||||
}
|
||||
|
||||
/// Opens an [encryptWithKey] envelope; throws [ExportCryptoException].
|
||||
Future<String> decryptWithKey(Object? envelope, ExportKey key) async {
|
||||
final Uint8List nonce;
|
||||
final Uint8List sealed;
|
||||
try {
|
||||
final map = envelope! as Map;
|
||||
if (envelopeKeyId(map) != key.kid) throw const FormatException('kid');
|
||||
nonce = base64Decode(map['nonce']! as String);
|
||||
sealed = base64Decode(map['ciphertext']! as String);
|
||||
} on Object {
|
||||
throw const ExportCryptoException('malformed envelope');
|
||||
}
|
||||
if (nonce.length != _nonceBytes || sealed.length < _macBytes) {
|
||||
throw const ExportCryptoException('malformed envelope');
|
||||
}
|
||||
final cut = sealed.length - _macBytes;
|
||||
try {
|
||||
final clear = await AesGcm.with256bits().decrypt(
|
||||
SecretBox(
|
||||
sealed.sublist(0, cut),
|
||||
nonce: nonce,
|
||||
mac: Mac(sealed.sublist(cut)),
|
||||
),
|
||||
secretKey: SecretKey(key.bytes),
|
||||
aad: _aad(key.kid),
|
||||
);
|
||||
return utf8.decode(clear);
|
||||
} on Object {
|
||||
throw const ExportCryptoException('wrong key or tampered data');
|
||||
}
|
||||
}
|
||||
@ -1,126 +0,0 @@
|
||||
/// The export keyring: random 256-bit AES keys that unlock data exports.
|
||||
///
|
||||
/// Keys live in the OS keystore and also sync between devices as the
|
||||
/// `export_keys` document (see `export_keyring_sync.dart`), so an export made
|
||||
/// on one device opens on another. It is a keyring, not a single key: a key
|
||||
/// 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.
|
||||
///
|
||||
/// The synced copy is end-to-end encrypted under the shared crdt-sync
|
||||
/// passphrase (`sync_e2e.dart`), on `diet-guard-sync/devices-e2e`. The old
|
||||
/// plaintext `diet-guard-sync/devices/<id>/export_keys.json` nodes are
|
||||
/// copied over once and then neither read nor written by this app.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
|
||||
/// Keystore entry holding the whole ring as JSON.
|
||||
const keyringStorageKey = 'diet_guard.export_keyring';
|
||||
|
||||
final _kidShape = RegExp(r'^[0-9a-f]{16}$');
|
||||
const _keyBytes = 32;
|
||||
|
||||
/// One export key.
|
||||
class ExportKey {
|
||||
/// Creates a key; [kid] is 16 hex chars, [bytes] 32 bytes.
|
||||
const ExportKey(this.kid, this.bytes, this.createdAt);
|
||||
|
||||
/// Random id written into every export sealed with this key.
|
||||
final String kid;
|
||||
|
||||
/// The AES-256 key.
|
||||
final List<int> bytes;
|
||||
|
||||
/// When it was minted (UTC); the newest key signs new exports.
|
||||
final DateTime createdAt;
|
||||
|
||||
/// True when [kid] and [bytes] have the shape a real key has.
|
||||
bool get isWellFormed => _kidShape.hasMatch(kid) && bytes.length == _keyBytes;
|
||||
}
|
||||
|
||||
/// A keyring over an injected keystore.
|
||||
///
|
||||
/// Reads and writes throw when the keystore is unavailable or holds garbage;
|
||||
/// callers treat that as "no keyring" and never fall back to plaintext. A
|
||||
/// garbled ring is not replaced, since that would destroy the keys in it.
|
||||
class ExportKeyring {
|
||||
/// Creates a ring over [read]/[write] (the OS keystore in the app).
|
||||
ExportKeyring({required this.read, required this.write});
|
||||
|
||||
/// Reads a keystore entry, or null when absent.
|
||||
final SecretReader read;
|
||||
|
||||
/// Writes a keystore entry.
|
||||
final SecretWriter write;
|
||||
|
||||
/// Every key held, in no particular order.
|
||||
Future<List<ExportKey>> all() async {
|
||||
final raw = await read(keyringStorageKey);
|
||||
if (raw == null || raw.isEmpty) return [];
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! Map) throw StateError('export keyring is corrupt');
|
||||
return [
|
||||
for (final MapEntry(key: kid, value: entry) in decoded.entries)
|
||||
ExportKey(
|
||||
kid as String,
|
||||
base64Decode((entry as Map)['k'] as String),
|
||||
DateTime.parse(entry['t'] as String).toUtc(),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// The key with id [kid], or null when this device does not hold it.
|
||||
Future<ExportKey?> byId(String kid) async {
|
||||
for (final key in await all()) {
|
||||
if (key.kid == kid) return key;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The newest key, minting and storing one if the ring is empty.
|
||||
Future<ExportKey> ensureNewest() async {
|
||||
var keys = await all();
|
||||
if (keys.isEmpty) {
|
||||
final rng = Random.secure();
|
||||
final fresh = ExportKey(
|
||||
[
|
||||
for (var i = 0; i < 8; i++) rng.nextInt(256),
|
||||
].map((b) => b.toRadixString(16).padLeft(2, '0')).join(),
|
||||
[for (var i = 0; i < _keyBytes; i++) rng.nextInt(256)],
|
||||
DateTime.now().toUtc(),
|
||||
);
|
||||
await mergeKeys([fresh]);
|
||||
keys = [fresh];
|
||||
}
|
||||
return keys.reduce(
|
||||
(a, b) =>
|
||||
a.createdAt.isAfter(b.createdAt) ||
|
||||
(a.createdAt == b.createdAt && a.kid.compareTo(b.kid) > 0)
|
||||
? a
|
||||
: b,
|
||||
);
|
||||
}
|
||||
|
||||
/// Adds the well-formed keys whose id is not held yet; never overwrites.
|
||||
Future<void> mergeKeys(Iterable<ExportKey> incoming) async {
|
||||
final held = {for (final key in await all()) key.kid: key};
|
||||
final before = held.length;
|
||||
for (final key in incoming) {
|
||||
if (key.isWellFormed) held.putIfAbsent(key.kid, () => key);
|
||||
}
|
||||
if (held.length == before) return;
|
||||
await write(
|
||||
keyringStorageKey,
|
||||
jsonEncode({
|
||||
for (final key in held.values)
|
||||
key.kid: {
|
||||
'k': base64Encode(key.bytes),
|
||||
't': key.createdAt.toIso8601String(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,51 +0,0 @@
|
||||
/// The app's real export keyring and its on-demand key pull.
|
||||
library;
|
||||
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:diet_guard_app/services/export_keyring.dart';
|
||||
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/github_client_factory.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:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
|
||||
// Platform-channel code (keystore, network); the logic it wires lives in
|
||||
// export_keyring*.dart and is covered there.
|
||||
// coverage:ignore-start
|
||||
const _secure = FlutterSecureStorage();
|
||||
|
||||
/// The keyring backed by the OS keystore.
|
||||
ExportKeyring defaultKeyring() => ExportKeyring(
|
||||
read: (key) => _secure.read(key: key),
|
||||
write: (key, value) => _secure.write(key: key, value: value),
|
||||
);
|
||||
|
||||
/// One sync pull of the keyring, for an import that met an unknown key id.
|
||||
///
|
||||
/// Best effort: offline or signed out just leaves the key unknown, and the
|
||||
/// import reports that.
|
||||
Future<void> pullExportKeys() async {
|
||||
try {
|
||||
final client = createGitHubClient(await SyncSettings.load());
|
||||
try {
|
||||
await syncExportKeys(
|
||||
await openDietGuardStore(await syncBackend(client)),
|
||||
keyring: defaultKeyring(),
|
||||
devicesDir: syncDevicesDir,
|
||||
);
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
} on Object catch (error, stackTrace) {
|
||||
log(
|
||||
'export key pull failed',
|
||||
level: 900,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
}
|
||||
}
|
||||
// coverage:ignore-end
|
||||
@ -1,87 +0,0 @@
|
||||
/// 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
|
||||
/// concurrent mints on two devices both survive. [syncExportKeys] must be
|
||||
/// handed the end-to-end encrypted store (`sync_e2e.dart`): these are the
|
||||
/// keys that open every export.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/export_keyring.dart';
|
||||
import 'package:diet_guard_app/services/sync_device_id.dart';
|
||||
|
||||
const _keyField = 'k';
|
||||
const _createdField = 't';
|
||||
|
||||
Log _toLog(Iterable<ExportKey> keys, String deviceId) => {
|
||||
for (final key in keys)
|
||||
key.kid: Record(
|
||||
id: key.kid,
|
||||
fields: {
|
||||
_keyField: (
|
||||
base64Encode(key.bytes),
|
||||
Hlc.newTick(
|
||||
deviceId,
|
||||
wallTimeMsOverride: key.createdAt.millisecondsSinceEpoch,
|
||||
),
|
||||
),
|
||||
_createdField: (
|
||||
key.createdAt.toIso8601String(),
|
||||
Hlc.newTick(
|
||||
deviceId,
|
||||
wallTimeMsOverride: key.createdAt.millisecondsSinceEpoch,
|
||||
),
|
||||
),
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
List<ExportKey> _fromLog(Log log) {
|
||||
final keys = <ExportKey>[];
|
||||
for (final record in log.values) {
|
||||
try {
|
||||
keys.add(
|
||||
ExportKey(
|
||||
record.id,
|
||||
base64Decode(record.fields[_keyField]!.$1! as String),
|
||||
DateTime.parse(record.fields[_createdField]!.$1! as String).toUtc(),
|
||||
),
|
||||
);
|
||||
} on Object {
|
||||
continue; // a malformed peer record is skipped, never fatal
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/// Pulls peers' keys into [keyring], pushes this device's keys.
|
||||
///
|
||||
/// Runs even when the ring is empty, so a fresh device still receives keys.
|
||||
Future<void> syncExportKeys(
|
||||
RemoteStore client, {
|
||||
required ExportKeyring keyring,
|
||||
required String devicesDir,
|
||||
String? deviceId,
|
||||
}) async {
|
||||
final id = deviceId ?? currentSyncDeviceId;
|
||||
final merged = await syncLog(
|
||||
client: client,
|
||||
deviceId: id,
|
||||
legacyDeviceId: deviceId == null ? legacySyncDeviceId : null,
|
||||
pathPrefix: devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: _toLog(await keyring.all(), id),
|
||||
encode: (log) => jsonEncode({
|
||||
for (final entry in log.entries) entry.key: entry.value.toJson(),
|
||||
}),
|
||||
decode: (text) => (jsonDecode(text) as Map).cast<String, dynamic>().map(
|
||||
(kid, data) =>
|
||||
MapEntry(kid, Record.fromJson(data as Map<String, dynamic>)),
|
||||
),
|
||||
filename: 'export_keys.json',
|
||||
commitMessage: 'diet_guard_app sync',
|
||||
);
|
||||
await keyring.mergeKeys(_fromLog(merged));
|
||||
}
|
||||
@ -104,4 +104,3 @@ Future<void> clearAccount() async {
|
||||
/// the desktop wrapper re-provisioning after the next sign-in.
|
||||
Future<void> forgetAccountMarker() =>
|
||||
_secure.delete(key: kFirebaseAccountKey);
|
||||
// coverage:ignore-end
|
||||
|
||||
@ -181,6 +181,8 @@ Future<FirebaseRestClient?> openFirebaseWithGoogle({
|
||||
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
|
||||
}
|
||||
|
||||
// coverage:ignore-end
|
||||
|
||||
/// Wraps [github] so Firebase is primary and GitHub is kept as a mirror.
|
||||
///
|
||||
/// Returns [github] unchanged when this device has not been set up for
|
||||
|
||||
11
app/lib/services/google_platform.dart
Normal file
11
app/lib/services/google_platform.dart
Normal file
@ -0,0 +1,11 @@
|
||||
/// Platform gate for the programmatic Google sign-in flow.
|
||||
///
|
||||
/// Conditional export because the answer differs per platform *and* because
|
||||
/// asking the plugin directly is unsafe: `supportsAuthenticate()` throws
|
||||
/// `UnimplementedError` where no implementation is registered -- an `Error`,
|
||||
/// not an `Exception`, so it escapes an ordinary catch and would take down
|
||||
/// the settings screen's `build()`.
|
||||
library;
|
||||
|
||||
export 'google_platform_io.dart'
|
||||
if (dart.library.js_interop) 'google_platform_web.dart';
|
||||
10
app/lib/services/google_platform_io.dart
Normal file
10
app/lib/services/google_platform_io.dart
Normal file
@ -0,0 +1,10 @@
|
||||
/// Whether the programmatic Google sign-in flow exists on this platform.
|
||||
///
|
||||
/// The io half: Android has the Credential Manager flow; Linux desktop does
|
||||
/// not, and this app's desktop build is the web one anyway.
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
/// True only on Android, the one platform shipping the programmatic flow.
|
||||
bool get googleSignInSupported => Platform.isAndroid;
|
||||
8
app/lib/services/google_platform_web.dart
Normal file
8
app/lib/services/google_platform_web.dart
Normal file
@ -0,0 +1,8 @@
|
||||
/// Whether the programmatic Google sign-in flow exists on this platform.
|
||||
///
|
||||
/// The web half: Google Identity Services signs in only through its own
|
||||
/// rendered button, so `authenticate()` throws `UnimplementedError` here.
|
||||
library;
|
||||
|
||||
/// Always false: the web plugin has no programmatic sign-in.
|
||||
bool get googleSignInSupported => false;
|
||||
@ -2,10 +2,9 @@
|
||||
///
|
||||
/// Why this is its own file: `crdt_sync` is deliberately pure Dart (only
|
||||
/// `crypto` and `http`), because the same library runs on Linux desktop and
|
||||
/// headless under systemd, where Android's AccountManager does not exist. So
|
||||
/// the platform side lives in the `google_account_token` plugin (system
|
||||
/// account chooser, no browser, no Google client library) and the library
|
||||
/// only ever receives a token string through a closure.
|
||||
/// headless under systemd, where `google_sign_in` does not exist. So the
|
||||
/// plugin lives here, in the app, and the library only ever receives a token
|
||||
/// string through a closure.
|
||||
///
|
||||
/// What this buys: on a fresh install the sync account is reached by tapping
|
||||
/// one account-picker row instead of typing a long password on a phone
|
||||
@ -15,7 +14,8 @@ library;
|
||||
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:google_account_token/google_account_token.dart' as plugin;
|
||||
import 'package:diet_guard_app/services/google_platform.dart' as platform_gate;
|
||||
import 'package:google_sign_in/google_sign_in.dart';
|
||||
|
||||
/// The account the security rules pin.
|
||||
///
|
||||
@ -50,36 +50,73 @@ const kServerClientId =
|
||||
|
||||
/// Whether this platform can sign in programmatically.
|
||||
///
|
||||
/// True only on Android, the one platform with an AccountManager. The desktop
|
||||
/// build of this app *is* the web build, so without this check the "Sign in
|
||||
/// with Google" button would show on desktop and always report "cancelled".
|
||||
/// False on web, where Google Identity Services only signs in through its own
|
||||
/// rendered button: `authenticate()` throws `UnimplementedError` there. The
|
||||
/// desktop build of this app *is* the web build, so without this check the
|
||||
/// "Sign in with Google" button would crash the settings screen on desktop
|
||||
/// rather than falling back; see `google_platform.dart` for why this is a
|
||||
/// platform check rather than a question asked of the plugin.
|
||||
///
|
||||
/// Also false when no client id is compiled in: a button that cannot possibly
|
||||
/// succeed is worse than no button, and without this check an unconfigured
|
||||
/// build reports "cancelled" and sends you debugging the OAuth console for a
|
||||
/// problem that is really a missing constant.
|
||||
bool get googleSignInSupported =>
|
||||
plugin.googleAccountTokenSupported && kServerClientId.isNotEmpty;
|
||||
platform_gate.googleSignInSupported && kServerClientId.isNotEmpty;
|
||||
|
||||
/// Returns a Google ID token for the signed-in account, or null.
|
||||
///
|
||||
/// Null rather than throwing when the user dismisses the picker: cancelling is
|
||||
/// an ordinary outcome, and the caller falls back to the password path.
|
||||
///
|
||||
/// [signInFn] and [serverClientId] exist for tests that bypass the plugin or
|
||||
/// need another audience.
|
||||
/// [signInFn] and [serverClientId] exist for tests, which cannot reach the
|
||||
/// platform channel the plugin uses.
|
||||
Future<String?> googleIdToken({
|
||||
Future<String?> Function()? signInFn,
|
||||
String serverClientId = kServerClientId,
|
||||
}) async {
|
||||
if (signInFn != null) return await signInFn();
|
||||
if (serverClientId.isEmpty) {
|
||||
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID would otherwise
|
||||
// fail inside the plugin with a far less obvious message.
|
||||
log(
|
||||
'Google sign-in unavailable: no Web OAuth client id; falling back to '
|
||||
'Google sign-in unavailable: GOOGLE_SERVER_CLIENT_ID was not set at '
|
||||
'build time; falling back to the password path',
|
||||
level: 900,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
// The plugin reaches the OS account picker through a platform channel,
|
||||
// which `flutter test` has no binding for -- the same reason main.dart and
|
||||
// firebase_backend.dart's keystore adapters are excluded. Everything above
|
||||
// this point is pure Dart and is covered.
|
||||
// coverage:ignore-start
|
||||
try {
|
||||
await GoogleSignIn.instance.initialize(serverClientId: serverClientId);
|
||||
if (!GoogleSignIn.instance.supportsAuthenticate()) {
|
||||
// Web/desktop: sign-in must go through the rendered GIS button, which
|
||||
// this app does not host yet. Fall back rather than throwing.
|
||||
log(
|
||||
'Google sign-in is not available on this platform; falling back to '
|
||||
'the password path',
|
||||
level: 900,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
return await plugin.googleIdToken(serverClientId: serverClientId);
|
||||
final account = await GoogleSignIn.instance.authenticate();
|
||||
return account.authentication.idToken;
|
||||
} on GoogleSignInException catch (error, stackTrace) {
|
||||
// Includes the user simply dismissing the picker, which is not an error
|
||||
// worth surfacing -- but log it, because a *configuration* failure
|
||||
// (unregistered SHA-1, wrong client id) arrives through the same path and
|
||||
// is otherwise indistinguishable from "the user changed their mind".
|
||||
log(
|
||||
'Google sign-in did not complete',
|
||||
level: 900,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
// coverage:ignore-end
|
||||
}
|
||||
|
||||
@ -1,161 +0,0 @@
|
||||
/// 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 in `store` (`kuchnia_delivery.json`), so a restart or an outage still
|
||||
/// has them (offline first); 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 'dart:convert';
|
||||
|
||||
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/document_store.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),
|
||||
this.store,
|
||||
}) : _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;
|
||||
|
||||
/// Keeps the day's dishes across restarts; null keeps them in memory only.
|
||||
final DocumentStore? store;
|
||||
|
||||
/// The document [store] holds the last fetched delivery in.
|
||||
static const documentName = 'kuchnia_delivery.json';
|
||||
|
||||
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 stored = await _readStored(dayKey);
|
||||
if (stored.isNotEmpty) {
|
||||
_cachedDay = dayKey;
|
||||
return _cachedDishes = stored;
|
||||
}
|
||||
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;
|
||||
await _writeStored(dayKey, result.dishes);
|
||||
return _cachedDishes = result.dishes;
|
||||
}
|
||||
_lastEmptyFetch = _now();
|
||||
return const [];
|
||||
}
|
||||
|
||||
Future<List<KuchniaDish>> _readStored(String dayKey) async {
|
||||
final target = store;
|
||||
if (target == null) return const [];
|
||||
try {
|
||||
final raw = await target.read(documentName);
|
||||
if (raw == null) return const [];
|
||||
final data = jsonDecode(raw);
|
||||
if (data is! Map<String, Object?> || data['day'] != dayKey) {
|
||||
return const [];
|
||||
}
|
||||
final dishes = data['dishes'];
|
||||
if (dishes is! List) return const [];
|
||||
return [
|
||||
for (final item in dishes)
|
||||
if (item is Map<String, Object?>) KuchniaDish.fromJson(item),
|
||||
];
|
||||
} on Object {
|
||||
// A missing, foreign or malformed file is "nothing stored": fetch again.
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _writeStored(String dayKey, List<KuchniaDish> dishes) async {
|
||||
final target = store;
|
||||
if (target == null) return;
|
||||
final body = {
|
||||
'day': dayKey,
|
||||
'dishes': [for (final dish in dishes) dish.toJson()],
|
||||
};
|
||||
try {
|
||||
await target.write(documentName, jsonEncode(body));
|
||||
} on Exception {
|
||||
// Best-effort: an unsaved delivery only costs a refetch after a restart.
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -3,12 +3,10 @@
|
||||
/// The Dart mirror of `diet_guard/_kuchnia_log.py`'s `fill_plan` and
|
||||
/// `log_dishes`. KEEP IN SYNC, gated by the shared parity fixture.
|
||||
///
|
||||
/// **Delivered counts as eaten (override, 2026-11-17).** The old rule was "a
|
||||
/// delivered meal is not an eaten meal, so nothing logs without a confirm
|
||||
/// tap". kuhy overrode it ("LOG EVEN WITHOUT TAP"): [logDishes] is now also
|
||||
/// 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.
|
||||
/// **Nothing here runs without an explicit confirm tap.** A delivered meal is
|
||||
/// not an eaten meal: logging unattended would let the delivery note satisfy
|
||||
/// the very checkpoints the gate exists to enforce. [logDishes] is only ever
|
||||
/// reached from the second tap of `FillAllFlow`.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
@ -17,7 +15,6 @@ import 'package:diet_guard_app/models/local_time.dart';
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/models/slot.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';
|
||||
|
||||
@ -101,34 +98,25 @@ Future<Set<int>> loggedSlotsOn(LogStorageService store, DateTime day) async {
|
||||
/// (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.
|
||||
///
|
||||
/// [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.
|
||||
Future<List<SlottedDish>> logDishes(
|
||||
List<SlottedDish> chosen, {
|
||||
LogStorageService? storage,
|
||||
DateTime? day,
|
||||
String Function(SlottedDish item)? idFor,
|
||||
}) async {
|
||||
final store = storage ?? LogStorageService.instance;
|
||||
final seen = {
|
||||
for (final entry in await dayEntries(store, day))
|
||||
_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>[];
|
||||
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);
|
||||
if (!seen.add(key)) continue;
|
||||
await store.logMeal(
|
||||
item.dish.name,
|
||||
dishNutrition(item.dish),
|
||||
slotMinute: item.slot,
|
||||
id: id,
|
||||
when: day == null
|
||||
? null
|
||||
: DateTime(
|
||||
|
||||
@ -4,10 +4,12 @@
|
||||
/// fail-closed boundary: every [KuchniaError] is turned into a reason string
|
||||
/// here, so no caller can be broken by a catering outage.
|
||||
///
|
||||
/// **Nothing is logged from here: this only banks.** Dishes land in the
|
||||
/// *curated* bank. Logging them is `kuchnia_autolog.dart`'s job, which kuhy
|
||||
/// allowed without a tap on 2026-11-17 ("LOG EVEN WITHOUT TAP"; it was
|
||||
/// "delivered is not eaten" before), under deterministic ids with an undo.
|
||||
/// **Nothing is ever logged from here.** A delivered meal is not an eaten
|
||||
/// meal: dishes land in the *curated* bank and the user still taps to log
|
||||
/// each one. If the import logged automatically, the gate would satisfy its
|
||||
/// own checkpoint from a delivery note, and the log would record what the
|
||||
/// 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
|
||||
/// the log on every meal, so anything written there would vanish at the next
|
||||
|
||||
@ -74,15 +74,6 @@ bool energyIsConsistent(double kcal, double protein, double carbs, double fat) {
|
||||
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.
|
||||
///
|
||||
/// [fallbackPriority] is the 1-based payload position, used when
|
||||
@ -122,7 +113,6 @@ KuchniaDish? parseMeal(Object? meal, int fallbackPriority) {
|
||||
grams: grams,
|
||||
priority: priority,
|
||||
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.
|
||||
///
|
||||
/// **Since 2026-11-17 the log screen no longer prefills from this queue**: a
|
||||
/// delivered dish logs itself when its slot is due (`kuchnia_autolog.dart`;
|
||||
/// kuhy overrode "delivered is not eaten", "LOG EVEN WITHOUT TAP"). What
|
||||
/// remains here is the offer/mark bookkeeping and the fetched-today marker.
|
||||
/// The queue itself still writes no log entry.
|
||||
/// **A delivered meal is not an eaten meal.** This queue only ever *prefills*
|
||||
/// the form; the user still taps to log 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.
|
||||
///
|
||||
/// Two things are load-bearing:
|
||||
///
|
||||
|
||||
@ -1,55 +0,0 @@
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/confirm_cue_player.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// `lightImpact` + `confirm` on a recorded meal, whatever its kcal.
|
||||
abstract final class LogFeedback {
|
||||
/// Swapped out by test/flutter_test_config.dart.
|
||||
static Future<void> Function() playConfirmCue = playConfirmCueAsset;
|
||||
|
||||
/// Fires both without awaiting, so the write is not delayed.
|
||||
static void mealLogged() {
|
||||
unawaited(HapticFeedback.lightImpact());
|
||||
if (AppSettingsService.soundOnLog) {
|
||||
unawaited(playConfirmCue());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -10,7 +10,6 @@ import 'package:diet_guard_app/models/nutrition.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_factory.dart';
|
||||
import 'package:diet_guard_app/services/log_entry_lookup.dart';
|
||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
@ -40,8 +39,10 @@ class LogStorageService {
|
||||
|
||||
final DocumentStore _store;
|
||||
|
||||
/// Initializes the singleton against the platform document store (files on
|
||||
/// Android, IndexedDB in the browser-hosted desktop app).
|
||||
/// Initializes the singleton against the platform document store: files in
|
||||
/// the app's documents directory on Android (phone-sandboxed; no
|
||||
/// external-storage permission needed), IndexedDB in the browser-hosted
|
||||
/// desktop app.
|
||||
static Future<LogStorageService> init() async {
|
||||
if (_instance != null) return _instance!;
|
||||
final svc = LogStorageService._(await openDocumentStore());
|
||||
@ -87,7 +88,8 @@ class LogStorageService {
|
||||
|
||||
/// Persists the full log to the store, mirroring `_state._write_log`.
|
||||
///
|
||||
/// Atomicity against a concurrent reader is the store's job.
|
||||
/// Atomicity against a concurrent reader is the store's job (see
|
||||
/// `FileDocumentStore.write`'s temp-file-and-rename), not this method's.
|
||||
Future<void> writeLog(DayLog log) async {
|
||||
final encoded = <String, Object?>{
|
||||
for (final mapEntry in log.entries)
|
||||
@ -96,34 +98,27 @@ class LogStorageService {
|
||||
await _store.write(documentName, jsonEncode(encoded));
|
||||
}
|
||||
|
||||
/// Appends an entry for [desc] to [when]'s day (today's when null).
|
||||
/// Appends a signed-on-PC-eventually entry for [desc] to [when]'s day (or
|
||||
/// today's, when [when] is null).
|
||||
///
|
||||
/// Mirrors `_state.log_meal`: never computes an `hmac` (the phone never
|
||||
/// holds the key; the PC re-signs on merge). [when] pre-logs a future
|
||||
/// date/slot and must not be in the past. [slotMinute] is a 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.
|
||||
/// Mirrors `_state.log_meal`: always assigns a fresh `id`, never computes
|
||||
/// an `hmac` (the phone never holds the shared key -- the PC re-signs on
|
||||
/// merge, see Milestone 3). [when] lets a caller pre-log a meal against a
|
||||
/// future date/slot; must not be in the past. [slotMinute] is the slot's
|
||||
/// minute of day (`slotForLog`'s result), never an hour.
|
||||
Future<FoodEntry> logMeal(
|
||||
String desc,
|
||||
Nutrition nutrition, {
|
||||
int? slotMinute,
|
||||
List<MealComponent>? components,
|
||||
DateTime? when,
|
||||
String? id,
|
||||
}) async {
|
||||
if (when != null && when.isBefore(DateTime.now())) {
|
||||
throw ArgumentError.value(when, 'when', 'cannot log a meal in the past');
|
||||
}
|
||||
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(
|
||||
id: id ?? const Uuid().v4(),
|
||||
id: const Uuid().v4(),
|
||||
time: isoLocalSeconds(now),
|
||||
desc: desc,
|
||||
grams: nutrition.grams,
|
||||
@ -135,6 +130,7 @@ class LogStorageService {
|
||||
slotMinute: slotMinute,
|
||||
components: components,
|
||||
);
|
||||
final log = await readLog();
|
||||
log.putIfAbsent(localDateKey(now), () => []).add(entry);
|
||||
await writeLog(log);
|
||||
return entry;
|
||||
@ -169,6 +165,9 @@ class LogStorageService {
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
final log = await readLog();
|
||||
final entries =
|
||||
@ -184,7 +183,7 @@ class LogStorageService {
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// Today's total calories, mirrors `_state.today_total_kcal`.
|
||||
/// Returns today's total calories, mirrors `_state.today_total_kcal`.
|
||||
Future<double> todayTotalKcal() async {
|
||||
final entries = await todayEntries();
|
||||
var total = 0.0;
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
/// 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';
|
||||
@ -1,11 +0,0 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
@ -1,2 +0,0 @@
|
||||
/// Web has no cache file: the picker returns an in-memory blob.
|
||||
Future<void> discardPickedFile(String path) async {}
|
||||
@ -1,76 +0,0 @@
|
||||
/// 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,9 +20,8 @@ abstract class NotificationBackend {
|
||||
/// of the app.
|
||||
Future<bool?> requestPermission();
|
||||
|
||||
/// Posts (or replaces) the notification for [slot], titled with the slot's
|
||||
/// clock time and carrying no body text.
|
||||
Future<void> show(int slot, String title);
|
||||
/// Posts (or replaces) the notification for [slot].
|
||||
Future<void> show(int slot, String title, String body);
|
||||
|
||||
/// Removes the notification for [slot], if one is showing.
|
||||
Future<void> cancel(int slot);
|
||||
|
||||
@ -15,8 +15,7 @@ class LocalNotificationsBackend implements NotificationBackend {
|
||||
final FlutterLocalNotificationsPlugin plugin;
|
||||
|
||||
static const _channelId = 'diet_guard_due_slot';
|
||||
// The app's proper name, same as the launcher label (no descriptive text).
|
||||
static const _channelName = 'DietGuard';
|
||||
static const _channelName = 'Meal reminders';
|
||||
|
||||
@override
|
||||
Future<void> initialize() async {
|
||||
@ -24,20 +23,6 @@ class LocalNotificationsBackend implements NotificationBackend {
|
||||
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
|
||||
);
|
||||
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.
|
||||
@ -62,7 +47,7 @@ class LocalNotificationsBackend implements NotificationBackend {
|
||||
Future.value();
|
||||
|
||||
@override
|
||||
Future<void> show(int slot, String title) async {
|
||||
Future<void> show(int slot, String title, String body) async {
|
||||
const details = NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
_channelId,
|
||||
@ -71,7 +56,12 @@ class LocalNotificationsBackend implements NotificationBackend {
|
||||
priority: Priority.high,
|
||||
),
|
||||
);
|
||||
await plugin.show(id: slot, title: title, notificationDetails: details);
|
||||
await plugin.show(
|
||||
id: slot,
|
||||
title: title,
|
||||
body: body,
|
||||
notificationDetails: details,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@ -36,13 +36,13 @@ class WebNotificationBackend implements NotificationBackend {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> show(int slot, String title) async {
|
||||
Future<void> show(int slot, String title, String body) async {
|
||||
// Posting without permission throws; a silent no-op matches this
|
||||
// service's degrade-quietly stance everywhere else.
|
||||
if (!_granted) return;
|
||||
_shown[slot] = web.Notification(
|
||||
title,
|
||||
web.NotificationOptions(tag: 'diet_guard_slot_$slot'),
|
||||
web.NotificationOptions(body: body, tag: 'diet_guard_slot_$slot'),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -86,9 +86,11 @@ class NotificationService {
|
||||
await _backend.cancel(id);
|
||||
}
|
||||
for (final slot in due) {
|
||||
// The title is only the overdue slot's clock time (a number from the
|
||||
// user's own schedule); the launcher icon is the second channel.
|
||||
await _backend.show(slot, slotLabel(slot));
|
||||
await _backend.show(
|
||||
slot,
|
||||
'Meal not logged',
|
||||
"You haven't logged your ${slotLabel(slot)} meal yet.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,42 +0,0 @@
|
||||
/// 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,24 +14,16 @@ import 'package:diet_guard_app/services/wake_alarm_weights.dart';
|
||||
|
||||
/// 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
|
||||
/// that never loaded it), so it can neither publish nor clobber anything.
|
||||
Future<void> syncBody(
|
||||
RemoteStore client, {
|
||||
required String devicesDir,
|
||||
RemoteStore? wakeAlarm,
|
||||
}) async {
|
||||
Future<void> syncBody(RemoteStore client, {required String devicesDir}) async {
|
||||
if (!BodyService.isInitialized) return;
|
||||
if (wakeAlarm != null) await ingestWakeAlarmWeights(wakeAlarm);
|
||||
await ingestWakeAlarmWeights(client);
|
||||
final merged = await syncLog(
|
||||
client: client,
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: bodyToLog(BodyService.instance.document),
|
||||
encode: encodeBodyForPush,
|
||||
decode: parseRemoteBody,
|
||||
|
||||
@ -1,49 +0,0 @@
|
||||
/// Budget record local side, shared by the sync tick and the data import.
|
||||
library;
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/meal_schedule_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge_schedule.dart';
|
||||
|
||||
/// This device's budget record; schedule-only edits stamp it at the epoch.
|
||||
Log localBudgetLog() {
|
||||
final updatedAt = AppSettingsService.dailyKcalGoalUpdatedAt;
|
||||
final scheduleEntries = MealScheduleService.history.entries;
|
||||
final recordStamp =
|
||||
updatedAt ??
|
||||
(scheduleEntries.isEmpty ? null : MealScheduleService.updatedAt);
|
||||
final localRecord = recordStamp == null
|
||||
? null
|
||||
: <String, dynamic>{
|
||||
'v': 2,
|
||||
'b': AppSettingsService.dailyKcalGoal,
|
||||
't': (updatedAt ?? DateTime.fromMillisecondsSinceEpoch(0))
|
||||
.toIso8601String(),
|
||||
};
|
||||
return budgetToLog(
|
||||
localRecord,
|
||||
BudgetHistoryService.schedule.entries,
|
||||
scheduleEntries,
|
||||
);
|
||||
}
|
||||
|
||||
/// Applies a merged budget [Log]: history, schedule, then the scalar.
|
||||
Future<void> applyBudgetLog(Log merged) async {
|
||||
await BudgetHistoryService.instance.applyMerged(logToHistory(merged));
|
||||
if (MealScheduleService.isInitialized) {
|
||||
await MealScheduleService.instance.applyMerged(
|
||||
logToScheduleHistory(merged),
|
||||
updatedAt: MealScheduleService.updatedAt,
|
||||
);
|
||||
}
|
||||
final budget = logToBudget(merged);
|
||||
final mergedKcal = budget?['b'];
|
||||
if (budget == null || mergedKcal is! int) return;
|
||||
await AppSettingsService.instance.applySyncedBudget(
|
||||
mergedKcal,
|
||||
updatedAt: DateTime.tryParse(budget['t'] as String? ?? ''),
|
||||
);
|
||||
}
|
||||
@ -5,15 +5,6 @@ import 'package:diet_guard_app/services/github_client_factory.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
/// Where every device's synced files live on the remote: the end-to-end
|
||||
/// 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.
|
||||
///
|
||||
/// The same key the sibling apps (`todo`, `home_inventory`, `wake_alarm`)
|
||||
|
||||
@ -1,102 +0,0 @@
|
||||
/// 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,7 +53,8 @@ abstract final class SyncHealth {
|
||||
_recordFailure(SyncFailureKind.unconfigured);
|
||||
|
||||
/// Marks a tick that had a backend but failed to publish.
|
||||
static Future<void> recordFailure() => _recordFailure(SyncFailureKind.failed);
|
||||
static Future<void> recordFailure() =>
|
||||
_recordFailure(SyncFailureKind.failed);
|
||||
|
||||
static Future<void> _recordFailure(SyncFailureKind kind) =>
|
||||
_withPrefs((prefs) => prefs.setString(_kFailureKind, kind.name));
|
||||
@ -154,16 +155,6 @@ class SyncHealthStatus {
|
||||
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) {
|
||||
if (since.inDays >= 1) {
|
||||
return '${since.inDays}d ago';
|
||||
|
||||
@ -12,40 +12,29 @@
|
||||
/// since a budget (unlike a food-log entry) can be edited repeatedly.
|
||||
library;
|
||||
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/services/export_keyring_default.dart';
|
||||
import 'package:diet_guard_app/services/export_keyring_sync.dart';
|
||||
import 'package:diet_guard_app/services/app_settings_service.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/foodbank_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/meal_schedule_service.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_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_kuchnia.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge_schedule.dart';
|
||||
import 'package:diet_guard_app/services/sync_state_factory.dart';
|
||||
|
||||
const String _devicesDir = syncDevicesDir;
|
||||
const _devicesDir = 'diet-guard-sync/devices';
|
||||
|
||||
/// 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
|
||||
/// [GitHubSyncError] from the client for the caller (auto-sync / the manual
|
||||
/// "Sync now" action) to decide how to report.
|
||||
Future<DayLog> runSync(
|
||||
RemoteStore backend, {
|
||||
SyncStateStore? stateStore,
|
||||
}) async {
|
||||
final client = await openDietGuardStore(backend);
|
||||
final wakeAlarm = await openWakeAlarmStore(backend);
|
||||
Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
|
||||
final logService = LogStorageService.instance;
|
||||
final local = await logService.readLog();
|
||||
|
||||
@ -54,7 +43,6 @@ Future<DayLog> runSync(
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: _devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: dayLogToLog(local),
|
||||
encode: encodeLogForPush,
|
||||
decode: parseRemoteLog,
|
||||
@ -75,8 +63,7 @@ Future<DayLog> runSync(
|
||||
await _syncFoodBank(client);
|
||||
await _syncManualBank(client);
|
||||
await _syncKuchniaCredential(client);
|
||||
await _syncExportKeys(client);
|
||||
await syncBody(client, devicesDir: _devicesDir, wakeAlarm: wakeAlarm);
|
||||
await syncBody(client, devicesDir: _devicesDir);
|
||||
return merged;
|
||||
}
|
||||
|
||||
@ -91,7 +78,6 @@ Future<void> _syncFoodBank(RemoteStore client) async {
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: _devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: foodBankToLog(await FoodBankService.instance.readBank()),
|
||||
encode: encodeFoodBankForPush,
|
||||
decode: parseRemoteFoodBank,
|
||||
@ -114,7 +100,6 @@ Future<void> _syncManualBank(RemoteStore client) async {
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: _devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: manualBankToLog(local),
|
||||
encode: encodeManualBankForPush,
|
||||
decode: parseRemoteManualBank,
|
||||
@ -125,45 +110,80 @@ Future<void> _syncManualBank(RemoteStore client) async {
|
||||
}
|
||||
|
||||
/// Pulls other devices' budgets, merges, applies the winner locally, pushes.
|
||||
///
|
||||
/// Reuses [syncLog] (it always pushes the merged result, even an empty
|
||||
/// one -- harmless and consistent with the food-log sync above). This
|
||||
/// device contributes nothing to the merge until the goal has been
|
||||
/// explicitly set at least once (see
|
||||
/// [AppSettingsService.dailyKcalGoalUpdatedAt]), so a fresh install's
|
||||
/// unset 2200 default can never spuriously outrank a real budget synced
|
||||
/// from elsewhere.
|
||||
Future<void> _syncBudget(RemoteStore client) async {
|
||||
final updatedAt = AppSettingsService.dailyKcalGoalUpdatedAt;
|
||||
final scheduleEntries = MealScheduleService.history.entries;
|
||||
// `budgetToLog` returns an empty Log for a null record, which would also
|
||||
// drop the `sched:` fields. A device that has edited its schedule but never
|
||||
// its budget still has something to contribute, so synthesise a record from
|
||||
// the schedule's own edit time in that case. Its `value` carries the
|
||||
// unset-default budget, but that loses every LWW race against a device that
|
||||
// has actually set one, because this stamp is older than any real edit.
|
||||
final scheduleStamp = MealScheduleService.updatedAt;
|
||||
final recordStamp =
|
||||
updatedAt ?? (scheduleEntries.isEmpty ? null : scheduleStamp);
|
||||
final localRecord = recordStamp == null
|
||||
? null
|
||||
: <String, dynamic>{
|
||||
'v': 2,
|
||||
'b': AppSettingsService.dailyKcalGoal,
|
||||
't': (updatedAt ?? DateTime.fromMillisecondsSinceEpoch(0))
|
||||
.toIso8601String(),
|
||||
};
|
||||
|
||||
final mergedBudgetLog = await syncLog(
|
||||
client: client,
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: _devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: localBudgetLog(),
|
||||
localLog: budgetToLog(
|
||||
localRecord,
|
||||
BudgetHistoryService.schedule.entries,
|
||||
scheduleEntries,
|
||||
),
|
||||
encode: encodeBudgetForPush,
|
||||
decode: parseRemoteBudget,
|
||||
filename: 'budget.json',
|
||||
commitMessage: 'diet_guard_app sync',
|
||||
);
|
||||
await applyBudgetLog(mergedBudgetLog);
|
||||
|
||||
// The history merges by field union, so it is applied unconditionally --
|
||||
// independently of whether the scalar budget resolved to anything.
|
||||
await BudgetHistoryService.instance.applyMerged(
|
||||
logToHistory(mergedBudgetLog),
|
||||
);
|
||||
// Same reasoning for the meal schedule: field-union merge, so applied
|
||||
// regardless of how the scalar budget resolved.
|
||||
if (MealScheduleService.isInitialized) {
|
||||
await MealScheduleService.instance.applyMerged(
|
||||
logToScheduleHistory(mergedBudgetLog),
|
||||
updatedAt: scheduleStamp,
|
||||
);
|
||||
}
|
||||
|
||||
/// Syncs the export keyring; best effort, since sync must not fail on it.
|
||||
Future<void> _syncExportKeys(RemoteStore client) async {
|
||||
try {
|
||||
await syncExportKeys(
|
||||
client,
|
||||
keyring: defaultKeyring(),
|
||||
devicesDir: _devicesDir,
|
||||
final merged = logToBudget(mergedBudgetLog);
|
||||
final mergedKcal = merged?['b'];
|
||||
if (merged == null || mergedKcal is! int) return;
|
||||
await AppSettingsService.instance.applySyncedBudget(
|
||||
mergedKcal,
|
||||
updatedAt: DateTime.tryParse(merged['t'] as String? ?? ''),
|
||||
);
|
||||
} on Object catch (error, stackTrace) {
|
||||
log(
|
||||
'export key sync failed',
|
||||
level: 900,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pulls peers' catering credentials, merges, applies the winner locally.
|
||||
///
|
||||
/// 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
|
||||
/// syncs at all. Sealed end-to-end like the rest of the synced state.
|
||||
/// syncs at all. It is plaintext on the wire, like the rest of the synced
|
||||
/// state; see `sync_merge_kuchnia.dart`.
|
||||
///
|
||||
/// 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
|
||||
@ -175,7 +195,6 @@ Future<void> _syncKuchniaCredential(RemoteStore client) async {
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: _devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: credentialToLog(
|
||||
KuchniaCredentialService.username,
|
||||
KuchniaCredentialService.password,
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
/// Morning weigh-ins from the wake-alarm app, as Body weight candidates.
|
||||
///
|
||||
/// The wake-alarm phone app publishes
|
||||
/// `wake-alarm-sync/devices-e2e/<id>/alarm.json` (end-to-end encrypted, read
|
||||
/// through wake-alarm's own `EncryptingStore`): a crdt_sync Log whose
|
||||
/// `wake-alarm-sync/devices/<id>/alarm.json`: a crdt_sync Log whose
|
||||
/// `alarm` record carries `fields[name] = [value, hlc]`. Two fields hold
|
||||
/// weights:
|
||||
///
|
||||
@ -26,7 +25,7 @@ import 'package:diet_guard_app/services/body_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_merge_body.dart';
|
||||
|
||||
/// Where the wake-alarm app publishes, one directory per device.
|
||||
const wakeAlarmDevicesDir = 'wake-alarm-sync/devices-e2e';
|
||||
const wakeAlarmDevicesDir = 'wake-alarm-sync/devices';
|
||||
|
||||
const _latestField = 'latest_weight_kg';
|
||||
const _sessionsField = 'morning_sessions';
|
||||
|
||||
@ -1,246 +0,0 @@
|
||||
/// 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),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,134 +0,0 @@
|
||||
/// 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);
|
||||
}
|
||||
@ -1,80 +0,0 @@
|
||||
/// 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),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
/// 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.
|
||||
library;
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Builds the app's single dark `ThemeData` from the shared token set.
|
||||
ThemeData buildAppTheme() {
|
||||
@ -195,9 +195,6 @@ abstract final class AppWidth {
|
||||
/// value reads as a layout error rather than an affordance.
|
||||
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.
|
||||
///
|
||||
/// 700px, i.e. 768 minus typical window chrome: the supported floor is a
|
||||
@ -205,39 +202,3 @@ abstract final class AppWidth {
|
||||
/// phone-portrait test sizes never exercise.
|
||||
static const double shortViewport = 700;
|
||||
}
|
||||
|
||||
/// Motion durations, hand-transcribed from the shared token source
|
||||
/// `~/src/utils/unified-design-system/DOCS-motion.md`; edit both together.
|
||||
///
|
||||
/// Reduced motion collapses every step to zero via [resolve]. Haptics and
|
||||
/// sound are not motion and must NOT be routed through this.
|
||||
abstract final class AppDuration {
|
||||
/// No animation; the reduced-motion target.
|
||||
static const Duration instant = Duration.zero;
|
||||
|
||||
/// 120ms -- state change on an element already under the finger.
|
||||
static const Duration fast = Duration(milliseconds: 120);
|
||||
|
||||
/// 200ms -- the default: things entering or moving within the view.
|
||||
static const Duration base = Duration(milliseconds: 200);
|
||||
|
||||
/// 320ms -- full-surface change; the ceiling, not a midpoint.
|
||||
static const Duration slow = Duration(milliseconds: 320);
|
||||
|
||||
/// [d], or [instant] when the OS asks for reduced motion.
|
||||
static Duration resolve(BuildContext context, Duration d) =>
|
||||
MediaQuery.disableAnimationsOf(context) ? instant : d;
|
||||
}
|
||||
|
||||
/// Motion easing curves, hand-transcribed from the same token source as
|
||||
/// [AppDuration] (`DOCS-motion.md`).
|
||||
abstract final class AppCurve {
|
||||
/// Default for anything that starts and ends on screen.
|
||||
static const Cubic standard = Cubic(0.2, 0, 0, 1);
|
||||
|
||||
/// Entering the screen: full speed, eases to rest.
|
||||
static const Cubic decelerate = Cubic(0, 0, 0, 1);
|
||||
|
||||
/// Leaving the screen: eases in, exits at speed.
|
||||
static const Cubic accelerate = Cubic(0.3, 0, 1, 1);
|
||||
}
|
||||
|
||||
@ -2,13 +2,12 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// A tappable list of [FoodSuggestion]s, each filling the form on tap.
|
||||
///
|
||||
/// When [compact] is true, only the top [compactLimit] suggestions render as
|
||||
/// compact single-line rows, with a "N more" button opening the full list in a
|
||||
/// When [compact] is true, only the top 3 suggestions render as compact
|
||||
/// single-line rows, with a "N more" button opening the full list in a
|
||||
/// bottom sheet so nothing becomes unreachable.
|
||||
class AutocompleteSuggestionList extends StatelessWidget {
|
||||
/// Creates an [AutocompleteSuggestionList] for [suggestions].
|
||||
@ -16,8 +15,6 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
||||
required this.suggestions,
|
||||
required this.onSelected,
|
||||
this.compact = false,
|
||||
this.compactLimit = 3,
|
||||
this.reserveHeight = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@ -31,16 +28,7 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
||||
/// of the full unbounded list.
|
||||
final bool compact;
|
||||
|
||||
/// 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;
|
||||
static const int _compactLimit = 3;
|
||||
|
||||
Future<void> _showMore(BuildContext context) async {
|
||||
await showModalBottomSheet<void>(
|
||||
@ -59,15 +47,6 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
||||
|
||||
@override
|
||||
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 (!compact) {
|
||||
return ListView.builder(
|
||||
@ -78,19 +57,15 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
||||
return ListTile(
|
||||
dense: true,
|
||||
title: Text(suggestion.name),
|
||||
subtitle: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: MacroFigure(
|
||||
kind: MacroKind.kcal,
|
||||
value: suggestion.nutrition.kcal.toStringAsFixed(0),
|
||||
),
|
||||
subtitle: Text(
|
||||
'${suggestion.nutrition.kcal.toStringAsFixed(0)} kcal',
|
||||
),
|
||||
onTap: () => onSelected(suggestion),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
final shown = suggestions.take(compactLimit).toList();
|
||||
final shown = suggestions.take(_compactLimit).toList();
|
||||
final remaining = suggestions.length - shown.length;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@ -101,34 +76,17 @@ class AutocompleteSuggestionList extends StatelessWidget {
|
||||
onTap: () => onSelected(suggestion),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
suggestion.name,
|
||||
'${suggestion.name} · '
|
||||
'${suggestion.nutrition.kcal.toStringAsFixed(0)} kcal',
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
MacroFigure(
|
||||
kind: MacroKind.kcal,
|
||||
value: suggestion.nutrition.kcal.toStringAsFixed(0),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (remaining > 0)
|
||||
TextButton(
|
||||
onPressed: () => _showMore(context),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.more_horiz, semanticLabel: 'More'),
|
||||
const SizedBox(width: 4),
|
||||
Text('+$remaining'),
|
||||
],
|
||||
),
|
||||
child: Text('$remaining more'),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@ -2,23 +2,23 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/period_average.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';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Displays this week's and this month's average kcal/day and their bands.
|
||||
///
|
||||
/// Mirrors `_calendar_view.py`'s `averages_text`, minus the words: each period
|
||||
/// 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.
|
||||
/// Mirrors `_calendar_view.py`'s `averages_text`: "Avg/day (to yesterday):
|
||||
/// week NNNN kcal (band) · month NNNN kcal (band)".
|
||||
///
|
||||
/// 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
|
||||
/// doing right now", which is what the Today progress card is for.
|
||||
class AverageSummaryRow extends StatelessWidget {
|
||||
/// Creates an [AverageSummaryRow].
|
||||
const AverageSummaryRow({required this.week, required this.month, super.key});
|
||||
const AverageSummaryRow({
|
||||
required this.week,
|
||||
required this.month,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The current ISO week's average, through yesterday.
|
||||
final PeriodAverage week;
|
||||
@ -26,72 +26,18 @@ class AverageSummaryRow extends StatelessWidget {
|
||||
/// The current calendar month's average, through yesterday.
|
||||
final PeriodAverage month;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
_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;
|
||||
static String _part(PeriodAverage period) {
|
||||
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),
|
||||
],
|
||||
],
|
||||
if (avg == null) return bandLabel(period.band);
|
||||
return '${avg.round()} kcal (${bandLabel(period.band)})';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Text(
|
||||
'Avg/day (to yesterday): week ${_part(week)} · month ${_part(month)}',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,13 +2,9 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/services/activity_kcal.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/services/body_steps.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_section.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';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// How many of the newest sessions to list.
|
||||
const int activityListLimit = 10;
|
||||
@ -59,118 +55,48 @@ class ActivityCard extends StatelessWidget {
|
||||
final lastDay = steps.isEmpty
|
||||
? null
|
||||
: steps.keys.reduce((a, b) => a.compareTo(b) > 0 ? a : b);
|
||||
final muted = Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
return BodySection(
|
||||
semanticLabel: 'Activity',
|
||||
title: 'Activity',
|
||||
children: [
|
||||
if (sessions == null && steps.isEmpty)
|
||||
const StatusCue(
|
||||
kind: CueKind.info,
|
||||
icon: Icons.directions_run,
|
||||
semanticLabel: 'No activity data yet -- published by the PC.',
|
||||
),
|
||||
const BodyNote('No activity data yet -- published by the PC.'),
|
||||
if (means != null) ...[
|
||||
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'),
|
||||
],
|
||||
),
|
||||
BodyNote('Mean daily exercise, last $window full days:'),
|
||||
for (final name in activityFormulas)
|
||||
_FormulaRow(name, whole(means[name] ?? 0)),
|
||||
BodyStatRow(name, '${whole(means[name] ?? 0)} kcal/day'),
|
||||
],
|
||||
if (lastDay != null && stepKcal != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs),
|
||||
child: Row(
|
||||
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,
|
||||
),
|
||||
],
|
||||
),
|
||||
BodyNote(
|
||||
'Steps outside workouts: ${steps[lastDay]} on $lastDay; above '
|
||||
'$stepBaseline/day they add ${whole(stepKcal)} kcal/day '
|
||||
'(included above).',
|
||||
),
|
||||
if (onConnectSteps != null)
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: OutlinedButton(
|
||||
child: OutlinedButton.icon(
|
||||
icon: const Icon(Icons.directions_walk),
|
||||
label: const Text('Connect Health Connect steps'),
|
||||
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)
|
||||
const StatusCue(
|
||||
kind: CueKind.warn,
|
||||
icon: Icons.monitor_weight,
|
||||
semanticLabel: 'Enter your weight to estimate exercise kcal.',
|
||||
),
|
||||
const BodyNote('Enter your weight to estimate exercise kcal.'),
|
||||
if (sessions != null && kg != null) ...[
|
||||
const Divider(),
|
||||
if (newest.isEmpty)
|
||||
const StatusCue(
|
||||
kind: CueKind.info,
|
||||
icon: Icons.event_busy,
|
||||
semanticLabel: 'No workouts in the last 28 days.',
|
||||
),
|
||||
const BodyNote('No workouts in the last 28 days.'),
|
||||
for (final session in newest.take(activityListLimit))
|
||||
_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 {
|
||||
const _SessionTile({required this.result});
|
||||
|
||||
@ -180,67 +106,22 @@ class _SessionTile extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final session = result.session;
|
||||
final km = session.km;
|
||||
final muted = Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(session.day),
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
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: [
|
||||
final distance = km == null ? '' : ', ${oneDecimal(km)} km';
|
||||
final kcal = [
|
||||
for (final name in activityFormulas)
|
||||
FormulaFigure(
|
||||
name,
|
||||
whole(result.kcal[name]!),
|
||||
fallback: result.fallback.contains(name),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
_formulaKcal(name, result.kcal[name]!, result.fallback.contains(name)),
|
||||
].join(' · ');
|
||||
return ListTile(
|
||||
dense: true,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('${session.day} ${session.label}'),
|
||||
subtitle: Text(
|
||||
'${whole(session.minutes)} min$distance\n$kcal kcal',
|
||||
),
|
||||
isThreeLine: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _formulaKcal(String name, double kcal, bool fallback) =>
|
||||
'$name ${whole(kcal)}${fallback ? '~' : ''}';
|
||||
|
||||
@ -1,74 +1,52 @@
|
||||
/// 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.
|
||||
/// A titled card, the building block of every Body screen section.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/services/body_calc.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// A card with [children] stacked in it; [semanticLabel] names it for screen
|
||||
/// readers and tests and is never painted.
|
||||
/// A card with a title row and [children] stacked below it.
|
||||
class BodySection extends StatelessWidget {
|
||||
/// Creates a section.
|
||||
const BodySection({
|
||||
required this.semanticLabel,
|
||||
required this.title,
|
||||
required this.children,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Spoken name of the section.
|
||||
final String semanticLabel;
|
||||
/// Section heading.
|
||||
final String title;
|
||||
|
||||
/// Section content.
|
||||
final List<Widget> children;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Semantics(
|
||||
container: true,
|
||||
label: semanticLabel,
|
||||
child: Card(
|
||||
final theme = Theme.of(context);
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: AppSpacing.md),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: children,
|
||||
),
|
||||
children: [
|
||||
Text(title, style: theme.textTheme.titleMedium),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
...children,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]).
|
||||
/// A label on the left, a value on the right; one line of a stats card.
|
||||
class BodyStatRow extends StatelessWidget {
|
||||
/// A row led by a formula's proper name.
|
||||
const BodyStatRow.named(this.name, this.value, {this.color, super.key})
|
||||
: icon = null,
|
||||
semanticLabel = null;
|
||||
/// Creates a row.
|
||||
const BodyStatRow(this.label, this.value, {this.color, super.key});
|
||||
|
||||
/// A row led by [icon], spoken as [semanticLabel].
|
||||
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;
|
||||
/// What the value is.
|
||||
final String label;
|
||||
|
||||
/// The formatted value.
|
||||
final String value;
|
||||
@ -78,19 +56,11 @@ class BodyStatRow extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final lead = icon;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: lead == null
|
||||
? Text(name!)
|
||||
: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Icon(lead, size: 20, semanticLabel: semanticLabel),
|
||||
),
|
||||
),
|
||||
Expanded(child: Text(label)),
|
||||
Text(
|
||||
value,
|
||||
style: TextStyle(
|
||||
@ -104,8 +74,28 @@ class BodyStatRow extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// `74.99` -> `"75.0 kg"`, null -> a dash. Half-up, like the PC.
|
||||
String formatKg(double? kg) => kg == null ? '—' : '${oneDecimal(kg)} kg';
|
||||
/// A muted one-line explanation (missing data, notes).
|
||||
class BodyNote extends StatelessWidget {
|
||||
/// 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.
|
||||
String oneDecimal(double value) => halfUp(value, 1).toStringAsFixed(1);
|
||||
|
||||
@ -2,25 +2,8 @@
|
||||
library;
|
||||
|
||||
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: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);
|
||||
}
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// BMI, BMI Prime, Trefethen's BMI and the WHO category.
|
||||
class BmiCard extends StatelessWidget {
|
||||
@ -34,40 +17,30 @@ class BmiCard extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final report = bmiReport(bio);
|
||||
final (low, high) = healthyRange(bio);
|
||||
final (icon, kind) = bmiBandCue(report.category);
|
||||
final tint = kind.tint(context);
|
||||
final normal = report.category == 'normal';
|
||||
return BodySection(
|
||||
semanticLabel: 'BMI',
|
||||
title: 'BMI',
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(icon, color: tint, semanticLabel: report.category),
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
Text(
|
||||
BodyStatRow(
|
||||
'BMI',
|
||||
oneDecimal(report.bmi),
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.headlineMedium?.copyWith(color: tint),
|
||||
color: normal ? null : Theme.of(context).colorScheme.error,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
BodyStatRow.named(
|
||||
'BMI Prime',
|
||||
halfUp(report.prime, 2).toStringAsFixed(2),
|
||||
),
|
||||
BodyStatRow.named('Trefethen', oneDecimal(report.trefethen)),
|
||||
BodyStatRow.icon(
|
||||
Icons.favorite,
|
||||
BodyStatRow('Category', report.category),
|
||||
BodyStatRow('BMI Prime', halfUp(report.prime, 2).toStringAsFixed(2)),
|
||||
BodyStatRow('Trefethen (new BMI)', oneDecimal(report.trefethen)),
|
||||
BodyStatRow(
|
||||
'Healthy weight for your height (BMI 18.5-24.9)',
|
||||
'${oneDecimal(low)}-${oneDecimal(high)} kg',
|
||||
),
|
||||
const BodyNote(bmiPrimeNote),
|
||||
const BodyNote(trefethenNote),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every ideal-weight formula; a dash where one is undefined.
|
||||
/// Every ideal-weight formula; `n/a` where one is undefined.
|
||||
class IdealWeightCard extends StatelessWidget {
|
||||
/// Creates the card for [bio].
|
||||
const IdealWeightCard({required this.bio, super.key});
|
||||
@ -78,25 +51,26 @@ class IdealWeightCard extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final formulas = idealWeights(bio);
|
||||
final undefined = formulas.any((f) => f.value == null);
|
||||
final summary = idealSummary(formulas);
|
||||
return BodySection(
|
||||
semanticLabel: 'Ideal weight',
|
||||
title: 'Ideal weight',
|
||||
children: [
|
||||
for (final formula in formulas)
|
||||
BodyStatRow.named(formula.name, formatKg(formula.value)),
|
||||
BodyStatRow(formula.name, formatKg(formula.value)),
|
||||
if (summary != null) ...[
|
||||
const Divider(),
|
||||
BodyStatRow.icon(
|
||||
Icons.functions,
|
||||
'Average of all',
|
||||
formatKg(summary.$1),
|
||||
),
|
||||
BodyStatRow.icon(
|
||||
Icons.swap_horiz,
|
||||
BodyStatRow('Average of all', formatKg(summary.$1)),
|
||||
BodyStatRow(
|
||||
'Ideal range',
|
||||
'${oneDecimal(summary.$2)}-${oneDecimal(summary.$3)} kg',
|
||||
),
|
||||
],
|
||||
const BodyNote(brocaNote),
|
||||
if (undefined)
|
||||
const BodyNote(
|
||||
'Devine, Robinson, Miller and Hamwi are undefined below 152.4 cm.',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@ -116,29 +90,14 @@ class BmrCard extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BodySection(
|
||||
semanticLabel: 'Resting metabolism (BMR)',
|
||||
title: 'Resting metabolism (BMR)',
|
||||
children: [
|
||||
for (final formula in bmrFormulas(bio, bodyFatPct))
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2),
|
||||
child: Row(
|
||||
children: [
|
||||
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,
|
||||
),
|
||||
],
|
||||
),
|
||||
BodyStatRow(
|
||||
formula.name,
|
||||
formula.value == null
|
||||
? 'n/a -- log a body-fat %'
|
||||
: '${whole(formula.value!)} kcal',
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@ -1,148 +0,0 @@
|
||||
/// 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.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
/// One tile: a big [icon] (spoken as [semanticLabel]), an optional headline
|
||||
/// [value] and the [builder] of the full card shown in the sheet.
|
||||
class BodyTileSpec {
|
||||
/// Creates a tile spec.
|
||||
const BodyTileSpec({
|
||||
required this.semanticLabel,
|
||||
required this.icon,
|
||||
required this.builder,
|
||||
this.value,
|
||||
this.valueIcon,
|
||||
});
|
||||
|
||||
/// Spoken name of the section; never painted.
|
||||
final String semanticLabel;
|
||||
|
||||
/// The section's glyph.
|
||||
final IconData icon;
|
||||
|
||||
/// Headline number for the tile (null when the section has none).
|
||||
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.
|
||||
final WidgetBuilder builder;
|
||||
}
|
||||
|
||||
/// Height of one tile row (dp).
|
||||
const double bodyTileHeight = 84;
|
||||
|
||||
/// Lays [tiles] out two per row, in order.
|
||||
class BodyTileGrid extends StatelessWidget {
|
||||
/// Creates the grid.
|
||||
const BodyTileGrid({required this.tiles, super.key});
|
||||
|
||||
/// Tiles in display order.
|
||||
final List<BodyTileSpec> tiles;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
for (var i = 0; i < tiles.length; i += 2) ...[
|
||||
if (i > 0) const SizedBox(height: AppSpacing.sm),
|
||||
SizedBox(
|
||||
height: bodyTileHeight,
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: _Tile(tiles[i])),
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
Expanded(
|
||||
child: i + 1 < tiles.length
|
||||
? _Tile(tiles[i + 1])
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Tile extends StatelessWidget {
|
||||
const _Tile(this.spec);
|
||||
|
||||
final BodyTileSpec spec;
|
||||
|
||||
Future<void> _open(BuildContext context) => showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
useSafeArea: true,
|
||||
builder: (sheet) => SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
child: spec.builder(sheet),
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final value = spec.value;
|
||||
final valueIcon = spec.valueIcon;
|
||||
return Card(
|
||||
margin: EdgeInsets.zero,
|
||||
child: Semantics(
|
||||
button: true,
|
||||
label: spec.semanticLabel,
|
||||
child: InkWell(
|
||||
onTap: () => _open(context),
|
||||
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.sm),
|
||||
child: Row(
|
||||
children: [
|
||||
ExcludeSemantics(
|
||||
child: Icon(
|
||||
spec.icon,
|
||||
size: 36,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
// 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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user