mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-12 17:50:48 +01:00
Compare commits
No commits in common. "main" and "v1.0.136" have entirely different histories.
@ -108,9 +108,9 @@ repos:
|
||||
# the manifest becomes an unresolvable hook environment rather
|
||||
# than merely an old one.
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.0#subdirectory=crdt-sync
|
||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.2#subdirectory=freedays
|
||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.3#subdirectory=sickdays
|
||||
- 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
|
||||
|
||||
12
AGENTS.md
12
AGENTS.md
@ -43,18 +43,6 @@ A sync tick pulls every other device's log from `kuhyx/syncs`
|
||||
`(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.
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,8 +18,6 @@ import 'package:diet_guard_app/services/body_prefs.dart';
|
||||
import 'package:diet_guard_app/services/body_service.dart';
|
||||
import 'package:diet_guard_app/services/health_steps.dart';
|
||||
import 'package:diet_guard_app/services/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';
|
||||
@ -111,13 +109,22 @@ class _BodyScreenState extends State<BodyScreen> {
|
||||
final (exercise, _, _) = bodyExercise(body, bio, today);
|
||||
final tiles = _tiles(body, bio, exercise);
|
||||
return Scaffold(
|
||||
appBar: AppBar(),
|
||||
appBar: AppBar(title: const Text('Body')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.prose),
|
||||
child: BodyTileGrid(tiles: tiles),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
BodyTileGrid(tiles: tiles),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
BodyNote(
|
||||
'Age ${bodyAgeText(body, today)} · synced with the PC.',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@ -152,12 +159,8 @@ class _BodyScreenState extends State<BodyScreen> {
|
||||
) {
|
||||
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,
|
||||
title: 'Profile',
|
||||
builder: (_) => ProfileCard(onSaved: _onChanged),
|
||||
);
|
||||
final goal = bio == null
|
||||
@ -171,65 +174,45 @@ class _BodyScreenState extends State<BodyScreen> {
|
||||
return [
|
||||
if (_profileAtTop) profile,
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Daily calorie target',
|
||||
icon: Icons.flag,
|
||||
value: goal == null ? null : '$goal',
|
||||
valueIcon: goal == null ? null : MacroKind.kcal.icon,
|
||||
title: 'Daily calorie target',
|
||||
value: goal == null ? null : '$goal kcal',
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
title: 'Daily calorie target',
|
||||
children: [BodyNote(bodyMissingNote(body))],
|
||||
)
|
||||
: GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
|
||||
),
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Weight',
|
||||
icon: Icons.monitor_weight,
|
||||
title: 'Weight',
|
||||
value: weight == null ? null : formatKg(weight),
|
||||
builder: (_) => WeightCard(onChanged: _onChanged),
|
||||
),
|
||||
if (bio != null) ...[
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'BMI',
|
||||
icon: Icons.accessibility_new,
|
||||
title: 'BMI',
|
||||
value: oneDecimal(bmiReport(bio).bmi),
|
||||
builder: (_) => BmiCard(bio: bio),
|
||||
),
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Ideal weight',
|
||||
icon: Icons.balance,
|
||||
title: 'Ideal weight',
|
||||
builder: (_) => IdealWeightCard(bio: bio),
|
||||
),
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Resting metabolism (BMR)',
|
||||
icon: Icons.bedtime,
|
||||
value: whole(tableBmr(bio, bodyFat).value!),
|
||||
valueIcon: MacroKind.kcal.icon,
|
||||
title: 'Resting metabolism (BMR)',
|
||||
value: '${whole(tableBmr(bio, bodyFat).value!)} kcal',
|
||||
builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat),
|
||||
),
|
||||
],
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Activity',
|
||||
icon: Icons.directions_run,
|
||||
title: 'Activity',
|
||||
builder: (_) => ValueListenableBuilder<bool>(
|
||||
valueListenable: _canConnectSteps,
|
||||
builder: (_, canConnect, _) => _activityCard(canConnect: canConnect),
|
||||
),
|
||||
),
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Week planner',
|
||||
icon: Icons.calendar_view_week,
|
||||
title: 'Week planner (info only)',
|
||||
builder: (_) => WeekPlanCard(
|
||||
defaultTarget: AppSettingsService.dailyKcalGoal,
|
||||
logged: _logged,
|
||||
@ -237,8 +220,7 @@ class _BodyScreenState extends State<BodyScreen> {
|
||||
),
|
||||
if (!_profileAtTop) profile,
|
||||
BodyTileSpec(
|
||||
semanticLabel: 'Body fat',
|
||||
icon: Icons.percent,
|
||||
title: 'Body fat',
|
||||
value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %',
|
||||
builder: (_) => BodyFatCard(onChanged: _onChanged),
|
||||
),
|
||||
|
||||
@ -6,7 +6,6 @@ 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:flutter/material.dart' show IconData, Icons;
|
||||
|
||||
/// Builds the person from the stored profile and newest weight, or null
|
||||
/// when anything the formulas need is missing.
|
||||
@ -62,16 +61,7 @@ Map<String, double> kcalByDay(DayLog log) => {
|
||||
.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).
|
||||
/// Why the numbers are missing.
|
||||
String bodyMissingNote(BodyService body) {
|
||||
if (body.latestWeight == null && body.birth == null) {
|
||||
return 'Set your profile and enter your weight to see BMI, ideal '
|
||||
@ -81,8 +71,8 @@ String bodyMissingNote(BodyService body) {
|
||||
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) {
|
||||
/// The age line value.
|
||||
String bodyAgeText(BodyService body, DateTime today) {
|
||||
final birth = DateTime.tryParse(body.birth ?? '');
|
||||
return birth == null ? null : '${ageOn(birth, today)}';
|
||||
return birth == null ? 'unknown' : '${ageOn(birth, today)}';
|
||||
}
|
||||
|
||||
@ -17,8 +17,6 @@ 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';
|
||||
@ -155,8 +153,9 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
||||
if (_loading) {
|
||||
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(
|
||||
@ -169,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),
|
||||
@ -215,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,
|
||||
@ -234,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,7 +8,6 @@ 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:flutter/material.dart';
|
||||
@ -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!),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
||||
@ -153,16 +153,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)
|
||||
@ -186,19 +185,19 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
|
||||
? 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),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: _openAddDialog,
|
||||
child: const Icon(Icons.add, semanticLabel: 'Add manual entry'),
|
||||
tooltip: 'Add manual entry',
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@ -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',
|
||||
controller: _controller,
|
||||
autofocus: true,
|
||||
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);
|
||||
|
||||
@ -13,7 +13,6 @@ 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';
|
||||
@ -95,86 +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: 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,
|
||||
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),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
||||
@ -159,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)
|
||||
@ -192,11 +191,8 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
? 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.',
|
||||
),
|
||||
|
||||
@ -45,23 +45,28 @@ List<Widget> logMealAppBarActions({
|
||||
required VoidCallback onBody,
|
||||
}) => [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'),
|
||||
icon: const Icon(Icons.monitor_weight),
|
||||
tooltip: 'Body',
|
||||
onPressed: onBody,
|
||||
),
|
||||
IconButton(
|
||||
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, semanticLabel: 'History'),
|
||||
icon: const Icon(Icons.history),
|
||||
tooltip: 'History',
|
||||
onPressed: onHistory,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'),
|
||||
icon: const Icon(Icons.calendar_month),
|
||||
tooltip: 'Calendar',
|
||||
onPressed: onCalendar,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'),
|
||||
icon: const Icon(Icons.settings),
|
||||
tooltip: 'Sync settings',
|
||||
onPressed: onSettings,
|
||||
),
|
||||
];
|
||||
|
||||
@ -12,23 +12,8 @@ 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:diet_guard_app/ui/cues.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// One fill tap's status (see [CountCue]).
|
||||
typedef FillCue = CountCue;
|
||||
|
||||
/// The cue for a tap's [outcome]: dishes logged (ok + N), a proposal of
|
||||
/// [armed] dishes (info + N), or nothing done (warn + 0: no delivery, every
|
||||
/// slot taken, or the fetch failed).
|
||||
FillCue fillCue(FillOutcome outcome, {required int armed}) {
|
||||
final written = outcome.written.length;
|
||||
final label = outcome.message;
|
||||
if (written > 0) return (label: label, kind: CueKind.ok, count: written);
|
||||
if (armed > 0) return (label: label, kind: CueKind.info, count: armed);
|
||||
return (label: label, kind: CueKind.warn, count: 0);
|
||||
}
|
||||
|
||||
/// Drives the screen's [FillAllFlow] and tidies the screen after a fill.
|
||||
mixin LogMealFillMixin<T extends StatefulWidget>
|
||||
on LogMealSyncMixin<T>, LogMealKuchniaMixin<T>, LogMealFutureMixin<T> {
|
||||
@ -36,9 +21,8 @@ mixin LogMealFillMixin<T extends StatefulWidget>
|
||||
/// armed proposal along with it.
|
||||
FillAllFlow fillFlow = FillAllFlow();
|
||||
|
||||
/// Shows [cue] as a status cue (its label is only spoken). Supplied by the
|
||||
/// screen.
|
||||
void showFillStatus(FillCue cue);
|
||||
/// 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.
|
||||
@ -65,13 +49,7 @@ mixin LogMealFillMixin<T extends StatefulWidget>
|
||||
// for the next tick, and the user is told the batch did not finish.
|
||||
await publishAfterLog();
|
||||
await refreshSlots();
|
||||
if (mounted) {
|
||||
showFillStatus((
|
||||
label: 'Fill all failed: $error',
|
||||
kind: CueKind.error,
|
||||
count: null,
|
||||
));
|
||||
}
|
||||
if (mounted) showFillStatus('Fill all failed: $error');
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
@ -81,17 +59,13 @@ mixin LogMealFillMixin<T extends StatefulWidget>
|
||||
await _afterFill(outcome.written, later: day != null);
|
||||
}
|
||||
if (!mounted) return;
|
||||
showFillStatus(fillCue(outcome, armed: fillFlow.armedCount));
|
||||
showFillStatus(outcome.message);
|
||||
}
|
||||
|
||||
/// Disarms a proposal without writing anything.
|
||||
void onFillCancel() {
|
||||
fillFlow.cancel();
|
||||
showFillStatus((
|
||||
label: 'Fill all cancelled — nothing logged.',
|
||||
kind: CueKind.info,
|
||||
count: null,
|
||||
));
|
||||
showFillStatus('Fill all cancelled — nothing logged.');
|
||||
}
|
||||
|
||||
/// Publishes the batch once and drops the filled dishes from the delivery
|
||||
|
||||
@ -16,7 +16,6 @@ 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/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||
import 'package:diet_guard_app/widgets/slot_selector_row.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@ -52,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)),
|
||||
@ -92,34 +91,21 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Row(
|
||||
children: [
|
||||
// Today is the default and shows nothing; only a picked date (data)
|
||||
// is shown, marked by the calendar glyph.
|
||||
if (date != null) ...[
|
||||
Icon(
|
||||
Icons.event,
|
||||
size: 18,
|
||||
color: scheme.onSurfaceVariant,
|
||||
semanticLabel: 'Log date',
|
||||
),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
],
|
||||
Expanded(
|
||||
child: date == null ? const SizedBox() : Text(localDateKey(date)),
|
||||
),
|
||||
IconButton(
|
||||
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: Icon(
|
||||
Icons.date_range,
|
||||
size: 18,
|
||||
semanticLabel: date == null ? 'Log for later' : 'Change date',
|
||||
),
|
||||
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,
|
||||
),
|
||||
],
|
||||
|
||||
@ -25,12 +25,9 @@ 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/ui/cues.dart';
|
||||
import 'package:diet_guard_app/widgets/macro_input_row.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
CountCue _cue(String l, CueKind k, [int? n]) => (label: l, kind: k, count: n);
|
||||
|
||||
/// Writes [dish]'s name and macros into the log form's controllers.
|
||||
///
|
||||
/// Free function rather than a mixin method so the numeric formatting is
|
||||
@ -141,20 +138,16 @@ mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
|
||||
/// not be re-offered) and still records the fetch, so a successful tap
|
||||
/// also spares the automatic path a second walk.
|
||||
///
|
||||
/// Returns the cue to show (a spoken line, a glyph kind and a dish count),
|
||||
/// or null when a dish was prefilled and the form speaks for itself.
|
||||
Future<CountCue?> loadDeliveryOnTap() async {
|
||||
if (!KuchniaQueueService.isInitialized) {
|
||||
return _cue('Catering is not ready yet.', CueKind.warn);
|
||||
}
|
||||
/// 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 _cue(result.reason!, CueKind.error);
|
||||
if (result.dishes.isEmpty) {
|
||||
return _cue('No delivery today.', CueKind.warn, 0);
|
||||
}
|
||||
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(
|
||||
@ -168,7 +161,7 @@ mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
|
||||
},
|
||||
);
|
||||
if (KuchniaQueueService.next == null) {
|
||||
return _cue('All delivered dishes are already logged.', CueKind.ok, 0);
|
||||
return 'All delivered dishes are already logged.';
|
||||
}
|
||||
prefillNextDish();
|
||||
return null;
|
||||
@ -186,22 +179,16 @@ mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
|
||||
/// the 250-line cap, and this is the mixin's own behaviour anyway.
|
||||
Future<void> loadDeliveryAndReport() async {
|
||||
setState(() => deliveryBusy = true);
|
||||
CountCue? cue;
|
||||
String? message;
|
||||
try {
|
||||
cue = await loadDeliveryOnTap();
|
||||
message = await loadDeliveryOnTap();
|
||||
} finally {
|
||||
if (mounted) setState(() => deliveryBusy = false);
|
||||
}
|
||||
if (!mounted || cue == null) return;
|
||||
// The outcome sentence stays as the spoken label; the snackbar paints
|
||||
// the dish glyph in the kind's tint plus the count (0 = none to log).
|
||||
showCueSnack(
|
||||
if (!mounted || message == null) return;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
kind: cue.kind,
|
||||
semanticLabel: cue.label,
|
||||
icon: Icons.restaurant,
|
||||
count: cue.count,
|
||||
);
|
||||
).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
|
||||
/// Prefills the form with the next queued dish, if there is one.
|
||||
|
||||
@ -18,7 +18,6 @@ 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_schedule_service.dart';
|
||||
import 'package:diet_guard_app/ui/cues.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/fill_all_row.dart';
|
||||
@ -60,14 +59,9 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
@override
|
||||
int? selectedSlot;
|
||||
String _source = 'manual';
|
||||
CueState? _cue; // painted as a tinted icon, never as text
|
||||
String? _status;
|
||||
TodayProgress? _progress;
|
||||
|
||||
void _setCue(CueKind kind, String? label, [int? count]) {
|
||||
_cue = label == null ? null : CueState.next(_cue, kind, label, count);
|
||||
_progress = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@ -123,8 +117,10 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
@override
|
||||
void onDishPrefilled() => setState(() => _source = 'catering');
|
||||
@override
|
||||
void showFillStatus(FillCue cue) =>
|
||||
setState(() => _setCue(cue.kind, cue.label, cue.count));
|
||||
void showFillStatus(String message) => setState(() {
|
||||
_status = message;
|
||||
_progress = null;
|
||||
});
|
||||
|
||||
void _onSuggestionSelected(FoodSuggestion suggestion) {
|
||||
fillControllersFromSuggestion(suggestion, _descController, _macros);
|
||||
@ -137,12 +133,18 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
Future<void> _onLogMeal() async {
|
||||
final desc = _descController.text.trim();
|
||||
if (desc.isEmpty) {
|
||||
setState(() => _setCue(CueKind.error, 'Type what you ate first.'));
|
||||
setState(() {
|
||||
_status = 'Type what you ate first.';
|
||||
_progress = null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
final target = resolveLogTarget(selectedSlot);
|
||||
if (target.error != null) {
|
||||
setState(() => _setCue(CueKind.error, target.error));
|
||||
setState(() {
|
||||
_status = target.error;
|
||||
_progress = null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
// On the tap, before the write/sync: waiting for them is just latency.
|
||||
@ -169,7 +171,7 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
// becomes a dead letter -- the exact regression the PC gate once shipped.
|
||||
advanceQueueAfterLog(desc);
|
||||
setState(() {
|
||||
_setCue(CueKind.info, queueStatusLine);
|
||||
_status = queueStatusLine;
|
||||
_progress = buildTodayProgress(log, logged: entry);
|
||||
});
|
||||
}
|
||||
@ -178,8 +180,7 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
// No title: the app's identity is the launcher icon, and the five
|
||||
// destination glyphs fill the bar.
|
||||
title: const Text('Diet Guard'),
|
||||
actions: [
|
||||
...logMealAppBarActions(
|
||||
onFoodBank: onOpenFoodBank,
|
||||
@ -205,10 +206,9 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
setState(() => selectedSlot = slot),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
IconField(
|
||||
TextField(
|
||||
controller: _descController,
|
||||
icon: Icons.fastfood,
|
||||
semanticLabel: 'What did you eat?',
|
||||
decoration: const InputDecoration(labelText: 'What did you eat?'),
|
||||
),
|
||||
AutocompleteSuggestionList(
|
||||
suggestions: _suggestions,
|
||||
@ -231,12 +231,12 @@ class _LogMealScreenState extends State<LogMealScreen>
|
||||
busy: fillFlow.busy || deliveryBusy,
|
||||
armedCount: fillFlow.armedCount,
|
||||
),
|
||||
// Mutually exclusive: _cue carries a validation complaint or
|
||||
// queue note, _progress the post-log summary; the two may stack
|
||||
// only after a log that leaves dishes queued.
|
||||
if (_cue != null) ...[
|
||||
// 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),
|
||||
_cue!.widget,
|
||||
Text(_status!),
|
||||
],
|
||||
if (_progress != null) ...[
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
|
||||
@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,39 +18,21 @@ library;
|
||||
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:flutter/material.dart';
|
||||
|
||||
/// What a delivery fetch reports: a cue [kind], a spoken [label] (never
|
||||
/// painted) and, when dishes were banked, their [count] (painted as a number).
|
||||
class FetchOutcome {
|
||||
/// Creates an outcome.
|
||||
const FetchOutcome(this.kind, this.label, {this.count});
|
||||
|
||||
/// Icon/colour of the cue.
|
||||
final CueKind kind;
|
||||
|
||||
/// Spoken description; never painted.
|
||||
final String label;
|
||||
|
||||
/// Dishes banked, shown as a bare number next to the cue.
|
||||
final int? count;
|
||||
}
|
||||
|
||||
/// Fetches today's delivery and reports what was banked.
|
||||
///
|
||||
/// Deliberately "banked", not "logged": a delivered meal is not an eaten
|
||||
/// 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<FetchOutcome> fetchTodaysDelivery() async {
|
||||
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.
|
||||
@ -61,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();
|
||||
@ -83,7 +69,7 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
||||
);
|
||||
bool _obscured = true;
|
||||
bool _busy = false;
|
||||
Widget? _status;
|
||||
String? _status;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
@ -99,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 {
|
||||
@ -113,65 +93,62 @@ 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),
|
||||
),
|
||||
onPressed: () => setState(() => _obscured = !_obscured),
|
||||
),
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
@ -179,27 +156,29 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
|
||||
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 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),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@ -6,8 +6,6 @@ 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,9 +15,6 @@ 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';
|
||||
@ -154,26 +149,30 @@ 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')),
|
||||
// Capped at the prose width: on the ~1366px desktop window the
|
||||
// paragraphs below ran ~180 chars/line, twice tokens.md rule 21's limit.
|
||||
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,
|
||||
),
|
||||
),
|
||||
@ -187,30 +186,15 @@ 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()),
|
||||
),
|
||||
@ -219,27 +203,42 @@ class _SettingsScreenState extends State<SettingsScreen>
|
||||
.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(
|
||||
onPressed: _requestBatteryExemption,
|
||||
icon: const Icon(
|
||||
Icons.battery_alert,
|
||||
semanticLabel: 'Disable battery optimization',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _requestBatteryExemption,
|
||||
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),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
||||
@ -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;
|
||||
|
||||
|
||||
@ -31,6 +31,16 @@ 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.';
|
||||
|
||||
/// The lean-mass formula the calorie table switches to with a body fat %.
|
||||
const String katchMcArdle = 'Katch-McArdle';
|
||||
|
||||
|
||||
@ -6,10 +6,10 @@
|
||||
/// 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.
|
||||
/// NOTE: the synced copy sits in Firebase RTDB in plaintext, so Firebase can
|
||||
/// read these keys (and therefore the sealed login in any export it could get
|
||||
/// hold of) until crdt E2E lands. `export_keys` must move under that
|
||||
/// encryption too: `~/src/utils/TODO-crdt-e2e-encryption.md`.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
@ -8,7 +8,6 @@ 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';
|
||||
|
||||
@ -32,7 +31,7 @@ Future<void> pullExportKeys() async {
|
||||
final client = createGitHubClient(await SyncSettings.load());
|
||||
try {
|
||||
await syncExportKeys(
|
||||
await openDietGuardStore(await syncBackend(client)),
|
||||
await syncBackend(client),
|
||||
keyring: defaultKeyring(),
|
||||
devicesDir: syncDevicesDir,
|
||||
);
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
/// 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.
|
||||
/// concurrent mints on two devices both survive. See `export_keyring.dart`
|
||||
/// for the plaintext-at-Firebase caveat.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
@ -71,7 +70,6 @@ Future<void> syncExportKeys(
|
||||
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(),
|
||||
|
||||
@ -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.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -5,14 +5,8 @@ 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';
|
||||
/// Where every device's synced files live on the remote.
|
||||
const syncDevicesDir = 'diet-guard-sync/devices';
|
||||
|
||||
/// SharedPreferences key holding this install's device id.
|
||||
///
|
||||
|
||||
@ -1,86 +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 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';
|
||||
|
||||
@ -24,7 +24,6 @@ import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/services/sync_body.dart';
|
||||
import 'package:diet_guard_app/services/sync_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_state_factory.dart';
|
||||
@ -33,19 +32,10 @@ const String _devicesDir = syncDevicesDir;
|
||||
|
||||
/// 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 +44,6 @@ Future<DayLog> runSync(
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: _devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: dayLogToLog(local),
|
||||
encode: encodeLogForPush,
|
||||
decode: parseRemoteLog,
|
||||
@ -76,7 +65,7 @@ Future<DayLog> runSync(
|
||||
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 +80,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 +102,6 @@ Future<void> _syncManualBank(RemoteStore client) async {
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: _devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: manualBankToLog(local),
|
||||
encode: encodeManualBankForPush,
|
||||
decode: parseRemoteManualBank,
|
||||
@ -131,7 +118,6 @@ Future<void> _syncBudget(RemoteStore client) async {
|
||||
deviceId: currentSyncDeviceId,
|
||||
legacyDeviceId: legacySyncDeviceId,
|
||||
pathPrefix: _devicesDir,
|
||||
revsPath: syncRevsDir,
|
||||
localLog: localBudgetLog(),
|
||||
encode: encodeBudgetForPush,
|
||||
decode: parseRemoteBudget,
|
||||
@ -163,7 +149,8 @@ Future<void> _syncExportKeys(RemoteStore client) async {
|
||||
///
|
||||
/// 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 +162,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/material.dart';
|
||||
import 'package:flutter/services.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,129 +0,0 @@
|
||||
/// An icon-captioned text field: the glyph is painted, the words are only a
|
||||
/// spoken label (see [IconField]).
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.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,
|
||||
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;
|
||||
|
||||
/// 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,
|
||||
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:flutter/material.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:flutter/material.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,
|
||||
);
|
||||
}
|
||||
@ -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
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_suggestion.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// A tappable list of [FoodSuggestion]s, each filling the form on tap.
|
||||
@ -58,12 +57,8 @@ 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),
|
||||
);
|
||||
@ -81,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,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
MacroFigure(
|
||||
kind: MacroKind.kcal,
|
||||
value: suggestion.nutrition.kcal.toStringAsFixed(0),
|
||||
),
|
||||
],
|
||||
child: Text(
|
||||
'${suggestion.name} · '
|
||||
'${suggestion.nutrition.kcal.toStringAsFixed(0)} kcal',
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
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: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,12 +2,8 @@
|
||||
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:flutter/material.dart';
|
||||
|
||||
/// How many of the newest sessions to list.
|
||||
@ -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: [
|
||||
for (final name in activityFormulas)
|
||||
FormulaFigure(
|
||||
name,
|
||||
whole(result.kcal[name]!),
|
||||
fallback: result.fallback.contains(name),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
final distance = km == null ? '' : ', ${oneDecimal(km)} km';
|
||||
final kcal = [
|
||||
for (final name in activityFormulas)
|
||||
_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: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(
|
||||
margin: const EdgeInsets.only(bottom: AppSpacing.md),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: children,
|
||||
),
|
||||
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: [
|
||||
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,26 +2,9 @@
|
||||
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:flutter/material.dart';
|
||||
|
||||
/// The BMI band as glyph + colour (never colour alone): a green check inside
|
||||
/// the healthy range, an amber or red arrow towards the side it is off by.
|
||||
(IconData, CueKind) bmiBandCue(String category) {
|
||||
if (category == 'normal') return (Icons.check_circle, CueKind.ok);
|
||||
if (category.contains('thinness')) {
|
||||
return (Icons.trending_down, CueKind.warn);
|
||||
}
|
||||
if (category.startsWith('overweight')) {
|
||||
return (Icons.trending_up, CueKind.warn);
|
||||
}
|
||||
if (category.startsWith('obese')) return (Icons.trending_up, CueKind.error);
|
||||
return (Icons.help_outline, CueKind.info);
|
||||
}
|
||||
|
||||
/// BMI, BMI Prime, Trefethen's BMI and the WHO category.
|
||||
class BmiCard extends StatelessWidget {
|
||||
/// Creates the card for [bio].
|
||||
@ -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(
|
||||
oneDecimal(report.bmi),
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.headlineMedium?.copyWith(color: tint),
|
||||
),
|
||||
],
|
||||
BodyStatRow(
|
||||
'BMI',
|
||||
oneDecimal(report.bmi),
|
||||
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,25 @@ 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',
|
||||
),
|
||||
],
|
||||
if (undefined)
|
||||
const BodyNote(
|
||||
'Devine, Robinson and Miller are undefined below 152.4 cm.',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@ -116,29 +89,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,34 +1,22 @@
|
||||
/// The Body screen's overview: two-column icon tiles that fit one phone
|
||||
/// The Body screen's overview: two-column metric 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:flutter/material.dart';
|
||||
|
||||
/// One tile: a big [icon] (spoken as [semanticLabel]), an optional headline
|
||||
/// [value] and the [builder] of the full card shown in the sheet.
|
||||
/// One tile: a section [title], 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,
|
||||
});
|
||||
const BodyTileSpec({required this.title, required this.builder, this.value});
|
||||
|
||||
/// Spoken name of the section; never painted.
|
||||
final String semanticLabel;
|
||||
|
||||
/// The section's glyph.
|
||||
final IconData icon;
|
||||
/// Section name, the same text the full card carries.
|
||||
final String title;
|
||||
|
||||
/// 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;
|
||||
}
|
||||
@ -88,58 +76,33 @@ class _Tile extends StatelessWidget {
|
||||
@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,
|
||||
child: InkWell(
|
||||
onTap: () => _open(context),
|
||||
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.sm),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
spec.title,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
if (spec.value != null)
|
||||
Text(
|
||||
spec.value!,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
// The whole space beside the glyph goes to the value; it
|
||||
// scales down instead of ellipsizing ("70.0 kg" must show).
|
||||
Expanded(
|
||||
child: Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: FittedBox(
|
||||
fit: BoxFit.scaleDown,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (valueIcon != null)
|
||||
Icon(
|
||||
valueIcon,
|
||||
size: 18,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
if (value != null)
|
||||
Text(
|
||||
value,
|
||||
maxLines: 1,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@ -1,230 +0,0 @@
|
||||
/// Dated-value entry card: save or delete any day, undo a delete, and chart
|
||||
/// the history. Shared by weight and body fat (see `weight_card.dart`).
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/local_time.dart';
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||
import 'package:diet_guard_app/widgets/body/weight_chart.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// Enters/deletes a day's value and charts the history.
|
||||
class DatedValueCard extends StatefulWidget {
|
||||
/// Creates the card.
|
||||
const DatedValueCard({
|
||||
required this.semanticLabel,
|
||||
required this.fieldSemanticLabel,
|
||||
required this.icon,
|
||||
required this.unit,
|
||||
required this.min,
|
||||
required this.max,
|
||||
required this.latest,
|
||||
required this.series,
|
||||
required this.onSave,
|
||||
required this.onDelete,
|
||||
required this.onChanged,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Spoken name of the card; never painted.
|
||||
final String semanticLabel;
|
||||
|
||||
/// Spoken name of the input; never painted.
|
||||
final String fieldSemanticLabel;
|
||||
|
||||
/// Glyph captioning the input.
|
||||
final IconData icon;
|
||||
|
||||
/// Unit suffix (`kg`, `%`).
|
||||
final String unit;
|
||||
|
||||
/// Smallest accepted value.
|
||||
final double min;
|
||||
|
||||
/// Largest accepted value.
|
||||
final double max;
|
||||
|
||||
/// Newest `(day, value)`, or null.
|
||||
final (String, double)? latest;
|
||||
|
||||
/// Every live `(day, value)`, oldest first.
|
||||
final List<(String, double)> series;
|
||||
|
||||
/// Writes a value for a day.
|
||||
final Future<void> Function(String day, double value) onSave;
|
||||
|
||||
/// Deletes a day.
|
||||
final Future<void> Function(String day) onDelete;
|
||||
|
||||
/// Called once a value has been written or deleted.
|
||||
final VoidCallback onChanged;
|
||||
|
||||
@override
|
||||
State<DatedValueCard> createState() => _DatedValueCardState();
|
||||
}
|
||||
|
||||
class _DatedValueCardState extends State<DatedValueCard> {
|
||||
final _value = TextEditingController();
|
||||
String _day = localDateKey(DateTime.now());
|
||||
Widget? _status;
|
||||
(String, double)? _undo;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_value.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String _fmt(double value) => '${oneDecimal(value)} ${widget.unit}';
|
||||
|
||||
Future<void> _pickDay() async {
|
||||
final picked = await pickDate(
|
||||
context: context,
|
||||
firstDate: DateTime(2000),
|
||||
lastDate: DateTime.now(),
|
||||
initialDate: DateTime.parse(_day),
|
||||
);
|
||||
if (picked == null || !mounted) return;
|
||||
setState(() => _day = localDateKey(picked));
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final value = double.tryParse(_value.text.replaceAll(',', '.'));
|
||||
if (value == null || value < widget.min || value > widget.max) {
|
||||
setState(
|
||||
() => _status = StatusCue(
|
||||
key: UniqueKey(),
|
||||
kind: CueKind.error,
|
||||
icon: widget.icon,
|
||||
semanticLabel:
|
||||
'${widget.semanticLabel} must be ${whole(widget.min)}-'
|
||||
'${whole(widget.max)} ${widget.unit}.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await widget.onSave(_day, value);
|
||||
if (!mounted) return;
|
||||
_value.clear();
|
||||
setState(() {
|
||||
_undo = null;
|
||||
_status = StatusCue(
|
||||
key: UniqueKey(),
|
||||
kind: CueKind.ok,
|
||||
semanticLabel: 'Saved ${_fmt(value)} for $_day.',
|
||||
);
|
||||
});
|
||||
widget.onChanged();
|
||||
}
|
||||
|
||||
/// Deletes at once; the undo arrow restores the value that was there.
|
||||
Future<void> _delete() async {
|
||||
final day = _day;
|
||||
final removed = [
|
||||
for (final point in widget.series)
|
||||
if (point.$1 == day) point,
|
||||
];
|
||||
await widget.onDelete(day);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_undo = removed.isEmpty ? null : removed.first;
|
||||
_status = StatusCue(
|
||||
key: UniqueKey(),
|
||||
kind: CueKind.ok,
|
||||
icon: Icons.delete_outline,
|
||||
semanticLabel: 'Deleted $day.',
|
||||
);
|
||||
});
|
||||
widget.onChanged();
|
||||
}
|
||||
|
||||
Future<void> _restore() async {
|
||||
final undo = _undo;
|
||||
if (undo == null) return;
|
||||
await widget.onSave(undo.$1, undo.$2);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_undo = null;
|
||||
_status = null;
|
||||
});
|
||||
widget.onChanged();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final latest = widget.latest;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final undo = _undo;
|
||||
return BodySection(
|
||||
semanticLabel: widget.semanticLabel,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.update, size: 18, semanticLabel: 'Latest'),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
if (latest == null)
|
||||
Icon(Icons.block, size: 18, color: scheme.outline)
|
||||
else
|
||||
// Scales down instead of clipping on a narrow sheet.
|
||||
Flexible(
|
||||
child: FittedBox(
|
||||
fit: BoxFit.scaleDown,
|
||||
child: Text('${_fmt(latest.$2)} ${latest.$1}', maxLines: 1),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: IconField(
|
||||
icon: widget.icon,
|
||||
semanticLabel: widget.fieldSemanticLabel,
|
||||
controller: _value,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
||||
],
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: _pickDay,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [const Icon(Icons.event, size: 18), Text(' $_day')],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
if (_status != null) _status! else const SizedBox.shrink(),
|
||||
if (undo != null)
|
||||
IconButton(
|
||||
onPressed: _restore,
|
||||
icon: const Icon(Icons.undo, semanticLabel: 'Undo'),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.delete_outline,
|
||||
semanticLabel: 'Delete this day',
|
||||
),
|
||||
onPressed: _delete,
|
||||
),
|
||||
IconButton.filled(
|
||||
onPressed: _save,
|
||||
icon: const Icon(Icons.check, semanticLabel: 'Save'),
|
||||
),
|
||||
],
|
||||
),
|
||||
WeightChart(series: widget.series),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,65 +0,0 @@
|
||||
/// A kcal formula shown as a glyph + number; its proper name is only the
|
||||
/// glyph's spoken label.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/services/activity_kcal.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// One distinct glyph per entry of [activityFormulas].
|
||||
const Map<String, IconData> formulaIcons = {
|
||||
'MET': Icons.speed,
|
||||
'ACSM': Icons.functions,
|
||||
'Per-km': Icons.straighten,
|
||||
};
|
||||
|
||||
/// The glyph for formula [name], spoken as the formula's proper name.
|
||||
class FormulaGlyph extends StatelessWidget {
|
||||
/// Creates a glyph for [name].
|
||||
const FormulaGlyph(this.name, {this.size = 16, super.key});
|
||||
|
||||
/// The formula's proper name (a key of [formulaIcons]).
|
||||
final String name;
|
||||
|
||||
/// Glyph size.
|
||||
final double size;
|
||||
|
||||
// The proper name is spoken only: a tooltip paints on long-press.
|
||||
@override
|
||||
Widget build(BuildContext context) => Icon(
|
||||
formulaIcons[name],
|
||||
size: size,
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
semanticLabel: name,
|
||||
);
|
||||
}
|
||||
|
||||
/// Glyph + number (a trailing `~` marks a figure that reuses the MET value).
|
||||
class FormulaFigure extends StatelessWidget {
|
||||
/// Creates a figure.
|
||||
const FormulaFigure(
|
||||
this.name,
|
||||
this.value, {
|
||||
this.fallback = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The formula's proper name.
|
||||
final String name;
|
||||
|
||||
/// The formatted kcal number.
|
||||
final String value;
|
||||
|
||||
/// Whether the figure is a fallback to the MET value.
|
||||
final bool fallback;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
FormulaGlyph(name),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Text(fallback ? '$value~' : value),
|
||||
],
|
||||
);
|
||||
}
|
||||
@ -1,7 +1,6 @@
|
||||
/// The Body screen's top line as marks instead of a sentence: direction
|
||||
/// arrow, amount, unit, per-period calendar, activity glyph, then a bolt and
|
||||
/// the daily kcal answer. Every mark is tappable and opens a picker; the
|
||||
/// choice is saved (and synced) immediately. Informational only.
|
||||
/// The Body screen's top line: "To [lose] [0.5] [kg] / [week] on
|
||||
/// [Moderate] eat 2019 kcal". Every bracket is tappable and opens a picker;
|
||||
/// the choice is saved (and synced) immediately. Informational only.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
@ -10,15 +9,12 @@ 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/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||
import 'package:diet_guard_app/widgets/body/goal_icons.dart';
|
||||
import 'package:diet_guard_app/widgets/body/goal_pickers.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The goal row and its answer.
|
||||
/// The goal sentence and its answer.
|
||||
class GoalCard extends StatefulWidget {
|
||||
/// Creates the card.
|
||||
const GoalCard({
|
||||
@ -51,59 +47,26 @@ class _GoalCardState extends State<GoalCard> {
|
||||
await setGoal(BodyService.instance, picked);
|
||||
}
|
||||
|
||||
/// A bordered, tappable mark spoken as [spoken]; [child] is its look.
|
||||
Widget _choice(
|
||||
String spoken,
|
||||
Widget child,
|
||||
Future<Goal?> Function(BuildContext, Goal) picker,
|
||||
) {
|
||||
Widget _choice(String text, Future<Goal?> Function(BuildContext, Goal) p) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Semantics(
|
||||
button: true,
|
||||
label: spoken,
|
||||
child: InkWell(
|
||||
onTap: () => unawaited(_pick(picker)),
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.sm,
|
||||
vertical: AppSpacing.xs,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
border: Border.all(color: scheme.outline),
|
||||
),
|
||||
child: ExcludeSemantics(
|
||||
child: DefaultTextStyle.merge(
|
||||
style: TextStyle(
|
||||
color: scheme.primary,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
child: IconTheme.merge(
|
||||
data: IconThemeData(color: scheme.primary),
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
return InkWell(
|
||||
onTap: () => unawaited(_pick(p)),
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xs),
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: scheme.primary,
|
||||
fontWeight: FontWeight.w600,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: scheme.primary,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _iconChoice(
|
||||
String spoken,
|
||||
IconData icon,
|
||||
Future<Goal?> Function(BuildContext, Goal) picker, {
|
||||
String? caption,
|
||||
}) => _choice(
|
||||
spoken,
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [Icon(icon), if (caption != null) Text(caption)],
|
||||
),
|
||||
picker,
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
@ -113,81 +76,51 @@ class _GoalCardState extends State<GoalCard> {
|
||||
final tdee = target.tdee;
|
||||
final maintain = _goal.direction == 'maintain';
|
||||
return BodySection(
|
||||
semanticLabel: 'Daily calorie target',
|
||||
title: 'Daily calorie target',
|
||||
children: [
|
||||
Wrap(
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: AppSpacing.sm,
|
||||
runSpacing: AppSpacing.sm,
|
||||
runSpacing: AppSpacing.xs,
|
||||
children: [
|
||||
_iconChoice(
|
||||
_goal.direction,
|
||||
directionIcon(_goal.direction),
|
||||
pickDirection,
|
||||
),
|
||||
const Text('To'),
|
||||
_choice(_goal.direction, pickDirection),
|
||||
if (!maintain) ...[
|
||||
_choice(
|
||||
formatG(_goal.amount),
|
||||
Text(formatG(_goal.amount)),
|
||||
pickAmount,
|
||||
),
|
||||
_choice(_goal.weightUnit, Text(_goal.weightUnit), pickWeightUnit),
|
||||
_iconChoice(
|
||||
_goal.timeUnit,
|
||||
timeUnitIcon(_goal.timeUnit),
|
||||
pickTimeUnit,
|
||||
),
|
||||
_choice(formatG(_goal.amount), pickAmount),
|
||||
_choice(_goal.weightUnit, pickWeightUnit),
|
||||
const Text('/'),
|
||||
_choice(_goal.timeUnit, pickTimeUnit),
|
||||
],
|
||||
_iconChoice(
|
||||
activityLabel(_goal.activity),
|
||||
activityIcon(_goal.activity),
|
||||
pickActivity,
|
||||
caption: activityCaption(_goal.activity),
|
||||
),
|
||||
if (kcal != null)
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(MacroKind.kcal.icon, color: theme.colorScheme.primary),
|
||||
Text(
|
||||
'$kcal',
|
||||
style: theme.textTheme.headlineMedium?.copyWith(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
const Text('on'),
|
||||
_choice(activityLabel(_goal.activity), pickActivity),
|
||||
if (kcal != null) ...[
|
||||
const Text('eat '),
|
||||
Text(
|
||||
'$kcal',
|
||||
style: theme.textTheme.headlineMedium?.copyWith(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const Text(' kcal'),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
if (kcal == null)
|
||||
const StatusCue(
|
||||
kind: CueKind.warn,
|
||||
icon: Icons.directions_run,
|
||||
semanticLabel: 'no workouts published yet (the PC publishes them).',
|
||||
),
|
||||
const BodyNote('no workouts published yet (the PC publishes them).'),
|
||||
if (target.belowFloor)
|
||||
const StatusCue(
|
||||
kind: CueKind.error,
|
||||
icon: Icons.vertical_align_bottom,
|
||||
semanticLabel: 'That is below the $minTargetKcal kcal floor.',
|
||||
Text(
|
||||
'That is below the $minTargetKcal kcal floor.',
|
||||
style: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
if (tdee != null)
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.balance,
|
||||
size: 18,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
semanticLabel: 'Maintenance',
|
||||
),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
MacroFigure(kind: MacroKind.kcal, value: whole(tdee), size: 16),
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
Text(target.bmrName),
|
||||
],
|
||||
BodyNote(
|
||||
'Maintenance ${whole(tdee)} kcal (${target.bmrName} resting '
|
||||
'burn x activity); 1 kg of fat = ${formatG(kcalPerKg)} kcal.',
|
||||
),
|
||||
const BodyNote(
|
||||
'Informational only — the budget is never changed from here.',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,45 +0,0 @@
|
||||
/// Glyphs for the goal's enumerations (direction, time unit, activity), so
|
||||
/// the goal reads as a row of icons and numbers instead of a sentence.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/services/body_energy.dart';
|
||||
import 'package:diet_guard_app/widgets/body/formula_figure.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Lose = down arrow, maintain = level bar, gain = up arrow.
|
||||
IconData directionIcon(String direction) => switch (direction) {
|
||||
'lose' => Icons.south,
|
||||
'gain' => Icons.north,
|
||||
_ => Icons.drag_handle,
|
||||
};
|
||||
|
||||
/// Day / week / month / year as calendar views of growing span.
|
||||
IconData timeUnitIcon(String unit) => switch (unit) {
|
||||
'day' => Icons.calendar_view_day,
|
||||
'week' => Icons.calendar_view_week,
|
||||
'month' => Icons.calendar_view_month,
|
||||
_ => Icons.event_repeat,
|
||||
};
|
||||
|
||||
/// The five levels ramp from a chair to a barbell; a measured choice wears
|
||||
/// its formula's glyph (the same one the Activity sheet shows next to kcal).
|
||||
IconData activityIcon(String key) => switch (key) {
|
||||
'sedentary' => Icons.chair,
|
||||
'light' => Icons.directions_walk,
|
||||
'moderate' => Icons.directions_bike,
|
||||
'very' => Icons.directions_run,
|
||||
'extra' => Icons.fitness_center,
|
||||
_ when key.startsWith(measuredPrefix) =>
|
||||
formulaIcons[key.substring(measuredPrefix.length)] ?? Icons.speed,
|
||||
_ => Icons.speed,
|
||||
};
|
||||
|
||||
/// Numeric caption under an activity icon: the TDEE multiplier of a level.
|
||||
/// Null for a measured formula (its glyph names it; the proper name is only
|
||||
/// spoken) and for an unknown key.
|
||||
String? activityCaption(String key) {
|
||||
for (final level in activityLevels) {
|
||||
if (level.key == key) return formatG(level.factor);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -1,141 +1,71 @@
|
||||
/// The pickers behind each tappable mark of the goal row.
|
||||
/// The pickers behind each tappable word of the goal sentence.
|
||||
///
|
||||
/// Each returns the edited [Goal], or null when dismissed. Options are icons
|
||||
/// (plus a number or proper name where one exists); the spoken name of every
|
||||
/// option is its semantic label.
|
||||
/// Each returns the edited [Goal], or null when dismissed.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/services/body_energy.dart';
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/body/goal_icons.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// One choice in a picker sheet.
|
||||
typedef PickerOption = ({
|
||||
String value,
|
||||
String spoken,
|
||||
IconData icon,
|
||||
String? caption,
|
||||
});
|
||||
|
||||
Future<String?> _sheet(
|
||||
BuildContext context,
|
||||
List<PickerOption> options,
|
||||
String title,
|
||||
List<(String, String, String?)> options,
|
||||
String selected,
|
||||
) => showModalBottomSheet<String>(
|
||||
context: context,
|
||||
builder: (context) => SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
child: Wrap(
|
||||
spacing: AppSpacing.sm,
|
||||
runSpacing: AppSpacing.sm,
|
||||
children: [
|
||||
for (final option in options)
|
||||
_OptionButton(
|
||||
option: option,
|
||||
selected: option.value == selected,
|
||||
onTap: () => Navigator.of(context).pop(option.value),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
ListTile(title: Text(title)),
|
||||
for (final (value, label, subtitle) in options)
|
||||
ListTile(
|
||||
title: Text(label),
|
||||
subtitle: subtitle == null ? null : Text(subtitle),
|
||||
selected: value == selected,
|
||||
trailing: value == selected ? const Icon(Icons.check) : null,
|
||||
onTap: () => Navigator.of(context).pop(value),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
class _OptionButton extends StatelessWidget {
|
||||
const _OptionButton({
|
||||
required this.option,
|
||||
required this.selected,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final PickerOption option;
|
||||
final bool selected;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final tint = selected ? scheme.primary : scheme.onSurfaceVariant;
|
||||
return Semantics(
|
||||
button: true,
|
||||
selected: selected,
|
||||
label: option.spoken,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||
child: Container(
|
||||
width: 72,
|
||||
padding: const EdgeInsets.all(AppSpacing.sm),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||
border: Border.all(
|
||||
color: selected ? scheme.primary : scheme.outline,
|
||||
),
|
||||
color: selected ? scheme.primary.withValues(alpha: 0.16) : null,
|
||||
),
|
||||
child: ExcludeSemantics(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(option.icon, color: tint, size: 28),
|
||||
if (option.caption != null)
|
||||
Text(
|
||||
option.caption!,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(color: tint),
|
||||
),
|
||||
if (selected)
|
||||
Icon(Icons.check, size: 14, color: scheme.primary),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Lose / maintain / gain.
|
||||
Future<Goal?> pickDirection(BuildContext context, Goal goal) async {
|
||||
final value = await _sheet(context, [
|
||||
for (final d in directions)
|
||||
(value: d, spoken: d, icon: directionIcon(d), caption: null),
|
||||
final value = await _sheet(context, 'Direction', [
|
||||
for (final d in directions) (d, d, null),
|
||||
], goal.direction);
|
||||
return value == null ? null : goal.copyWith(direction: value);
|
||||
}
|
||||
|
||||
/// Kilograms, pounds, grams or stones (the unit symbols are the captions).
|
||||
/// Kilograms, pounds, grams or stones.
|
||||
Future<Goal?> pickWeightUnit(BuildContext context, Goal goal) async {
|
||||
final value = await _sheet(context, [
|
||||
for (final u in weightUnits.keys)
|
||||
(value: u, spoken: u, icon: Icons.scale, caption: u),
|
||||
final value = await _sheet(context, 'Weight unit', [
|
||||
for (final u in weightUnits.keys) (u, u, null),
|
||||
], goal.weightUnit);
|
||||
return value == null ? null : goal.copyWith(weightUnit: value);
|
||||
}
|
||||
|
||||
/// Per day, week, month or year.
|
||||
Future<Goal?> pickTimeUnit(BuildContext context, Goal goal) async {
|
||||
final value = await _sheet(context, [
|
||||
for (final u in timeUnits.keys)
|
||||
(value: u, spoken: u, icon: timeUnitIcon(u), caption: null),
|
||||
final value = await _sheet(context, 'Per', [
|
||||
for (final u in timeUnits.keys) (u, u, null),
|
||||
], goal.timeUnit);
|
||||
return value == null ? null : goal.copyWith(timeUnit: value);
|
||||
}
|
||||
|
||||
/// The five levels, then the three measured formulas.
|
||||
Future<Goal?> pickActivity(BuildContext context, Goal goal) async {
|
||||
final value = await _sheet(context, [
|
||||
final meaning = {for (final l in activityLevels) l.key: l.meaning};
|
||||
final value = await _sheet(context, 'Activity', [
|
||||
for (final key in activityChoices)
|
||||
(
|
||||
value: key,
|
||||
spoken: activityLabel(key),
|
||||
icon: activityIcon(key),
|
||||
caption: activityCaption(key),
|
||||
key,
|
||||
activityLabel(key),
|
||||
meaning[key] ?? 'BMR x 1.2 + your real workouts and steps',
|
||||
),
|
||||
], goal.activity);
|
||||
return value == null ? null : goal.copyWith(activity: value);
|
||||
@ -165,7 +95,6 @@ class _AmountDialogState extends State<_AmountDialog> {
|
||||
late final _controller = TextEditingController(
|
||||
text: formatG(widget.goal.amount),
|
||||
);
|
||||
bool _rejected = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
@ -175,17 +104,14 @@ class _AmountDialogState extends State<_AmountDialog> {
|
||||
|
||||
void _submit() {
|
||||
final typed = double.tryParse(_controller.text.replaceAll(',', '.'));
|
||||
if (typed != null && typed >= 0) {
|
||||
Navigator.of(context).pop(typed);
|
||||
return;
|
||||
}
|
||||
setState(() => _rejected = true);
|
||||
if (typed != null && typed >= 0) Navigator.of(context).pop(typed);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final goal = widget.goal;
|
||||
return AlertDialog(
|
||||
title: Text('How much (${goal.weightUnit} / ${goal.timeUnit})'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
@ -200,29 +126,23 @@ class _AmountDialogState extends State<_AmountDialog> {
|
||||
),
|
||||
],
|
||||
),
|
||||
IconField(
|
||||
icon: Icons.edit,
|
||||
semanticLabel: 'Other amount',
|
||||
TextField(
|
||||
controller: _controller,
|
||||
decoration: const InputDecoration(labelText: 'Other amount'),
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
||||
],
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
if (_rejected)
|
||||
const StatusCue(kind: CueKind.error, semanticLabel: 'not a number'),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||
),
|
||||
IconButton.filled(
|
||||
onPressed: _submit,
|
||||
icon: const Icon(Icons.check, semanticLabel: 'OK'),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(onPressed: _submit, child: const Text('OK')),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@ -3,10 +3,8 @@ library;
|
||||
|
||||
import 'package:diet_guard_app/models/local_time.dart';
|
||||
import 'package:diet_guard_app/services/body_service.dart';
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
@ -26,7 +24,7 @@ class _ProfileCardState extends State<ProfileCard> {
|
||||
final _height = TextEditingController();
|
||||
String? _birth;
|
||||
String? _sex;
|
||||
Widget? _status;
|
||||
String? _status;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@ -47,7 +45,7 @@ class _ProfileCardState extends State<ProfileCard> {
|
||||
Future<void> _pickBirth() async {
|
||||
final now = DateTime.now();
|
||||
final initial = DateTime.tryParse(_birth ?? '') ?? DateTime(now.year - 30);
|
||||
final picked = await pickDate(
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(1900),
|
||||
lastDate: now,
|
||||
@ -61,14 +59,7 @@ class _ProfileCardState extends State<ProfileCard> {
|
||||
Future<void> _save() async {
|
||||
final height = double.tryParse(_height.text.replaceAll(',', '.'));
|
||||
if (height == null || height < 50 || height > 260) {
|
||||
setState(
|
||||
() => _status = StatusCue(
|
||||
key: UniqueKey(),
|
||||
kind: CueKind.error,
|
||||
icon: Icons.height,
|
||||
semanticLabel: 'Height must be 50-260 cm.',
|
||||
),
|
||||
);
|
||||
setState(() => _status = 'Height must be 50-260 cm.');
|
||||
return;
|
||||
}
|
||||
await BodyService.instance.setProfile(
|
||||
@ -77,45 +68,28 @@ class _ProfileCardState extends State<ProfileCard> {
|
||||
sex: _sex,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(
|
||||
() => _status = StatusCue(
|
||||
key: UniqueKey(),
|
||||
kind: CueKind.ok,
|
||||
semanticLabel: 'Saved.',
|
||||
),
|
||||
);
|
||||
setState(() => _status = 'Saved.');
|
||||
widget.onSaved();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final birth = _birth;
|
||||
final status = _status;
|
||||
return BodySection(
|
||||
semanticLabel: 'Profile',
|
||||
title: 'Profile',
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: TextButton(
|
||||
onPressed: _pickBirth,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.cake,
|
||||
color: birth == null ? scheme.error : null,
|
||||
semanticLabel: 'Birth date',
|
||||
),
|
||||
if (birth != null) Text(' $birth'),
|
||||
],
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: Text('Born: ${_birth ?? 'not set'}')),
|
||||
TextButton.icon(
|
||||
icon: const Icon(Icons.cake),
|
||||
label: const Text('Birth date'),
|
||||
onPressed: _pickBirth,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
IconField(
|
||||
icon: Icons.height,
|
||||
semanticLabel: 'Height (cm)',
|
||||
TextField(
|
||||
controller: _height,
|
||||
decoration: const InputDecoration(labelText: 'Height (cm)'),
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
||||
@ -123,16 +97,9 @@ class _ProfileCardState extends State<ProfileCard> {
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
SegmentedButton<String>(
|
||||
showSelectedIcon: false,
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: 'm',
|
||||
icon: Icon(Icons.male, semanticLabel: 'Male'),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: 'f',
|
||||
icon: Icon(Icons.female, semanticLabel: 'Female'),
|
||||
),
|
||||
ButtonSegment(value: 'm', label: Text('Male')),
|
||||
ButtonSegment(value: 'f', label: Text('Female')),
|
||||
],
|
||||
selected: {?_sex},
|
||||
emptySelectionAllowed: true,
|
||||
@ -142,11 +109,8 @@ class _ProfileCardState extends State<ProfileCard> {
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
Row(
|
||||
children: [
|
||||
if (status != null) Expanded(child: status) else const Spacer(),
|
||||
IconButton.filled(
|
||||
onPressed: _save,
|
||||
icon: const Icon(Icons.check, semanticLabel: 'Save profile'),
|
||||
),
|
||||
Expanded(child: BodyNote(_status ?? 'Syncs to the PC.')),
|
||||
FilledButton(onPressed: _save, child: const Text('Save profile')),
|
||||
],
|
||||
),
|
||||
],
|
||||
|
||||
@ -4,10 +4,7 @@
|
||||
/// day overrides it (a planned feast on Saturday too).
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/services/body_energy.dart';
|
||||
import 'package:diet_guard_app/services/week_plan.dart';
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@ -56,7 +53,8 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
|
||||
Widget build(BuildContext context) {
|
||||
final target = int.tryParse(_target.text) ?? widget.defaultTarget;
|
||||
final typed = <int, int>{
|
||||
for (var i = 0; i < 7; i++) i: ?int.tryParse(_days[i].text),
|
||||
for (var i = 0; i < 7; i++)
|
||||
i: ?int.tryParse(_days[i].text),
|
||||
};
|
||||
final plan = planWeek(
|
||||
widget.today ?? DateTime.now(),
|
||||
@ -66,39 +64,41 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
|
||||
);
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return BodySection(
|
||||
semanticLabel: 'Week planner',
|
||||
title: 'Week planner (info only)',
|
||||
children: [
|
||||
SpokenLabel(
|
||||
semanticLabel: 'Weekly average target (kcal/day)',
|
||||
child: TextField(
|
||||
controller: _target,
|
||||
decoration: InputDecoration(
|
||||
prefixIcon: ExcludeSemantics(
|
||||
child: Icon(MacroKind.kcal.icon, color: MacroKind.kcal.color),
|
||||
),
|
||||
hintText: '${widget.defaultTarget}',
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||
onChanged: (_) => setState(() {}),
|
||||
TextField(
|
||||
controller: _target,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Weekly average target (kcal/day)',
|
||||
hintText: '${widget.defaultTarget}',
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
for (var i = 0; i < 7; i++)
|
||||
Row(
|
||||
children: [
|
||||
// Day of month, not a weekday word: rows run Monday..Sunday.
|
||||
SizedBox(width: 32, child: Text(plan.days[i].day.substring(8))),
|
||||
SizedBox(width: 48, child: Text(plan.days[i].weekday)),
|
||||
Expanded(
|
||||
child: _DayFigure(plan.days[i], belowFloor: plan.belowFloor),
|
||||
child: Text(
|
||||
'${plan.days[i].kcal} kcal ${_sourceLabel(plan.days[i])}',
|
||||
style: TextStyle(
|
||||
color: plan.days[i].source == 'plan' && plan.belowFloor
|
||||
? scheme.error
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 96,
|
||||
child: IconField(
|
||||
icon: Icons.rice_bowl,
|
||||
semanticLabel: 'ate…',
|
||||
child: TextField(
|
||||
controller: _days[i],
|
||||
dense: true,
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'ate…',
|
||||
isDense: true,
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||
onChanged: (_) => setState(() {}),
|
||||
@ -107,86 +107,26 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
_Summary(plan, scheme),
|
||||
BodyNote(_summary(plan)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A day's kcal with a glyph for where the number came from.
|
||||
class _DayFigure extends StatelessWidget {
|
||||
const _DayFigure(this.day, {required this.belowFloor});
|
||||
String _sourceLabel(DayPlan day) => switch (day.source) {
|
||||
'typed' => '(typed)',
|
||||
'logged' => '(logged)',
|
||||
'unlogged' => '(not logged -- type it)',
|
||||
_ => '(plan)',
|
||||
};
|
||||
|
||||
final DayPlan day;
|
||||
final bool belowFloor;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final (icon, spoken) = switch (day.source) {
|
||||
'typed' => (Icons.edit, '(typed)'),
|
||||
'logged' => (Icons.check, '(logged)'),
|
||||
'unlogged' => (Icons.help_outline, '(not logged -- type it)'),
|
||||
_ => (Icons.insights, '(plan)'),
|
||||
};
|
||||
final bad = day.source == 'plan' && belowFloor;
|
||||
final unlogged = day.source == 'unlogged';
|
||||
final tint = bad
|
||||
? scheme.error
|
||||
: unlogged
|
||||
? CueKind.warn.tint(context)
|
||||
: null;
|
||||
return Row(
|
||||
children: [
|
||||
MacroFigure(kind: MacroKind.kcal, value: '${day.kcal}', size: 16),
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
Icon(icon, size: 16, color: tint, semanticLabel: spoken),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What to eat on the open days, or the finished week's average.
|
||||
class _Summary extends StatelessWidget {
|
||||
const _Summary(this.plan, this.scheme);
|
||||
|
||||
final WeekPlan plan;
|
||||
final ColorScheme scheme;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final per = plan.perRemaining;
|
||||
if (per == null) {
|
||||
return Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.check_circle,
|
||||
color: CueKind.ok.tint(context),
|
||||
semanticLabel: 'Every day is known: week average',
|
||||
),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
MacroFigure(kind: MacroKind.kcal, value: whole(plan.weekAvg)),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Row(
|
||||
children: [
|
||||
const Icon(Icons.restaurant, size: 18, semanticLabel: 'Eat'),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
MacroFigure(kind: MacroKind.kcal, value: '$per'),
|
||||
const SizedBox(width: AppSpacing.md),
|
||||
const Icon(Icons.flag_outlined, size: 18, semanticLabel: 'average'),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Text('${plan.targetAvg}'),
|
||||
if (plan.belowFloor) ...[
|
||||
const SizedBox(width: AppSpacing.md),
|
||||
const StatusCue(
|
||||
kind: CueKind.error,
|
||||
icon: Icons.vertical_align_bottom,
|
||||
semanticLabel: 'below the $minTargetKcal kcal floor',
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
String _summary(WeekPlan plan) {
|
||||
final per = plan.perRemaining;
|
||||
if (per == null) {
|
||||
return 'Every day is known: week average '
|
||||
'${whole(plan.weekAvg)} kcal.';
|
||||
}
|
||||
final floor = plan.belowFloor ? ' -- below the 1200 kcal floor!' : '';
|
||||
return 'Eat $per kcal on each open day to average '
|
||||
'${plan.targetAvg}$floor';
|
||||
}
|
||||
|
||||
@ -5,11 +5,12 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/body_document.dart';
|
||||
import 'package:diet_guard_app/models/local_time.dart';
|
||||
import 'package:diet_guard_app/services/body_service.dart';
|
||||
import 'package:diet_guard_app/widgets/body/dated_value_card.dart';
|
||||
import 'package:diet_guard_app/widgets/body/body_section.dart';
|
||||
import 'package:diet_guard_app/widgets/body/weight_chart.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
export 'package:diet_guard_app/widgets/body/dated_value_card.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// Weight: 20-400 kg; wake-alarm weigh-ins land here too.
|
||||
class WeightCard extends StatelessWidget {
|
||||
@ -23,12 +24,12 @@ class WeightCard extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final body = BodyService.instance;
|
||||
return DatedValueCard(
|
||||
semanticLabel: 'Weight',
|
||||
fieldSemanticLabel: 'Weight (kg)',
|
||||
icon: Icons.monitor_weight,
|
||||
title: 'Weight',
|
||||
fieldLabel: 'Weight (kg)',
|
||||
unit: 'kg',
|
||||
min: 20,
|
||||
max: 400,
|
||||
hint: 'Morning weigh-ins from wake-alarm appear here.',
|
||||
latest: body.latestWeight,
|
||||
series: body.weightSeries,
|
||||
onSave: body.setWeight,
|
||||
@ -50,12 +51,12 @@ class BodyFatCard extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final body = BodyService.instance;
|
||||
return DatedValueCard(
|
||||
semanticLabel: 'Body fat',
|
||||
fieldSemanticLabel: 'Body fat (%)',
|
||||
icon: Icons.percent,
|
||||
title: 'Body fat',
|
||||
fieldLabel: 'Body fat (%)',
|
||||
unit: '%',
|
||||
min: minBodyFat,
|
||||
max: maxBodyFat,
|
||||
hint: 'With a body fat %, targets use the lean-mass (Katch-McArdle) BMR.',
|
||||
latest: body.latestBodyFat,
|
||||
series: body.bodyFatSeries,
|
||||
onSave: body.setBodyFat,
|
||||
@ -64,3 +65,150 @@ class BodyFatCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Enters/deletes a day's value and charts the history.
|
||||
class DatedValueCard extends StatefulWidget {
|
||||
/// Creates the card.
|
||||
const DatedValueCard({
|
||||
required this.title,
|
||||
required this.fieldLabel,
|
||||
required this.unit,
|
||||
required this.min,
|
||||
required this.max,
|
||||
required this.hint,
|
||||
required this.latest,
|
||||
required this.series,
|
||||
required this.onSave,
|
||||
required this.onDelete,
|
||||
required this.onChanged,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Section heading.
|
||||
final String title;
|
||||
|
||||
/// Input label.
|
||||
final String fieldLabel;
|
||||
|
||||
/// Unit suffix (`kg`, `%`).
|
||||
final String unit;
|
||||
|
||||
/// Smallest accepted value.
|
||||
final double min;
|
||||
|
||||
/// Largest accepted value.
|
||||
final double max;
|
||||
|
||||
/// Note shown until something is saved.
|
||||
final String hint;
|
||||
|
||||
/// Newest `(day, value)`, or null.
|
||||
final (String, double)? latest;
|
||||
|
||||
/// Every live `(day, value)`, oldest first.
|
||||
final List<(String, double)> series;
|
||||
|
||||
/// Writes a value for a day.
|
||||
final Future<void> Function(String day, double value) onSave;
|
||||
|
||||
/// Deletes a day.
|
||||
final Future<void> Function(String day) onDelete;
|
||||
|
||||
/// Called once a value has been written or deleted.
|
||||
final VoidCallback onChanged;
|
||||
|
||||
@override
|
||||
State<DatedValueCard> createState() => _DatedValueCardState();
|
||||
}
|
||||
|
||||
class _DatedValueCardState extends State<DatedValueCard> {
|
||||
final _value = TextEditingController();
|
||||
String _day = localDateKey(DateTime.now());
|
||||
String? _status;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_value.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String _fmt(double value) => '${oneDecimal(value)} ${widget.unit}';
|
||||
|
||||
Future<void> _pickDay() async {
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2000),
|
||||
lastDate: DateTime.now(),
|
||||
initialDate: DateTime.parse(_day),
|
||||
);
|
||||
if (picked == null || !mounted) return;
|
||||
setState(() => _day = localDateKey(picked));
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final value = double.tryParse(_value.text.replaceAll(',', '.'));
|
||||
if (value == null || value < widget.min || value > widget.max) {
|
||||
setState(
|
||||
() => _status =
|
||||
'${widget.title} must be ${whole(widget.min)}-'
|
||||
'${whole(widget.max)} ${widget.unit}.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
await widget.onSave(_day, value);
|
||||
if (!mounted) return;
|
||||
_value.clear();
|
||||
setState(() => _status = 'Saved ${_fmt(value)} for $_day.');
|
||||
widget.onChanged();
|
||||
}
|
||||
|
||||
Future<void> _delete() async {
|
||||
await widget.onDelete(_day);
|
||||
if (!mounted) return;
|
||||
setState(() => _status = 'Deleted $_day.');
|
||||
widget.onChanged();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final latest = widget.latest;
|
||||
return BodySection(
|
||||
title: widget.title,
|
||||
children: [
|
||||
BodyStatRow(
|
||||
'Latest',
|
||||
latest == null ? 'none yet' : '${_fmt(latest.$2)} (${latest.$1})',
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _value,
|
||||
decoration: InputDecoration(labelText: widget.fieldLabel),
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
|
||||
],
|
||||
),
|
||||
),
|
||||
TextButton(onPressed: _pickDay, child: Text(_day)),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: BodyNote(_status ?? widget.hint)),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
tooltip: 'Delete this day',
|
||||
onPressed: _delete,
|
||||
),
|
||||
FilledButton(onPressed: _save, child: const Text('Save')),
|
||||
],
|
||||
),
|
||||
WeightChart(series: widget.series),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,12 +4,11 @@
|
||||
/// drawn to scale rather than evenly spaced.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:fl_chart/fl_chart.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Selectable chart ranges, `(spoken name, days)`; null days = everything.
|
||||
/// Selectable chart ranges, `(label, days)`; null days = everything.
|
||||
const List<(String, int?)> weightChartRanges = [
|
||||
('30d', 30),
|
||||
('90d', 90),
|
||||
@ -62,19 +61,11 @@ class _WeightChartState extends State<WeightChart> {
|
||||
Wrap(
|
||||
spacing: AppSpacing.sm,
|
||||
children: [
|
||||
for (final (spoken, days) in weightChartRanges)
|
||||
SpokenLabel(
|
||||
semanticLabel: spoken,
|
||||
child: ChoiceChip(
|
||||
// Days as a bare numeral; "everything" as the infinity glyph.
|
||||
label: ExcludeSemantics(
|
||||
child: days == null
|
||||
? const Icon(Icons.all_inclusive, size: 18)
|
||||
: Text('$days'),
|
||||
),
|
||||
selected: _days == days,
|
||||
onSelected: (_) => setState(() => _days = days),
|
||||
),
|
||||
for (final (label, days) in weightChartRanges)
|
||||
ChoiceChip(
|
||||
label: Text(label),
|
||||
selected: _days == days,
|
||||
onSelected: (_) => setState(() => _days = days),
|
||||
),
|
||||
],
|
||||
),
|
||||
@ -82,14 +73,7 @@ class _WeightChartState extends State<WeightChart> {
|
||||
SizedBox(
|
||||
height: 200,
|
||||
child: points.length < 2
|
||||
? Center(
|
||||
child: Icon(
|
||||
Icons.show_chart,
|
||||
size: 64,
|
||||
color: Theme.of(context).colorScheme.outline,
|
||||
semanticLabel: 'Need two readings for a graph.',
|
||||
),
|
||||
)
|
||||
? const Center(child: Text('Need two readings for a graph.'))
|
||||
: _chart(context, points),
|
||||
),
|
||||
],
|
||||
|
||||
@ -1,13 +0,0 @@
|
||||
/// Returns the activity-type icon for [kind].
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Activity kind icons used by _SessionTile (in `activity_card.dart`).
|
||||
IconData kindIcon(String kind) => switch (kind) {
|
||||
'run' => Icons.directions_run,
|
||||
'walk' => Icons.directions_walk,
|
||||
'cycle' => Icons.directions_bike,
|
||||
'strength' => Icons.fitness_center,
|
||||
_ => Icons.sports,
|
||||
};
|
||||
@ -46,6 +46,23 @@ class DayStatusCalendar extends StatelessWidget {
|
||||
/// outside the displayed month is never tappable regardless.
|
||||
final void Function(DateTime day)? onDaySelected;
|
||||
|
||||
static const _weekHeaders = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
|
||||
|
||||
static const _monthNames = [
|
||||
'January',
|
||||
'February',
|
||||
'March',
|
||||
'April',
|
||||
'May',
|
||||
'June',
|
||||
'July',
|
||||
'August',
|
||||
'September',
|
||||
'October',
|
||||
'November',
|
||||
'December',
|
||||
];
|
||||
|
||||
String _dateKey(int year, int m, int day) =>
|
||||
'$year-${m.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}';
|
||||
|
||||
@ -112,18 +129,13 @@ class DayStatusCalendar extends StatelessWidget {
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
Icons.chevron_left,
|
||||
color: scheme.onSurfaceVariant,
|
||||
semanticLabel: 'Previous month',
|
||||
),
|
||||
icon: Icon(Icons.chevron_left, color: scheme.onSurfaceVariant),
|
||||
visualDensity: VisualDensity.compact,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onPrevMonth,
|
||||
),
|
||||
// Numeric month/year: a month name would be written chrome.
|
||||
Text(
|
||||
'${m.toString().padLeft(2, '0')} · $year',
|
||||
'${_monthNames[m - 1]} $year',
|
||||
style: TextStyle(
|
||||
color: scheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
@ -131,11 +143,7 @@ class DayStatusCalendar extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
Icons.chevron_right,
|
||||
color: scheme.onSurfaceVariant,
|
||||
semanticLabel: 'Next month',
|
||||
),
|
||||
icon: Icon(Icons.chevron_right, color: scheme.onSurfaceVariant),
|
||||
visualDensity: VisualDensity.compact,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onNextMonth,
|
||||
@ -145,23 +153,25 @@ class DayStatusCalendar extends StatelessWidget {
|
||||
const SizedBox(height: AppSpacing.xs + 2),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
// Weekday names are gone: seven dots mark the Monday-first
|
||||
// columns, the two weekend ones in the accent colour.
|
||||
children: [
|
||||
for (var col = 0; col < 7; col++)
|
||||
SizedBox(
|
||||
width: 30,
|
||||
child: Center(
|
||||
child: Icon(
|
||||
Icons.circle,
|
||||
size: col >= 5 ? 8 : 5,
|
||||
color: col >= 5
|
||||
? scheme.primary
|
||||
: scheme.onSurfaceVariant,
|
||||
children: _weekHeaders
|
||||
.map(
|
||||
(h) => SizedBox(
|
||||
width: 30,
|
||||
child: Text(
|
||||
h,
|
||||
textAlign: TextAlign.center,
|
||||
// Two-letter day abbreviations are UI chrome (like a
|
||||
// badge/tag), deliberately kept below the 16px body
|
||||
// floor rather than forced to grow past their slot.
|
||||
style: TextStyle(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.label - 2,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.xs),
|
||||
...List.generate(rows, (row) {
|
||||
@ -208,10 +218,9 @@ class DayStatusCalendar extends StatelessWidget {
|
||||
// and no semantics for a screen reader. InkWell is a focus
|
||||
// stop and is activated by Enter/Space.
|
||||
final date = DateTime(year, m, day);
|
||||
final semanticLabel = 'View $day/$m/$year';
|
||||
return Semantics(
|
||||
button: true,
|
||||
label: semanticLabel,
|
||||
label: 'View $day/$m/$year',
|
||||
child: InkWell(
|
||||
onTap: () => onDaySelected!(date),
|
||||
customBorder: const CircleBorder(),
|
||||
|
||||
@ -9,8 +9,8 @@ import 'package:diet_guard_app/services/kuchnia_client.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Spoken name of the resting button (never painted).
|
||||
const fillAllLabel = 'Fill all with catering';
|
||||
/// Resting label, mirroring the PC gate's "🍱 Fill all".
|
||||
const fillAllLabel = '🍱 Fill all with catering';
|
||||
|
||||
/// Fill-all button; relabels to "✓ Confirm (N)" once a proposal is armed.
|
||||
class FillAllRow extends StatelessWidget {
|
||||
@ -52,42 +52,26 @@ class FillAllRow extends StatelessWidget {
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: busy ? null : onFill,
|
||||
child: _face(context, armed),
|
||||
child: FittedBox(
|
||||
fit: BoxFit.scaleDown,
|
||||
child: Text(_label(armed), maxLines: 1),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (armed) ...[
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
IconButton(
|
||||
TextButton(
|
||||
onPressed: busy ? null : onCancel,
|
||||
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Resting glyph; spinner while busy; double check + count once armed.
|
||||
Widget _face(BuildContext context, bool armed) {
|
||||
if (busy) {
|
||||
return const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
);
|
||||
}
|
||||
if (!armed) {
|
||||
return const Icon(Icons.playlist_add_check, semanticLabel: fillAllLabel);
|
||||
}
|
||||
final success =
|
||||
(Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark)
|
||||
.success;
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.done_all, color: success, semanticLabel: 'Confirm'),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Text('$armedCount'),
|
||||
],
|
||||
);
|
||||
String _label(bool armed) {
|
||||
if (busy) return 'Working…';
|
||||
if (armed) return '✓ Confirm ($armedCount)';
|
||||
return fillAllLabel;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,124 +0,0 @@
|
||||
/// Icon-only chrome shared by the history and food-bank filter sheets: the
|
||||
/// clear control, the apply bar and the sort chooser. Each control paints a
|
||||
/// glyph and speaks its old caption only through its semantic label.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Top row of a filter sheet: one clear-everything icon, right-aligned.
|
||||
class FilterSheetHeader extends StatelessWidget {
|
||||
/// Creates a header whose clear icon calls [onClear].
|
||||
const FilterSheetHeader({required this.onClear, super.key});
|
||||
|
||||
/// Called when the clear icon is pressed.
|
||||
final VoidCallback onClear;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 4, 8, 0),
|
||||
child: Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.filter_list_off, semanticLabel: 'Clear all'),
|
||||
onPressed: onClear,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Bottom bar of a filter sheet: one full-width check button.
|
||||
class FilterApplyBar extends StatelessWidget {
|
||||
/// Creates an apply bar that calls [onApply].
|
||||
const FilterApplyBar({required this.onApply, super.key});
|
||||
|
||||
/// Called when the check is pressed.
|
||||
final VoidCallback onApply;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: onApply,
|
||||
child: const Icon(Icons.check, semanticLabel: 'Apply'),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// One choice in a [SortChoiceRow]: a glyph, its tint and its spoken name.
|
||||
class SortOption<T> {
|
||||
/// Creates an option selecting [value].
|
||||
const SortOption(this.value, this.icon, this.semanticLabel, {this.color});
|
||||
|
||||
/// The value reported when chosen.
|
||||
final T value;
|
||||
|
||||
/// Painted glyph.
|
||||
final IconData icon;
|
||||
|
||||
/// Spoken name; never painted.
|
||||
final String semanticLabel;
|
||||
|
||||
/// Glyph tint; the theme default when null.
|
||||
final Color? color;
|
||||
}
|
||||
|
||||
/// Icon chips for the sort field plus an arrow for the direction.
|
||||
class SortChoiceRow<T> extends StatelessWidget {
|
||||
/// Creates a chooser over [options] with [selected] active.
|
||||
const SortChoiceRow({
|
||||
required this.options,
|
||||
required this.selected,
|
||||
required this.ascending,
|
||||
required this.onChanged,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Choices in display order.
|
||||
final List<SortOption<T>> options;
|
||||
|
||||
/// The active choice.
|
||||
final T selected;
|
||||
|
||||
/// Whether the sort runs ascending.
|
||||
final bool ascending;
|
||||
|
||||
/// Called with the new field and direction.
|
||||
final void Function({required T field, required bool asc}) onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
for (final o in options)
|
||||
ChoiceChip(
|
||||
label: Icon(
|
||||
o.icon,
|
||||
size: 18,
|
||||
color: o.color,
|
||||
semanticLabel: o.semanticLabel,
|
||||
),
|
||||
selected: selected == o.value,
|
||||
onSelected: (_) => onChanged(field: o.value, asc: ascending),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
||||
semanticLabel: ascending ? 'Ascending' : 'Descending',
|
||||
),
|
||||
onPressed: () => onChanged(field: selected, asc: !ascending),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -6,11 +6,9 @@
|
||||
/// screen owns the other's controls.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The free-text search-by-name field in the filter sheet.
|
||||
/// The free-text "search by name" field in the filter sheet.
|
||||
///
|
||||
/// Stateful only to own its [TextEditingController]; the query itself lives in
|
||||
/// the screen's [HistoryFilter].
|
||||
@ -46,11 +44,13 @@ class NameSearchFieldState extends State<NameSearchField> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconField(
|
||||
icon: Icons.search,
|
||||
semanticLabel: 'Search by name',
|
||||
return TextField(
|
||||
controller: _controller,
|
||||
dense: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Search by name',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: widget.onChanged,
|
||||
);
|
||||
}
|
||||
@ -112,7 +112,7 @@ class SliderSelectedLabel extends StatelessWidget {
|
||||
class FilterRangeRow extends StatelessWidget {
|
||||
/// Creates a range row bounded by [maxValue].
|
||||
const FilterRangeRow({
|
||||
required this.kind,
|
||||
required this.label,
|
||||
required this.sliderKey,
|
||||
required this.maxValue,
|
||||
required this.min,
|
||||
@ -123,8 +123,8 @@ class FilterRangeRow extends StatelessWidget {
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Which nutrient this range filters; its glyph heads the row.
|
||||
final MacroKind kind;
|
||||
/// Section heading, e.g. `Protein range (g)`.
|
||||
final String label;
|
||||
|
||||
/// Widget key on the slider itself, so tests can drive one row.
|
||||
final Key sliderKey;
|
||||
@ -158,14 +158,7 @@ class FilterRangeRow extends StatelessWidget {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Icon(
|
||||
kind.icon,
|
||||
color: kind.color,
|
||||
semanticLabel: kind.semanticLabel(compact: false),
|
||||
),
|
||||
),
|
||||
Text(label, style: Theme.of(context).textTheme.labelLarge),
|
||||
if (showEndpointLabels)
|
||||
SliderEndpointLabels(lo: '0', hi: '${maxValue.round()}$unit'),
|
||||
RangeSlider(
|
||||
|
||||
@ -4,8 +4,6 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Prompts for a new manually-curated food bank entry.
|
||||
@ -55,50 +53,49 @@ class AddEntryDialogState extends State<AddEntryDialog> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _field(MacroKind kind, TextEditingController ctrl) => Padding(
|
||||
Widget _field(String label, TextEditingController ctrl) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: IconField(
|
||||
icon: kind.icon,
|
||||
iconColor: kind.color,
|
||||
semanticLabel: kind.semanticLabel(compact: false),
|
||||
child: TextField(
|
||||
controller: ctrl,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
dense: true,
|
||||
decoration: InputDecoration(labelText: label, isDense: true),
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Add to food bank'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: IconField(
|
||||
icon: Icons.restaurant,
|
||||
semanticLabel: 'Name',
|
||||
child: TextField(
|
||||
controller: _name,
|
||||
dense: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Name',
|
||||
isDense: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
_field(MacroKind.perGrams, _grams),
|
||||
_field(MacroKind.kcal, _kcal),
|
||||
_field(MacroKind.protein, _protein),
|
||||
_field(MacroKind.carbs, _carbs),
|
||||
_field(MacroKind.fat, _fat),
|
||||
_field('Reference grams', _grams),
|
||||
_field('Kcal', _kcal),
|
||||
_field('Protein (g)', _protein),
|
||||
_field('Carbs (g)', _carbs),
|
||||
_field('Fat (g)', _fat),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: _save,
|
||||
child: const Icon(Icons.check, semanticLabel: 'Save to bank'),
|
||||
child: const Text('Save to bank'),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@ -4,9 +4,6 @@
|
||||
/// range rows come from `widgets/filters/`, shared with the history sheet.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:diet_guard_app/widgets/filters/filter_chrome.dart';
|
||||
import 'package:diet_guard_app/widgets/filters/filter_fields.dart';
|
||||
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@ -66,35 +63,6 @@ class FbFilterSheet extends StatelessWidget {
|
||||
/// Called when the user clears every criterion.
|
||||
final VoidCallback onClear;
|
||||
|
||||
static final List<SortOption<FbSortField>> _sortOptions = [
|
||||
const SortOption(FbSortField.count, Icons.repeat, 'Usage count'),
|
||||
const SortOption(FbSortField.name, Icons.sort_by_alpha, 'Name'),
|
||||
SortOption(
|
||||
FbSortField.kcal,
|
||||
MacroKind.kcal.icon,
|
||||
'Kcal',
|
||||
color: MacroKind.kcal.color,
|
||||
),
|
||||
SortOption(
|
||||
FbSortField.protein,
|
||||
MacroKind.protein.icon,
|
||||
'Protein',
|
||||
color: MacroKind.protein.color,
|
||||
),
|
||||
SortOption(
|
||||
FbSortField.carbs,
|
||||
MacroKind.carbs.icon,
|
||||
'Carbs',
|
||||
color: MacroKind.carbs.color,
|
||||
),
|
||||
SortOption(
|
||||
FbSortField.fat,
|
||||
MacroKind.fat.icon,
|
||||
'Fat',
|
||||
color: MacroKind.fat.color,
|
||||
),
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DraggableScrollableSheet(
|
||||
@ -103,17 +71,35 @@ class FbFilterSheet extends StatelessWidget {
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scroll) => Column(
|
||||
children: [
|
||||
FilterSheetHeader(onClear: onClear),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Filter & Sort',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: onClear,
|
||||
child: const Text('Clear all'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
controller: scroll,
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
IconField(
|
||||
icon: Icons.search,
|
||||
semanticLabel: 'Search by name',
|
||||
dense: true,
|
||||
TextField(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Search by name',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
isDense: true,
|
||||
),
|
||||
controller: TextEditingController(text: filter.nameQuery)
|
||||
..selection = TextSelection.collapsed(
|
||||
offset: filter.nameQuery.length,
|
||||
@ -125,7 +111,7 @@ class FbFilterSheet extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilterRangeRow(
|
||||
kind: MacroKind.kcal,
|
||||
label: 'Kcal range',
|
||||
sliderKey: const Key('fb-kcal-range-slider'),
|
||||
maxValue: maxKcal,
|
||||
min: filter.minKcal,
|
||||
@ -138,7 +124,7 @@ class FbFilterSheet extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
kind: MacroKind.protein,
|
||||
label: 'Protein range (g)',
|
||||
sliderKey: const Key('fb-protein-range-slider'),
|
||||
maxValue: maxProtein,
|
||||
min: filter.minProtein,
|
||||
@ -152,7 +138,7 @@ class FbFilterSheet extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
kind: MacroKind.carbs,
|
||||
label: 'Carbs range (g)',
|
||||
sliderKey: const Key('fb-carbs-range-slider'),
|
||||
maxValue: maxCarbs,
|
||||
min: filter.minCarbs,
|
||||
@ -166,7 +152,7 @@ class FbFilterSheet extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
kind: MacroKind.fat,
|
||||
label: 'Fat range (g)',
|
||||
sliderKey: const Key('fb-fat-range-slider'),
|
||||
maxValue: maxFat,
|
||||
min: filter.minFat,
|
||||
@ -179,16 +165,74 @@ class FbFilterSheet extends StatelessWidget {
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
),
|
||||
SortChoiceRow<FbSortField>(
|
||||
options: _sortOptions,
|
||||
selected: sortField,
|
||||
ascending: ascending,
|
||||
onChanged: onSortChanged,
|
||||
Text(
|
||||
'Sort by',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButton<FbSortField>(
|
||||
isExpanded: true,
|
||||
value: sortField,
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.count,
|
||||
child: Text('Usage count'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.name,
|
||||
child: Text('Name'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.kcal,
|
||||
child: Text('Kcal'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.protein,
|
||||
child: Text('Protein'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.carbs,
|
||||
child: Text('Carbs'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: FbSortField.fat,
|
||||
child: Text('Fat'),
|
||||
),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) {
|
||||
onSortChanged(field: v, asc: ascending);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
||||
),
|
||||
tooltip: ascending ? 'Ascending' : 'Descending',
|
||||
onPressed: () =>
|
||||
onSortChanged(field: sortField, asc: !ascending),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
FilterApplyBar(onApply: onApply),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: onApply,
|
||||
child: const Text('Apply'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@ -2,13 +2,9 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// One banked food: its name, macros, and how often it has been logged.
|
||||
///
|
||||
/// Macros are glyph + number pairs; the reference weight carries the scale
|
||||
/// glyph, the use count keeps its `×N` numeral.
|
||||
class RecordTile extends StatelessWidget {
|
||||
/// Creates a [RecordTile] for [record].
|
||||
const RecordTile(this.record, {super.key});
|
||||
@ -18,23 +14,19 @@ class RecordTile extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
String n(double v) => v.toStringAsFixed(0);
|
||||
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: Wrap(
|
||||
spacing: 12,
|
||||
children: [
|
||||
MacroFigure(kind: MacroKind.kcal, value: n(record.kcal)),
|
||||
if (record.grams > 0)
|
||||
MacroFigure(kind: MacroKind.perGrams, value: '${n(record.grams)}g'),
|
||||
MacroFigure(kind: MacroKind.protein, value: '${n(record.proteinG)}g'),
|
||||
MacroFigure(kind: MacroKind.carbs, value: '${n(record.carbsG)}g'),
|
||||
MacroFigure(kind: MacroKind.fat, value: '${n(record.fatG)}g'),
|
||||
],
|
||||
),
|
||||
subtitle: Text('${record.kcal.toStringAsFixed(0)} kcal$per · $macros'),
|
||||
trailing: record.count > 0
|
||||
? Text(
|
||||
'×${n(record.count)}',
|
||||
'×${record.count.toStringAsFixed(0)}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
)
|
||||
: null,
|
||||
|
||||
@ -4,7 +4,6 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/food_bank_record.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@ -60,13 +59,11 @@ class FbTile extends StatelessWidget {
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: MacroFigure(
|
||||
kind: MacroKind.kcal,
|
||||
value: record.kcal.toStringAsFixed(0),
|
||||
size: 14,
|
||||
),
|
||||
child: Text(
|
||||
'${record.kcal.toStringAsFixed(0)} kcal',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
if (record.count > 0)
|
||||
|
||||
@ -3,13 +3,10 @@
|
||||
/// Split out of `history_screen.dart` to hold the repo's 250-line cap.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:diet_guard_app/widgets/filters/filter_chrome.dart';
|
||||
import 'package:diet_guard_app/widgets/filters/filter_fields.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_filter.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_filter_sort.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The draggable bottom sheet that edits the history filter and sort order.
|
||||
@ -76,7 +73,20 @@ class FilterSheet extends StatelessWidget {
|
||||
maxChildSize: 0.95,
|
||||
builder: (context, scroll) => Column(
|
||||
children: [
|
||||
FilterSheetHeader(onClear: onClear),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Filter & Sort',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
TextButton(onPressed: onClear, child: const Text('Clear all')),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
@ -95,24 +105,21 @@ class FilterSheet extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Date range: the glyph alone means "any date"; once a range
|
||||
// is set its dates (data, not chrome) appear beside it.
|
||||
OutlinedButton(
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.date_range,
|
||||
semanticLabel: 'Date range',
|
||||
),
|
||||
if (filter.dateRange != null) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(dateRangeLabel(filter.dateRange!)),
|
||||
],
|
||||
],
|
||||
// Date range
|
||||
Text(
|
||||
'Date range',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
OutlinedButton.icon(
|
||||
icon: const Icon(Icons.date_range),
|
||||
label: Text(
|
||||
filter.dateRange == null
|
||||
? 'Any date'
|
||||
: dateRangeLabel(filter.dateRange!),
|
||||
),
|
||||
onPressed: () async {
|
||||
final picked = await pickDateRange(
|
||||
final picked = await showDateRangePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime.now().add(const Duration(days: 1)),
|
||||
@ -125,20 +132,17 @@ class FilterSheet extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
if (filter.dateRange != null)
|
||||
IconButton(
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
filter.dateRange = null;
|
||||
onFilterChanged(filter);
|
||||
},
|
||||
icon: const Icon(
|
||||
Icons.event_busy,
|
||||
semanticLabel: 'Clear date range',
|
||||
),
|
||||
child: const Text('Clear date range'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
FilterRangeRow(
|
||||
kind: MacroKind.kcal,
|
||||
label: 'Kcal range',
|
||||
sliderKey: const Key('kcal-range-slider'),
|
||||
maxValue: maxKcal,
|
||||
min: filter.minKcal,
|
||||
@ -150,7 +154,7 @@ class FilterSheet extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
kind: MacroKind.protein,
|
||||
label: 'Protein range (g)',
|
||||
sliderKey: const Key('protein-range-slider'),
|
||||
maxValue: maxProtein,
|
||||
min: filter.minProtein,
|
||||
@ -163,7 +167,7 @@ class FilterSheet extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
kind: MacroKind.carbs,
|
||||
label: 'Carbs range (g)',
|
||||
sliderKey: const Key('carbs-range-slider'),
|
||||
maxValue: maxCarbs,
|
||||
min: filter.minCarbs,
|
||||
@ -176,7 +180,7 @@ class FilterSheet extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
FilterRangeRow(
|
||||
kind: MacroKind.fat,
|
||||
label: 'Fat range (g)',
|
||||
sliderKey: const Key('fat-range-slider'),
|
||||
maxValue: maxFat,
|
||||
min: filter.minFat,
|
||||
@ -206,7 +210,16 @@ class FilterSheet extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
FilterApplyBar(onApply: onApply),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: onApply,
|
||||
child: const Text('Apply'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@ -3,12 +3,8 @@
|
||||
/// Split from `history_filter_sheet.dart` for the repo's 250-line cap. Both are
|
||||
/// stateless and report upward: the live filter and sort order belong to the
|
||||
/// screen, so nothing here holds state that could disagree with what is shown.
|
||||
/// Every control is a glyph; its old caption lives only in the semantic label.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:diet_guard_app/ui/source_icon.dart';
|
||||
import 'package:diet_guard_app/widgets/filters/filter_chrome.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_filter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@ -19,7 +15,7 @@ import 'package:flutter/material.dart';
|
||||
/// a constraint on what `source` may contain.
|
||||
const _sources = ['manual', 'food bank'];
|
||||
|
||||
/// Single-select chips filtering by entry source, with an "all" reset.
|
||||
/// Single-select chips filtering by entry source, with an "All" reset.
|
||||
class FilterSourceChips extends StatelessWidget {
|
||||
/// Creates source chips with [selected] currently active.
|
||||
const FilterSourceChips({
|
||||
@ -28,38 +24,41 @@ class FilterSourceChips extends StatelessWidget {
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The active source, or null for "all".
|
||||
/// The active source, or null for "All".
|
||||
final String? selected;
|
||||
|
||||
/// Called with the chosen source, or null when the reset chip is tapped.
|
||||
/// Called with the chosen source, or null when "All" is tapped.
|
||||
final ValueChanged<String?> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
FilterChip(
|
||||
label: const Icon(
|
||||
Icons.all_inclusive,
|
||||
size: 18,
|
||||
semanticLabel: 'All',
|
||||
),
|
||||
selected: selected == null,
|
||||
onSelected: (_) => onSelected(null),
|
||||
Text('Source', style: Theme.of(context).textTheme.labelLarge),
|
||||
const SizedBox(height: 4),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
FilterChip(
|
||||
label: const Text('All'),
|
||||
selected: selected == null,
|
||||
onSelected: (_) => onSelected(null),
|
||||
),
|
||||
for (final src in _sources)
|
||||
FilterChip(
|
||||
label: Text(src),
|
||||
selected: selected == src,
|
||||
onSelected: (_) => onSelected(src),
|
||||
),
|
||||
],
|
||||
),
|
||||
for (final src in _sources)
|
||||
FilterChip(
|
||||
label: SourceMark(src, size: 18),
|
||||
selected: selected == src,
|
||||
onSelected: (_) => onSelected(src),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sort-field chips plus their ascending/descending toggle.
|
||||
/// The sort-field dropdown plus its ascending/descending toggle.
|
||||
class FilterSortControls extends StatelessWidget {
|
||||
/// Creates sort controls reflecting [sortField] and [ascending].
|
||||
const FilterSortControls({
|
||||
@ -79,44 +78,63 @@ class FilterSortControls extends StatelessWidget {
|
||||
final void Function({required HistorySortField field, required bool asc})
|
||||
onSortChanged;
|
||||
|
||||
static final List<SortOption<HistorySortField>> _options = [
|
||||
const SortOption(HistorySortField.date, Icons.calendar_today, 'Date'),
|
||||
SortOption(
|
||||
HistorySortField.kcal,
|
||||
MacroKind.kcal.icon,
|
||||
'Kcal',
|
||||
color: MacroKind.kcal.color,
|
||||
),
|
||||
SortOption(
|
||||
HistorySortField.protein,
|
||||
MacroKind.protein.icon,
|
||||
'Protein',
|
||||
color: MacroKind.protein.color,
|
||||
),
|
||||
SortOption(
|
||||
HistorySortField.carbs,
|
||||
MacroKind.carbs.icon,
|
||||
'Carbs',
|
||||
color: MacroKind.carbs.color,
|
||||
),
|
||||
SortOption(
|
||||
HistorySortField.fat,
|
||||
MacroKind.fat.icon,
|
||||
'Fat',
|
||||
color: MacroKind.fat.color,
|
||||
),
|
||||
const SortOption(
|
||||
HistorySortField.description,
|
||||
Icons.sort_by_alpha,
|
||||
'Description',
|
||||
),
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => SortChoiceRow<HistorySortField>(
|
||||
options: _options,
|
||||
selected: sortField,
|
||||
ascending: ascending,
|
||||
onChanged: onSortChanged,
|
||||
);
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Sort by', style: Theme.of(context).textTheme.labelLarge),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButton<HistorySortField>(
|
||||
isExpanded: true,
|
||||
value: sortField,
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.date,
|
||||
child: Text('Date'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.kcal,
|
||||
child: Text('Kcal'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.protein,
|
||||
child: Text('Protein'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.carbs,
|
||||
child: Text('Carbs'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.fat,
|
||||
child: Text('Fat'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: HistorySortField.description,
|
||||
child: Text('Description'),
|
||||
),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) {
|
||||
onSortChanged(field: v, asc: ascending);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
ascending ? Icons.arrow_upward : Icons.arrow_downward,
|
||||
),
|
||||
tooltip: ascending ? 'Ascending' : 'Descending',
|
||||
onPressed: () => onSortChanged(field: sortField, asc: !ascending),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -170,17 +170,29 @@ String dateRangeLabel(DateTimeRange r) =>
|
||||
'${r.start.toString().substring(0, 10)}'
|
||||
' – ${r.end.toString().substring(0, 10)}';
|
||||
|
||||
/// Render a `YYYY-MM-DD` key as numeric `DD.MM.YYYY` (no weekday or month
|
||||
/// names: those were written words, and a date is a number).
|
||||
/// Render a `YYYY-MM-DD` key as a short `Wed 12 Aug`-style label.
|
||||
///
|
||||
/// Falls back to the raw key when it cannot be parsed, so a malformed date
|
||||
/// shows something rather than throwing inside a list build.
|
||||
String formatDay(String dateKey) {
|
||||
try {
|
||||
final d = DateTime.parse(dateKey);
|
||||
final day = d.day.toString().padLeft(2, '0');
|
||||
final month = d.month.toString().padLeft(2, '0');
|
||||
return '$day.$month.${d.year}';
|
||||
const wd = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||||
const mo = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
];
|
||||
return '${wd[d.weekday - 1]} ${d.day} ${mo[d.month - 1]} ${d.year}';
|
||||
} on Exception {
|
||||
return dateKey;
|
||||
}
|
||||
|
||||
@ -3,14 +3,9 @@
|
||||
/// Split out of `history_screen.dart` to hold the repo's 250-line cap.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:diet_guard_app/models/food_entry.dart';
|
||||
import 'package:diet_guard_app/services/budget_history_service.dart';
|
||||
import 'package:diet_guard_app/services/log_storage_service.dart';
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:diet_guard_app/ui/source_icon.dart';
|
||||
import 'package:diet_guard_app/widgets/history/history_grouping.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@ -89,44 +84,28 @@ class DayHeaderTile extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
Icons.restaurant,
|
||||
size: 14,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
semanticLabel: 'entries',
|
||||
Text(
|
||||
'${header.entryCount}'
|
||||
' ${header.entryCount == 1 ? 'entry' : 'entries'}',
|
||||
style: textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(width: 3),
|
||||
Text('${header.entryCount}', style: textTheme.bodySmall),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
MacroKind.kcal.icon,
|
||||
size: 14,
|
||||
color: kcalColor,
|
||||
semanticLabel: 'kcal',
|
||||
),
|
||||
const SizedBox(width: 3),
|
||||
Text(
|
||||
'${header.totalKcal.round()} / $goal',
|
||||
'${header.totalKcal.round()} / $goal kcal',
|
||||
style: textTheme.bodySmall?.copyWith(color: kcalColor),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
MacroFigure(
|
||||
kind: MacroKind.protein,
|
||||
value: '${header.totalProtein.round()}g',
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
MacroFigure(
|
||||
kind: MacroKind.carbs,
|
||||
value: '${header.totalCarbs.round()}g',
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
MacroFigure(
|
||||
kind: MacroKind.fat,
|
||||
value: '${header.totalFat.round()}g',
|
||||
Text(
|
||||
'P ${header.totalProtein.round()}g · '
|
||||
'C ${header.totalCarbs.round()}g · '
|
||||
'F ${header.totalFat.round()}g',
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
@ -156,13 +135,7 @@ class EntryTile extends StatelessWidget {
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.restaurant),
|
||||
title: Text(entry.desc),
|
||||
subtitle: Row(
|
||||
children: [
|
||||
Flexible(child: Text(entry.time, overflow: TextOverflow.ellipsis)),
|
||||
const SizedBox(width: 8),
|
||||
SourceMark(entry.source),
|
||||
],
|
||||
),
|
||||
subtitle: Text('${entry.time} • ${entry.source}'),
|
||||
// Delete needs a focusable control, not just a long-press. Long-press has
|
||||
// no keyboard equivalent at all, so on the desktop build (a Chrome --app
|
||||
// window) deleting an entry was pointer-only: unreachable by keyboard and
|
||||
@ -171,18 +144,12 @@ class EntryTile extends StatelessWidget {
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
MacroFigure(
|
||||
kind: MacroKind.kcal,
|
||||
value: entry.kcal.toStringAsFixed(0),
|
||||
size: 14,
|
||||
),
|
||||
Text('${entry.kcal.toStringAsFixed(0)} kcal'),
|
||||
if (canDelete)
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.delete_outline,
|
||||
semanticLabel: 'Delete entry',
|
||||
),
|
||||
onPressed: () => unawaited(_delete(context)),
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
tooltip: 'Delete entry',
|
||||
onPressed: () => _confirmDelete(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
@ -190,33 +157,35 @@ class EntryTile extends StatelessWidget {
|
||||
// Delete remains id-only to avoid ambiguous time+desc matches.
|
||||
onTap: () => onEdit?.call(),
|
||||
// Retained as a redundant pointer shortcut, never the only route.
|
||||
onLongPress: canDelete ? () => unawaited(_delete(context)) : null,
|
||||
onLongPress: canDelete ? () => _confirmDelete(context) : null,
|
||||
);
|
||||
}
|
||||
|
||||
/// Deletes at once and offers an icon-only undo instead of asking first.
|
||||
///
|
||||
/// The snackbar is raised before the awaits because the reload that
|
||||
/// follows rebuilds the list and may dispose this tile's context. Undo
|
||||
/// writes the live copy back over the tombstone (same id), then reloads.
|
||||
Future<void> _delete(BuildContext context) async {
|
||||
showCueSnack(
|
||||
context,
|
||||
kind: CueKind.ok,
|
||||
icon: Icons.delete_outline,
|
||||
semanticLabel: 'Entry deleted',
|
||||
onUndo: () => unawaited(_restore()),
|
||||
Future<void> _confirmDelete(BuildContext context) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
title: const Text('Delete entry?'),
|
||||
content: Text('Remove "${entry.desc}" from history?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
await LogStorageService.instance.deleteEntry(entry.id!);
|
||||
await onDelete?.call();
|
||||
}
|
||||
|
||||
Future<void> _restore() async {
|
||||
await LogStorageService.instance.updateEntry(
|
||||
entry.copyWithDeleted(),
|
||||
entry,
|
||||
);
|
||||
await onDelete?.call();
|
||||
if (confirmed == true) {
|
||||
await LogStorageService.instance.deleteEntry(entry.id!);
|
||||
await onDelete?.call();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -52,44 +52,44 @@ class LogMealActionsRow extends StatelessWidget {
|
||||
final canFetch = canFetchDelivery ?? kuchniaFetchSupported;
|
||||
return Row(
|
||||
children: [
|
||||
// Expanded so the delivery button takes the slack and pushes the log
|
||||
// button right; the queue is a numeral next to the icon, so there is
|
||||
// no wide label to clip. While fetching the icon becomes a spinner.
|
||||
// Flexible, not Spacer-and-hope: `OutlinedButton.icon` lays its label
|
||||
// out unbounded, so on a narrow phone the queue suffix renders wider
|
||||
// than the row and is clipped without ever throwing an overflow. The
|
||||
// Flexible caps the width and the FittedBox scales the text into it.
|
||||
if (canFetch)
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: deliveryBusy ? null : onLoadDelivery,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
if (deliveryBusy)
|
||||
const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
else
|
||||
const Icon(
|
||||
Icons.restaurant,
|
||||
semanticLabel: "Load today's catering delivery",
|
||||
),
|
||||
if (dishesQueued > 0) ...[
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Text('$dishesQueued'),
|
||||
],
|
||||
],
|
||||
child: Tooltip(
|
||||
message: "Load today's catering delivery",
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: deliveryBusy ? null : onLoadDelivery,
|
||||
icon: const Icon(Icons.restaurant),
|
||||
label: FittedBox(
|
||||
fit: BoxFit.scaleDown,
|
||||
child: Text(_label, maxLines: 1),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// No Spacer when the delivery button is present: it is a flex child
|
||||
// too and would split the free space with the Expanded above.
|
||||
// No Spacer: it is a flex child too, so it would split the free space
|
||||
// with the Flexible above and re-create the clipping this guards
|
||||
// against. The Flexible takes the slack and pushes the log button
|
||||
// right on its own.
|
||||
if (!canFetch) const Spacer(),
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
FilledButton(
|
||||
onPressed: onLog,
|
||||
child: const Icon(Icons.check_circle, semanticLabel: 'Log meal'),
|
||||
Tooltip(
|
||||
message: 'Log meal',
|
||||
child: FilledButton(
|
||||
onPressed: onLog,
|
||||
child: const Icon(Icons.check_circle),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String get _label {
|
||||
if (deliveryBusy) return 'Loading…';
|
||||
if (dishesQueued > 0) return "Today's delivery ($dishesQueued more to go)";
|
||||
return "Today's delivery";
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,8 +4,6 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/nutrition.dart';
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Text controllers for one macro-entry row, owned by the calling screen so
|
||||
@ -93,8 +91,7 @@ class MacroControllers {
|
||||
}
|
||||
}
|
||||
|
||||
/// A row of number-entry fields, each captioned by an icon: calories,
|
||||
/// macros, and the
|
||||
/// A labeled row of number-entry fields for calories, macros, and the
|
||||
/// optional reference-weight-vs-eaten-weight split.
|
||||
///
|
||||
/// Layout mirrors the Python gate's macro section: the reference weight
|
||||
@ -119,59 +116,76 @@ class MacroInputRow extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final fields = [
|
||||
_macroField(MacroKind.perGrams, controllers.perGrams),
|
||||
_macroField(MacroKind.kcal, controllers.kcal),
|
||||
_macroField(MacroKind.protein, controllers.protein),
|
||||
_macroField(MacroKind.carbs, controllers.carbs),
|
||||
_macroField(MacroKind.fat, controllers.fat),
|
||||
_macroField(MacroKind.eaten, controllers.grams),
|
||||
];
|
||||
if (compact) {
|
||||
return Row(
|
||||
children: [
|
||||
for (final (i, field) in fields.indexed) ...[
|
||||
if (i > 0) const SizedBox(width: 4),
|
||||
Expanded(child: field),
|
||||
],
|
||||
Expanded(child: _macroField('per', controllers.perGrams)),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(child: _macroField('kcal', controllers.kcal)),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(child: _macroField('P', controllers.protein)),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(child: _macroField('C', controllers.carbs)),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(child: _macroField('F', controllers.fat)),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: Tooltip(
|
||||
message: "blank = same as 'per (g)'",
|
||||
child: _macroField('eaten', controllers.grams),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
// Reference weight and kcal share a line, then the three macros, then the
|
||||
// eaten weight: the same order the Python gate shows them in.
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// per-gram reference weight and kcal on the same line.
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
SizedBox(width: 96, child: fields[0]),
|
||||
SizedBox(
|
||||
width: 72,
|
||||
child: _macroField('per (g)', controllers.perGrams),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: fields[1]),
|
||||
Expanded(child: _macroField('kcal', controllers.kcal)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
for (final (i, field) in fields.sublist(2, 5).indexed) ...[
|
||||
if (i > 0) const SizedBox(width: 8),
|
||||
Expanded(child: field),
|
||||
],
|
||||
Expanded(child: _macroField('protein g', controllers.protein)),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: _macroField('carbs g', controllers.carbs)),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: _macroField('fat g', controllers.fat)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
fields[5],
|
||||
_macroField(
|
||||
'eaten (g)',
|
||||
controllers.grams,
|
||||
helperText: "blank = same as 'per (g)'",
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _macroField(MacroKind kind, TextEditingController controller) {
|
||||
return IconField(
|
||||
icon: kind.icon,
|
||||
iconColor: kind.color,
|
||||
semanticLabel: kind.semanticLabel(compact: compact),
|
||||
Widget _macroField(
|
||||
String label,
|
||||
TextEditingController controller, {
|
||||
String? helperText,
|
||||
}) {
|
||||
return TextField(
|
||||
controller: controller,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
dense: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
helperText: helperText,
|
||||
isDense: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,7 +4,6 @@ library;
|
||||
|
||||
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||
import 'package:diet_guard_app/models/slot.dart';
|
||||
import 'package:diet_guard_app/ui/icon_field.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/meal_time_dropdown.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@ -62,9 +61,15 @@ class MealScheduleEditor extends StatelessWidget {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Meal times', style: theme.textTheme.titleMedium),
|
||||
const SizedBox(height: AppSpacing.xs),
|
||||
Text(
|
||||
'Checkpoints are spread evenly between your first and last meal.',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
MealTimeDropdown(
|
||||
icon: Icons.light_mode_outlined,
|
||||
semanticLabel: 'First meal',
|
||||
label: 'First meal',
|
||||
value: schedule.firstMinute,
|
||||
minMinute: 0,
|
||||
maxMinute: _firstMax,
|
||||
@ -73,8 +78,7 @@ class MealScheduleEditor extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
MealTimeDropdown(
|
||||
icon: Icons.dark_mode_outlined,
|
||||
semanticLabel: 'Last meal',
|
||||
label: 'Last meal',
|
||||
value: schedule.lastMinute,
|
||||
// At least one grid step after the first meal: the shortest window
|
||||
// that still holds two distinct checkpoints.
|
||||
@ -85,26 +89,21 @@ class MealScheduleEditor extends StatelessWidget {
|
||||
const SizedBox(height: 12),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.field),
|
||||
child: SpokenLabel(
|
||||
semanticLabel: 'Meals per day',
|
||||
child: InputDecorator(
|
||||
decoration: const InputDecoration(
|
||||
prefixIcon: ExcludeSemantics(child: Icon(Icons.restaurant)),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<int>(
|
||||
value: counts.contains(schedule.count)
|
||||
? schedule.count
|
||||
: counts.last,
|
||||
isDense: true,
|
||||
isExpanded: true,
|
||||
items: [
|
||||
for (final count in counts)
|
||||
DropdownMenuItem(value: count, child: Text('$count')),
|
||||
],
|
||||
onChanged: (count) =>
|
||||
count == null ? null : onChanged(_with(count: count)),
|
||||
),
|
||||
child: InputDecorator(
|
||||
decoration: const InputDecoration(labelText: 'Meals per day'),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<int>(
|
||||
value: counts.contains(schedule.count)
|
||||
? schedule.count
|
||||
: counts.last,
|
||||
isDense: true,
|
||||
isExpanded: true,
|
||||
items: [
|
||||
for (final count in counts)
|
||||
DropdownMenuItem(value: count, child: Text('$count')),
|
||||
],
|
||||
onChanged: (count) =>
|
||||
count == null ? null : onChanged(_with(count: count)),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@ -6,7 +6,6 @@ import 'dart:async';
|
||||
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||
import 'package:diet_guard_app/models/slot.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/pickers.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Picks a minute of day, offering the 15-minute grid within
|
||||
@ -27,8 +26,7 @@ import 'package:flutter/material.dart';
|
||||
class MealTimeDropdown extends StatelessWidget {
|
||||
/// Creates a [MealTimeDropdown].
|
||||
const MealTimeDropdown({
|
||||
required this.icon,
|
||||
required this.semanticLabel,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.minMinute,
|
||||
required this.maxMinute,
|
||||
@ -37,11 +35,8 @@ class MealTimeDropdown extends StatelessWidget {
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The painted caption glyph, e.g. a sun for the first meal.
|
||||
final IconData icon;
|
||||
|
||||
/// The spoken caption, e.g. "First meal"; never painted.
|
||||
final String semanticLabel;
|
||||
/// The field label, e.g. "First meal".
|
||||
final String label;
|
||||
|
||||
/// The current minute of day.
|
||||
final int value;
|
||||
@ -57,8 +52,8 @@ class MealTimeDropdown extends StatelessWidget {
|
||||
/// while the clock button may go to 23:44). Defaults to [maxMinute].
|
||||
final int? gridMaxMinute;
|
||||
|
||||
/// Called with the chosen minute, always within [minMinute]..[maxMinute]
|
||||
/// (the time picker cannot pick outside it). Not called when dismissed.
|
||||
/// Called with the chosen minute, already clamped into
|
||||
/// [minMinute]..[maxMinute]. Not called when the picker is dismissed.
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
/// The minutes listed, ascending: the grid marks in range plus [value].
|
||||
@ -78,15 +73,27 @@ class MealTimeDropdown extends StatelessWidget {
|
||||
}.toList()..sort();
|
||||
}
|
||||
|
||||
int _clampToRange(int minute) => minute < minMinute
|
||||
? minMinute
|
||||
: (minute > maxMinute ? maxMinute : minute);
|
||||
|
||||
Future<void> _pickExact(BuildContext context) async {
|
||||
final picked = await pickTime(
|
||||
final picked = await showTimePicker(
|
||||
context: context,
|
||||
initialTime: TimeOfDay(hour: value ~/ 60, minute: value % 60),
|
||||
minMinute: minMinute,
|
||||
maxMinute: maxMinute,
|
||||
helpText: label,
|
||||
// The rest of the app writes times as HH:MM; an AM/PM dial here would
|
||||
// be the one place that reads differently.
|
||||
builder: (context, child) => MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
|
||||
child: child!,
|
||||
),
|
||||
);
|
||||
if (picked == null) return;
|
||||
onChanged(picked.hour * 60 + picked.minute);
|
||||
// Clamped rather than rejected: the picker cannot be told the range, and
|
||||
// the nearest legal minute is what `MealSchedule.normalized` would
|
||||
// produce anyway -- doing it here keeps the dropdown's own contract.
|
||||
onChanged(_clampToRange(picked.hour * 60 + picked.minute));
|
||||
}
|
||||
|
||||
@override
|
||||
@ -96,37 +103,29 @@ class MealTimeDropdown extends StatelessWidget {
|
||||
spacing: AppSpacing.xs,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Semantics(
|
||||
label: semanticLabel,
|
||||
container: true,
|
||||
child: InputDecorator(
|
||||
decoration: InputDecoration(
|
||||
prefixIcon: ExcludeSemantics(child: Icon(icon)),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<int>(
|
||||
value: value,
|
||||
isDense: true,
|
||||
isExpanded: true,
|
||||
items: [
|
||||
for (final minute in options)
|
||||
DropdownMenuItem(
|
||||
value: minute,
|
||||
child: Text(slotLabel(minute)),
|
||||
),
|
||||
],
|
||||
onChanged: (minute) =>
|
||||
minute == null ? null : onChanged(minute),
|
||||
),
|
||||
child: InputDecorator(
|
||||
decoration: InputDecoration(labelText: label),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<int>(
|
||||
value: value,
|
||||
isDense: true,
|
||||
isExpanded: true,
|
||||
items: [
|
||||
for (final minute in options)
|
||||
DropdownMenuItem(
|
||||
value: minute,
|
||||
child: Text(slotLabel(minute)),
|
||||
),
|
||||
],
|
||||
onChanged: (minute) =>
|
||||
minute == null ? null : onChanged(minute),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(
|
||||
Icons.schedule,
|
||||
semanticLabel: 'Type or pick an exact time',
|
||||
),
|
||||
icon: const Icon(Icons.schedule),
|
||||
tooltip: 'Type or pick an exact time',
|
||||
onPressed: () => unawaited(_pickExact(context)),
|
||||
),
|
||||
],
|
||||
|
||||
@ -1,127 +0,0 @@
|
||||
/// The date and date-range dialog: month chips above, the day grid with the
|
||||
/// year wheel beside it, check and close icons below.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/date_grid.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/date_selection.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/month_chips.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/picker_frame.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/year_wheel.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// Width of the year wheel beside the grid.
|
||||
const double kYearWheelWidth = 64;
|
||||
|
||||
/// Pops a `DateTime` (single mode) or a `DateTimeRange` (range mode).
|
||||
///
|
||||
/// Keyboard: arrows move the grid cursor by a day or a week, Space taps the
|
||||
/// cursor day in range mode, Enter confirms, Esc cancels.
|
||||
class DateDialog extends StatefulWidget {
|
||||
/// Creates a [DateDialog] over [selection].
|
||||
const DateDialog({
|
||||
required this.selection,
|
||||
this.startOnYear = false,
|
||||
this.today,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The selection to edit; its mode decides the popped type.
|
||||
final DateSelection selection;
|
||||
|
||||
/// Focus the year wheel first (the birth-date flow) instead of the grid.
|
||||
final bool startOnYear;
|
||||
|
||||
/// The day to ring; now when null (a seam for tests).
|
||||
final DateTime? today;
|
||||
|
||||
@override
|
||||
State<DateDialog> createState() => _DateDialogState();
|
||||
}
|
||||
|
||||
class _DateDialogState extends State<DateDialog> {
|
||||
DateSelection get _sel => widget.selection;
|
||||
bool _gridFocused = false;
|
||||
|
||||
void _confirm() => Navigator.of(
|
||||
context,
|
||||
).pop<Object>(_sel.range ? _sel.dateRange : _sel.start);
|
||||
|
||||
KeyEventResult _key(FocusNode _, KeyEvent event) {
|
||||
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
final step = switch (event.logicalKey) {
|
||||
LogicalKeyboardKey.arrowLeft => -1,
|
||||
LogicalKeyboardKey.arrowRight => 1,
|
||||
LogicalKeyboardKey.arrowUp => -7,
|
||||
LogicalKeyboardKey.arrowDown => 7,
|
||||
_ => 0,
|
||||
};
|
||||
if (step != 0) {
|
||||
setState(() => _sel.moveCursor(step));
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (_sel.range && event.logicalKey == LogicalKeyboardKey.space) {
|
||||
setState(() => _sel.tap(_sel.cursor));
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => PickerFrame(
|
||||
canConfirm: _sel.canConfirm,
|
||||
onConfirm: _confirm,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
MonthChips(
|
||||
year: _sel.year,
|
||||
selected: _sel.month,
|
||||
allowed: (m) => _sel.monthAllowed(_sel.year, m),
|
||||
onTap: (m) => setState(() => _sel.showMonth(m)),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final gridWidth =
|
||||
constraints.maxWidth - kYearWheelWidth - AppSpacing.sm;
|
||||
return SizedBox(
|
||||
height: gridWidth / 7 * (kGridCells ~/ 7),
|
||||
child: Row(
|
||||
spacing: AppSpacing.sm,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Focus(
|
||||
autofocus: !widget.startOnYear,
|
||||
onKeyEvent: _key,
|
||||
onFocusChange: (f) => setState(() => _gridFocused = f),
|
||||
child: DateGrid(
|
||||
selection: _sel,
|
||||
today: widget.today ?? DateTime.now(),
|
||||
showCursor: _gridFocused,
|
||||
onTap: (day) => setState(() => _sel.tap(day)),
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: kYearWheelWidth,
|
||||
child: YearWheel(
|
||||
firstYear: _sel.first.year,
|
||||
lastYear: _sel.last.year,
|
||||
value: _sel.year,
|
||||
autofocus: widget.startOnYear,
|
||||
onChanged: (y) => setState(() => _sel.showYear(y)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -1,74 +0,0 @@
|
||||
/// The day grid: one month of numerals, Monday first, with no weekday header.
|
||||
///
|
||||
/// One widget serves the single-date and the range picker; the mode lives in
|
||||
/// [DateSelection], so the range picker is a mode of this grid, not a copy.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/pickers/date_selection.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/numeral_cell.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Six rows of seven: every month fits, and the dialog never changes height.
|
||||
const int kGridCells = 42;
|
||||
|
||||
/// The shown month of [selection] as a numeral grid.
|
||||
///
|
||||
/// Today has a ring; weekends are dimmed with a dot; out-of-range days are
|
||||
/// dimmed further and inert. The chosen day, or both range ends, are filled;
|
||||
/// the days of a range are shaded.
|
||||
class DateGrid extends StatelessWidget {
|
||||
/// Creates a [DateGrid].
|
||||
const DateGrid({
|
||||
required this.selection,
|
||||
required this.today,
|
||||
required this.onTap,
|
||||
this.showCursor = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The selection being edited (read only here).
|
||||
final DateSelection selection;
|
||||
|
||||
/// Today's date, ringed.
|
||||
final DateTime today;
|
||||
|
||||
/// Called with a tapped in-range day.
|
||||
final ValueChanged<DateTime> onTap;
|
||||
|
||||
/// Whether to outline the keyboard cursor (the grid has focus).
|
||||
final bool showCursor;
|
||||
|
||||
bool _inBand(DateTime day) {
|
||||
final start = selection.start;
|
||||
final end = selection.end;
|
||||
if (start == null || end == null || start == end) return false;
|
||||
return !day.isBefore(start) && !day.isAfter(end);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = MaterialLocalizations.of(context);
|
||||
final year = selection.year;
|
||||
final month = selection.month;
|
||||
final lead = DateTime(year, month).weekday - DateTime.monday;
|
||||
final days = DateUtils.getDaysInMonth(year, month);
|
||||
return numeralRows(7, [
|
||||
for (var i = 0; i < lead; i++) const SizedBox.shrink(),
|
||||
for (var d = 1; d <= days; d++) _cell(DateTime(year, month, d), l10n),
|
||||
for (var i = lead + days; i < kGridCells; i++) const SizedBox.shrink(),
|
||||
]);
|
||||
}
|
||||
|
||||
Widget _cell(DateTime day, MaterialLocalizations l10n) => NumeralCell(
|
||||
key: ValueKey(day),
|
||||
label: '${day.day}',
|
||||
semanticLabel: l10n.formatFullDate(day),
|
||||
onTap: () => onTap(day),
|
||||
enabled: selection.allows(day),
|
||||
selected: day == selection.start || day == selection.end,
|
||||
band: _inBand(day),
|
||||
ring: DateUtils.isSameDay(day, today),
|
||||
dot: day.weekday >= DateTime.saturday,
|
||||
focused: showCursor && day == selection.cursor,
|
||||
);
|
||||
}
|
||||
@ -1,140 +0,0 @@
|
||||
/// The date picker's selection rules, kept free of widgets so each rule is a
|
||||
/// plain unit test: bounds clamp, the two-tap range, the month/year day clamp.
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart' show DateTimeRange, DateUtils;
|
||||
|
||||
/// What the date picker has chosen, and which month it is showing.
|
||||
///
|
||||
/// Every date is date-only (midnight local); days are stepped with
|
||||
/// `DateTime(y, m, d + n)`, never a `Duration`, so DST cannot shift a day.
|
||||
class DateSelection {
|
||||
/// A single-date selection starting on [initial], clamped into bounds.
|
||||
DateSelection.single({
|
||||
required DateTime first,
|
||||
required DateTime last,
|
||||
DateTime? initial,
|
||||
}) : first = DateUtils.dateOnly(first),
|
||||
last = DateUtils.dateOnly(last),
|
||||
range = false {
|
||||
start = _clamp(initial ?? DateTime.now());
|
||||
_init(start!);
|
||||
}
|
||||
|
||||
/// A two-tap range selection. A preset [initial] range counts as both taps
|
||||
/// done, so it can be confirmed at once.
|
||||
DateSelection.range({
|
||||
required DateTime first,
|
||||
required DateTime last,
|
||||
DateTimeRange? initial,
|
||||
}) : first = DateUtils.dateOnly(first),
|
||||
last = DateUtils.dateOnly(last),
|
||||
range = true {
|
||||
if (initial != null) {
|
||||
start = _clamp(initial.start);
|
||||
end = _clamp(initial.end);
|
||||
}
|
||||
_init(start ?? _clamp(DateTime.now()));
|
||||
}
|
||||
|
||||
/// Earliest selectable day.
|
||||
final DateTime first;
|
||||
|
||||
/// Latest selectable day.
|
||||
final DateTime last;
|
||||
|
||||
/// Whether this is the two-tap range mode.
|
||||
final bool range;
|
||||
|
||||
/// The chosen day (single mode) or the range start.
|
||||
DateTime? start;
|
||||
|
||||
/// The range end; null until the second tap.
|
||||
DateTime? end;
|
||||
|
||||
/// The keyboard cursor; equals [start] in single mode.
|
||||
late DateTime cursor;
|
||||
|
||||
/// Shown year.
|
||||
late int year;
|
||||
|
||||
/// Shown month, 1-12.
|
||||
late int month;
|
||||
|
||||
void _init(DateTime at) {
|
||||
cursor = at;
|
||||
year = at.year;
|
||||
month = at.month;
|
||||
}
|
||||
|
||||
DateTime _clamp(DateTime day) {
|
||||
final d = DateUtils.dateOnly(day);
|
||||
if (d.isBefore(first)) return first;
|
||||
return d.isAfter(last) ? last : d;
|
||||
}
|
||||
|
||||
/// Whether [day] lies within the bounds.
|
||||
bool allows(DateTime day) => !day.isBefore(first) && !day.isAfter(last);
|
||||
|
||||
/// Whether any day of month [m] of year [y] lies within the bounds.
|
||||
bool monthAllowed(int y, int m) =>
|
||||
!DateTime(y, m + 1, 0).isBefore(first) && !DateTime(y, m).isAfter(last);
|
||||
|
||||
/// Whether the check may be pressed: always in single mode, after both
|
||||
/// taps in range mode.
|
||||
bool get canConfirm => !range || end != null;
|
||||
|
||||
/// The range chosen so far, once both ends are set.
|
||||
DateTimeRange? get dateRange =>
|
||||
end == null ? null : DateTimeRange(start: start!, end: end!);
|
||||
|
||||
/// A tap on [day]. Out-of-range days are inert. In range mode: the first
|
||||
/// tap sets the start, the second the end (in either order), a third
|
||||
/// restarts from [day].
|
||||
void tap(DateTime day) {
|
||||
if (!allows(day)) return;
|
||||
cursor = day;
|
||||
if (!range) {
|
||||
start = day;
|
||||
} else if (start == null || end != null) {
|
||||
start = day;
|
||||
end = null;
|
||||
} else if (day.isBefore(start!)) {
|
||||
end = start;
|
||||
start = day;
|
||||
} else {
|
||||
end = day;
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the cursor by [days], following it into another month. Stops at
|
||||
/// the bounds. In single mode the selection moves with it.
|
||||
void moveCursor(int days) {
|
||||
final day = DateTime(cursor.year, cursor.month, cursor.day + days);
|
||||
if (!allows(day)) return;
|
||||
_init(day);
|
||||
if (!range) start = day;
|
||||
}
|
||||
|
||||
/// Shows month [m] of the shown year.
|
||||
void showMonth(int m) => _show(year, m);
|
||||
|
||||
/// Shows year [y], keeping the month where the bounds allow.
|
||||
void showYear(int y) => _show(y, month);
|
||||
|
||||
/// Shows ([y], [m]), pulling the month into bounds and the cursor day to
|
||||
/// the new month's last day where it is shorter. A range's chosen ends
|
||||
/// never move.
|
||||
void _show(int y, int m) {
|
||||
var shown = m;
|
||||
if (y == first.year && shown < first.month) shown = first.month;
|
||||
if (y == last.year && shown > last.month) shown = last.month;
|
||||
final day = math.min(cursor.day, DateUtils.getDaysInMonth(y, shown));
|
||||
year = y;
|
||||
month = shown;
|
||||
cursor = _clamp(DateTime(y, shown, day));
|
||||
if (!range) start = cursor;
|
||||
}
|
||||
}
|
||||
@ -1,30 +0,0 @@
|
||||
/// The endless child delegate of the looping time wheels.
|
||||
library;
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// An endless delegate that passes the absolute index to its builder, so a
|
||||
/// tapped item knows which of its many copies it is (the framework's
|
||||
/// looping delegate only hands out the wrapped child).
|
||||
class LoopWheelDelegate extends ListWheelChildDelegate {
|
||||
/// Creates a delegate looping over [count] values.
|
||||
LoopWheelDelegate(this.count, this.builder);
|
||||
|
||||
/// Number of distinct values before the wheel wraps.
|
||||
final int count;
|
||||
|
||||
/// Builds the item at an absolute (unwrapped) index.
|
||||
final Widget Function(int index) builder;
|
||||
|
||||
@override
|
||||
Widget? build(BuildContext context, int index) => builder(index);
|
||||
|
||||
@override
|
||||
int? get estimatedChildCount => null;
|
||||
|
||||
@override
|
||||
int trueIndexOf(int index) => index % count;
|
||||
|
||||
@override
|
||||
bool shouldRebuild(covariant ListWheelChildDelegate oldDelegate) => true;
|
||||
}
|
||||
@ -1,46 +0,0 @@
|
||||
/// The month row of the date picker: numerals 1-12 instead of month names.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/pickers/numeral_cell.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Twelve numeral chips in two rows of six; months wholly outside the bounds
|
||||
/// are dimmed and inert.
|
||||
class MonthChips extends StatelessWidget {
|
||||
/// Creates a [MonthChips].
|
||||
const MonthChips({
|
||||
required this.year,
|
||||
required this.selected,
|
||||
required this.allowed,
|
||||
required this.onTap,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The shown year (for the spoken month names).
|
||||
final int year;
|
||||
|
||||
/// The shown month, 1-12.
|
||||
final int selected;
|
||||
|
||||
/// Whether month 1-12 has any day within the bounds.
|
||||
final bool Function(int month) allowed;
|
||||
|
||||
/// Called with a tapped allowed month.
|
||||
final ValueChanged<int> onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = MaterialLocalizations.of(context);
|
||||
return numeralRows(6, aspectRatio: 1.6, [
|
||||
for (var m = 1; m <= 12; m++)
|
||||
NumeralCell(
|
||||
key: ValueKey('month-$m'),
|
||||
label: '$m',
|
||||
semanticLabel: l10n.formatMonthYear(DateTime(year, m)),
|
||||
onTap: () => onTap(m),
|
||||
enabled: allowed(m),
|
||||
selected: m == selected,
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,153 +0,0 @@
|
||||
/// One tappable numeral of the pickers' grids (a day, a month), plus the
|
||||
/// equal-width row layout both grids use.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Alpha of a weekend numeral: dimmed, with a dot as the second channel.
|
||||
const double kWeekendAlpha = 0.6;
|
||||
|
||||
/// Alpha of an out-of-range numeral: far below [kWeekendAlpha], so an
|
||||
/// out-of-range weekend never reads like an in-range one.
|
||||
const double kDisabledAlpha = 0.25;
|
||||
|
||||
/// Alpha of the shaded band between two range ends.
|
||||
const double kBandAlpha = 0.3;
|
||||
|
||||
/// A numeral in a stadium. Every visual state is a field, so tests assert
|
||||
/// state rather than colours.
|
||||
class NumeralCell extends StatelessWidget {
|
||||
/// Creates a [NumeralCell].
|
||||
const NumeralCell({
|
||||
required this.label,
|
||||
required this.semanticLabel,
|
||||
required this.onTap,
|
||||
this.enabled = true,
|
||||
this.selected = false,
|
||||
this.band = false,
|
||||
this.ring = false,
|
||||
this.dot = false,
|
||||
this.focused = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The painted numeral.
|
||||
final String label;
|
||||
|
||||
/// The spoken name (a full date, a month); never painted.
|
||||
final String semanticLabel;
|
||||
|
||||
/// Called on tap when [enabled].
|
||||
final VoidCallback onTap;
|
||||
|
||||
/// Out-of-range cells are dimmed and inert.
|
||||
final bool enabled;
|
||||
|
||||
/// Filled: the chosen value (a range end is a filled cap).
|
||||
final bool selected;
|
||||
|
||||
/// Shaded background: inside a chosen range.
|
||||
final bool band;
|
||||
|
||||
/// Outlined: today.
|
||||
final bool ring;
|
||||
|
||||
/// Dimmed with a dot below: a weekend.
|
||||
final bool dot;
|
||||
|
||||
/// The keyboard cursor.
|
||||
final bool focused;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final alpha = !enabled ? kDisabledAlpha : (dot ? kWeekendAlpha : 1.0);
|
||||
final fg = selected
|
||||
? scheme.onPrimary
|
||||
: scheme.onSurface.withValues(alpha: alpha);
|
||||
final edge = ring || focused
|
||||
? BorderSide(color: focused ? scheme.outline : scheme.primary, width: 2)
|
||||
: BorderSide.none;
|
||||
final shape = StadiumBorder(side: edge);
|
||||
return Semantics(
|
||||
label: semanticLabel,
|
||||
button: true,
|
||||
selected: selected,
|
||||
enabled: enabled,
|
||||
// excludeSemantics drops the InkWell's own tap action, so the node
|
||||
// offers it here or a screen reader cannot pick a day.
|
||||
onTap: enabled ? onTap : null,
|
||||
excludeSemantics: true,
|
||||
child: ColoredBox(
|
||||
// Translucent, not primaryContainer: in this theme that equals
|
||||
// primary, which hid the filled range ends inside the band.
|
||||
color: band
|
||||
? scheme.primary.withValues(alpha: kBandAlpha)
|
||||
: Colors.transparent,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(2),
|
||||
child: Material(
|
||||
type: MaterialType.transparency,
|
||||
child: InkWell(
|
||||
customBorder: shape,
|
||||
canRequestFocus: false,
|
||||
onTap: enabled ? onTap : null,
|
||||
child: Ink(
|
||||
decoration: ShapeDecoration(
|
||||
shape: shape,
|
||||
color: selected ? scheme.primary : null,
|
||||
),
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: fg,
|
||||
fontWeight: selected ? FontWeight.bold : null,
|
||||
),
|
||||
),
|
||||
if (dot)
|
||||
Container(
|
||||
width: 4,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: fg,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Lays [cells] out in rows of [columns] equal-width cells, each
|
||||
/// [aspectRatio] wide per unit of height; a short last row is padded.
|
||||
Widget numeralRows(int columns, List<Widget> cells, {double aspectRatio = 1}) =>
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (var r = 0; r < cells.length; r += columns)
|
||||
Row(
|
||||
children: [
|
||||
for (var c = r; c < r + columns; c++)
|
||||
Expanded(
|
||||
child: AspectRatio(
|
||||
aspectRatio: aspectRatio,
|
||||
child: c < cells.length
|
||||
? cells[c]
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
@ -1,238 +0,0 @@
|
||||
/// A controlled numeral wheel: the year wheel and both time wheels.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/loop_wheel_delegate.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/numeral_cell.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// Height of one wheel item.
|
||||
const double kWheelItemExtent = 40;
|
||||
|
||||
/// A wheel of the values `offset .. offset + count - 1`, optionally looping.
|
||||
///
|
||||
/// Controlled: [value] is the truth and the wheel animates to it when the
|
||||
/// parent changes it. Mouse drag scrolls (web excludes the mouse from drag by
|
||||
/// default), a tap on any item selects it, arrow keys step by one. Values
|
||||
/// failing [enabled] are dimmed and inert: [onChanged] never reports them and
|
||||
/// a wheel that settles on one springs back to [value].
|
||||
class NumeralWheel extends StatefulWidget {
|
||||
/// Creates a [NumeralWheel].
|
||||
const NumeralWheel({
|
||||
required this.count,
|
||||
required this.value,
|
||||
required this.onChanged,
|
||||
required this.semanticLabel,
|
||||
this.offset = 0,
|
||||
this.loop = false,
|
||||
this.digits = 1,
|
||||
this.enabled,
|
||||
this.autofocus = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Number of values.
|
||||
final int count;
|
||||
|
||||
/// The value at index 0.
|
||||
final int offset;
|
||||
|
||||
/// The current value.
|
||||
final int value;
|
||||
|
||||
/// Called with each newly centred allowed value.
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
/// The spoken name of the wheel ("Year"); never painted.
|
||||
final String semanticLabel;
|
||||
|
||||
/// Whether the last value wraps to the first.
|
||||
final bool loop;
|
||||
|
||||
/// Zero-padded width of each numeral (2 for `05`).
|
||||
final int digits;
|
||||
|
||||
/// Which values may be picked; all when null.
|
||||
final bool Function(int value)? enabled;
|
||||
|
||||
/// Whether the wheel takes keyboard focus when it appears.
|
||||
final bool autofocus;
|
||||
|
||||
@override
|
||||
State<NumeralWheel> createState() => _NumeralWheelState();
|
||||
}
|
||||
|
||||
class _NumeralWheelState extends State<NumeralWheel> {
|
||||
late final FixedExtentScrollController _controller =
|
||||
FixedExtentScrollController(initialItem: widget.value - widget.offset);
|
||||
late int _centred = widget.value - widget.offset;
|
||||
bool _focused = false;
|
||||
|
||||
int _valueAt(int index) =>
|
||||
widget.offset + (widget.loop ? index % widget.count : index);
|
||||
|
||||
bool _ok(int value) => widget.enabled?.call(value) ?? true;
|
||||
|
||||
/// The index nearest the centre that shows [value] (a loop has many).
|
||||
int _indexOf(int value) {
|
||||
final target = value - widget.offset;
|
||||
if (!widget.loop) return target;
|
||||
final n = widget.count;
|
||||
final delta = (target - _centred) % n;
|
||||
return delta > n ~/ 2 ? _centred + delta - n : _centred + delta;
|
||||
}
|
||||
|
||||
void _goTo(int index) => _controller.animateToItem(
|
||||
index,
|
||||
duration: AppDuration.fast,
|
||||
curve: AppCurve.standard,
|
||||
);
|
||||
|
||||
bool get _scrolling =>
|
||||
_controller.hasClients && _controller.position.isScrollingNotifier.value;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(NumeralWheel old) {
|
||||
super.didUpdateWidget(old);
|
||||
// Not mid-drag: the parent echoing an intermediate value must not yank
|
||||
// the wheel out from under the pointer.
|
||||
if (widget.value != _valueAt(_centred) && !_scrolling) {
|
||||
_afterFrame(() => _goTo(_indexOf(widget.value)));
|
||||
}
|
||||
}
|
||||
|
||||
void _afterFrame(VoidCallback action) =>
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) action();
|
||||
});
|
||||
|
||||
/// The allowed value nearest [value], by value and never across the wrap
|
||||
/// (08:00 out of range means 08:15, not 08:59). A fast drag can skip every
|
||||
/// allowed value on its way past an end, so the last reported value is no
|
||||
/// anchor.
|
||||
int _nearestAllowed(int value) {
|
||||
final last = widget.offset + widget.count - 1;
|
||||
for (var d = 1; d < widget.count; d++) {
|
||||
for (final v in [value - d, value + d]) {
|
||||
if (v >= widget.offset && v <= last && _ok(v)) return v;
|
||||
}
|
||||
}
|
||||
return widget.value;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _centre(int index) {
|
||||
setState(() => _centred = index);
|
||||
final value = _valueAt(index);
|
||||
if (_ok(value) && value != widget.value) widget.onChanged(value);
|
||||
}
|
||||
|
||||
KeyEventResult _key(FocusNode _, KeyEvent event) {
|
||||
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
final step = switch (event.logicalKey) {
|
||||
LogicalKeyboardKey.arrowUp => -1,
|
||||
LogicalKeyboardKey.arrowDown => 1,
|
||||
_ => 0,
|
||||
};
|
||||
if (step == 0) return KeyEventResult.ignored;
|
||||
final next = _centred + step;
|
||||
final inList = widget.loop || (next >= 0 && next < widget.count);
|
||||
if (inList && _ok(_valueAt(next))) _goTo(next);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
Widget _item(BuildContext context, int index) {
|
||||
final value = _valueAt(index);
|
||||
final ok = _ok(value);
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final centred = index == _centred;
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: ok ? () => _goTo(index) : null,
|
||||
child: Center(
|
||||
child: Text(
|
||||
'$value'.padLeft(widget.digits, '0'),
|
||||
key: ValueKey('wheel-$value'),
|
||||
style: TextStyle(
|
||||
fontSize: centred ? AppTextSize.title : AppTextSize.subtitle,
|
||||
fontWeight: centred ? FontWeight.bold : null,
|
||||
color: scheme.onSurface.withValues(alpha: ok ? 1 : kDisabledAlpha),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final behavior = ScrollConfiguration.of(context).copyWith(
|
||||
dragDevices: PointerDeviceKind.values.toSet(),
|
||||
scrollbars: false,
|
||||
);
|
||||
return Semantics(
|
||||
label: widget.semanticLabel,
|
||||
container: true,
|
||||
child: Focus(
|
||||
autofocus: widget.autofocus,
|
||||
onKeyEvent: _key,
|
||||
onFocusChange: (f) => setState(() => _focused = f),
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
Container(
|
||||
height: kWheelItemExtent,
|
||||
decoration: BoxDecoration(
|
||||
color: scheme.primaryContainer,
|
||||
border: _focused
|
||||
? Border.all(color: scheme.outline, width: 2)
|
||||
: null,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
),
|
||||
),
|
||||
NotificationListener<ScrollEndNotification>(
|
||||
onNotification: (_) {
|
||||
if (!_ok(_valueAt(_centred))) {
|
||||
_afterFrame(
|
||||
() => _goTo(_indexOf(_nearestAllowed(_valueAt(_centred)))),
|
||||
);
|
||||
} else if (_valueAt(_centred) != widget.value) {
|
||||
_afterFrame(() => _goTo(_indexOf(widget.value)));
|
||||
}
|
||||
return false;
|
||||
},
|
||||
child: ScrollConfiguration(
|
||||
behavior: behavior,
|
||||
child: ListWheelScrollView.useDelegate(
|
||||
controller: _controller,
|
||||
itemExtent: kWheelItemExtent,
|
||||
physics: const FixedExtentScrollPhysics(),
|
||||
diameterRatio: 1.6,
|
||||
onSelectedItemChanged: _centre,
|
||||
childDelegate: widget.loop
|
||||
? LoopWheelDelegate(
|
||||
widget.count,
|
||||
(i) => _item(context, i),
|
||||
)
|
||||
: ListWheelChildBuilderDelegate(
|
||||
childCount: widget.count,
|
||||
builder: _item,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,75 +0,0 @@
|
||||
/// The shared dialog around every picker: a centred, width-capped [Dialog]
|
||||
/// with a close icon (cancel) and a check icon (confirm), no words.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// Picker chrome. Outside tap and Esc cancel (the dialog route's own
|
||||
/// dismiss); Enter confirms when [canConfirm].
|
||||
///
|
||||
/// The icons carry spoken-only `semanticLabel`s and no `tooltip:`, which
|
||||
/// would paint the word on long-press.
|
||||
class PickerFrame extends StatelessWidget {
|
||||
/// Creates a [PickerFrame].
|
||||
const PickerFrame({
|
||||
required this.child,
|
||||
required this.canConfirm,
|
||||
required this.onConfirm,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The picker body.
|
||||
final Widget child;
|
||||
|
||||
/// Whether the check is enabled (a half-chosen range is not).
|
||||
final bool canConfirm;
|
||||
|
||||
/// Pops the dialog with the chosen value.
|
||||
final VoidCallback onConfirm;
|
||||
|
||||
void _enter() {
|
||||
if (canConfirm) onConfirm();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Dialog(
|
||||
insetPadding: const EdgeInsets.all(AppSpacing.md),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: AppWidth.picker),
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Around the body only: Enter on a focused close icon must
|
||||
// reach that button (cancel), not bubble up into a confirm.
|
||||
CallbackShortcuts(
|
||||
bindings: {
|
||||
const SingleActivator(LogicalKeyboardKey.enter): _enter,
|
||||
const SingleActivator(LogicalKeyboardKey.numpadEnter): _enter,
|
||||
},
|
||||
child: child,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
spacing: AppSpacing.sm,
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.close, semanticLabel: 'Cancel'),
|
||||
),
|
||||
IconButton.filled(
|
||||
onPressed: canConfirm ? onConfirm : null,
|
||||
icon: const Icon(Icons.check, semanticLabel: 'Confirm'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -1,67 +0,0 @@
|
||||
/// Icon-only replacements for `showDatePicker`, `showDateRangePicker` and
|
||||
/// `showTimePicker`, which paint "Select date", "Cancel", "OK" and tooltips.
|
||||
///
|
||||
/// Same arguments as the framework calls, so a call site changes by one
|
||||
/// function name. Dropped on purpose: the weekday header, month names and
|
||||
/// both text-entry modes (see the textgate rework report).
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/pickers/date_dialog.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/date_selection.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/time_dialog.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Picks one day in [firstDate]..[lastDate]; null when cancelled.
|
||||
///
|
||||
/// [initialDatePickerMode] `year` focuses the year wheel first.
|
||||
Future<DateTime?> pickDate({
|
||||
required BuildContext context,
|
||||
required DateTime firstDate,
|
||||
required DateTime lastDate,
|
||||
DateTime? initialDate,
|
||||
DatePickerMode initialDatePickerMode = DatePickerMode.day,
|
||||
}) => showDialog<DateTime>(
|
||||
context: context,
|
||||
builder: (_) => DateDialog(
|
||||
selection: DateSelection.single(
|
||||
first: firstDate,
|
||||
last: lastDate,
|
||||
initial: initialDate,
|
||||
),
|
||||
startOnYear: initialDatePickerMode == DatePickerMode.year,
|
||||
),
|
||||
);
|
||||
|
||||
/// Picks a range of days in [firstDate]..[lastDate] by two taps; null when
|
||||
/// cancelled.
|
||||
Future<DateTimeRange?> pickDateRange({
|
||||
required BuildContext context,
|
||||
required DateTime firstDate,
|
||||
required DateTime lastDate,
|
||||
DateTimeRange? initialDateRange,
|
||||
}) => showDialog<DateTimeRange>(
|
||||
context: context,
|
||||
builder: (_) => DateDialog(
|
||||
selection: DateSelection.range(
|
||||
first: firstDate,
|
||||
last: lastDate,
|
||||
initial: initialDateRange,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/// Picks a 24 h time whose minute of day lies in [minMinute]..[maxMinute];
|
||||
/// null when cancelled.
|
||||
Future<TimeOfDay?> pickTime({
|
||||
required BuildContext context,
|
||||
required TimeOfDay initialTime,
|
||||
int minMinute = 0,
|
||||
int maxMinute = 24 * 60 - 1,
|
||||
}) => showDialog<TimeOfDay>(
|
||||
context: context,
|
||||
builder: (_) => TimeDialog(
|
||||
initialMinute: initialTime.hour * 60 + initialTime.minute,
|
||||
minMinute: minMinute,
|
||||
maxMinute: maxMinute,
|
||||
),
|
||||
);
|
||||
@ -1,52 +0,0 @@
|
||||
/// The time dialog: hour and minute wheels between check and close icons.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/pickers/picker_frame.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/time_wheels.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Pops the chosen [TimeOfDay], always within [minMinute]..[maxMinute].
|
||||
class TimeDialog extends StatefulWidget {
|
||||
/// Creates a [TimeDialog]; [initialMinute] is clamped into range, since a
|
||||
/// value written by another device may lie outside it.
|
||||
const TimeDialog({
|
||||
required this.initialMinute,
|
||||
required this.minMinute,
|
||||
required this.maxMinute,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The starting minute of day.
|
||||
final int initialMinute;
|
||||
|
||||
/// Earliest allowed minute of day.
|
||||
final int minMinute;
|
||||
|
||||
/// Latest allowed minute of day.
|
||||
final int maxMinute;
|
||||
|
||||
@override
|
||||
State<TimeDialog> createState() => _TimeDialogState();
|
||||
}
|
||||
|
||||
class _TimeDialogState extends State<TimeDialog> {
|
||||
late int _minute = clampMinute(
|
||||
widget.initialMinute,
|
||||
widget.minMinute,
|
||||
widget.maxMinute,
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => PickerFrame(
|
||||
canConfirm: true,
|
||||
onConfirm: () => Navigator.of(
|
||||
context,
|
||||
).pop(TimeOfDay(hour: _minute ~/ 60, minute: _minute % 60)),
|
||||
child: TimeWheels(
|
||||
minute: _minute,
|
||||
minMinute: widget.minMinute,
|
||||
maxMinute: widget.maxMinute,
|
||||
onChanged: (m) => setState(() => _minute = m),
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -1,91 +0,0 @@
|
||||
/// The time picker's two looping wheels: hour 00-23 and minute 00-59, 24 h.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/pickers/numeral_wheel.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Width of one time wheel.
|
||||
const double kTimeWheelWidth = 72;
|
||||
|
||||
/// Whether hour [h] holds any minute of day in [min]..[max].
|
||||
bool hourAllowed(int h, int min, int max) =>
|
||||
h * 60 + 59 >= min && h * 60 <= max;
|
||||
|
||||
/// [minute] of day pulled into [min]..[max].
|
||||
int clampMinute(int minute, int min, int max) => minute.clamp(min, max);
|
||||
|
||||
/// Hour and minute wheels for a minute of day within [minMinute]..[maxMinute].
|
||||
///
|
||||
/// Hours and minutes outside the range are dimmed and inert. Changing the
|
||||
/// hour pulls the minute to the nearest allowed one in that hour, so the
|
||||
/// value reported is always in range.
|
||||
class TimeWheels extends StatelessWidget {
|
||||
/// Creates a [TimeWheels].
|
||||
const TimeWheels({
|
||||
required this.minute,
|
||||
required this.minMinute,
|
||||
required this.maxMinute,
|
||||
required this.onChanged,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// The current minute of day (in range).
|
||||
final int minute;
|
||||
|
||||
/// Earliest allowed minute of day.
|
||||
final int minMinute;
|
||||
|
||||
/// Latest allowed minute of day.
|
||||
final int maxMinute;
|
||||
|
||||
/// Called with each new in-range minute of day.
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hour = minute ~/ 60;
|
||||
Widget wheel(Widget child) => SizedBox(
|
||||
width: kTimeWheelWidth,
|
||||
height: kWheelItemExtent * 5,
|
||||
child: child,
|
||||
);
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: AppSpacing.xs,
|
||||
children: [
|
||||
wheel(
|
||||
NumeralWheel(
|
||||
key: const ValueKey('hour'),
|
||||
count: 24,
|
||||
value: hour,
|
||||
loop: true,
|
||||
digits: 2,
|
||||
semanticLabel: 'Hour',
|
||||
autofocus: true,
|
||||
enabled: (h) => hourAllowed(h, minMinute, maxMinute),
|
||||
onChanged: (h) => onChanged(
|
||||
clampMinute(h * 60 + minute % 60, minMinute, maxMinute),
|
||||
),
|
||||
),
|
||||
),
|
||||
const Text(':', style: TextStyle(fontSize: AppTextSize.title)),
|
||||
wheel(
|
||||
NumeralWheel(
|
||||
key: const ValueKey('minute'),
|
||||
count: 60,
|
||||
value: minute % 60,
|
||||
loop: true,
|
||||
digits: 2,
|
||||
semanticLabel: 'Minute',
|
||||
enabled: (m) {
|
||||
final v = hour * 60 + m;
|
||||
return v >= minMinute && v <= maxMinute;
|
||||
},
|
||||
onChanged: (m) => onChanged(hour * 60 + m),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
/// The date picker's year wheel: numerals, no loop.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/pickers/numeral_wheel.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Out-of-range years listed beyond each bound, dimmed and inert, so the
|
||||
/// wheel's ends read as limits rather than as a list that just stops.
|
||||
const int kYearWheelPad = 2;
|
||||
|
||||
/// A non-looping wheel of the years [firstYear]..[lastYear], plus
|
||||
/// [kYearWheelPad] dimmed, inert years past each end (a wheel dragged onto
|
||||
/// one springs back).
|
||||
class YearWheel extends StatelessWidget {
|
||||
/// Creates a [YearWheel].
|
||||
const YearWheel({
|
||||
required this.firstYear,
|
||||
required this.lastYear,
|
||||
required this.value,
|
||||
required this.onChanged,
|
||||
this.autofocus = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
/// Earliest listed year.
|
||||
final int firstYear;
|
||||
|
||||
/// Latest listed year.
|
||||
final int lastYear;
|
||||
|
||||
/// The shown year.
|
||||
final int value;
|
||||
|
||||
/// Called with a newly centred year.
|
||||
final ValueChanged<int> onChanged;
|
||||
|
||||
/// Whether the wheel takes keyboard focus on open (the birth-date flow).
|
||||
final bool autofocus;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => NumeralWheel(
|
||||
count: lastYear - firstYear + 1 + 2 * kYearWheelPad,
|
||||
offset: firstYear - kYearWheelPad,
|
||||
enabled: (y) => y >= firstYear && y <= lastYear,
|
||||
value: value,
|
||||
onChanged: onChanged,
|
||||
semanticLabel: 'Year',
|
||||
autofocus: autofocus,
|
||||
);
|
||||
}
|
||||
@ -2,15 +2,13 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/day_status.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Displays the logging streak, adherence streak, and year-to-date tally.
|
||||
///
|
||||
/// Mirrors `_calendar_view.py`'s `streaks_text`/`ytd_text` data, as glyphs and
|
||||
/// numerals: pencil + N (logging streak), flame + N (adherence streak),
|
||||
/// calendar-check + X/Y (days logged of days elapsed), medal + Z (days within
|
||||
/// budget).
|
||||
/// Mirrors `_calendar_view.py`'s `streaks_text`/`ytd_text` formatting:
|
||||
/// "Logging streak: N day(s) · Adherence streak: N day(s)" and
|
||||
/// "This year: logged X/Y days · Z within budget".
|
||||
class StreakSummaryRow extends StatelessWidget {
|
||||
/// Creates a [StreakSummaryRow].
|
||||
const StreakSummaryRow({
|
||||
@ -29,80 +27,27 @@ class StreakSummaryRow extends StatelessWidget {
|
||||
/// This year's logged/elapsed/adherent day counts.
|
||||
final YtdTally tally;
|
||||
|
||||
static String _plural(int count) => count == 1 ? 'day' : 'days';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final status = theme.extension<AppStatusColors>() ?? AppStatusColors.dark;
|
||||
return Column(
|
||||
children: [
|
||||
Wrap(
|
||||
alignment: WrapAlignment.center,
|
||||
spacing: AppSpacing.lg,
|
||||
children: [
|
||||
_Figure(
|
||||
icon: Icons.edit_note,
|
||||
color: theme.colorScheme.primary,
|
||||
semanticLabel: 'Logging streak',
|
||||
value: '$loggingStreak',
|
||||
style: theme.textTheme.titleSmall,
|
||||
),
|
||||
_Figure(
|
||||
icon: Icons.local_fire_department,
|
||||
color: status.warning,
|
||||
semanticLabel: 'Adherence streak',
|
||||
value: '$adherenceStreak',
|
||||
style: theme.textTheme.titleSmall,
|
||||
),
|
||||
],
|
||||
Text(
|
||||
'Logging streak: $loggingStreak ${_plural(loggingStreak)} · '
|
||||
'Adherence streak: $adherenceStreak ${_plural(adherenceStreak)}',
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.titleSmall,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.xs),
|
||||
Wrap(
|
||||
alignment: WrapAlignment.center,
|
||||
spacing: AppSpacing.lg,
|
||||
children: [
|
||||
_Figure(
|
||||
icon: Icons.event_available,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
semanticLabel: 'Days logged this year',
|
||||
value: '${tally.loggedDays}/${tally.elapsedDays}',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
_Figure(
|
||||
icon: Icons.verified,
|
||||
color: status.success,
|
||||
semanticLabel: 'Days within budget',
|
||||
value: '${tally.adherentDays}',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'This year: logged ${tally.loggedDays}/${tally.elapsedDays} days · '
|
||||
'${tally.adherentDays} within budget',
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Figure extends StatelessWidget {
|
||||
const _Figure({
|
||||
required this.icon,
|
||||
required this.color,
|
||||
required this.semanticLabel,
|
||||
required this.value,
|
||||
required this.style,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
final String semanticLabel;
|
||||
final String value;
|
||||
final TextStyle? style;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, color: color, size: 18, semanticLabel: semanticLabel),
|
||||
const SizedBox(width: 4),
|
||||
Text(value, style: style),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@ -40,22 +40,16 @@ class SyncHealthBanner extends StatelessWidget {
|
||||
border: Border.all(color: warning.withValues(alpha: 0.5)),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
// A glyph and, once an hour or more has passed, the elapsed time as a
|
||||
// numeral (`2d`). The sentence survives only as the spoken label.
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.cloud_off,
|
||||
size: 18,
|
||||
color: warning,
|
||||
semanticLabel: message,
|
||||
),
|
||||
Icon(Icons.cloud_off, size: 18, color: warning),
|
||||
const SizedBox(width: 8),
|
||||
if (status?.agoShort case final ago?)
|
||||
Text(
|
||||
ago,
|
||||
Expanded(
|
||||
child: Text(
|
||||
message,
|
||||
style: theme.textTheme.bodySmall?.copyWith(color: warning),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/slot.dart';
|
||||
import 'package:diet_guard_app/ui/macro_kind.dart';
|
||||
import 'package:diet_guard_app/ui/theme.dart';
|
||||
import 'package:diet_guard_app/widgets/progress_motion.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@ -88,6 +87,8 @@ class TodayProgressCard extends StatelessWidget {
|
||||
/// The values to display.
|
||||
final TodayProgress progress;
|
||||
|
||||
static String _plural(int count) => count == 1 ? 'day' : 'days';
|
||||
|
||||
static String _grams(double value) => '${value.round()}g';
|
||||
|
||||
/// Whole numbers without decimals; fractions exactly, never rounded.
|
||||
@ -97,7 +98,6 @@ class TodayProgressCard extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final status = theme.extension<AppStatusColors>() ?? AppStatusColors.dark;
|
||||
final slot = progress.loggedSlotMinute;
|
||||
final logged = progress.loggedKcal;
|
||||
final from = progress.previousKcal ?? progress.consumedKcal;
|
||||
@ -118,55 +118,31 @@ class TodayProgressCard extends StatelessWidget {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (slot != null && logged != null) ...[
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.check_circle,
|
||||
size: 16,
|
||||
color: status.success,
|
||||
semanticLabel: 'logged',
|
||||
),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Text(slotLabel(slot), style: theme.textTheme.labelMedium),
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
MacroFigure(kind: MacroKind.kcal, value: _kcal(logged)),
|
||||
],
|
||||
Text(
|
||||
'✓ ${slotLabel(slot)} · ${_kcal(logged)} kcal',
|
||||
style: theme.textTheme.labelMedium,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.xs),
|
||||
],
|
||||
CountUp(from: from, to: progress.consumedKcal, builder: _kcalRow),
|
||||
const SizedBox(height: AppSpacing.xs),
|
||||
Row(
|
||||
children: [
|
||||
MacroFigure(
|
||||
kind: MacroKind.protein,
|
||||
value: _grams(progress.proteinG),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.md),
|
||||
MacroFigure(
|
||||
kind: MacroKind.carbs,
|
||||
value: _grams(progress.carbsG),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.md),
|
||||
MacroFigure(kind: MacroKind.fat, value: _grams(progress.fatG)),
|
||||
],
|
||||
Text(
|
||||
'P ${_grams(progress.proteinG)} · '
|
||||
'C ${_grams(progress.carbsG)} · '
|
||||
'F ${_grams(progress.fatG)}',
|
||||
style: theme.textTheme.labelSmall,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.xs),
|
||||
CountUp(
|
||||
from: streakFrom.toDouble(),
|
||||
to: progress.adherenceStreak.toDouble(),
|
||||
builder: (context, value) => Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.local_fire_department,
|
||||
size: 16,
|
||||
color: status.warning,
|
||||
semanticLabel: 'adherence streak',
|
||||
),
|
||||
const SizedBox(width: 3),
|
||||
Text('${value.round()}', style: theme.textTheme.labelMedium),
|
||||
],
|
||||
),
|
||||
builder: (context, value) {
|
||||
final days = value.round();
|
||||
return Text(
|
||||
'Adherence streak: $days ${_plural(days)}',
|
||||
style: theme.textTheme.labelSmall,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
@ -180,49 +156,24 @@ class TodayProgressCard extends StatelessWidget {
|
||||
final colors = theme.colorScheme;
|
||||
final remaining = progress.budgetKcal - consumed;
|
||||
final over = remaining < 0;
|
||||
final tint = over ? colors.error : colors.onSurface;
|
||||
// Bar fill = share of the budget used; it turns red AND the right-hand
|
||||
// glyph flips from a flag (room left) to a warning (over) past the budget.
|
||||
final used = progress.budgetKcal > 0
|
||||
? (consumed / progress.budgetKcal).clamp(0.0, 1.0)
|
||||
: 1.0;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.baseline,
|
||||
textBaseline: TextBaseline.alphabetic,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
MacroKind.kcal.icon,
|
||||
size: 18,
|
||||
color: MacroKind.kcal.color,
|
||||
semanticLabel: 'kcal',
|
||||
),
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Text(
|
||||
'${consumed.round()} / ${progress.budgetKcal}',
|
||||
style: theme.textTheme.titleMedium?.copyWith(color: tint),
|
||||
),
|
||||
const Spacer(),
|
||||
Icon(
|
||||
over ? Icons.warning_amber_rounded : Icons.flag_outlined,
|
||||
size: 16,
|
||||
color: over ? colors.error : colors.onSurfaceVariant,
|
||||
semanticLabel: over ? 'over budget' : 'left',
|
||||
),
|
||||
const SizedBox(width: 3),
|
||||
Text(
|
||||
'${remaining.abs().round()}',
|
||||
style: theme.textTheme.labelMedium?.copyWith(color: tint),
|
||||
),
|
||||
],
|
||||
Text(
|
||||
'${consumed.round()} / ${progress.budgetKcal}',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
color: over ? colors.error : colors.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.xs),
|
||||
LinearProgressIndicator(
|
||||
value: used,
|
||||
minHeight: 6,
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
color: over ? colors.error : colors.primary,
|
||||
backgroundColor: colors.surfaceContainerHighest,
|
||||
const SizedBox(width: AppSpacing.xs),
|
||||
Text('kcal', style: theme.textTheme.labelSmall),
|
||||
const Spacer(),
|
||||
Text(
|
||||
'${remaining.abs().round()} ${over ? 'over' : 'left'}',
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: over ? colors.error : colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@ -5,10 +5,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: android_file_picker
|
||||
sha256: "04c1306eda42c23ecbf449c909f4fa05c5e66fc48cf5f994d8d08b9d45e5396b"
|
||||
sha256: "03d3dd3cb578ab26b1e528aeea27bf6b976942f5a24e3da82d270369b8e161a8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.5"
|
||||
version: "2.1.2"
|
||||
archive:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -157,20 +157,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: crdt_sync_dart
|
||||
ref: "crdt_sync_dart-v0.14.1"
|
||||
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df
|
||||
ref: "crdt_sync_dart-v0.11.3"
|
||||
resolved-ref: a2e7334dfec5131170a084510d70361d53dc40bc
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.14.1"
|
||||
crdt_sync_flutter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: crdt_sync_flutter
|
||||
ref: "crdt_sync_flutter-v0.8.1"
|
||||
resolved-ref: "3225af8365481677d61a8cabec0c0ad4d0407567"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.8.1"
|
||||
version: "0.11.3"
|
||||
cross_file:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -199,11 +190,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: data_transfer_flutter
|
||||
ref: "data_transfer_flutter-v0.2.2"
|
||||
resolved-ref: eef7af4c86837ee82891493587ff3456297e5dea
|
||||
ref: "data_transfer_flutter-v0.2.0"
|
||||
resolved-ref: bbb7f0f0c0cd891518418472955c8a2ac6cbca4d
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.2.2"
|
||||
version: "0.2.0"
|
||||
dbus:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -272,26 +263,26 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker
|
||||
sha256: "079dc46b753abbddb7f77cd87e6ed9ecc62902580707514568321bdf8e050a86"
|
||||
sha256: "02f2945a7f29535c735f6b283c3c5553810566d3052d730429aec78fe9d06592"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "13.3.3"
|
||||
version: "13.3.1"
|
||||
file_picker_darwin:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker_darwin
|
||||
sha256: daeb0219f6279c73eb9c63ae9a566beef04ae13d59b8feba0be2a7f3b258d3d4
|
||||
sha256: b845af092ca7a3cff0e768029f835157d371a8341750f4158a7ad358143b0e54
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.2"
|
||||
version: "2.4.1"
|
||||
file_picker_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker_linux
|
||||
sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b"
|
||||
sha256: c6562fc7d426db2fb85ea66fe2627953d2709932df5584ceaacf0aa5e39cf4da
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.4"
|
||||
version: "2.0.2"
|
||||
file_picker_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -304,10 +295,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_picker_web
|
||||
sha256: "50749a6da2984fc29609e102ad4d80fd1d07e6895150f8e4922086167d9d45d8"
|
||||
sha256: a2288008280aabe371aff029466b3405e60838e0a1d714767488c59b926c8b8c
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.2.1"
|
||||
version: "4.2.0"
|
||||
file_selector:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -384,10 +375,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: fl_chart
|
||||
sha256: "9f11b0b87a6b1843f5ca666ade4a62c08da1a6b7f9efeb91bb2c6f3fa6e31a9a"
|
||||
sha256: "5ed69b8be550c6276c8f0bc25c09704fb061018ed1b1681867ad18fcf477e7b7"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.1"
|
||||
version: "1.3.0"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
@ -405,10 +396,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_local_notifications
|
||||
sha256: "58f9ea245d7194363c05f7a012bbc73291736c2d8b5f555a8e0ea3f9121868b4"
|
||||
sha256: e99e9c6078d1359ba131b2c1eb8d68837170836a01bf2cea3cf2fa13e62ac2ac
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "23.0.1"
|
||||
version: "23.0.0"
|
||||
flutter_local_notifications_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -437,10 +428,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_local_notifications_windows
|
||||
sha256: "8e80ac29433c71e267493b397457e3a8430c5c1d9c76bb58a6971c016cdba3d7"
|
||||
sha256: c2d6efe9ba585d5f560d8b329131f00fe745834848e6221b22d1f62e0f0b16e2
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.1"
|
||||
version: "4.0.0"
|
||||
flutter_secure_storage:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@ -503,11 +494,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: github_device_auth
|
||||
ref: "github_device_auth-v0.4.0"
|
||||
resolved-ref: "3084080d744c348a217727e26a6be838e7d5a4ff"
|
||||
ref: "github_device_auth-v0.3.2"
|
||||
resolved-ref: "4ccaba1bb3e495ef72d70c6a7e7d7ec98d755792"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.4.0"
|
||||
version: "0.3.2"
|
||||
google_account_token:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@ -553,10 +544,10 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: idb_shim
|
||||
sha256: "507d8f3154fa4e41165941c5aa8509c6bf155bb30f76ba25a00d1e7ba1dd64c9"
|
||||
sha256: "60965b556624f7018ec26205283e32670bc78c6fe1388d4b90bdfe6b2311b87b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.11.3"
|
||||
version: "2.11.2"
|
||||
image:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -833,10 +824,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sembast
|
||||
sha256: "4f71f8c95105918fa207065429c913f38d0fb05fec9f3a745bbf4c113f5d482b"
|
||||
sha256: "35775a26edbdf0d891bab304929a712e103c9d9a6e2fb5ebbd8437bb3139615a"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.10.1"
|
||||
version: "3.10.0"
|
||||
share_plus:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -950,11 +941,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: sync_settings_ui
|
||||
ref: "sync_settings_ui-v0.7.3"
|
||||
resolved-ref: "02d9d689e921d80ec155af9903164c3d2d259dce"
|
||||
ref: "sync_settings_ui-v0.5.2"
|
||||
resolved-ref: "648bde44b1756485d95ca3c3a8714cd2015d5be4"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.7.3"
|
||||
version: "0.5.2"
|
||||
synchronized:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -1119,10 +1110,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: windows_file_picker
|
||||
sha256: cd1be37ada0abcfaa55bddb7410e8515844e35cd77669c35d9a28a15722299d8
|
||||
sha256: "18452aa293de3b6961c6d05b0e71b4be7bb90c67635abdd3aa5c4e75dd875072"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.2"
|
||||
version: "2.0.1"
|
||||
workmanager:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
|
||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
||||
description: "Companion phone app for diet_guard: log meals on the go."
|
||||
publish_to: 'none'
|
||||
|
||||
version: 1.0.157+1
|
||||
version: 1.0.136+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
@ -12,14 +12,8 @@ dependencies:
|
||||
crdt_sync:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: crdt_sync_dart-v0.14.1
|
||||
ref: crdt_sync_dart-v0.11.3
|
||||
path: crdt_sync_dart
|
||||
# Keystore-backed end-to-end encryption open + the passphrase lock button.
|
||||
crdt_sync_flutter:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: crdt_sync_flutter-v0.8.1
|
||||
path: crdt_sync_flutter
|
||||
crypto: 3.0.8
|
||||
cryptography: 2.9.0
|
||||
|
||||
@ -27,12 +21,12 @@ dependencies:
|
||||
data_transfer_flutter:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: data_transfer_flutter-v0.2.2
|
||||
ref: data_transfer_flutter-v0.2.0
|
||||
path: data_transfer_flutter
|
||||
fl_chart: 1.3.1
|
||||
fl_chart: 1.3.0
|
||||
flutter:
|
||||
sdk: flutter
|
||||
flutter_local_notifications: 23.0.1
|
||||
flutter_local_notifications: 23.0.0
|
||||
flutter_secure_storage: 11.2.0
|
||||
|
||||
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
|
||||
@ -40,7 +34,7 @@ dependencies:
|
||||
github_device_auth:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: github_device_auth-v0.4.0
|
||||
ref: github_device_auth-v0.3.2
|
||||
path: github_device_auth
|
||||
# One-tap Google ID token via the framework AccountManager chooser (FOSS).
|
||||
google_account_token:
|
||||
@ -50,7 +44,7 @@ dependencies:
|
||||
path: google_account_token
|
||||
health: 13.3.2
|
||||
http: 1.6.0
|
||||
idb_shim: 2.11.3
|
||||
idb_shim: 2.11.2
|
||||
path: 1.9.1
|
||||
path_provider: 2.1.6
|
||||
permission_handler: 13.0.2
|
||||
@ -63,7 +57,7 @@ dependencies:
|
||||
sync_settings_ui:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: sync_settings_ui-v0.7.3
|
||||
ref: sync_settings_ui-v0.5.2
|
||||
path: sync_settings_ui
|
||||
url_launcher: 6.3.3
|
||||
uuid: 4.6.0
|
||||
|
||||
@ -1,153 +0,0 @@
|
||||
// Guard: whatever the desktop wrapper answers with an error status reaches
|
||||
// the Chrome --app window as a status code with an EMPTY body -- never an
|
||||
// error sentence painted in place of the app. Terminal stderr lines (the
|
||||
// launcher's own log) are not covered: they are terminal text and stay.
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:diet_guard_app/desktop/github_proxy.dart';
|
||||
import 'package:diet_guard_app/desktop/wrapper_server.dart';
|
||||
import 'package:diet_guard_app/services/desktop_wrapper.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// Removes <title> and <style> tags, strips all remaining HTML tags, and
|
||||
/// returns every [A-Za-z]{2,} match — i.e. all visible words the browser would
|
||||
/// paint for a top-level navigation.
|
||||
List<String> paintedWords(String html) {
|
||||
var noTitle = html.replaceAll(RegExp(r'<title>.*?</title>', dotAll: true), '');
|
||||
var noStyle = noTitle.replaceAll(RegExp(r'<style>.*?</style>', dotAll: true), '');
|
||||
var noTags = noStyle.replaceAll(RegExp(r'<[^>]*>'), '');
|
||||
return RegExp(r'[A-Za-z]{2,}').allMatches(noTags).map((m) => m.group(0)!).toList();
|
||||
}
|
||||
|
||||
void main() {
|
||||
late Directory tempDir;
|
||||
late WrapperServer server;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_no_text_');
|
||||
final webRoot = p.join(tempDir.path, 'web');
|
||||
final dataDir = p.join(tempDir.path, 'data');
|
||||
await Directory(webRoot).create(recursive: true);
|
||||
File(p.join(webRoot, 'index.html')).writeAsStringSync('<html></html>');
|
||||
// A FILE where the documents directory belongs: a POST then throws
|
||||
// inside the handler, which is the wrapper's 500 path.
|
||||
await Directory(dataDir).create(recursive: true);
|
||||
File(p.join(dataDir, 'documents')).writeAsStringSync('');
|
||||
server = WrapperServer(
|
||||
webRoot: webRoot,
|
||||
dataDir: dataDir,
|
||||
gitHubProxy: GitHubProxy(
|
||||
tokenPath: p.join(tempDir.path, 'sync_token'),
|
||||
fallbackTokenPath: p.join(tempDir.path, 'fallback_token'),
|
||||
httpClient: MockClient((_) async => http.Response('{}', 200)),
|
||||
),
|
||||
);
|
||||
await server.start(0);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await server.stop();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
Uri url(String path) => Uri.parse('http://localhost:${server.port}$path');
|
||||
|
||||
// (method, path, expected status): every error route the wrapper owns.
|
||||
final cases = <(String, String, int)>[
|
||||
('GET', '/missing.js', HttpStatus.notFound),
|
||||
('GET', '/github/nope', HttpStatus.notFound),
|
||||
('GET', WrapperPaths.documents, HttpStatus.badRequest),
|
||||
('PUT', '${WrapperPaths.documents}log.json', HttpStatus.methodNotAllowed),
|
||||
('GET', '${WrapperPaths.documents}absent.json', HttpStatus.notFound),
|
||||
('GET', kSyncAccountPath, HttpStatus.notFound),
|
||||
(
|
||||
'POST',
|
||||
'${WrapperPaths.documents}log.json',
|
||||
HttpStatus.internalServerError,
|
||||
),
|
||||
];
|
||||
|
||||
for (final (method, path, status) in cases) {
|
||||
test('$method $path answers $status with an empty body', () async {
|
||||
final response = await http.Response.fromStream(
|
||||
await http.Client().send(http.Request(method, url(path))),
|
||||
);
|
||||
expect(response.statusCode, status);
|
||||
expect(response.body, isEmpty, reason: 'nothing painted in the window');
|
||||
});
|
||||
|
||||
test('$method $path loaded as a page shows only an icon', () async {
|
||||
final request = http.Request(method, url(path))
|
||||
..headers['sec-fetch-mode'] = 'navigate';
|
||||
final response = await http.Response.fromStream(
|
||||
await http.Client().send(request),
|
||||
);
|
||||
expect(response.statusCode, status);
|
||||
expect(response.headers['content-type'], contains('text/html'));
|
||||
expect(response.body, contains('<svg'));
|
||||
expect(paintedWords(response.body), isEmpty);
|
||||
});
|
||||
}
|
||||
|
||||
group('proxy error responses', () {
|
||||
late Directory tempDir;
|
||||
late WrapperServer server;
|
||||
|
||||
setUp(() async {
|
||||
tempDir = await Directory.systemTemp.createTemp('diet_guard_proxy_err_');
|
||||
final webRoot = p.join(tempDir.path, 'web');
|
||||
final dataDir = p.join(tempDir.path, 'data');
|
||||
await Directory(webRoot).create(recursive: true);
|
||||
File(p.join(webRoot, 'index.html')).writeAsStringSync('<html></html>');
|
||||
await Directory(dataDir).create(recursive: true);
|
||||
File(p.join(dataDir, 'documents')).writeAsStringSync('');
|
||||
final tokenPath = p.join(tempDir.path, 'sync_token');
|
||||
await File(tokenPath).writeAsString('t');
|
||||
server = WrapperServer(
|
||||
webRoot: webRoot,
|
||||
dataDir: dataDir,
|
||||
gitHubProxy: GitHubProxy(
|
||||
tokenPath: tokenPath,
|
||||
fallbackTokenPath: p.join(tempDir.path, 'fallback_token'),
|
||||
httpClient: MockClient((_) async =>
|
||||
http.Response('{"message": "Bad credentials"}', 401)),
|
||||
),
|
||||
);
|
||||
await server.start(0);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await server.stop();
|
||||
await tempDir.delete(recursive: true);
|
||||
});
|
||||
|
||||
Uri url(String path) => Uri.parse('http://localhost:${server.port}$path');
|
||||
|
||||
test('a proxy error loaded as a page shows only an icon', () async {
|
||||
final request = http.Request('GET', url('/github/api/repos/o/r/contents/x'))
|
||||
..headers['sec-fetch-mode'] = 'navigate';
|
||||
final response = await http.Response.fromStream(
|
||||
await http.Client().send(request),
|
||||
);
|
||||
expect(response.statusCode, HttpStatus.unauthorized);
|
||||
expect(response.headers['content-type'], contains('text/html'));
|
||||
expect(response.body, contains('<svg'));
|
||||
expect(paintedWords(response.body), isEmpty);
|
||||
});
|
||||
|
||||
test('the app fetch still gets the proxy error body', () async {
|
||||
final response = await http.Response.fromStream(
|
||||
await http.Client().send(http.Request(
|
||||
'GET',
|
||||
url('/github/api/repos/o/r/contents/x'),
|
||||
)),
|
||||
);
|
||||
expect(response.statusCode, HttpStatus.unauthorized);
|
||||
expect(response.body, contains('Bad credentials'));
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
/// A GitHub stand-in that persists the end-to-end encryption header, which
|
||||
/// the sync service writes and re-reads; every other request goes to [inner].
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
|
||||
/// Wraps [inner] so `…/e2e` PUTs are stored and served back on GET.
|
||||
MockClient e2eMock(Future<http.Response> Function(http.Request) inner) {
|
||||
String? header;
|
||||
return MockClient((request) async {
|
||||
if (request.url.path.endsWith('/e2e.json')) {
|
||||
// Firebase REST: the value is a JSON-encoded string.
|
||||
if (request.method == 'PUT') {
|
||||
header = jsonDecode(request.body) as String;
|
||||
return http.Response(request.body, 200);
|
||||
}
|
||||
return http.Response(jsonEncode(header), 200);
|
||||
}
|
||||
if (!request.url.path.endsWith('/e2e')) return inner(request);
|
||||
if (request.method == 'PUT') {
|
||||
final body = jsonDecode(request.body) as Map<String, dynamic>;
|
||||
header = utf8.decode(base64.decode(body['content'] as String));
|
||||
return http.Response(jsonEncode({'content': {}, 'sha': 'h'}), 200);
|
||||
}
|
||||
final text = header;
|
||||
if (text == null) return http.Response('', 404);
|
||||
return http.Response(
|
||||
jsonEncode({'content': base64.encode(utf8.encode(text)), 'sha': 'h'}),
|
||||
200,
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -1,5 +1,3 @@
|
||||
import 'package:crdt_sync/crdt_sync.dart' show Argon2Params, resetE2eCopyMemo;
|
||||
import 'package:diet_guard_app/services/sync_e2e.dart' show e2eArgon2Params;
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
@ -14,19 +12,10 @@ void installFakeSecureStorage({
|
||||
Map<String, String>? initial,
|
||||
bool throwing = false,
|
||||
}) {
|
||||
const channel = MethodChannel('plugins.it_nomads.com/flutter_secure_storage');
|
||||
resetE2eCopyMemo();
|
||||
e2eArgon2Params = const Argon2Params(
|
||||
memoryKiB: 8,
|
||||
iterations: 1,
|
||||
parallelism: 1,
|
||||
const channel = MethodChannel(
|
||||
'plugins.it_nomads.com/flutter_secure_storage',
|
||||
);
|
||||
// Sync is end-to-end encrypted, so a device with no passphrase is locked;
|
||||
// tests that sync start with one unless they pass their own `initial`.
|
||||
final store = <String, String>{
|
||||
'crdt_sync_e2e_passphrase': 'test-passphrase',
|
||||
...?initial,
|
||||
};
|
||||
final store = <String, String>{...?initial};
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
|
||||
|
||||
@ -1,12 +1,10 @@
|
||||
/// The "Fill all with catering" row: glyph per state, Cancel only when armed.
|
||||
/// The "Fill all with catering" row: label per state, Cancel only when armed.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/widgets/fill_all_row.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'label_finders.dart';
|
||||
|
||||
Future<void> _pump(
|
||||
WidgetTester tester, {
|
||||
bool canFetch = true,
|
||||
@ -33,30 +31,26 @@ void main() {
|
||||
await _pump(t, canFetch: false, armed: 3);
|
||||
|
||||
expect(find.byType(OutlinedButton), findsNothing);
|
||||
expect(byIconLabel(fillAllLabel), findsNothing);
|
||||
expect(byIconLabel('Cancel'), findsNothing);
|
||||
expect(find.text(fillAllLabel), findsNothing);
|
||||
expect(find.text('Cancel'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('resting: the fill glyph and no Cancel', (t) async {
|
||||
testWidgets('resting: the fill label and no Cancel', (t) async {
|
||||
await _pump(t);
|
||||
|
||||
expect(byIconLabel(fillAllLabel), findsOneWidget);
|
||||
expect(find.byIcon(Icons.playlist_add_check), findsOneWidget);
|
||||
expect(byIconLabel('Cancel'), findsNothing);
|
||||
expect(find.text('🍱 Fill all with catering'), findsOneWidget);
|
||||
expect(find.text('Cancel'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('armed: double check with the count, and a Cancel button', (
|
||||
t,
|
||||
) async {
|
||||
testWidgets('armed: Confirm (N) and a Cancel button', (t) async {
|
||||
await _pump(t, armed: 3);
|
||||
|
||||
expect(byIconLabel('Confirm'), findsOneWidget);
|
||||
expect(find.text('3'), findsOneWidget);
|
||||
expect(byIconLabel(fillAllLabel), findsNothing);
|
||||
expect(byIconLabel('Cancel'), findsOneWidget);
|
||||
expect(find.text('✓ Confirm (3)'), findsOneWidget);
|
||||
expect(find.text(fillAllLabel), findsNothing);
|
||||
expect(find.text('Cancel'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('busy: spinner and both controls disabled', (t) async {
|
||||
testWidgets('busy: Working… and both controls disabled', (t) async {
|
||||
var fills = 0;
|
||||
var cancels = 0;
|
||||
await _pump(
|
||||
@ -67,15 +61,15 @@ void main() {
|
||||
onCancel: () => cancels++,
|
||||
);
|
||||
|
||||
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
||||
expect(byIconLabel('Confirm'), findsNothing);
|
||||
expect(find.text('Working…'), findsOneWidget);
|
||||
expect(find.text('✓ Confirm (3)'), findsNothing);
|
||||
expect(
|
||||
t.widget<OutlinedButton>(find.byType(OutlinedButton)).onPressed,
|
||||
isNull,
|
||||
);
|
||||
expect(t.widget<IconButton>(find.byType(IconButton)).onPressed, isNull);
|
||||
expect(t.widget<TextButton>(find.byType(TextButton)).onPressed, isNull);
|
||||
await t.tap(find.byType(OutlinedButton), warnIfMissed: false);
|
||||
await t.tap(find.byType(IconButton), warnIfMissed: false);
|
||||
await t.tap(find.byType(TextButton), warnIfMissed: false);
|
||||
expect(fills + cancels, 0);
|
||||
});
|
||||
|
||||
@ -89,8 +83,8 @@ void main() {
|
||||
onCancel: () => cancels++,
|
||||
);
|
||||
|
||||
await t.tap(byIconLabel('Confirm'));
|
||||
await t.tap(byIconLabel('Cancel'));
|
||||
await t.tap(find.text('✓ Confirm (2)'));
|
||||
await t.tap(find.text('Cancel'));
|
||||
|
||||
expect([fills, cancels], [1, 1]);
|
||||
});
|
||||
|
||||
@ -22,7 +22,6 @@ import 'package:diet_guard_app/widgets/day_status_calendar.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/semantics.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'label_finders.dart';
|
||||
|
||||
/// Landscape and *short* — the supported floor. Phone-portrait sizes, which is
|
||||
/// all the existing suite pinned, exercise neither constraint.
|
||||
@ -177,7 +176,7 @@ void main() {
|
||||
// Delete used to be bound only to onLongPress, which has no keyboard
|
||||
// equivalent whatsoever.
|
||||
expect(
|
||||
byIconLabel('Delete entry'),
|
||||
find.byTooltip('Delete entry'),
|
||||
findsOneWidget,
|
||||
reason: 'delete needs a tab-reachable control, not long-press only',
|
||||
);
|
||||
@ -208,7 +207,7 @@ void main() {
|
||||
|
||||
// Delete stays id-only to avoid ambiguous time+desc matches, so the
|
||||
// control must be absent rather than present-and-failing.
|
||||
expect(byIconLabel('Delete entry'), findsNothing);
|
||||
expect(find.byTooltip('Delete entry'), findsNothing);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,46 +0,0 @@
|
||||
/// Finders for text-free controls: they match the spoken label that icons and
|
||||
/// [Semantics] carry, so tests keep addressing widgets by name without any
|
||||
/// visible text.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// Finds an [Icon] with this `semanticLabel`.
|
||||
Finder byIconLabel(String label) =>
|
||||
find.byWidgetPredicate((w) => w is Icon && w.semanticLabel == label);
|
||||
|
||||
/// Finds a [Semantics] node with this label.
|
||||
Finder bySemLabel(String label) => find.byWidgetPredicate(
|
||||
(w) => w is Semantics && w.properties.label == label,
|
||||
);
|
||||
|
||||
/// Finds the [TextField] captioned [label] (an [IconField] or a bare
|
||||
/// [Semantics] wrapper).
|
||||
Finder fieldByLabel(String label) =>
|
||||
find.descendant(of: bySemLabel(label), matching: find.byType(TextField));
|
||||
|
||||
/// Finds the tappable control whose icon or semantics carries [label].
|
||||
Finder controlByLabel(String label) => find
|
||||
.ancestor(
|
||||
of: byIconLabel(label),
|
||||
matching: find.byWidgetPredicate(
|
||||
(w) => w is IconButton || w is ButtonStyleButton || w is InkResponse,
|
||||
),
|
||||
)
|
||||
.first;
|
||||
|
||||
/// Finds a [StatusCue] of [kind].
|
||||
Finder cueOfKind(CueKind kind) =>
|
||||
find.byWidgetPredicate((w) => w is StatusCue && w.kind == kind);
|
||||
|
||||
/// Finds a [StatusCue] whose spoken label is [label].
|
||||
Finder cueLabelled(String label) =>
|
||||
find.byWidgetPredicate((w) => w is StatusCue && w.semanticLabel == label);
|
||||
|
||||
/// Finds the chip ([FilterChip] or [ChoiceChip]) whose icon carries [label].
|
||||
Finder chipByLabel(String label) => find.ancestor(
|
||||
of: byIconLabel(label),
|
||||
matching: find.byWidgetPredicate((w) => w is FilterChip || w is ChoiceChip),
|
||||
);
|
||||
@ -1,90 +0,0 @@
|
||||
// Guard: the Body screen, every tile sheet and the activity-method chooser
|
||||
// paint no words (only numbers, unit symbols, MET and workout labels).
|
||||
// Workout labels are content only for manual workouts (source == 'manual').
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'label_finders.dart';
|
||||
import 'no_words_support.dart';
|
||||
import 'screens/body_screen_support.dart';
|
||||
|
||||
/// Workout labels the PC published (content, see `seedPerson`), plus the
|
||||
/// proper names of the BMI / ideal-weight / BMR formulas that label their
|
||||
/// figures (DOUBT rows in keep.md: kept from the first pilot, outside the
|
||||
/// activity sheet). Activity formulas (ACSM, Per-km) are NOT here: that sheet
|
||||
/// and its chooser show glyphs only. Only manual workouts carry human content.
|
||||
const Set<String> _workouts = {
|
||||
'walk to the shop',
|
||||
'Harris-Benedict (revised 1984)',
|
||||
'Peterson (BMI 22)',
|
||||
'Mifflin-St Jeor',
|
||||
'Katch-McArdle',
|
||||
'Cunningham',
|
||||
'BMI Prime',
|
||||
'Trefethen',
|
||||
'Devine',
|
||||
'Robinson',
|
||||
'Miller',
|
||||
};
|
||||
|
||||
void main() {
|
||||
late MemoryDocStore store;
|
||||
|
||||
setUp(() async {
|
||||
store = MemoryDocStore();
|
||||
await setUpBodyServices(store);
|
||||
});
|
||||
tearDown(tearDownBodyServices);
|
||||
|
||||
test('the checker flags an injected word (canary)', () {
|
||||
expect(wordsIn('70.0 kg'), isEmpty);
|
||||
expect(wordsIn('265 MET'), isEmpty);
|
||||
expect(wordsIn('Measured (ACSM)'), isNotEmpty);
|
||||
expect(wordsIn('walk to the shop 4 km', content: _workouts), ['km']);
|
||||
expect(wordsIn('walk to the shop', content: _workouts), isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('canary: a painted word fails the guard', (tester) async {
|
||||
await tester.pumpWidget(const MaterialApp(home: Text('Activity')));
|
||||
expect(() => expectNoWords(tester), throwsA(isA<TestFailure>()));
|
||||
});
|
||||
|
||||
for (final seeded in [false, true]) {
|
||||
testWidgets('body tiles and sheets paint no words (seeded: $seeded)', (
|
||||
tester,
|
||||
) async {
|
||||
if (seeded) await seedPerson(store);
|
||||
await pumpBody(tester);
|
||||
final found = wordyStrings(
|
||||
tester,
|
||||
content: _workouts,
|
||||
minStrings: 5,
|
||||
where: 'tiles',
|
||||
);
|
||||
for (final title in tileTitles(tester)) {
|
||||
await openTile(tester, title);
|
||||
found.addAll(wordyStrings(tester, content: _workouts, where: title));
|
||||
await closeSheet(tester);
|
||||
}
|
||||
expect(found, isEmpty);
|
||||
});
|
||||
}
|
||||
|
||||
testWidgets('the activity-method chooser paints no words', (tester) async {
|
||||
await seedPerson(store);
|
||||
await pumpBody(tester);
|
||||
await openTile(tester, 'Daily calorie target');
|
||||
await tester.tap(bySemLabel('Moderate').first);
|
||||
await tester.pumpAndSettle();
|
||||
expectNoWords(
|
||||
tester,
|
||||
content: _workouts,
|
||||
minStrings: 8,
|
||||
where: 'activity chooser',
|
||||
);
|
||||
await tester.tap(bySemLabel('Measured (ACSM)').last);
|
||||
await tester.pumpAndSettle();
|
||||
expectNoWords(tester, content: _workouts, where: 'measured goal');
|
||||
});
|
||||
}
|
||||
@ -1,77 +0,0 @@
|
||||
// Guard: a catering fetch / fill reports with a glyph and a dish count; its
|
||||
// sentence is only the spoken label.
|
||||
|
||||
import 'package:diet_guard_app/screens/log_meal_fill_mixin.dart';
|
||||
import 'package:diet_guard_app/services/kuchnia_spread.dart';
|
||||
import 'package:diet_guard_app/ui/cues.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'label_finders.dart';
|
||||
import 'no_words_support.dart';
|
||||
|
||||
void main() {
|
||||
group('fillCue', () {
|
||||
test('nothing to fill paints a warning and 0', () {
|
||||
final cue = fillCue((
|
||||
message: 'No catering delivery today.',
|
||||
written: const <SlottedDish>[],
|
||||
), armed: 0);
|
||||
expect(cue.kind, CueKind.warn);
|
||||
expect(cue.count, 0);
|
||||
expect(cue.label, 'No catering delivery today.');
|
||||
});
|
||||
|
||||
test('a proposal paints its armed count', () {
|
||||
final cue = fillCue((
|
||||
message: 'Will log 3',
|
||||
written: const <SlottedDish>[],
|
||||
), armed: 3);
|
||||
expect((cue.kind, cue.count), (CueKind.info, 3));
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('a counted cue paints only the glyph and the number', (
|
||||
tester,
|
||||
) async {
|
||||
final state = CueState.next(
|
||||
null,
|
||||
CueKind.ok,
|
||||
'Logged 4 catering dishes.',
|
||||
4,
|
||||
);
|
||||
await tester.pumpWidget(MaterialApp(home: Scaffold(body: state.widget)));
|
||||
expect(find.text('4'), findsOneWidget);
|
||||
expect(cueLabelled('Logged 4 catering dishes.'), findsOneWidget);
|
||||
expectNoWords(tester, minStrings: 2, where: 'fill cue');
|
||||
});
|
||||
|
||||
testWidgets('the delivery snackbar paints the dish glyph and 0', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (context) => TextButton(
|
||||
onPressed: () => showCueSnack(
|
||||
context,
|
||||
kind: CueKind.warn,
|
||||
semanticLabel: 'No delivery today.',
|
||||
icon: Icons.restaurant,
|
||||
count: 0,
|
||||
),
|
||||
child: const Icon(Icons.local_shipping),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.byType(TextButton));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
expect(find.byIcon(Icons.restaurant), findsOneWidget);
|
||||
expect(find.text('0'), findsOneWidget);
|
||||
expectNoWords(tester, minStrings: 3, where: 'delivery snack');
|
||||
});
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user