dashPi: a self-hosted home dashboard, its sync server and phone app

The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-10-24 09:35:12 +02:00
commit fb3c01cdd7
333 changed files with 45151 additions and 0 deletions

View file

@ -0,0 +1,45 @@
// Products kept from the archive ("food.product", food_model.dart): stored as the dashboard's db.save_product
// does (uid "p:<food_id>"), found again by id / barcode / name (folded), and their added sugar.
import 'dart:io';
import 'package:dash_app/health/food_model.dart';
import 'package:dash_app/health/sugar.dart';
import 'package:dash_app/sync/store.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final store = SyncStore('${Directory.systemTemp.createTempSync('product').path}/d.db', 'test00000000');
final item = {
'id': 24032663211215, 'name': 'Zarte Haferflocken', 'brand': 'Kölln', 'barcode': '4032663211215', 'countries': 'germany',
'category': 'Kölln · Rolled oats', 'nutriscore': 'a', 'nova': 1, 'labels': null, 'sugars_in': '', 'dairy': 0, 'added_sugar': null,
'per100': {'kcal': 372, 'protein': 13.5, 'carbs': 58.7, 'sugar': 0.7, 'fat': 7},
'portions': [{'label': 'serving (40 g)', 'grams': 40}],
};
test('kept, found again, synced under p:<id>', () {
final f = keepProduct(store, item)!;
expect(f.foodId, 24032663211215);
expect(f.portions.single.grams, 40);
expect(store.row(tProduct, 'p:24032663211215')!['food_id'], 24032663211215);
expect(keptProduct(store, 24032663211215)!.name, 'Zarte Haferflocken');
expect(keptByBarcode(store, '4032663211215').single.brand, 'Kölln');
expect(keptProducts(store, 'kolln hafer', fold: fold).single.foodId, 24032663211215);
expect(keptProducts(store, 'muesli', fold: fold), isEmpty);
});
test('not a product: refused', () {
expect(keepProduct(store, {...item, 'id': 123}), isNull);
expect(keepProduct(store, {...item, 'name': ' '}), isNull);
});
test('added sugar: the label figure first, else its ingredients', () {
final oats = keepProduct(store, item)!;
expect(foodPart(oats, 0.7, 100), 0); // sugars_in "" → natural
final cereal = keepProduct(store, {...item, 'id': 20000000000017, 'name': 'Choco cereal', 'sugars_in': 'sugar',
'added_sugar': 20, 'per100': {'kcal': 390, 'sugar': 25}})!;
expect(foodPart(cereal, 25, 100), 20); // the label's 20 of 25 g
final zero = keepProduct(store, {...item, 'id': 20000000000018, 'name': 'Wafer', 'nova': 4, 'sugars_in': 'sugar', 'added_sugar': 0,
'per100': {'kcal': 500, 'sugar': 30}})!;
expect(foodPart(zero, 30, 100), 30); // "0 added" yet sugar in the ingredients: the 0 is ignored
});
}

View file

@ -0,0 +1,35 @@
// app/location.dart against a stand-in for MainActivity's "dash/location": a fix, or why there's none.
import 'package:dash_app/app/location.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const ch = MethodChannel('dash/location');
Future<(({double lat, double lon})?, String)> run(Map<String, Object?> answers) async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(ch, (c) async => answers[c.method]);
var why = '';
final at = await whereAmI(none: (w) => why = w);
return (at, why);
}
test('not allowed, refused again', () async {
expect(await run({'status': {'allowed': false, 'enabled': true}, 'ask': false}), (null, 'location not allowed'));
});
test('switched off', () async {
expect(await run({'status': {'allowed': true, 'enabled': false}}), (null, 'location off'));
});
test('the last fix', () async {
final (at, _) = await run({'status': {'allowed': true, 'enabled': true}, 'last': {'lat': 47.17, 'lon': 24.06}});
expect((at!.lat, at.lon), (47.17, 24.06));
});
test('allowed now, a new fix', () async {
final (at, _) = await run({'status': {'allowed': false, 'enabled': true}, 'ask': true, 'last': null, 'current': {'lat': 46.77, 'lon': 23.6}});
expect(at!.lat, 46.77);
});
test('nothing found', () async {
expect(await run({'status': {'allowed': true, 'enabled': true}, 'last': null, 'current': null}), (null, 'no location found'));
});
}

107
app/test/notes_test.dart Normal file
View file

@ -0,0 +1,107 @@
// Notes: the sync's "keep both copies" (SyncStore.forks — the same cases as the dashboard's syncdb
// "fork"), saving on an old version, and ticking checkboxes. flutter test test/notes_test.dart
import 'dart:io';
import 'package:dash_app/notes/markdown.dart';
import 'package:dash_app/notes/notes_model.dart';
import 'package:dash_app/sync/store.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final dir = Directory.systemTemp.createTempSync('notes_test');
var k = 0;
SyncStore dev(String name) => SyncStore('${dir.path}/${k++}.db', name);
/// Everything [from] hasn't sent yet → the others.
void send(SyncStore from, List<SyncStore> to) {
final (changes, mark) = from.changes();
from.markPushed(mark);
for (final s in to) {
s.apply(changes);
}
}
List<String> show(SyncStore s) =>
[for (final n in allNotes(s)) '${n.body}${n.origin != null ? ' (copy)' : ''}${n.pinned ? ' (pinned)' : ''}']..sort();
String main(SyncStore s) => allNotes(s).firstWhere((n) => n.origin == null).id;
void edit(SyncStore s, String body) {
final n = getNote(s, main(s))!;
saveNote(s, id: n.id, body: body, base: n.rev);
sleep(const Duration(milliseconds: 3));
}
test('two devices editing one note keep both texts, and all agree', () {
final a = dev('aaaaaaaaaaaa'), b = dev('bbbbbbbbbbbb'), c = dev('cccccccccccc');
saveNote(a, body: 'v0');
send(a, [b, c]);
edit(a, 'v1');
edit(a, 'v2');
send(a, [b, c]);
expect(show(b), ['v2'], reason: 'one after the other: no copy');
edit(a, 'A-text');
edit(b, 'B-text');
send(a, [b, c]);
send(b, [a, c]);
expect(show(a), ['A-text (copy)', 'B-text']);
expect(show(b), show(a));
expect(show(c), show(a));
// b edits the text, then a (older text) pins: b's text + a's pin, everywhere
edit(b, 'B2');
send(b, [c]);
setNote(a, main(a), {'pinned': 1});
send(a, [b, c]);
send(b, [a, c]);
send(c, [a, b]);
expect(show(a), ['A-text (copy)', 'B2 (pinned)']);
expect(show(b), show(a));
expect(show(c), show(a));
// a copy deleted on one device is gone everywhere and not made again
a.delete(noteTable, allNotes(a).firstWhere((n) => n.origin != null).id);
send(a, [b, c]);
expect(show(b), ['B2 (pinned)']);
expect(show(c), ['B2 (pinned)']);
});
test('typing goes on in one version until it has been sent', () {
final a = dev('aaaaaaaaaaaa');
final (id, _) = saveNote(a, body: 'x');
final r0 = getNote(a, id)!.rev;
saveNote(a, id: id, body: 'xy', base: r0);
expect(getNote(a, id)!.rev, r0);
a.markPushed(a.changes().$2);
saveNote(a, id: id, body: 'xyz', base: r0);
final n = getNote(a, id)!;
expect(n.rev, isNot(r0));
expect(n.r['revs'], '$r0 ${n.rev}');
});
test('a save on an old version becomes a copy', () {
final a = dev('aaaaaaaaaaaa'), b = dev('bbbbbbbbbbbb');
final (id, _) = saveNote(a, body: 'start');
send(a, [b]);
final seen = getNote(b, id)!.rev; // b opens it …
edit(a, 'changed on a');
send(a, [b]); // … a's change arrives while b types
final (nid, conflict) = saveNote(b, id: id, body: 'typed on b', base: seen);
expect(conflict, isTrue);
expect(nid, isNot(id));
expect(show(b), ['changed on a', 'typed on b (copy)']);
});
test('checkboxes tick by their number, outside code blocks', () {
const src = '- [ ] one\n```\n- [ ] not this\n```\n> - [x] two\n1. [ ] three';
expect(toggleTask(src, 0), contains('- [x] one'));
expect(toggleTask(src, 1), contains('> - [ ] two'));
expect(toggleTask(src, 2), contains('1. [x] three'));
expect(toggleTask(src, 2), contains('- [ ] not this'));
});
test('title, tags, folders', () {
expect(noteTitle('\n\n## Shopping list\n- milk'), 'Shopping list');
expect(noteTags('#home and #Work/acme, not a#b, `#code`, # heading'), ['home', 'work/acme']);
expect(cleanFolder(' Work / Acme/ '), 'Work/Acme');
});
}

51
app/test/sugar_test.dart Normal file
View file

@ -0,0 +1,51 @@
// sugar.dart against the dashboard's plugins/food/sugar.py: the same kinds for the same foods (the table
// below is sugar.kind's output — regenerate it there when the rules change) and the same folding.
import 'package:dash_app/health/sugar.dart';
import 'package:flutter_test/flutter_test.dart';
// name, category, source, nova, labels, sugarsIn, dairy → kind
const cases = <(String, String, String, int?, String, String?, int?, String)>[
('Figs, dried, uncooked', 'Fruits and Fruit Juices', 'sr_legacy', null, '', null, null, 'natural'),
('Orange juice, raw', 'Fruits and Fruit Juices', 'sr_legacy', null, '', null, null, 'added'),
('Beverages, carbonated, cola, regular', 'Beverages', 'sr_legacy', null, '', null, null, 'added'),
('Alcoholic beverage, wine, table, red', 'Beverages', 'sr_legacy', null, '', null, null, 'added'),
('Yogurt, plain, whole milk', 'Dairy and Egg Products', 'sr_legacy', null, '', null, null, 'dairy'),
('Yogurt, fruit, low fat', 'Dairy and Egg Products', 'sr_legacy', null, '', null, null, 'dairy'),
('Zahăr brun', '', '', null, '', null, null, 'added'),
('Smântână 20%', '', '', null, '', null, null, 'dairy'),
('Sušienky s čokoládou', '', '', null, '', null, null, 'added'),
('Túró Rudi', '', '', null, '', null, null, 'dairy'),
('Apfelsaft naturtrüb', '', '', null, '', null, null, 'added'),
('Mandelmilch ungesüßt', '', '', null, '', null, null, 'natural'),
('Lapte de migdale', '', '', null, '', null, null, 'natural'),
('Iaurt grecesc', '', '', null, '', null, null, 'dairy'),
('Gemüsebrühe', '', '', null, '', null, null, 'natural'),
('Ciocolată neagră 70%', '', '', null, '', null, null, 'added'),
('Tomates pelées', 'Tomatoes', 'off', 3, '', '', 0, 'natural'),
('Biscuiți cu unt', 'Biscuits', 'off', 4, '', 'sugar, glucose syrup', 0, 'added'),
('Jogurt jahodový', 'Yogurts', 'off', 3, '', 'sugar', 1, 'dairy'),
('Jogurt biely', 'Yogurts', 'off', 3, '', '', 1, 'dairy'),
('Müsli ohne Zuckerzusatz', 'Cereals', 'off', 3, 'no added sugar', null, 0, 'natural'),
('Bio Haferflocken', '', 'off', 1, '', null, null, 'natural'),
('Sardine fillets', '', 'off', null, '', null, null, 'added'),
('Kefír', '', 'off', null, '', null, null, 'dairy'),
('Plant drink, oat', '', 'off', 4, '', '', 0, 'natural'),
('Cereals, oats, regular and quick, not fortified, dry', 'Breakfast Cereals', 'sr_legacy', null, '', null, null, 'natural'),
('Cereals ready-to-eat, POST, HONEY BUNCHES OF OATS, honey roasted', 'Breakfast Cereals', 'sr_legacy', null, '', null, null, 'added'),
('Wine, table, red', 'Wine', 'survey', null, '', null, null, 'added'),
];
void main() {
test('kinds match sugar.py', () {
for (final (name, category, source, nova, labels, sugarsIn, dairy, want) in cases) {
expect(sugarKind(name, category: category, source: source, nova: nova, labels: labels, sugarsIn: sugarsIn, dairy: dairy),
want, reason: name);
}
});
test('folding matches sugar.fold', () {
const want = {'Zahăr': 'zahar', 'ŠŤAVA': 'stava', 'Groß': 'gross', 'Łódź': 'lodz', 'smântână': 'smantana',
'Crème brûlée': 'creme brulee', 'tvaroh': 'tvaroh'};
want.forEach((w, f) => expect(fold(w), f, reason: w));
});
}

View file

@ -0,0 +1,74 @@
// Weather ▸ Current location when the phone can't tell where it is: the error banner on top, home (the first place) shown;
// no place at all: the banner, no crash.
import 'dart:io';
import 'package:dash_app/app/sync_service.dart';
import 'package:dash_app/sync/client.dart';
import 'package:dash_app/sync/store.dart';
import 'package:dash_app/weather/weather_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('no location → the banner, home shown', (tester) async {
tester.view.physicalSize = const Size(1200, 2700);
tester.view.devicePixelRatio = 3;
addTearDown(tester.view.reset);
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('dash/location'), (c) async =>
{'status': {'allowed': false, 'enabled': true}, 'ask': false}[c.method]);
final store = SyncStore('${Directory.systemTemp.createTempSync('wx').path}/d.db', 'test00000000');
store.setMeta('wx_here', 1); // Current location picked
store.setMetaText('wx_places', '[{"name": "Hometown, XX", "lat": 47.1, "lon": 24.0}]');
final sync = SyncService(SyncSettings(server: 'http://x.invalid', token: 't', account: 'a', name: 'n', device: 'test00000000',
key: Uint8List(32)), store);
await tester.pumpWidget(MaterialApp(home: WeatherPage(sync: sync)));
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
expect(find.text('Location isn\'t allowed for this app'), findsOneWidget);
expect(find.text('Showing Hometown (home) instead.'), findsOneWidget);
expect(find.text('Hometown'), findsOneWidget); // the title: home, not "Hometown (location not allowed)"
sync.dispose();
});
testWidgets('no location and no place → the banner, no crash', (tester) async {
tester.view.physicalSize = const Size(1200, 2700);
tester.view.devicePixelRatio = 3;
addTearDown(tester.view.reset);
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('dash/location'), (c) async =>
{'status': {'allowed': false, 'enabled': true}, 'ask': false}[c.method]);
final store = SyncStore('${Directory.systemTemp.createTempSync('wx').path}/d.db', 'test00000000');
final sync = SyncService(SyncSettings(server: 'http://x.invalid', token: 't', account: 'a', name: 'n', device: 'test00000000',
key: Uint8List(32)), store);
await tester.pumpWidget(MaterialApp(home: WeatherPage(sync: sync)));
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
expect(find.text('Location isn\'t allowed for this app'), findsOneWidget);
expect(tester.takeException(), isNull);
sync.dispose();
});
testWidgets("the dashboard's places (synced weather.place) come first: home from there", (tester) async {
tester.view.physicalSize = const Size(1200, 2700);
tester.view.devicePixelRatio = 3;
addTearDown(tester.view.reset);
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('dash/location'), (c) async =>
{'status': {'allowed': false, 'enabled': true}, 'ask': false}[c.method]);
final store = SyncStore('${Directory.systemTemp.createTempSync('wx').path}/d.db', 'test00000000');
store.apply([
{'t': 'weather.place', 'u': 'place:Townsville, XX', 'h': 5, 'd': 'pi0000000000',
'row': {'k': 'Townsville, XX', 'name': 'Townsville, XX', 'lat': 45.0, 'lon': 10.0, 'ord': 0}},
]);
store.setMeta('wx_here', 1);
final sync = SyncService(SyncSettings(server: 'http://x.invalid', token: 't', account: 'a', name: 'n', device: 'test00000000',
key: Uint8List(32)), store);
await tester.pumpWidget(MaterialApp(home: WeatherPage(sync: sync)));
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
expect(find.text('Showing Townsville (home) instead.'), findsOneWidget);
sync.dispose();
});
}

View file

@ -0,0 +1,112 @@
// work_model.dart against the dashboard's own numbers (plugins/workload views.week / report) on the
// same rows. The fixture is real data, so it isn't in the repo: make it on the Pi (rows in wire
// format + the Pi's results) and run WORK_FIXTURE=<file.json> flutter test test/work_model_test.dart
import 'dart:convert';
import 'dart:io';
import 'package:dash_app/sync/store.dart';
import 'package:dash_app/work/work_model.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final path = Platform.environment['WORK_FIXTURE'];
final skip = path == null ? 'WORK_FIXTURE not set' : null;
late SyncStore store;
late Map<String, dynamic> exp;
late DateTime now;
setUpAll(() {
if (path == null) return;
final fx = jsonDecode(File(path).readAsStringSync()) as Map<String, dynamic>;
exp = fx['expect'] as Map<String, dynamic>;
now = DateTime.parse(exp['today'] as String).add(const Duration(hours: 12));
final dir = Directory.systemTemp.createTempSync('work_test');
store = SyncStore('${dir.path}/data.db', 'test00000000');
for (final r in (fx['rows'] as List).cast<List>()) {
store.put(r[0] as String, r[1] as String, (r[2] as Map).cast<String, dynamic>());
}
});
test('weeks match the Pi', () {
final t = Tree(store);
for (final MapEntry(key: off, value: w) in (exp['weeks'] as Map<String, dynamic>).entries) {
final v = week(store, t, int.parse(off), now);
expect(hm(v.minutes), w['total'], reason: 'week $off total');
expect(hm(v.billableMinutes), w['billable'], reason: 'week $off billable');
expect([for (final e in (v.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key)))) money(e.value, e.key)],
w['amounts'], reason: 'week $off amounts');
expect([for (final d in v.days) [d.billableMinutes > 0 ? hm(d.billableMinutes) : '',
d.minutes - d.billableMinutes > 0 ? hm(d.minutes - d.billableMinutes) : '']], w['days'], reason: 'week $off days');
expect([for (final c in v.customers) [c.node.name, c.minutes > 0 ? hm(c.minutes) : '',
[for (final e in (c.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key)))) if (e.value != 0) money(e.value, e.key)].join(' · '),
c.rate]], w['customers'], reason: 'week $off customers');
}
}, skip: skip);
test('reports match the Pi', () {
final t = Tree(store);
for (final MapEntry(key: p, value: r) in (exp['reports'] as Map<String, dynamic>).entries) {
final (from, to) = presetRange(p, now)!;
final v = report(store, t, from, to);
String ams(Agg a) => [for (final e in (a.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key)))) money(e.value, e.key)].join('|');
expect(hm(v.total.m), r['total'], reason: '$p total');
expect(hm(v.total.bm), r['billable'], reason: '$p billable');
expect(ams(v.total), (r['amounts'] as List).join('|'), reason: '$p amounts');
expect(v.items.length, r['n'], reason: '$p entries');
expect([for (final x in v.rows) [x.node.name, x.depth, hm(x.agg.m), hm(x.agg.bm), ams(x.agg)]],
[for (final x in (r['rows'] as List).cast<List>()) [x[0], x[1], x[2], x[3], (x[4] as List).join('|')]], reason: '$p rows');
}
}, skip: skip);
test('saving round-trips and validates', () {
final t = Tree(store);
final leaf = t.walk().last.$1;
final f = EntryForm(node: leaf.id, day: DateTime(2030, 1, 1), startMin: 23 * 60, endMin: 60, billable: true, note: ' x ');
final id = saveEntry(store, t, f);
final r = store.row(tEntry, id)!;
expect(r['start'], '2030-01-01 23:00');
expect(r['end'], '2030-01-02 01:00'); // past midnight → the next day
expect(r['note'], 'x');
expect(() => saveEntry(store, t, EntryForm(node: leaf.id, day: DateTime(2030, 1, 1), startMin: 60, endMin: 60,
endDay: DateTime(2030, 1, 1), billable: true)), throwsA(isA<Invalid>()));
deleteEntry(store, id);
expect(store.row(tEntry, id), isNull);
// a node with booked time can't be deleted; a fresh one can, with its rates
final top = t.walk().first.$1;
expect(deleteNode(store, t, top.id), isFalse);
final nid = saveNode(store, t, NodeForm(kind: 'task', parent: top.id, name: 'Test', rates: [('', '12,5'), ('2031-01-01', '15')]));
final t2 = Tree(store);
expect(t2.rate(nid, '2030-06-01').$1, 12.5);
expect(t2.rate(nid, '2031-02-01').$1, 15);
expect(store.row(tRate, '$nid:$epoch')!['rate'], 12.5);
expect(() => saveNode(store, t2, NodeForm(kind: 'project', parent: nid, name: 'Bad')), throwsA(isA<Invalid>()));
expect(deleteNode(store, t2, nid), isTrue);
expect(store.row(tRate, '$nid:2031-01-01'), isNull);
}, skip: skip);
test('week numbers and blocks keep to the wall clock across summer time', () {
expect(isoWeek(DateTime.utc(2026, 10, 19)), 43);
expect(isoWeek(DateTime.utc(2026, 10, 26)), 44); // after the clocks went back on the 25th
expect(isoWeek(DateTime.utc(2026, 3, 30)), 14); // after they went forward on the 29th
expect(isoWeek(DateTime.utc(2026, 12, 28)), 53);
expect(isoWeek(DateTime.utc(2027, 1, 4)), 1);
final dir = Directory.systemTemp.createTempSync('dst');
final st = SyncStore('${dir.path}/d.db', 'dst000000000');
st.put(tNode, 'n', {'kind': 'client', 'parent_id': null, 'name': 'X', 'colour': '#ffb33a', 'billable': 1, 'currency': 'EUR',
'notes': '', 'archived': 0, 'created': ''});
st.put(tEntry, 'e', {'node_id': 'n', 'start': '2026-10-25 10:00', 'end': '2026-10-25 12:30', 'billable': 1, 'note': '',
'created': '', 'updated': ''});
final v = week(st, Tree(st), 0, DateTime(2026, 10, 21, 12));
final b = v.days[6].blocks.single;
expect([b.a, b.b], [600, 750]);
expect(hm(v.minutes), '2:30');
});
test('money and hours format like the Pi', () {
expect(money(1234567.5, 'EUR'), '1 234 567.50 EUR');
expect(money(0, 'RON'), '0.00 RON');
expect(hm(90), '1:30');
expect(num0(20.0), '20');
expect(num0(22.5), '22.5');
});
}

View file

@ -0,0 +1,144 @@
// The Work timeline's gestures on a phone-sized screen: hold an empty spot and drag = a new span; a block's
// grips = an earlier start / later end (never under 15 minutes); hold the block = move it. Holds start after
// holdDelay (250 ms — Flutter's long press would need 500). The Undo messages time out by themselves.
import 'dart:io';
import 'dart:typed_data';
import 'package:dash_app/app/sync_service.dart';
import 'package:dash_app/sync/client.dart';
import 'package:dash_app/sync/store.dart';
import 'package:dash_app/work/work_model.dart';
import 'package:dash_app/work/work_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('span, resize, move', (tester) async {
tester.view.physicalSize = const Size(1200, 2700); // a 400 × 900 phone at 3×
tester.view.devicePixelRatio = 3;
addTearDown(tester.view.reset);
final dir = Directory.systemTemp.createTempSync('resize');
final store = SyncStore('${dir.path}/d.db', 'test00000000');
final node = SyncStore.randomId(), id = SyncStore.randomId();
store.put(tNode, node, {'kind': 'client', 'name': 'Acme', 'created': '2026-10-01 00:00:00'});
final now = DateTime.now(), d = DateTime.utc(now.year, now.month, now.day);
store.put(tEntry, id, {'node_id': node, 'start': fmtMin(d.add(const Duration(hours: 10))),
'end': fmtMin(d.add(const Duration(hours: 11))), 'billable': 1, 'note': '', 'created': '2026-10-01 00:00:00'});
final sync = SyncService(SyncSettings(server: 'http://x.invalid', token: 't', account: 'a', name: 'n', device: 'test00000000',
key: Uint8List(32)), store);
await tester.pumpWidget(MaterialApp(home: Scaffold(body: WorkPage(sync: sync))));
await tester.pump(const Duration(milliseconds: 300));
// hold an empty spot at 14:00 and drag down to 16:00 → the sheet opens with 14:00–16:00
final two = tester.getTopLeft(find.text('14'));
var s = await tester.startGesture(Offset(two.dx + 200, two.dy + 7 + 10));
await tester.pump(const Duration(milliseconds: 300));
await s.moveBy(const Offset(0, 20));
await tester.pump();
await s.moveBy(const Offset(0, 2 * hourH - 30));
await tester.pump();
expect(find.textContaining('14:00–16:00'), findsOneWidget);
await s.up();
await tester.pumpAndSettle();
expect(find.text('14:00'), findsWidgets);
expect(find.text('16:00'), findsWidgets);
Navigator.of(tester.element(find.text('16:00').first)).pop();
await tester.pumpAndSettle();
String end() => (store.row(tEntry, id)!['end'] as String).split(' ').last;
String start() => (store.row(tEntry, id)!['start'] as String).split(' ').last;
Rect block() => tester.getRect(find.ancestor(of: find.textContaining(RegExp(r'\d\d:\d\d–\d\d:\d\d')), matching: find.byType(Stack)).first);
// bottom grip: hold 300 ms, drag down an hour → ends 12:00
var g = await tester.startGesture(block().bottomCenter - const Offset(0, 5));
await tester.pump(const Duration(milliseconds: 300));
await g.moveBy(const Offset(0, 20));
await tester.pump();
await g.moveBy(const Offset(0, hourH - 20));
await tester.pump();
expect(find.textContaining('10:00–12:00'), findsOneWidget);
await g.up();
await tester.pumpAndSettle();
expect(end(), '12:00');
await tester.pump(const Duration(seconds: 5)); // the Undo message times out
await tester.pumpAndSettle();
expect(find.text('Undo'), findsNothing);
// top grip: drag up half an hour → starts 09:30
g = await tester.startGesture(block().topCenter + const Offset(0, 5));
await tester.pump(const Duration(milliseconds: 300));
await g.moveBy(const Offset(0, -20));
await tester.pump();
await g.moveBy(const Offset(0, -hourH / 2 + 20));
await tester.pump();
await g.up();
await tester.pumpAndSettle();
expect(start(), '09:30');
expect(end(), '12:00');
await tester.pump(const Duration(seconds: 5));
await tester.pumpAndSettle();
// never shorter than 15 minutes: bottom grip dragged far up
g = await tester.startGesture(block().bottomCenter - const Offset(0, 5));
await tester.pump(const Duration(milliseconds: 300));
await g.moveBy(const Offset(0, -20));
await tester.pump();
await g.moveBy(const Offset(0, -5 * hourH));
await tester.pump();
await g.up();
await tester.pumpAndSettle();
expect(end(), '09:45');
await tester.pump(const Duration(seconds: 5));
await tester.pumpAndSettle();
// the middle: a 300 ms hold moves it (Flutter's long press would need 500)
g = await tester.startGesture(block().center);
await tester.pump(const Duration(milliseconds: 300));
await g.moveBy(const Offset(0, 20));
await g.moveBy(const Offset(0, hourH - 20));
await tester.pump();
await g.up();
await tester.pumpAndSettle();
expect((start(), end()), ('10:30', '10:45'));
// a tap on the block opens it
await tester.tap(find.text('Acme · 10:30–10:45'));
await tester.pumpAndSettle();
expect(find.text('10:30'), findsWidgets);
// drawing to the screen's bottom edge and holding there scrolls the day: the span reaches past what was showing
Navigator.of(tester.element(find.text('10:30').first)).pop();
await tester.pumpAndSettle();
await tester.pump(const Duration(seconds: 5));
await tester.pumpAndSettle();
final h14 = tester.getTopLeft(find.text('14'));
final bottom = tester.view.physicalSize.height / tester.view.devicePixelRatio;
final shown = (14 + (bottom - h14.dy) / hourH).floor(); // the last hour on screen when it starts
s = await tester.startGesture(Offset(h14.dx + 200, h14.dy + 7 + 10));
await tester.pump(const Duration(milliseconds: 300));
await s.moveTo(Offset(h14.dx + 200, bottom - 30));
await tester.pump();
for (var i = 0; i < 20; i++) {
await tester.pump(const Duration(milliseconds: 16));
}
final label = tester.widgetList<Text>(find.textContaining(RegExp(r'^14:00–'))).first.data!;
final to = int.parse(label.substring(6, 8));
expect(to, greaterThan(shown), reason: '$label, $shown:00 was the last hour showing');
await s.up();
await tester.pumpAndSettle();
expect(find.text(label.substring(6, 11)), findsWidgets); // the sheet has that end
// a block held at the bottom edge rides along: it lands beyond the last hour that was showing
Navigator.of(tester.element(find.text(label.substring(6, 11)).first)).pop();
await tester.pumpAndSettle();
await tester.pump(const Duration(seconds: 5));
await tester.pumpAndSettle();
final blk = tester.getCenter(find.text('Acme · 10:30–10:45'));
final lastShown = (10.5 + (bottom - blk.dy) / hourH).floor();
s = await tester.startGesture(blk);
await tester.pump(const Duration(milliseconds: 300));
await s.moveTo(Offset(blk.dx, bottom - 30));
await tester.pump();
for (var i = 0; i < 20; i++) {
await tester.pump(const Duration(milliseconds: 16));
}
await s.up();
await tester.pumpAndSettle();
expect(int.parse(start().substring(0, 2)), greaterThan(lastShown), reason: 'moved to ${start()}, $lastShown:00 was showing');
expect(end(), isNot('10:45'));
sync.dispose();
});
}