// Work: one week of booked time (the web page's /work). ‹ CW nn › on top (tap = this week), the // totals (hours, billable / not, money, the weekly target), the customers' hours this week, then // the days: on a phone a strip of the 7 days + the chosen day as a timeline; on a wide screen all // seven side by side. Tap an empty spot = book from there (15-minute snap); hold an empty spot and drag // up / down = book that span; tap a block = edit, // hold a block and drag = move it (15-minute snap; sideways = another day: a column on a wide // screen, a cell of the day strip on a phone); hold its top / bottom grip and drag = an earlier / later // start / end. Holds start after holdDelay (shorter than Flutter's long press). Dragging near the top / bottom // edge scrolls the day (the span / block follows), so spans longer than the screen can be drawn. The + books from now. From the Pi (when sent, switchable): // the calendar's events faintly behind (tap = book that time), Activity's blocks in a lane (tap = book it). import 'dart:async'; import 'dart:math'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../app/sync_service.dart'; import '../app/theme.dart'; import 'customers_page.dart'; import 'entry_sheet.dart'; import 'work_model.dart'; const hourH = 52.0; // px per hour in the timeline const holdDelay = Duration(milliseconds: 250); // hold before a move / resize / new span starts (Flutter's long press: 500 ms) /// [child] with a tap and a hold-and-drag that starts after [holdDelay]. Widget _hold({ required Widget child, GestureTapUpCallback? onTapUp, GestureLongPressStartCallback? onStart, GestureLongPressMoveUpdateCallback? onMove, GestureLongPressEndCallback? onEnd, VoidCallback? onCancel, HitTestBehavior? behavior, }) => RawGestureDetector( behavior: behavior, gestures: { if (onTapUp != null) TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( TapGestureRecognizer.new, (g) => g.onTapUp = onTapUp, ), LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers( () => LongPressGestureRecognizer(duration: holdDelay), (g) => g ..onLongPressStart = onStart ..onLongPressMoveUpdate = onMove ..onLongPressEnd = onEnd ..onLongPressCancel = onCancel, ), }, child: child, ); class WorkPage extends StatefulWidget { const WorkPage({super.key, required this.sync, this.s = const WorkSettings(), this.actions = const []}); final SyncService sync; final WorkSettings s; final List actions; // the shell's (sync icon, ⋮) — Work has its own bar: in landscape the week's ‹ CW › sits in it @override State createState() => _WorkPageState(); } class _WorkPageState extends State { int offset = 0; int sel = DateTime.now().weekday - 1; // the day shown on a phone final scroll = ScrollController(initialScrollOffset: 0); Timer? tick; // the calendar's events behind the week / Activity's lane (the web's "Activity" box), kept per device bool get showCal => widget.sync.store.metaText('work_cal') != '0'; bool get showAct => widget.sync.store.metaText('work_act') == '1'; bool get showSum => widget.sync.store.metaText('work_sum') != '0'; // landscape: the totals line void _toggle(String k, bool on) => setState(() => widget.sync.store.setMetaText(k, on ? '1' : '0')); @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) => _toFocus()); tick = Timer.periodic(const Duration(minutes: 1), (_) => mounted ? setState(() {}) : null); // the now line } @override void dispose() { tick?.cancel(); scroll.dispose(); super.dispose(); } /// Scroll to the focus hours (or just above now, when that's later). void _toFocus() { if (!scroll.hasClients) return; final now = DateTime.now(); final h = offset == 0 && now.hour > widget.s.dayEnd - 2 ? now.hour - 3.0 : widget.s.dayStart.toDouble(); scroll.jumpTo(min(scroll.position.maxScrollExtent, max(0, h * hourH - 8))); } void _go(int o) => setState(() { offset = o; if (o == 0) sel = DateTime.now().weekday - 1; }); @override Widget build(BuildContext context) => ListenableBuilder( listenable: widget.sync, builder: (context, _) { final store = widget.sync.store; final t = Tree(store, widget.s); final v = week(store, t, offset); final mq = MediaQuery.of(context); // landscape / wide: all 7 days; the week's nav goes into the bar and the totals into one thin line, // so the height is for the calendar final wide = mq.size.width >= 700 || mq.orientation == Orientation.landscape; return Scaffold( appBar: AppBar( title: const Text('Work'), // landscape: ‹ CW / dates › centred on the whole bar, its arrows fixed (a fixed-width middle) flexibleSpace: wide ? SafeArea(child: Center(child: _head(v, compact: true))) : null, actions: [..._switches(), ...widget.actions], ), body: LayoutBuilder( builder: (context, box) { final idx = wide ? [0, 1, 2, 3, 4, 5, 6] : [sel]; // sideways drag per day: a column (wide) or a cell of the day strip (phone) final dayW = wide ? (box.maxWidth - 24 - _Timeline.gutter) / 7 : (box.maxWidth - 20) / 7; return Stack( children: [ Column( children: [ if (!wide) _head(v), if (t.isEmpty) _empty() else ...[ if (wide) ...[if (showSum) _line(v)] else ...[_totals(v), if (v.customers.isNotEmpty) _customers(v), _strip(v)], if (wide) _dayHeads(v), Expanded(child: _timeline(t, v, idx, dayW)), ], ], ), if (!t.isEmpty) Positioned( right: 16, bottom: 16, child: FloatingActionButton( // the chosen day (phone) / today or the week's Monday (wide), from now rounded to 15 min onPressed: () => openEntry(context, widget.sync, s: widget.s, day: !wide ? v.days[sel].day : (offset == 0 ? null : v.days[0].day)), child: const Icon(Icons.add), ), ), ], ); }, ), ); }, ); /// Landscape: the totals, the switches and the customers in one line, the target as a hairline under it. Widget _line(WeekView v) { final target = widget.s.weekTarget; final p = target > 0 ? min(1.0, v.minutes / 60 / target) : null; final amounts = (v.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key))) .where((e) => e.value != 0) .map((e) => money(e.value, e.key)) .join(' · '); return Padding( padding: const EdgeInsets.fromLTRB(12, 0, 12, 0), child: Column( children: [ SizedBox( height: 40, child: Row( children: [ Text(hm(v.minutes), style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), const SizedBox(width: 8), Text('${hm(v.billableMinutes)} billable', style: const TextStyle(color: good, fontSize: 13)), if (v.minutes - v.billableMinutes > 0) Text(' + ${hm(v.minutes - v.billableMinutes)} not', style: const TextStyle(color: muted, fontSize: 13)), if (amounts.isNotEmpty) ...[ const SizedBox(width: 12), Text(amounts, style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13)), ], const SizedBox(width: 8), Expanded( child: ListView( scrollDirection: Axis.horizontal, reverse: true, // right-aligned, scrolls when there are many children: [ for (final c in v.customers.reversed) Padding( padding: const EdgeInsets.only(left: 6), child: Center( child: ActionChip( visualDensity: VisualDensity.compact, avatar: Icon(Icons.circle, size: 10, color: hexColor(c.node.colour ?? palette[0])), label: Text( [c.node.name, if (c.minutes > 0) hm(c.minutes)].join(' '), style: const TextStyle(fontSize: 12.5), ), onPressed: () => Navigator.push( context, MaterialPageRoute( builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: c.node.id), ), ), ), ), ), ], ), ), ], ), ), if (p != null) Tooltip( message: '${hm(v.minutes)} of ${num0(target)} h this week', child: LinearProgressIndicator(value: p, minHeight: 2, backgroundColor: card2, color: p >= 1 ? good : accent), ), ], ), ); } Widget _head(WeekView v, {bool compact = false}) { final sun = v.monday.add(const Duration(days: 6)); final cw = isoWeek(v.monday); const mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; final range = v.monday.month == sun.month ? '${v.monday.day}. – ${sun.day}. ${mon[sun.month - 1]} ${sun.year}' : '${v.monday.day}. ${mon[v.monday.month - 1]} – ${sun.day}. ${mon[sun.month - 1]} ${sun.year}'; if (compact) { // in the bar: ‹ CW 42 / 19. – 25. Oct 2026 › — a fixed-width middle, so the arrows never move return Row( mainAxisSize: MainAxisSize.min, children: [ IconButton(visualDensity: VisualDensity.compact, onPressed: () => _go(offset - 1), icon: const Icon(Icons.chevron_left)), SizedBox( width: 170, child: GestureDetector( onTap: () => _go(0), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( 'CW $cw', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: accent, height: 1.15), ), Text(range, style: const TextStyle(fontSize: 11.5, color: muted, height: 1.15)), ], ), ), ), IconButton(visualDensity: VisualDensity.compact, onPressed: () => _go(offset + 1), icon: const Icon(Icons.chevron_right)), ], ); } return Padding( padding: const EdgeInsets.fromLTRB(4, 4, 4, 0), child: Row( children: [ IconButton(onPressed: () => _go(offset - 1), icon: const Icon(Icons.chevron_left)), Expanded( child: GestureDetector( onTap: () => _go(0), child: Column( children: [ Text( 'CW $cw', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent), ), Text(range, style: const TextStyle(color: muted, fontSize: 12.5)), ], ), ), ), IconButton(onPressed: () => _go(offset + 1), icon: const Icon(Icons.chevron_right)), ], ), ); } Widget _empty() => Expanded( child: Center( child: Padding( padding: const EdgeInsets.all(24), child: Column( mainAxisSize: MainAxisSize.min, children: [ const Text( 'No customers yet. Add the first one — then book time on it here.', textAlign: TextAlign.center, style: TextStyle(color: muted), ), const SizedBox(height: 12), FilledButton.icon( onPressed: () => Navigator.push( context, MaterialPageRoute( builder: (_) => CustomersPage(sync: widget.sync, s: widget.s), ), ), icon: const Icon(Icons.add), label: const Text('Customer'), ), ], ), ), ), ); Widget _totals(WeekView v) { final target = widget.s.weekTarget; final p = target > 0 ? min(1.0, v.minutes / 60 / target) : null; final amounts = (v.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key))) .where((e) => e.value != 0) .map((e) => money(e.value, e.key)) .join(' · '); return Padding( padding: const EdgeInsets.fromLTRB(12, 6, 12, 0), child: Card( child: Padding( padding: const EdgeInsets.fromLTRB(14, 10, 14, 10), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text(hm(v.minutes), style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), const SizedBox(width: 10), Expanded( child: Text.rich( TextSpan( children: [ TextSpan( text: '${hm(v.billableMinutes)} billable', style: const TextStyle(color: good), ), if (v.minutes - v.billableMinutes > 0) TextSpan( text: ' + ${hm(v.minutes - v.billableMinutes)} not', style: const TextStyle(color: muted), ), ], ), ), ), if (amounts.isNotEmpty) Text(amounts, style: const TextStyle(fontWeight: FontWeight.w600)), ], ), if (p != null) ...[ const SizedBox(height: 8), Tooltip( message: '${hm(v.minutes)} of ${num0(target)} h this week', child: ClipRRect( borderRadius: BorderRadius.circular(4), child: LinearProgressIndicator(value: p, minHeight: 6, backgroundColor: card2, color: p >= 1 ? good : accent), ), ), ], ], ), ), ), ); } /// Calendar / Activity switches as icons in the bar (amber = shown) — only once the Pi has sent any. List _switches() { final store = widget.sync.store; bool has(String t) => store.db.select('SELECT 1 FROM rec WHERE t = ? LIMIT 1', [t]).isNotEmpty; Widget icon(String tip, IconData i, bool on, String k) => IconButton( tooltip: '$tip: ${on ? 'shown' : 'hidden'}', visualDensity: VisualDensity.compact, onPressed: () => _toggle(k, !on), icon: Icon(i, size: 21, color: on ? accent : muted), ); return [ if (has(tCal)) icon('Calendar events', Icons.event_note, showCal, 'work_cal'), if (has(tAct)) icon('Activity', Icons.insights, showAct, 'work_act'), ]; } Widget _customers(WeekView v) => SizedBox( height: 44, child: ListView( scrollDirection: Axis.horizontal, padding: const EdgeInsets.fromLTRB(12, 6, 12, 0), children: [ for (final c in v.customers) Padding( padding: const EdgeInsets.only(right: 6), child: Tooltip( message: [c.rate, if (c.node.notes.trim().isNotEmpty) c.node.notes.trim().split('\n').first].join(' · '), child: ActionChip( avatar: Icon(Icons.circle, size: 11, color: hexColor(c.node.colour ?? palette[0])), label: Text( [ c.node.name, if (c.minutes > 0) hm(c.minutes), ...c.amounts.entries.where((e) => e.value != 0).map((e) => money(e.value, e.key)), ].join(' '), ), onPressed: () => Navigator.push( context, MaterialPageRoute( builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: c.node.id), ), ), ), ), ), ], ), ); Widget _strip(WeekView v) { final most = v.days.fold(0.0, (m, d) => max(m, d.minutes)); final today = dayOf(DateTime.now()); return Padding( padding: const EdgeInsets.fromLTRB(10, 8, 10, 4), child: Row( children: [ for (var i = 0; i < 7; i++) () { final d = v.days[i]; final isToday = d.day.isAtSameMomentAs(today); return Expanded( child: GestureDetector( onTap: () => setState(() => sel = i), child: Container( margin: const EdgeInsets.symmetric(horizontal: 2), padding: const EdgeInsets.symmetric(vertical: 5), decoration: BoxDecoration(color: i == sel ? card2 : null, borderRadius: BorderRadius.circular(8)), child: Column( children: [ Text( '${const ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'][i]} ${d.day.day}', style: TextStyle(fontSize: 11.5, color: isToday ? accent : muted, fontWeight: isToday ? FontWeight.bold : null), ), const SizedBox(height: 4), SizedBox( height: 26, child: Align( alignment: Alignment.bottomCenter, child: FractionallySizedBox( heightFactor: most > 0 ? max(0.04, d.minutes / most) : 0.04, widthFactor: .5, child: Column( children: [ if (d.minutes > d.billableMinutes) Expanded( flex: (d.minutes - d.billableMinutes).round(), child: Container(color: muted.withValues(alpha: .6)), ), Expanded( flex: max(1, d.billableMinutes.round()), child: Container(color: d.minutes > 0 && d.billableMinutes > 0 ? good : card2), ), ], ), ), ), ), const SizedBox(height: 3), Text(d.minutes > 0 ? hm(d.minutes) : '', style: const TextStyle(fontSize: 11)), ], ), ), ), ); }(), ], ), ); } /// Landscape: one line per day ("Mon 19 9:00"); the corner above the hours shows / hides the totals line. Widget _dayHeads(WeekView v) { final today = dayOf(DateTime.now()); return Padding( padding: const EdgeInsets.fromLTRB(12, 0, 12, 2), child: Row( children: [ SizedBox( width: _Timeline.gutter, height: 24, child: IconButton( padding: EdgeInsets.zero, iconSize: 18, tooltip: showSum ? 'Hide the totals' : 'Show the totals', onPressed: () => _toggle('work_sum', !showSum), icon: Icon(showSum ? Icons.expand_less : Icons.expand_more, color: muted), ), ), for (final d in v.days) Expanded( child: Text.rich( TextSpan( children: [ TextSpan( text: '${const ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][d.day.weekday - 1]} ${d.day.day}', style: TextStyle(fontWeight: FontWeight.bold, color: d.day.isAtSameMomentAs(today) ? accent : null), ), if (d.minutes > 0) TextSpan( text: ' ${hm(d.minutes)}', style: const TextStyle(fontSize: 11.5, color: muted), ), ], ), textAlign: TextAlign.center, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ); } Widget _timeline(Tree t, WeekView v, List idx, double dayW) { final store = widget.sync.store; final gh = showCal ? ghosts(store, v.monday) : null; var ab = showAct ? actBlocks(store, v.monday) : null; if (ab != null && ab.every((d) => d.isEmpty)) ab = null; // no lane in a week Activity has nothing for return SingleChildScrollView( controller: scroll, padding: const EdgeInsets.fromLTRB(12, 4, 12, 80), child: _Timeline( tree: t, days: [for (final i in idx) v.days[i]], ghosts: [for (final i in idx) gh?[i] ?? const []], acts: ab == null ? null : [for (final i in idx) ab[i]], dayW: dayW, focus: (widget.s.dayStart, widget.s.dayEnd), onEmpty: (day, minute, [end]) => openEntry(context, widget.sync, s: widget.s, day: day, startMin: minute, endMin: end), onBlock: (e) => openEntry(context, widget.sync, s: widget.s, entry: e), onGhost: (g) => openEntry(context, widget.sync, s: widget.s, day: dayOf(g.s), startMin: g.a.round(), endMin: g.b.round(), note: g.title), onAct: (a, day) => openEntry( context, widget.sync, s: widget.s, day: day, startMin: (a.a / 5).round() * 5, endMin: (a.b / 5).round() * 5, note: a.what, node: guessNode(t, a.names), ), onMove: (e, minutes, days) => _move(t, e, minutes, days, v), onResize: _resize, ), ); } /// A block's grip dragged: its start ([top]) or end [minutes] earlier / later (snapped to 15, at least 15 minutes long). void _resize(WorkEntry e, bool top, int minutes) { if (minutes == 0) return; final old = widget.sync.store.row(tEntry, e.id); if (old == null) return; DateTime sh(DateTime x) => DateTime.utc(x.year, x.month, x.day, x.hour, x.minute + minutes); final s = top ? sh(e.s) : e.s, end = top ? e.e : sh(e.e); widget.sync.store.put(tEntry, e.id, {...old, 'start': fmtMin(s), 'end': fmtMin(end), 'updated': fmtSec(DateTime.now())}); widget.sync.changed(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('${two(s.hour)}:${two(s.minute)}–${two(end.hour)}:${two(end.minute)} · ${hm(end.difference(s).inMinutes)}'), persist: false, // with an action Flutter keeps it up until tapped action: SnackBarAction( label: 'Undo', onPressed: () { widget.sync.store.put(tEntry, e.id, old); widget.sync.changed(); }, ), ), ); } /// A dragged block: the same length, [days] later / earlier and shifted by [minutes] (snapped to 15). void _move(Tree t, WorkEntry e, int minutes, int days, WeekView v) { if (minutes == 0 && days == 0) return; DateTime sh(DateTime x) => DateTime.utc(x.year, x.month, x.day + days, x.hour, x.minute + minutes); final s = sh(e.s), end = sh(e.e); final old = widget.sync.store.row(tEntry, e.id); if (old == null) return; widget.sync.store.put(tEntry, e.id, {...old, 'start': fmtMin(s), 'end': fmtMin(end), 'updated': fmtSec(DateTime.now())}); widget.sync.changed(); if (days != 0) { // follow it: its day (and week) on a phone final w = dayOf(s).difference(v.monday).inDays; setState(() { offset += (w / 7).floor(); sel = w % 7; }); } ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( 'Moved to ${days != 0 ? '${dayLabel(dayOf(s))} ' : ''}${two(s.hour)}:${two(s.minute)}–${two(end.hour)}:${two(end.minute)}', ), persist: false, // with an action Flutter keeps it up until tapped action: SnackBarAction( label: 'Undo', onPressed: () { widget.sync.store.put(tEntry, e.id, old); widget.sync.changed(); }, ), ), ); } } /// The hours + the days' blocks, side by side (one day on a phone, seven on a wide screen): the /// calendar's events faintly behind, Activity's blocks in a lane on the right (when shown). class _Timeline extends StatefulWidget { const _Timeline({ required this.tree, required this.days, required this.ghosts, required this.acts, required this.dayW, required this.focus, required this.onEmpty, required this.onBlock, required this.onGhost, required this.onAct, required this.onMove, required this.onResize, }); static const gutter = 34.0; static const lane = .72; // the bookings' share of a day while Activity's lane is shown (the web's --bw) final Tree tree; final List days; final List> ghosts; final List>? acts; final double dayW; // px of sideways drag = one day (a strip cell on a phone, a column on a wide screen) final (int, int) focus; final void Function(DateTime day, int minute, [int? end]) onEmpty; // end: a held-and-dragged span final void Function(WorkEntry e) onBlock; final void Function(Ghost g) onGhost; final void Function(ActBlock a, DateTime day) onAct; final void Function(WorkEntry e, int minutes, int days) onMove; final void Function(WorkEntry e, bool top, int minutes) onResize; @override State<_Timeline> createState() => _TimelineState(); } class _TimelineState extends State<_Timeline> { String? dragging, resizing; // the block being moved / resized ("id@start"); drag = the finger's offset since the hold bool sizeTop = false; // resizing its start (else its end) Offset drag = Offset.zero; int? spanDay; // a new booking being drawn (held on an empty spot, dragged): its day column, the held slot, the finger int spanFrom = 0, spanTo = 0; static int _snap(double minutes) => (minutes / 15).round() * 15; static int _at(double dy) => min(24 * 60 - 15, max(0, _snap(dy / hourH * 60 - 7.5))); // the slot under a finger // the span drawn: the held slot always in it, out to the finger either way (int, int) get _span => spanTo >= spanFrom ? (spanFrom, max(spanTo, spanFrom + 15)) : (spanTo, spanFrom + 15); int get _days => widget.dayW > 0 ? (drag.dx / widget.dayW).round() : 0; // scrolling while a drag is near the timeline's top / bottom edge — the span / block / grip follows the finger Timer? _edge; double _speed = 0, _scroll0 = 0, _spanY = 0, _spanScroll = 0; // px per tick; where a move / span started Offset _finger = Offset.zero; // a move's / resize's finger offset since the hold ScrollPosition? get _pos => Scrollable.maybeOf(context)?.position; double get _px => _pos?.pixels ?? 0; void _follow() => setState(() { if (spanDay != null) spanTo = min(24 * 60, max(0, _snap((_spanY + _px - _spanScroll) / hourH * 60))); if (dragging != null || resizing != null) drag = _finger + Offset(0, _px - _scroll0); }); /// The finger at [global]: within [zone] of the visible top / bottom = scroll that way, faster nearer the edge. void _edgeAt(Offset global) { const zone = 64.0; final box = Scrollable.maybeOf(context)?.context.findRenderObject(); if (box is! RenderBox) return; final top = box.localToGlobal(Offset.zero).dy, bottom = top + box.size.height; final v = global.dy < top + zone ? global.dy - top - zone : global.dy > bottom - zone ? global.dy - bottom + zone : 0.0; _speed = (v / zone * 14).clamp(-22.0, 22.0); if (_speed == 0) return _stopEdge(); _edge ??= Timer.periodic(const Duration(milliseconds: 16), (_) { final p = _pos; if (p == null || !mounted) return _stopEdge(); final next = (p.pixels + _speed).clamp(p.minScrollExtent, p.maxScrollExtent); if (next != p.pixels) { p.jumpTo(next); _follow(); } }); } void _stopEdge() { _edge?.cancel(); _edge = null; _speed = 0; } @override void dispose() { _stopEdge(); super.dispose(); } @override Widget build(BuildContext context) { const h = 24 * hourH; final now = DateTime.now(), today = dayOf(now); return SizedBox( height: h, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: _Timeline.gutter, height: h, child: Stack( children: [ for (var i = 1; i < 24; i++) Positioned( top: i * hourH - 7, left: 0, child: Text(two(i), style: const TextStyle(fontSize: 11, color: muted)), ), ], ), ), for (var di = 0; di < widget.days.length; di++) Expanded( child: LayoutBuilder( builder: (context, box) { final d = widget.days[di]; final w = box.maxWidth, bw = widget.acts == null ? w : w * _Timeline.lane; final isToday = d.day.isAtSameMomentAs(today); return _hold( behavior: HitTestBehavior.opaque, onTapUp: (u) => widget.onEmpty(d.day, _at(u.localPosition.dy)), onStart: (u) { HapticFeedback.mediumImpact(); setState(() { spanDay = di; spanFrom = spanTo = _at(u.localPosition.dy); _spanY = u.localPosition.dy; _spanScroll = _px; }); }, onMove: (u) { _spanY = u.localPosition.dy; _spanScroll = _px; _follow(); _edgeAt(u.globalPosition); }, onEnd: (_) { _stopEdge(); final (a, b) = _span; setState(() => spanDay = null); widget.onEmpty(d.day, a, b); }, onCancel: () { _stopEdge(); setState(() => spanDay = null); }, child: Stack( clipBehavior: Clip.none, children: [ // the focus hours a shade lighter, hour lines Positioned( top: widget.focus.$1 * hourH, height: (widget.focus.$2 - widget.focus.$1) * hourH, left: 0, right: 0, child: Container(color: card.withValues(alpha: .55)), ), for (var i = 0; i <= 24; i++) Positioned( top: i * hourH, left: 0, right: 0, child: Container(height: 1, color: card2.withValues(alpha: .7)), ), Positioned(top: 0, bottom: 0, left: 0, child: Container(width: 1, color: card2.withValues(alpha: .7))), for (final g in widget.ghosts[di]) _ghost(g, bw), if (widget.acts != null) ...[ Positioned( top: 0, bottom: 0, left: bw + 1, child: Container(width: 1, color: card2), ), for (final a in widget.acts![di]) _act(a, d.day, bw + 3, w - bw - 4), ], for (final b in d.blocks) _block(b, bw), if (spanDay == di) _newSpan(bw), if (isToday) Positioned( top: (now.hour * 60 + now.minute) / 60 * hourH - 1, left: 0, right: 0, child: IgnorePointer(child: Container(height: 2, color: accent)), ), ], ), ); }, ), ), ], ), ); } /// The booking being drawn: from the held slot to the finger, its times on it. Widget _newSpan(double w) { final (a, b) = _span; return Positioned( top: a / 60 * hourH + 1, left: 2, width: w - 4, height: max(14.0, (b - a) / 60 * hourH - 2), child: IgnorePointer( child: Container( padding: const EdgeInsets.fromLTRB(5, 2, 4, 2), decoration: BoxDecoration( color: accent.withValues(alpha: .25), borderRadius: BorderRadius.circular(6), border: Border.all(color: accent, width: 1.5), boxShadow: const [BoxShadow(blurRadius: 8, color: Colors.black54)], ), child: Text( '${hhmm(a)}–${b == 24 * 60 ? '24:00' : hhmm(b)} · ${hm(b - a)}', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 12, color: Colors.white, fontWeight: FontWeight.w600), ), ), ), ); } /// A calendar event: a faint band with its title; tap = book its time. Widget _ghost(Ghost g, double w) { final c = hexColor(g.colour); final height = max(12.0, (g.b - g.a) / 60 * hourH - 1); return Positioned( top: g.a / 60 * hourH + 1, left: 1, width: w - 2, height: height, child: GestureDetector( onTap: () => widget.onGhost(g), child: Tooltip( message: '${g.title}\n${g.calendar} · ${hhmm(g.s.hour * 60 + g.s.minute)}–${g.b >= 1440 ? '24:00' : hhmm(g.e.hour * 60 + g.e.minute)}', child: Container( padding: const EdgeInsets.only(left: 5, top: 1, right: 2), decoration: BoxDecoration( color: c.withValues(alpha: .13), border: Border(left: BorderSide(color: c.withValues(alpha: .7), width: 3)), ), child: Text( g.title, maxLines: height > 30 ? 2 : 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11, color: c.withValues(alpha: .9), height: 1.1), ), ), ), ), ); } /// One of Activity's blocks in its lane; tap = book it (the customer guessed from its category). Widget _act(ActBlock a, DateTime day, double x, double w) { final c = hexColor(a.colour); final height = max(6.0, (a.b - a.a) / 60 * hourH - 1); return Positioned( top: a.a / 60 * hourH + 1, left: x, width: w, height: height, child: GestureDetector( onTap: () => widget.onAct(a, day), child: Tooltip( message: '${a.start}–${a.end} · ${a.dur}\n${a.path}${a.what.isNotEmpty ? '\n${a.what}' : ''}', child: Container( padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 1), decoration: BoxDecoration(color: c.withValues(alpha: .55), borderRadius: BorderRadius.circular(3)), child: height > 16 && w > 30 ? Text( a.name, maxLines: max(1, (height / 13).floor()), overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 10, color: Colors.white, height: 1.15), ) : null, ), ), ), ); } Widget _block(Block b, double w) { final t = widget.tree, e = b.e; final n = t.nodes[e.node], top = t.clientOf(e.node); final c = hexColor(t.colour(e.node)); final lw = (w - 4) / b.lanes; final key = '${e.id}@${b.a}'; final moving = dragging == key, sizing = resizing == key; final shift = moving ? _snap(drag.dy / hourH * 60) : 0, days = moving ? _days : 0; final grow = sizing ? _grow(e) : 0; // minutes the grabbed edge moved final a = b.a + (sizing && sizeTop ? grow : 0), z = b.b + (sizing && !sizeTop ? grow : 0); final y = a / 60 * hourH + (moving ? drag.dy : 0); final height = max(14.0, (z - a) / 60 * hourH - 2); final short = height < 34; final sm = e.s.hour * 60 + e.s.minute + shift + (sizing && sizeTop ? grow : 0), em = e.e.difference(dayOf(e.s)).inMinutes + shift + (sizing && !sizeTop ? grow : 0); // a block ending at midnight: 24:00; dragged sideways: the day it lands on final time = '${days != 0 ? '→ ${dayLabel(DateTime.utc(e.s.year, e.s.month, e.s.day + days)).split(' ').take(2).join(' ')} ' : ''}' '${hhmm(sm)}–${em == 24 * 60 ? '24:00' : hhmm(em)}'; // on a wide screen the block follows the finger into the other day's column; on a phone the label says where final dx = moving && widget.days.length > 1 ? days * widget.dayW : 0.0; return Positioned( top: y + 1, left: 2 + b.lane * lw + dx, width: lw - 2, height: height, child: Stack( fit: StackFit.expand, children: [ _hold( onTapUp: (_) => widget.onBlock(e), onStart: (_) { HapticFeedback.mediumImpact(); setState(() { dragging = key; drag = _finger = Offset.zero; _scroll0 = _px; }); }, onMove: (u) { _finger = u.offsetFromOrigin; _follow(); _edgeAt(u.globalPosition); }, onEnd: (_) { _stopEdge(); final m = _snap(drag.dy / hourH * 60), dd = _days; setState(() => dragging = null); widget.onMove(e, m, dd); }, onCancel: () { _stopEdge(); setState(() => dragging = null); }, child: Container( padding: const EdgeInsets.fromLTRB(5, 2, 4, 2), decoration: BoxDecoration( color: Color.alphaBlend(c.withValues(alpha: e.billable ? .9 : .3), bg), // opaque: the calendar's titles don't show through borderRadius: BorderRadius.vertical( top: Radius.circular(b.contBefore ? 0 : 6), bottom: Radius.circular(b.contAfter ? 0 : 6), ), border: e.billable ? null : Border.all(color: c, width: 1.2), boxShadow: moving || sizing ? const [BoxShadow(blurRadius: 8, color: Colors.black54)] : null, ), child: DefaultTextStyle.merge( style: TextStyle(fontSize: 12, color: e.billable ? const Color(0xFF0D1017) : Colors.white, height: 1.15), overflow: TextOverflow.ellipsis, child: short ? Text('${n?.name ?? '?'} · $time', maxLines: 1, style: const TextStyle(fontWeight: FontWeight.w600)) : Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(n?.name ?? '?', maxLines: 1, style: const TextStyle(fontWeight: FontWeight.bold)), if (top != null && n != null && top.id != n.id && height > 48) Text(top.name, maxLines: 1), Text('$time · ${hm(em - sm)}', maxLines: 1), if (e.note.isNotEmpty && height > 64) Text(e.note.split('\n').first, maxLines: 2), ], ), ), ), ), // grips: the start's on top (not on a piece continued from the day before), the end's at the bottom // the grabbed one stays while held, however short the block gets (gone, it would cancel the drag) if (!b.contBefore && (sizing ? sizeTop : height >= 40)) _grip(e, key, true, e.billable), if (!b.contAfter && (sizing ? !sizeTop : height >= 22)) _grip(e, key, false, e.billable), ], ), ); } /// Minutes the grabbed edge of [e] moved: snapped to 15, the entry staying at least 15 minutes long. int _grow(WorkEntry e) { final g = _snap(drag.dy / hourH * 60), len = e.e.difference(e.s).inMinutes; return sizeTop ? min(g, len - 15) : max(g, 15 - len); } /// A block's top / bottom edge: hold and drag = an earlier / later start ([top]) or end; a tap edits like the block. Widget _grip(WorkEntry e, String key, bool top, bool dark) => Positioned( key: ValueKey(top), // the top and bottom grips keep their own state when the other one comes or goes top: top ? 0 : null, bottom: top ? null : 0, left: 0, right: 0, height: 14, child: _hold( behavior: HitTestBehavior.opaque, onTapUp: (_) => widget.onBlock(e), onStart: (_) { HapticFeedback.selectionClick(); setState(() { resizing = key; sizeTop = top; drag = _finger = Offset.zero; _scroll0 = _px; }); }, onMove: (u) { _finger = u.offsetFromOrigin; _follow(); _edgeAt(u.globalPosition); }, onEnd: (_) { _stopEdge(); final m = _grow(e); setState(() => resizing = null); widget.onResize(e, top, m); }, onCancel: () { _stopEdge(); setState(() => resizing = null); }, child: Align( alignment: top ? Alignment.topCenter : Alignment.bottomCenter, child: Container( margin: const EdgeInsets.symmetric(vertical: 3), width: 22, height: 3, decoration: BoxDecoration( color: (dark ? const Color(0xFF0D1017) : Colors.white).withValues(alpha: resizing == key ? .9 : .45), borderRadius: BorderRadius.circular(2), ), ), ), ), ); }