diff --git a/.gitignore b/.gitignore index 52b9332cd..adbcd870f 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ .svn/ *.env *.bak +DESIGN.md # IntelliJ related *.iml diff --git a/assets/images/circles/circle-1-background.png b/assets/images/circles/circle-1-background.png new file mode 100644 index 000000000..cd10f465a Binary files /dev/null and b/assets/images/circles/circle-1-background.png differ diff --git a/assets/images/circles/circle-2-background.png b/assets/images/circles/circle-2-background.png new file mode 100644 index 000000000..1b8b29296 Binary files /dev/null and b/assets/images/circles/circle-2-background.png differ diff --git a/assets/images/circles/circle-3-background.png b/assets/images/circles/circle-3-background.png new file mode 100644 index 000000000..341915c95 Binary files /dev/null and b/assets/images/circles/circle-3-background.png differ diff --git a/assets/images/circles/circle-4-background.png b/assets/images/circles/circle-4-background.png new file mode 100644 index 000000000..b61faa28c Binary files /dev/null and b/assets/images/circles/circle-4-background.png differ diff --git a/assets/images/circles/circle-5-background.png b/assets/images/circles/circle-5-background.png new file mode 100644 index 000000000..ddef81b50 Binary files /dev/null and b/assets/images/circles/circle-5-background.png differ diff --git a/assets/images/circles/circle-6-background.png b/assets/images/circles/circle-6-background.png new file mode 100644 index 000000000..05af3dbf6 Binary files /dev/null and b/assets/images/circles/circle-6-background.png differ diff --git a/lib/app_provider.dart b/lib/app_provider.dart index 457ed67a4..f7f87cb81 100644 --- a/lib/app_provider.dart +++ b/lib/app_provider.dart @@ -19,6 +19,7 @@ import 'package:campus_mobile_experimental/core/providers/shuttle.dart'; import 'package:campus_mobile_experimental/core/providers/speed_test.dart'; import 'package:campus_mobile_experimental/core/providers/student_id.dart'; import 'package:campus_mobile_experimental/core/providers/user.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle_request_trace.dart'; import 'package:campus_mobile_experimental/ui/navigator/top.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:provider/provider.dart'; @@ -161,11 +162,10 @@ List dependentServices = [ var classDataProvider = ClassScheduleDataProvider(); return classDataProvider; }, + lazy: false, update: (_, userDataProvider, classScheduleDataProvider) { classScheduleDataProvider!.userDataProvider = userDataProvider; - final bool isLoggedIn = userDataProvider.isLoggedIn; - final bool isNotLoading = !classScheduleDataProvider.isLoading; - if (isLoggedIn && isNotLoading) classScheduleDataProvider.fetchData(); + classScheduleDataProvider.handleLoginStateChange(); return classScheduleDataProvider; }, ), @@ -176,6 +176,7 @@ List dependentServices = [ }, update: (_, userDataProvider, studentIdDataProvider) { studentIdDataProvider!.userDataProvider = userDataProvider; + userDataProvider.studentIdDataProvider = studentIdDataProvider; return studentIdDataProvider; }, ), @@ -204,16 +205,15 @@ List dependentServices = [ return availabilityDataProvider; }, ), - ChangeNotifierProxyProvider2( + ChangeNotifierProxyProvider( create: (_) { - var shuttleDataProvider = ShuttleDataProvider(); + var shuttleDataProvider = ShuttleDataProvider(requestTraceObserver: debugLogShuttleRequestTrace); return shuttleDataProvider; }, - update: (_, coordinates, userDataProvider, shuttleDataProvider) { + update: (_, userDataProvider, shuttleDataProvider) { print("UpdateProvider: shuttleDataProvider"); - shuttleDataProvider!.userCoords = coordinates; - shuttleDataProvider.userDataProvider = userDataProvider; - shuttleDataProvider.fetchStops(true); + shuttleDataProvider!.userDataProvider = userDataProvider; + shuttleDataProvider.fetchStops(true, refreshCatalog: false); return shuttleDataProvider; }, ), diff --git a/lib/app_router.dart b/lib/app_router.dart index 45cf92062..78058c850 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -129,7 +129,7 @@ class Router { return MaterialPageRoute( builder: (context) { Provider.of(context).changeTitle(settings.name); - return DiningList(); + return DiningList(showSearch: true); }, ); case RoutePaths.DINING_OPTION_DETAIL_VIEW: diff --git a/lib/core/models/shuttle_arrival.dart b/lib/core/models/shuttle_arrival.dart index 5ab0b9692..457351508 100644 --- a/lib/core/models/shuttle_arrival.dart +++ b/lib/core/models/shuttle_arrival.dart @@ -1,5 +1,7 @@ import 'dart:convert'; +import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; + List getArrivingShuttles(String str) { var shuttles = json.decode(str); List arrivingShuttles = []; @@ -9,6 +11,85 @@ List getArrivingShuttles(String str) { return arrivingShuttles; } +/// Default route color used when a OneBusAway route has no usable color. +/// Mirrors the "no arrivals found" color used by the Transit card UI. +const String oneBusAwayDefaultRouteColor = '#747678'; + +final RegExp _hexColorPattern = RegExp(r'^([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$'); + +/// Parses the envelope of a OneBusAway +/// `arrivals-and-departures-for-stop` response +/// (`{"code":200,"currentTime":...,"data":{"entry":{...},"references":{...}}}`) +/// into the existing [ArrivingShuttle] shape used by the Transit UI. +/// +/// - [agencyId]: when provided, arrivals for routes outside that agency are +/// dropped. The campus feed serves multiple agencies (MTS, NCTD, UCSD) at +/// the same stops; the Transit feature only tracks the campus shuttle +/// agency, matching the legacy feed's behavior. +/// - [nowMs]: overrides the reference "now" used to compute arrival times +/// (the envelope's `currentTime` by default, device clock as fallback). +/// +/// Arrivals without any usable arrival/departure time are skipped rather +/// than crashing (graceful degradation). +List arrivingShuttlesFromOneBusAwayEnvelope( + Map envelope, { + String? agencyId, + int? nowMs, +}) { + final dynamic data = envelope['data']; + if (data is! Map) return const []; + final dynamic entry = data['entry']; + if (entry is! Map) return const []; + final int now = nowMs ?? (envelope['currentTime'] as num?)?.toInt() ?? DateTime.now().millisecondsSinceEpoch; + final Map> routeReferences = _routeReferences(data); + final List shuttles = []; + final dynamic arrivals = entry['arrivalsAndDepartures']; + if (arrivals is! List) return const []; + for (final dynamic arrival in arrivals) { + if (arrival is! Map) continue; + final ArrivingShuttle? shuttle = ArrivingShuttle.fromOneBusAwayJson( + arrival, + routeReferences, + now, + agencyId: agencyId, + ); + if (shuttle != null) shuttles.add(shuttle); + } + return shuttles; +} + +Map> _routeReferences(Map data) { + final dynamic references = data['references']; + final dynamic routes = references is Map ? references['routes'] : null; + final Map> routeById = >{}; + if (routes is! List) return routeById; + for (final dynamic route in routes) { + if (route is! Map) continue; + final String? id = _asString(route['id']); + if (id != null && id.isNotEmpty) routeById[id] = route; + } + return routeById; +} + +String? _asString(dynamic value) => value == null ? null : value.toString(); + +String? _firstNonEmpty(List candidates) { + for (final String? candidate in candidates) { + if (candidate != null && candidate.trim().isNotEmpty) return candidate; + } + return null; +} + +/// Validates and canonicalizes a OneBusAway route color (e.g. `182b49`) +/// into the `#RRGGBB` hex string the Transit UI expects. Returns null when +/// the value is missing or not a valid hex color. +String? _normalizeHexColor(String? raw) { + if (raw == null) return null; + final String trimmed = raw.trim().replaceFirst('#', ''); + if (!_hexColorPattern.hasMatch(trimmed)) return null; + return '#$trimmed'; +} + class ArrivingShuttle { ArrivingShuttle({ required this.routeId, @@ -24,16 +105,89 @@ class ArrivingShuttle { String routeColor; int secondsToArrival; - factory ArrivingShuttle.fromJson(Map json) { + factory ArrivingShuttle.fromJson(Map json) => ArrivingShuttle( + routeId: json["routeId"], + routeName: json["routeName"], + routeStopId: json["routeStopId"], + routeColor: json["routeColor"], + secondsToArrival: json["secondsToArrival"], + ); + + /// Maps a OneBusAway `arrivalsAndDepartures` entry onto the existing model + /// shape. [routeReferences] holds the referenced routes keyed by their + /// OneBusAway route id; [nowMs] is the reference time used to compute the + /// seconds until arrival. Returns null when the entry cannot be mapped + /// (missing route id, no usable time, or outside [agencyId]). + static ArrivingShuttle? fromOneBusAwayJson( + Map arrival, + Map> routeReferences, + int nowMs, { + String? agencyId, + }) { + final String routeId = _asString(arrival['routeId']) ?? ''; + if (routeId.isEmpty) return null; + if (agencyId != null && agencyId.isNotEmpty && !routeId.startsWith('${agencyId}_')) return null; + if (arrival['arrivalEnabled'] == false && arrival['departureEnabled'] == false) return null; + + final int? etaMs = _etaMilliseconds(arrival, nowMs); + if (etaMs == null) return null; + + final Map? route = routeReferences[routeId]; + final String? stopId = _asString(arrival['stopId']); return ArrivingShuttle( - routeId: json["routeId"], - routeName: json["routeName"], - routeStopId: json["routeStopId"], - routeColor: json["routeColor"], - secondsToArrival: json["secondsToArrival"], + routeId: oneBusAwayIdToInt(routeId), + routeName: _routeName(arrival, route), + routeStopId: stopId == null || stopId.isEmpty ? null : oneBusAwayIdToInt(stopId), + routeColor: _normalizeHexColor(_asString(route?['color'])) ?? oneBusAwayDefaultRouteColor, + secondsToArrival: etaMs < 0 ? 0 : etaMs ~/ 1000, ); } + /// The legacy feed exposed a single human-readable route name. OneBusAway + /// splits this across several fields, so prefer the referenced route's + /// long name (e.g. "Outside Loop"), then its short name, then the fields + /// carried on the arrival itself, then the trip headsign. + static String _routeName(Map arrival, Map? route) => + _firstNonEmpty([ + _asString(route?['longName']), + _asString(route?['shortName']), + _asString(arrival['routeShortName']), + _asString(arrival['routeLongName']), + _asString(arrival['tripHeadsign']), + ]) ?? + 'Route'; + + /// Resolves the target epoch-milliseconds for the arrival, preferring + /// real-time predictions over scheduled times and arrival times over + /// departure times. Returns null when no usable time exists (the legacy + /// equivalent of an arrival with no ETA). + static int? _etaMilliseconds(Map arrival, int nowMs) { + final bool predicted = arrival['predicted'] == true; + final int predictedArrival = _asMillis(arrival['predictedArrivalTime']); + final int scheduledArrival = _asMillis(arrival['scheduledArrivalTime']); + final int predictedDeparture = _asMillis(arrival['predictedDepartureTime']); + final int scheduledDeparture = _asMillis(arrival['scheduledDepartureTime']); + + int? targetMs; + if (predicted && predictedArrival > 0) { + targetMs = predictedArrival; + } else if (scheduledArrival > 0) { + targetMs = scheduledArrival; + } else if (predicted && predictedDeparture > 0) { + targetMs = predictedDeparture; + } else if (scheduledDeparture > 0) { + targetMs = scheduledDeparture; + } + if (targetMs == null) return null; + return targetMs - nowMs; + } + + static int _asMillis(dynamic value) { + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value) ?? 0; + return 0; + } + Map toJson() => { "routeId": routeId, "routeName": routeName, diff --git a/lib/core/models/shuttle_stop.dart b/lib/core/models/shuttle_stop.dart index 064cedff6..7be6ccacb 100644 --- a/lib/core/models/shuttle_stop.dart +++ b/lib/core/models/shuttle_stop.dart @@ -13,13 +13,45 @@ List shuttleStopModelFromJson(String str) { String shuttleStopModelToJson(List data) => json.encode(List.from(data.map((x) => x.toJson()))); +/// Converts a OneBusAway identifier (e.g. `UCSD_1040`) into the integer id +/// used by the Transit UI and the persisted user profile. If the part after +/// the agency prefix is not numeric, falls back to a stable hash so ids stay +/// unique and non-negative. +int oneBusAwayIdToInt(String id) { + final int separatorIndex = id.lastIndexOf('_'); + final String numericPart = separatorIndex >= 0 ? id.substring(separatorIndex + 1) : id; + return int.tryParse(numericPart) ?? (id.hashCode & 0x7FFFFFFF); +} + +/// Parses the envelope of a OneBusAway `stops-for-agency` response +/// (`{"code":200,...,"data":{"list":[...]}}`) into the existing +/// [ShuttleStopModel] shape used by the Transit UI. +/// +/// Malformed entries are skipped so a single bad record cannot break the +/// whole stop list (graceful degradation). +List shuttleStopsFromOneBusAwayEnvelope(Map envelope) { + final dynamic data = envelope['data']; + if (data is! Map) return const []; + final dynamic list = data['list']; + if (list is! List) return const []; + return list + .whereType>() + .map(ShuttleStopModel.fromOneBusAwayJson) + .whereType() + .toList(); +} + class ShuttleStopModel { double lat; double lon; int id; String name; - ShuttleStopModel({required this.lat, required this.lon, required this.id, required this.name}); + /// Raw OneBusAway stop id (e.g. `UCSD_10378`), kept so the arrivals + /// endpoint can be queried with the exact id OneBusAway expects. + String? oneBusAwayId; + + ShuttleStopModel({required this.lat, required this.lon, required this.id, required this.name, this.oneBusAwayId}); ShuttleStopModel.fromJson(Map json) : lat = json["lat"].toDouble(), @@ -27,5 +59,24 @@ class ShuttleStopModel { id = json["id"], name = json["name"]; - Map toJson() => {"lat": lat, "lon": lon, "id": id, "name": name}; + /// Maps a OneBusAway stop object onto the existing model shape. Returns + /// null when required fields are missing or malformed. + static ShuttleStopModel? fromOneBusAwayJson(Map json) { + final dynamic lat = json['lat']; + final dynamic lon = json['lon']; + final String? rawId = json['id']?.toString(); + final String? name = json['name']?.toString(); + if (lat is! num || lon is! num || rawId == null || rawId.isEmpty || name == null) { + return null; + } + return ShuttleStopModel( + lat: lat.toDouble(), + lon: lon.toDouble(), + id: oneBusAwayIdToInt(rawId), + name: name, + oneBusAwayId: rawId, + ); + } + + Map toJson() => {"lat": lat, "lon": lon, "id": id, "name": name, "oneBusAwayId": oneBusAwayId}; } diff --git a/lib/core/providers/availability.dart b/lib/core/providers/availability.dart index 0c0cc176e..5848b1e81 100644 --- a/lib/core/providers/availability.dart +++ b/lib/core/providers/availability.dart @@ -6,6 +6,8 @@ import 'package:flutter/material.dart'; class AvailabilityDataProvider extends ChangeNotifier { /// STATES bool _isLoading = false; + bool _isFetching = false; + bool _refreshFailed = false; DateTime? _lastUpdated; String? _error; Map _locationViewState = {}; @@ -19,51 +21,62 @@ class AvailabilityDataProvider extends ChangeNotifier { /// SERVICES var _availabilityService = AvailabilityService(); - void fetchAvailability() async { - _isLoading = true; - _error = null; - notifyListeners(); + Future fetchAvailability({bool silent = false}) async { + if (_isFetching) return; + _isFetching = true; + try { + if (!silent) { + _isLoading = true; + _error = null; + notifyListeners(); + } - /// creating new map ensures we remove all unsupported lots - Map newMapOfLots = {}; - - if (await _availabilityService.fetchData()) { - Map newLocationViewState = {}; - - /// setting the LocationViewState based on user data - for (AvailabilityModel model in _availabilityService.data) { - String curName = model.name; - RegExpMatch? match = RegExp(r' \(\d+/\d+\)$').firstMatch(curName); - if (match != null) curName = curName.replaceRange(match.start, match.end, ''); - newMapOfLots[model.name] = model; - - /// if the user is logged out and has not put any preferences, - /// show all locations by default - final selectedLocations = userDataProvider.userProfileModel.selectedOccuspaceLocations ?? []; - final bool hasNoSelectedLocations = selectedLocations.isEmpty; - - if (hasNoSelectedLocations) - newLocationViewState[curName] = _locationViewState[curName] ?? true; - /// otherwise, LocationViewState should be true for all selectedOccuspaceLocations - else { - newLocationViewState[curName] = _locationViewState[curName] ?? selectedLocations.contains(curName); + /// creating new map ensures we remove all unsupported lots + Map newMapOfLots = {}; + + if (await _availabilityService.fetchData()) { + _refreshFailed = false; + _error = null; + Map newLocationViewState = {}; + + /// setting the LocationViewState based on user data + for (AvailabilityModel model in _availabilityService.data) { + String curName = model.name; + RegExpMatch? match = RegExp(r' \(\d+/\d+\)$').firstMatch(curName); + if (match != null) curName = curName.replaceRange(match.start, match.end, ''); + newMapOfLots[model.name] = model; + + /// if the user is logged out and has not put any preferences, + /// show all locations by default + final selectedLocations = userDataProvider.userProfileModel.selectedOccuspaceLocations ?? []; + final bool hasNoSelectedLocations = selectedLocations.isEmpty; + + if (hasNoSelectedLocations) + newLocationViewState[curName] = _locationViewState[curName] ?? true; + /// otherwise, LocationViewState should be true for all selectedOccuspaceLocations + else { + newLocationViewState[curName] = _locationViewState[curName] ?? selectedLocations.contains(curName); + } } - } - // After the loop, assign it: - _locationViewState = newLocationViewState; + // After the loop, assign it: + _locationViewState = newLocationViewState; - /// replace old list of lots with new one - _availabilityModels = newMapOfLots; + /// replace old list of lots with new one + _availabilityModels = newMapOfLots; - /// if the user is logged in we want to sync the order of parking lots amongst all devices - reorderLocations(userDataProvider.userProfileModel.selectedOccuspaceLocations); - _lastUpdated = DateTime.now(); - } else { - _error = _availabilityService.error; + /// if the user is logged in we want to sync the order of parking lots amongst all devices + reorderLocations(userDataProvider.userProfileModel.selectedOccuspaceLocations); + _lastUpdated = DateTime.now(); + } else { + _refreshFailed = true; + if (!silent) _error = _availabilityService.error; + } + } finally { + _isFetching = false; + _isLoading = false; + notifyListeners(); } - _isLoading = false; - notifyListeners(); } List makeOrderedList(List? order) { @@ -113,6 +126,7 @@ class AvailabilityDataProvider extends ChangeNotifier { /// SIMPLE GETTERS bool get isLoading => _isLoading; String? get error => _error; + bool get refreshFailed => _refreshFailed; DateTime? get lastUpdated => _lastUpdated; Map get locationViewState => _locationViewState; List get availabilityModels => diff --git a/lib/core/providers/classes.dart b/lib/core/providers/classes.dart index 79b2c5688..bb102967d 100644 --- a/lib/core/providers/classes.dart +++ b/lib/core/providers/classes.dart @@ -4,11 +4,18 @@ import 'package:campus_mobile_experimental/core/models/scheduled_class.dart'; import 'package:campus_mobile_experimental/core/providers/user.dart'; import 'package:campus_mobile_experimental/core/services/classes.dart'; import 'package:flutter/material.dart'; +import 'package:hive/hive.dart'; import 'package:intl/intl.dart'; class ClassScheduleDataProvider extends ChangeNotifier { /// STATES bool _isLoading = false; + String? _refreshingCardId; + bool _linkedRefreshActive = false; + bool _modelInitialized = false; + bool _fetchStarted = false; + bool? _wasLoggedIn; + int _sessionGeneration = 0; DateTime _lastUpdated = DateTime.now(); String? _error; int _selectedCourse = 0; @@ -45,67 +52,179 @@ class ClassScheduleDataProvider extends ChangeNotifier { /// SERVICES var _classScheduleService = ClassScheduleService(); - void fetchData() async { - if (!_isLoading) { - _isLoading = true; + /// Resets the day maps and rebuilds them from the given model. + void _applyModel(ClassScheduleModel model) { + _classScheduleModel = model; + + /// remove all old classes + _enrolledClasses = {'MO': [], 'TU': [], 'WE': [], 'TH': [], 'FR': [], 'SA': [], 'SU': [], 'OTHER': []}; + _finals = {'MO': [], 'TU': [], 'WE': [], 'TH': [], 'FR': [], 'SA': [], 'SU': [], 'OTHER': []}; + _midterms = {'MI': [], 'OTHER': []}; + + try { + _createMapOfClasses(); + _modelInitialized = true; + } catch (e) { + _error = e.toString(); + } + } + + Future loadFromCache() async { + if (_modelInitialized) return; + final int generation = _sessionGeneration; + + try { + final box = await Hive.openBox('ClassScheduleModel'); + final cachedJson = box.get('ClassScheduleModel') as String?; + if (cachedJson == null || cachedJson.isEmpty) return; + + final cachedModel = classScheduleModelFromJson(cachedJson); + if (_modelInitialized || generation != _sessionGeneration) return; + + /// A fast failed fetch may have set an error before this cache load + /// completed; good cached data wins. _error = null; + + _applyModel(cachedModel); notifyListeners(); - final bool termFetched = await _classScheduleService.fetchAcademicTerm(); - final bool isLoggedIn = _userDataProvider.isLoggedIn; - if (termFetched && isLoggedIn) { - _academicTermModel = _classScheduleService.academicTermModel!; - final Map headers = { - 'Authorization': 'Bearer ${_userDataProvider.authenticationModel.accessToken}', - }; - - /// erase old model - _classScheduleModel = ClassScheduleModel(); - - /// fetch grad courses - final bool grCoursesFetched = await _classScheduleService.fetchGRCourses(headers, _academicTermModel.termCode!); - if (grCoursesFetched) { - _classScheduleModel = _classScheduleService.grData; - } else { - _error = _classScheduleService.error.toString(); - } + } catch (_) { + /// A cache miss or unreadable cache is not an error; + /// the network fetch remains the source of truth. + } + } - /// fetch undergrad courses - final bool unCoursesFetched = await _classScheduleService.fetchUNCourses(headers, _academicTermModel.termCode!); - if (unCoursesFetched) { - if (_classScheduleModel.data != null) { - _classScheduleModel.data!.addAll(_classScheduleService.unData.data!); - } else { - _classScheduleModel = _classScheduleService.unData; - } - _error = null; - } else { - _error = _classScheduleService.error.toString(); - _isLoading = false; - notifyListeners(); + /// Called from the app_provider proxy update whenever UserDataProvider notifies. + void handleLoginStateChange() { + final bool isLoggedIn = _userDataProvider.isLoggedIn; + final bool wasLoggedIn = _wasLoggedIn ?? false; + _wasLoggedIn = isLoggedIn; - /// short circuit - return; + if (wasLoggedIn && !isLoggedIn) { + reset(); + return; + } + + if (!wasLoggedIn && isLoggedIn) { + WidgetsBinding.instance.addPostFrameCallback((_) async { + final studentId = _userDataProvider.studentIdDataProvider; + if (studentId != null) { + await Future.any([studentId.whenSettled(), Future.delayed(const Duration(milliseconds: 1000))]); } + startFetchIfNeeded(); + }); + } + } - /// remove all old classes - _enrolledClasses = {'MO': [], 'TU': [], 'WE': [], 'TH': [], 'FR': [], 'SA': [], 'SU': [], 'OTHER': []}; - _finals = {'MO': [], 'TU': [], 'WE': [], 'TH': [], 'FR': [], 'SA': [], 'SU': [], 'OTHER': []}; - _midterms = {'MI': [], 'OTHER': []}; + /// Single-flight per login session; the reload menu bypasses this gate. + void startFetchIfNeeded() { + if (_fetchStarted || _isLoading) return; + if (!_userDataProvider.isLoggedIn) return; - try { - _createMapOfClasses(); - } catch (e) { - _error = e.toString(); - } + _fetchStarted = true; + fetchData(); + } + + Future fetchData() async { + if (_isLoading) return; + + _selectedCourse = 0; + _isLoading = true; + _error = null; + notifyListeners(); + + if (!_userDataProvider.isLoggedIn) { + // TODO: determine what error to show to the user - December 2025 + _isLoading = false; + notifyListeners(); + return; + } + + final int generation = _sessionGeneration; + + /// fetch actual data + final bool termFetched = await _classScheduleService.fetchAcademicTerm(); + if (generation != _sessionGeneration) return; + if (!termFetched) { + if (!_modelInitialized) _error = _classScheduleService.error; + _isLoading = false; + notifyListeners(); + return; + } - _lastUpdated = DateTime.now(); + _academicTermModel = _classScheduleService.academicTermModel!; + final Map headers = { + 'Authorization': 'Bearer ${_userDataProvider.authenticationModel.accessToken}', + }; + + /// erase old model + ClassScheduleModel fetchedModel = ClassScheduleModel(); + bool fetchedAnyCourses = false; + + /// fetch grad courses + final bool grCoursesFetched = await _classScheduleService.fetchGRCourses(headers, _academicTermModel.termCode!); + if (generation != _sessionGeneration) return; + if (grCoursesFetched) { + fetchedModel = _classScheduleService.grData; + fetchedAnyCourses = true; + } + + /// fetch undergrad courses + final bool unCoursesFetched = await _classScheduleService.fetchUNCourses(headers, _academicTermModel.termCode!); + if (generation != _sessionGeneration) return; + if (unCoursesFetched) { + if (fetchedModel.data != null) { + if (_classScheduleService.unData.data != null) { + fetchedModel.data!.addAll(_classScheduleService.unData.data!); + } } else { - // TODO: determine what error to show to the user - December 2025 - _error = _classScheduleService.error; + fetchedModel = _classScheduleService.unData; } + fetchedAnyCourses = true; + } + + /// If we have nothing fresh to show, keep whatever is already displayed. + if (!fetchedAnyCourses) { + if (!_modelInitialized) _error = _classScheduleService.error; + _isLoading = false; + notifyListeners(); + return; + } + + /// Never replace a complete displayed schedule with partial data; + /// partial results are only applied when nothing is displayed. + if (_modelInitialized && (!grCoursesFetched || !unCoursesFetched)) { _isLoading = false; notifyListeners(); + return; + } + + final String newJson = classScheduleModelToJson(fetchedModel); + + /// Skip the redundant apply and cache write if the fresh data + /// matches what is already displayed. + if (_modelInitialized && newJson == classScheduleModelToJson(_classScheduleModel)) { + _isLoading = false; + notifyListeners(); + return; + } + + if (_refreshingCardId != null) { + _linkedRefreshActive = true; } + + _applyModel(fetchedModel); + _lastUpdated = DateTime.now(); + _isLoading = false; + notifyListeners(); + + /// A failed cache write must not discard the fresh UI update. Re-check + /// the generation so a logout during the box open cannot re-persist the + /// previous user's schedule into the just-cleared box. + try { + final box = await Hive.openBox('ClassScheduleModel'); + if (generation != _sessionGeneration) return; + await box.put('ClassScheduleModel', newJson); + } catch (_) {} } void _createMapOfClasses() { @@ -122,8 +241,6 @@ class ClassScheduleDataProvider extends ChangeNotifier { // print('\x1B[33m${enrolledCourses.length}\x1B[0m'); if (enrolledCourses.isEmpty) { _error = "No enrolled courses found."; - _isLoading = false; - notifyListeners(); } /// Now that we obtained the classes the student is enrolled in, let's display them! @@ -201,6 +318,27 @@ class ClassScheduleDataProvider extends ChangeNotifier { } } + Future reset() async { + _sessionGeneration++; + _modelInitialized = false; + _fetchStarted = false; + _isLoading = false; + _refreshingCardId = null; + _linkedRefreshActive = false; + _error = null; + _selectedCourse = 0; + _lastUpdated = DateTime.now(); + _enrolledClasses = {'MO': [], 'TU': [], 'WE': [], 'TH': [], 'FR': [], 'SA': [], 'SU': [], 'OTHER': []}; + _finals = {'MO': [], 'TU': [], 'WE': [], 'TH': [], 'FR': [], 'SA': [], 'SU': [], 'OTHER': []}; + _midterms = {'MI': [], 'OTHER': []}; + notifyListeners(); + + try { + final box = await Hive.openBox('ClassScheduleModel'); + await box.clear(); + } catch (_) {} + } + static DateTime _getStartTime(String time) { var times = time.split("-"); final format = DateFormat.Hm(); @@ -212,6 +350,19 @@ class ClassScheduleDataProvider extends ChangeNotifier { notifyListeners(); } + Future reload(String cardId) async { + if (_isLoading || _refreshingCardId != null) return; + + _refreshingCardId = cardId; + try { + await fetchData(); + } finally { + _refreshingCardId = null; + _linkedRefreshActive = false; + notifyListeners(); + } + } + List get upcomingCourses { try { /// get weekday and return scheduled classes associated with current weekday @@ -247,6 +398,8 @@ class ClassScheduleDataProvider extends ChangeNotifier { /// SIMPLE GETTERS get isLoading => _isLoading; + bool isRefreshing(String cardId) => _refreshingCardId == cardId || _linkedRefreshActive; + bool get hasData => _modelInitialized; get error => _error; get lastUpdated => _lastUpdated; get selectedCourse => _selectedCourse; diff --git a/lib/core/providers/dining.dart b/lib/core/providers/dining.dart index e0e9864e9..6a91f22df 100644 --- a/lib/core/providers/dining.dart +++ b/lib/core/providers/dining.dart @@ -104,23 +104,23 @@ class DiningDataProvider extends ChangeNotifier { } void populateDistances() { - final bool hasCoordinates = _coordinates != null; - final bool hasLatitude = _coordinates?.lat != null; - final bool hasLongitude = _coordinates?.lon != null; - if (hasCoordinates && hasLatitude && hasLongitude) { - for (DiningModel model in _diningModels.values.toList()) { - if (model.coordinates != null) { - var distance = calculateDistance( - _coordinates!.lat!, - _coordinates!.lon!, - model.coordinates!.lat!, - model.coordinates!.lon!, - ); - model.distance = distance.toDouble(); - } else { - model.distance = null; - } + final userLat = _coordinates?.lat; + final userLon = _coordinates?.lon; + for (final model in _diningModels.values) { + final lat = model.coordinates?.lat; + final lon = model.coordinates?.lon; + if (lat == null || lon == null) { + // Uncomment this print to see which dining locations have null coordinates. + // print( + // 'DiningDataProvider: Missing coordinates for "${model.name}" ' + // '(id: ${model.id}, lat: $lat, lon: $lon).', + // ); + model.distance = null; + continue; } + model.distance = userLat != null && userLon != null + ? calculateDistance(userLat, userLon, lat, lon).toDouble() + : null; } } diff --git a/lib/core/providers/shuttle.dart b/lib/core/providers/shuttle.dart index aae9b5365..588fb3970 100644 --- a/lib/core/providers/shuttle.dart +++ b/lib/core/providers/shuttle.dart @@ -1,17 +1,27 @@ +import 'dart:async'; import 'dart:math' as Math; import 'package:campus_mobile_experimental/core/models/location.dart'; import 'package:campus_mobile_experimental/core/models/shuttle_arrival.dart'; import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; import 'package:campus_mobile_experimental/core/providers/user.dart'; import 'package:campus_mobile_experimental/core/services/shuttle.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle_request_trace.dart'; +import 'package:flutter/foundation.dart' show listEquals; import 'package:flutter/material.dart'; class ShuttleDataProvider extends ChangeNotifier { + ShuttleDataProvider({ShuttleService? shuttleService, ShuttleRequestTraceObserver? requestTraceObserver}) + : _requestTraceObserver = requestTraceObserver, + _shuttleService = shuttleService ?? ShuttleService(requestTraceObserver: requestTraceObserver); + + static const int maxSelectedStops = 5; + /// STATES bool _isLoading = false; String? _error; double closestDistance = 10000000; Map> arrivalsToRender = {}; + final Map arrivalErrors = {}; Coordinates? _userCoords; /// MODELS @@ -22,32 +32,132 @@ class ShuttleDataProvider extends ChangeNotifier { UserDataProvider? userDataProvider; /// SERVICES - var _shuttleService = ShuttleService(); + final ShuttleService _shuttleService; + final ShuttleRequestTraceObserver? _requestTraceObserver; + Completer? _fetchStopsCompleter; + Future? _catalogRequest; + final Map> _arrivalRequests = {}; + bool _refreshRequested = false; + bool _refreshCatalogRequested = false; + bool _refreshArrivalsRequested = false; + List? _lastSelectedStopIds; + int _operationSequence = 0; + ShuttleRequestContext? _activeRequestContext; + + Future fetchStops(bool reloading, {bool refreshCatalog = true}) { + final selectedStopIds = _normalizedSelectedStopIds(requireKnownStop: fetchedStops != null); + if (!refreshCatalog && + fetchedStops != null && + _error == null && + listEquals(_lastSelectedStopIds, selectedStopIds)) { + final activeContext = _activeRequestContext; + _emit( + ShuttleRequestTraceEvent( + kind: activeContext == null + ? ShuttleRequestTraceKind.providerRequestSkipped + : ShuttleRequestTraceKind.providerRequestJoined, + context: activeContext ?? _newRequestContext(refreshCatalog: false), + ), + ); + return _fetchStopsCompleter?.future ?? Future.value(); + } + _refreshRequested = true; + _refreshCatalogRequested |= refreshCatalog; + _refreshArrivalsRequested |= refreshCatalog; + if (_fetchStopsCompleter != null) { + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerRequestJoined, + context: _activeRequestContext ?? _newRequestContext(refreshCatalog: refreshCatalog), + ), + ); + return _fetchStopsCompleter!.future; + } - void fetchStops(bool reloading) async { + final completer = Completer(); + _fetchStopsCompleter = completer; + _runFetchStops(reloading).then(completer.complete, onError: completer.completeError); + return completer.future; + } + + Future _runFetchStops(bool reloading) async { _isLoading = true; - _error = null; - notifyListeners(); + try { + do { + _refreshRequested = false; + final refreshCatalog = _refreshCatalogRequested; + final refreshArrivals = _refreshArrivalsRequested; + _refreshCatalogRequested = false; + _refreshArrivalsRequested = false; + _error = null; + final requestContext = _newRequestContext(refreshCatalog: refreshCatalog); + _activeRequestContext = requestContext; + _emit( + ShuttleRequestTraceEvent(kind: ShuttleRequestTraceKind.providerOperationStarted, context: requestContext), + ); + notifyListeners(); - /// create new map of shuttles/stops to display - Map newMapOfStops = {}; - if (await _shuttleService.fetchData()) { - _shuttleService.data.sort((a, b) => (a.name).compareTo(b.name)); + if (!await _ensureCatalog(refresh: refreshCatalog, requestContext: requestContext)) continue; - for (ShuttleStopModel model in _shuttleService.data) { - newMapOfStops[model.id] = model; - } - fetchedStops = newMapOfStops; + _lastSelectedStopIds = _normalizedSelectedStopIds(requireKnownStop: true); + await calculateClosestStop(); + await _reconcileArrivalInformation(refresh: refreshArrivals, requestContext: requestContext); + } while (_refreshRequested || _refreshCatalogRequested || _refreshArrivalsRequested); + } finally { + _fetchStopsCompleter = null; + _activeRequestContext = null; + _isLoading = false; + notifyListeners(); + } + } - /// if the user is logged in we want to sync the order of parking lots amongst all devices - if (userDataProvider != null && !reloading) reorderStops(userDataProvider!.userProfileModel.selectedStops); + Future _ensureCatalog({required bool refresh, required ShuttleRequestContext requestContext}) { + if (!refresh && fetchedStops != null) { + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerRequestSkipped, + context: requestContext, + endpoint: ShuttleRequestEndpoint.catalog, + ), + ); + return Future.value(true); + } + final activeRequest = _catalogRequest; + if (activeRequest != null) { + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerRequestJoined, + context: requestContext, + endpoint: ShuttleRequestEndpoint.catalog, + ), + ); + return activeRequest; + } - // get closest stop to current user - await calculateClosestStop(); - await getArrivalInformation(); + late final Future request; + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerRequestStarted, + context: requestContext, + endpoint: ShuttleRequestEndpoint.catalog, + ), + ); + request = _fetchCatalog(requestContext).whenComplete(() { + if (identical(_catalogRequest, request)) _catalogRequest = null; + }); + _catalogRequest = request; + return request; + } + + Future _fetchCatalog(ShuttleRequestContext requestContext) async { + if (!await _shuttleService.fetchData(requestContext: requestContext)) { + _error = _shuttleService.error; + return false; } - _isLoading = false; - notifyListeners(); + + final sortedStops = _shuttleService.data.toList()..sort((a, b) => a.name.compareTo(b.name)); + fetchedStops = {for (final stop in sortedStops) stop.id: stop}; + return true; } // TODO: unused function. If needed, rewrite w/ proper nullability - December 2025 @@ -68,31 +178,38 @@ class ShuttleDataProvider extends ChangeNotifier { void reorderStops(List? order) { /// update userProfileModel with selectedStops - userDataProvider!.userProfileModel.selectedStops = order; + userDataProvider!.userProfileModel.selectedStops = _normalizeStopIds( + order ?? const [], + requireKnownStop: fetchedStops != null, + ); if (userDataProvider!.isLoggedIn) { /// post updated userProfileModel for logged-in users userDataProvider!.postUserProfile(userDataProvider!.userProfileModel); } notifyListeners(); + fetchStops(true, refreshCatalog: false); } Future addStop(int stopID) async { - if (!userDataProvider!.userProfileModel.selectedStops!.contains(stopID)) { - userDataProvider!.userProfileModel.selectedStops!.add(stopID); - // update userprofilemodel locally and in database after a stop is added - userDataProvider!.postUserProfile(userDataProvider!.userProfileModel); - arrivalsToRender[stopID] = await fetchArrivalInformation(stopID); - } - notifyListeners(); + final selectedStopIds = _normalizedSelectedStopIds(requireKnownStop: fetchedStops != null); + final isKnownStop = fetchedStops?.containsKey(stopID) ?? false; + if (!isKnownStop || selectedStopIds.contains(stopID) || selectedStopIds.length >= maxSelectedStops) return; + + userDataProvider!.userProfileModel.selectedStops = [...selectedStopIds, stopID]; + // update userprofilemodel locally and in database after a stop is added + userDataProvider!.postUserProfile(userDataProvider!.userProfileModel); + await fetchStops(true, refreshCatalog: false); } Future removeStop(int? stopID) async { - if (userDataProvider!.userProfileModel.selectedStops!.contains(stopID)) { - userDataProvider!.userProfileModel.selectedStops!.remove(stopID); + final selectedStopIds = _normalizedSelectedStopIds(requireKnownStop: fetchedStops != null); + if (selectedStopIds.remove(stopID)) { + userDataProvider!.userProfileModel.selectedStops = selectedStopIds; // update userprofilemodel locally and in database after a stop is removed userDataProvider!.postUserProfile(userDataProvider!.userProfileModel); } notifyListeners(); + await fetchStops(true, refreshCatalog: false); } Future calculateClosestStop() async { @@ -127,20 +244,114 @@ class ShuttleDataProvider extends ChangeNotifier { } Future getArrivalInformation() async { - if (_closestStop != null) arrivalsToRender[_closestStop!.id] = await fetchArrivalInformation(_closestStop!.id); + final requestContext = _newRequestContext(refreshCatalog: false); + _emit(ShuttleRequestTraceEvent(kind: ShuttleRequestTraceKind.providerOperationStarted, context: requestContext)); + await _reconcileArrivalInformation(refresh: true, requestContext: requestContext); + } + + Future _reconcileArrivalInformation({ + required bool refresh, + required ShuttleRequestContext requestContext, + }) async { + final desiredStopIds = stopsToRender.map((stop) => stop.id).toSet(); + arrivalsToRender.removeWhere((stopId, _) => !desiredStopIds.contains(stopId)); + arrivalErrors.removeWhere((stopId, _) => !desiredStopIds.contains(stopId)); + + for (final stopId in desiredStopIds) { + if (!refresh && (arrivalsToRender.containsKey(stopId) || arrivalErrors.containsKey(stopId))) { + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerRequestSkipped, + context: requestContext, + endpoint: ShuttleRequestEndpoint.arrivals, + stopId: stopId.toString(), + ), + ); + continue; + } + if (!stopsToRender.any((stop) => stop.id == stopId)) { + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerRequestSkipped, + context: requestContext, + endpoint: ShuttleRequestEndpoint.arrivals, + stopId: stopId.toString(), + ), + ); + continue; + } - for (ShuttleStopModel stop in stopsToRender) { - arrivalsToRender[stop.id] = await fetchArrivalInformation(stop.id); + final result = await _sharedArrivalInformation(stopId, requestContext); + if (stopsToRender.any((stop) => stop.id == stopId)) { + arrivalsToRender[stopId] = result.arrivals; + if (result.error == null) { + arrivalErrors.remove(stopId); + } else { + arrivalErrors[stopId] = result.error!; + } + } else { + arrivalErrors.remove(stopId); + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerResultDiscarded, + context: requestContext, + endpoint: ShuttleRequestEndpoint.arrivals, + stopId: stopId.toString(), + ), + ); + } } notifyListeners(); } - Future> fetchArrivalInformation(int stopID) async { - List output = await _shuttleService.getArrivingInformation(stopID); + Future _sharedArrivalInformation(int stopId, ShuttleRequestContext requestContext) { + final activeRequest = _arrivalRequests[stopId]; + if (activeRequest != null) { + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerRequestJoined, + context: requestContext, + endpoint: ShuttleRequestEndpoint.arrivals, + stopId: stopId.toString(), + ), + ); + return activeRequest; + } + + late final Future request; + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.providerRequestStarted, + context: requestContext, + endpoint: ShuttleRequestEndpoint.arrivals, + stopId: stopId.toString(), + ), + ); + request = fetchArrivalInformation(stopId, requestContext: requestContext).whenComplete(() { + if (identical(_arrivalRequests[stopId], request)) _arrivalRequests.remove(stopId); + }); + _arrivalRequests[stopId] = request; + return request; + } + + Future fetchArrivalInformation(int stopID, {ShuttleRequestContext? requestContext}) async { + final result = await _shuttleService.getArrivingInformation(stopID, requestContext: requestContext); + final output = result.arrivals.toList(); output.sort((a, b) => a.secondsToArrival.compareTo(b.secondsToArrival)); - return output; + return ShuttleArrivalResult(arrivals: output, error: result.error); } + ShuttleRequestContext _newRequestContext({required bool refreshCatalog}) => ShuttleRequestContext( + operationId: ++_operationSequence, + trigger: refreshCatalog + ? ShuttleRequestTrigger.manualReload + : fetchedStops == null + ? ShuttleRequestTrigger.startup + : ShuttleRequestTrigger.selectionChange, + ); + + void _emit(ShuttleRequestTraceEvent event) => _requestTraceObserver?.call(event); + /// SIMPLE SETTERS set userCoords(Coordinates value) { _userCoords = value; @@ -153,16 +364,10 @@ class ShuttleDataProvider extends ChangeNotifier { get error => _error; ShuttleStopModel? get closestStop => _closestStop; List get stopsToRender { - var stopsToRenderList = []; - final bool hasStops = fetchedStops != null; - final bool hasSelectedStops = userDataProvider?.userProfileModel.selectedStops != null; - if (hasStops && hasSelectedStops) { - for (var i = 0; i < userDataProvider!.userProfileModel.selectedStops!.length; i++) { - int stopID = userDataProvider!.userProfileModel.selectedStops![i]!; - if (fetchedStops![stopID] != null) stopsToRenderList.add(fetchedStops![stopID]!); - } - } - return stopsToRenderList; + if (fetchedStops == null) return []; + return _normalizedSelectedStopIds( + requireKnownStop: true, + ).map((stopId) => fetchedStops![stopId]!).toList(growable: false); } Map get stopsNotSelected { @@ -173,4 +378,21 @@ class ShuttleDataProvider extends ChangeNotifier { } return output; } + + List _normalizedSelectedStopIds({required bool requireKnownStop}) { + final selectedStopIds = userDataProvider?.userProfileModel.selectedStops ?? const []; + return _normalizeStopIds(selectedStopIds, requireKnownStop: requireKnownStop); + } + + List _normalizeStopIds(Iterable selectedStopIds, {required bool requireKnownStop}) { + final normalized = []; + final seen = {}; + for (final stopId in selectedStopIds) { + if (stopId == null || !seen.add(stopId)) continue; + if (requireKnownStop && !(fetchedStops?.containsKey(stopId) ?? false)) continue; + if (normalized.length == maxSelectedStops) break; + normalized.add(stopId); + } + return normalized; + } } diff --git a/lib/core/providers/student_id.dart b/lib/core/providers/student_id.dart index 4f39b5546..0ff28f6cf 100644 --- a/lib/core/providers/student_id.dart +++ b/lib/core/providers/student_id.dart @@ -17,6 +17,7 @@ class StudentIdDataProvider extends ChangeNotifier { final _profile = _StudentIdRequest(); final _photoMetadata = _StudentIdRequest(); final _image = _StudentIdRequest(); + final Set> _inflight = {}; StudentIdNameModel _studentIdNameModel = StudentIdNameModel(); StudentIdPhotoModel _studentIdPhotoModel = StudentIdPhotoModel(); StudentIdProfileModel _studentIdProfileModel = StudentIdProfileModel(); @@ -111,7 +112,7 @@ class StudentIdDataProvider extends ChangeNotifier { void _startName() { if (_name.loading) return; - unawaited( + _track( _loadApi(_name, () => _studentIdService.fetchStudentIdName(_headers), (replacement) { _studentIdNameModel = _studentIdNameModel.mergeValid(replacement); return replacement.displayName.isNotEmpty; @@ -121,7 +122,7 @@ class StudentIdDataProvider extends ChangeNotifier { void _startProfile() { if (_profile.loading) return; - unawaited( + _track( _loadApi(_profile, () => _studentIdService.fetchStudentIdProfile(_headers), (replacement) { _studentIdProfileModel = _studentIdProfileModel.mergeValid(replacement); return replacement.barcode.isNotEmpty; @@ -131,7 +132,7 @@ class StudentIdDataProvider extends ChangeNotifier { void _startPhotoMetadata() { if (isPhotoLoading) return; - unawaited( + _track( _loadApi(_photoMetadata, () => _studentIdService.fetchStudentIdPhoto(_headers), ( replacement, ) { @@ -164,7 +165,25 @@ class StudentIdDataProvider extends ChangeNotifier { void _startImage(String url, {bool refetchOnFailure = false}) { if (_image.loading) return; - unawaited(_loadImage(url, refetchOnFailure: refetchOnFailure)); + _track(_loadImage(url, refetchOnFailure: refetchOnFailure)); + } + + /// Track a fire-and-forget request so whenSettled() can observe it. + /// Tracked futures never complete with an error: _loadApi and _loadImage + /// catch everything internally, so no error handling is needed here. + void _track(Future future) { + _inflight.add(future); + unawaited(future.whenComplete(() => _inflight.remove(future))); + } + + /// Resolves when the current session's requests have all settled, including + /// requests they spawn mid-flight (metadata -> image, image failure -> metadata + /// refetch). Re-snapshots the set each round because those spawned futures are + /// added while earlier ones are still being awaited. + Future whenSettled() async { + while (_inflight.isNotEmpty && !_disposed) { + await Future.wait(_inflight.toList()); + } } Future _loadImage(String url, {required bool refetchOnFailure}) async { diff --git a/lib/core/providers/user.dart b/lib/core/providers/user.dart index cd707deeb..321cf3c9e 100644 --- a/lib/core/providers/user.dart +++ b/lib/core/providers/user.dart @@ -5,6 +5,7 @@ import 'package:campus_mobile_experimental/core/models/authentication.dart'; import 'package:campus_mobile_experimental/core/models/user_profile.dart'; import 'package:campus_mobile_experimental/core/providers/cards.dart'; import 'package:campus_mobile_experimental/core/providers/notifications.dart'; +import 'package:campus_mobile_experimental/core/providers/student_id.dart'; import 'package:campus_mobile_experimental/core/services/authentication.dart'; import 'package:campus_mobile_experimental/core/services/tgpt_services/chat_persistence.dart'; import 'package:campus_mobile_experimental/core/services/user.dart'; @@ -34,6 +35,7 @@ class UserDataProvider extends ChangeNotifier { /// PROVIDERS late PushNotificationDataProvider _pushNotificationDataProvider; late CardsDataProvider cardsDataProvider; + StudentIdDataProvider? studentIdDataProvider; /// SERVICES var _authenticationService = AuthenticationService(); diff --git a/lib/core/services/one_bus_away_client.dart b/lib/core/services/one_bus_away_client.dart new file mode 100644 index 000000000..bfb4019f5 --- /dev/null +++ b/lib/core/services/one_bus_away_client.dart @@ -0,0 +1,278 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:dio/dio.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle_request_trace.dart'; + +/// Names of the machine environment variables that hold the OneBusAway API +/// base endpoint and API key (MA-685). Values come from the machine environment, +/// Dart defines, or the app's loaded .env and must never be hardcoded, committed, or logged. +const String oneBusAwayApiEnvVar = 'ONE_BUS_AWAY_API'; +const String oneBusAwayApiKeyEnvVar = 'ONE_BUS_AWAY_API_KEY'; + +/// Compile-time fallbacks, populated via +/// `flutter run --dart-define=ONE_BUS_AWAY_API=...` for device builds where +/// machine environment variables are not propagated into the app process. +/// Like the environment variables, these values are never stored in code. +const String _oneBusAwayApiDartDefine = String.fromEnvironment(oneBusAwayApiEnvVar); +const String _oneBusAwayApiKeyDartDefine = String.fromEnvironment(oneBusAwayApiKeyEnvVar); + +String _readOneBusAwaySetting(String name, String dartDefine) { + final String? environmentValue = Platform.environment[name]; + if (environmentValue != null && environmentValue.trim().isNotEmpty) return environmentValue.trim(); + if (dartDefine.trim().isNotEmpty) return dartDefine.trim(); + return dotenv.isInitialized ? (dotenv.env[name] ?? '').trim() : ''; +} + +/// Sanitized error type for all OneBusAway failures. Messages never include +/// request URLs, which embed the API key as a query parameter. +class OneBusAwayException implements Exception { + const OneBusAwayException(this.message); + + final String message; + + @override + String toString() => message; +} + +/// Holds OneBusAway configuration from the environment, Dart defines, or .env. +/// +/// Explicit [apiEndpoint]/[apiKey] values (used by dependency injection and +/// tests) always take precedence over the environment. +class OneBusAwayConfig { + OneBusAwayConfig({String? apiEndpoint, String? apiKey}) + : apiEndpoint = (apiEndpoint ?? _readOneBusAwaySetting(oneBusAwayApiEnvVar, _oneBusAwayApiDartDefine)).trim(), + apiKey = (apiKey ?? _readOneBusAwaySetting(oneBusAwayApiKeyEnvVar, _oneBusAwayApiKeyDartDefine)).trim(); + + final String apiEndpoint; + final String apiKey; + + bool get isConfigured => apiEndpoint.isNotEmpty && apiKey.isNotEmpty; + + /// Redacted representation: the endpoint and key must never appear in logs. + @override + String toString() => 'OneBusAwayConfig(configured: $isConfigured)'; +} + +/// Thin REST client for the OneBusAway APIs used by the Transit feature. +/// +/// All responses use the standard OneBusAway envelope: +/// `{"code":200,"currentTime":...,"data":{...}}`. This client validates the +/// envelope and returns the decoded map to the caller for model mapping. +class OneBusAwayClient { + OneBusAwayClient({ + OneBusAwayConfig? config, + Dio? dio, + Duration? timeout, + ShuttleRequestTraceObserver? requestTraceObserver, + }) : _config = config ?? OneBusAwayConfig(), + _timeout = timeout ?? const Duration(seconds: 15), + _requestTraceObserver = requestTraceObserver { + _dio = dio ?? Dio(); + _dio.options.connectTimeout = _timeout; + _dio.options.receiveTimeout = _timeout; + _dio.options.responseType = ResponseType.plain; + } + + /// Agency whose stops power the campus Transit screen. + static const String defaultAgencyId = 'UCSD'; + + static const String _stopsForAgencyPathTemplate = '/api/where/stops-for-agency'; + static const String _arrivalsForStopPathTemplate = '/api/where/arrivals-and-departures-for-stop'; + + late final Dio _dio; + final OneBusAwayConfig _config; + final Duration _timeout; + final ShuttleRequestTraceObserver? _requestTraceObserver; + int _logicalRequestSequence = 0; + + /// Fetches all stops served by [agencyId] (the campus shuttle agency by + /// default). OneBusAway replaces the legacy shuttle stops feed with + /// `GET {base}/api/where/stops-for-agency/{agencyId}.json`. + Future> fetchStopsForAgency({ + String agencyId = defaultAgencyId, + ShuttleRequestContext? requestContext, + }) => _get( + '$_stopsForAgencyPathTemplate/$agencyId.json', + endpoint: ShuttleRequestEndpoint.catalog, + requestContext: requestContext, + ); + + /// Fetches upcoming arrivals and departures for [stopId] (the raw + /// OneBusAway stop id, e.g. `UCSD_10772`). OneBusAway replaces the legacy + /// arrivals feed with + /// `GET {base}/api/where/arrivals-and-departures-for-stop/{stopId}.json`. + Future> fetchArrivalsAndDeparturesForStop( + String stopId, { + ShuttleRequestContext? requestContext, + }) => _get( + '$_arrivalsForStopPathTemplate/' + Uri.encodeComponent(stopId) + '.json', + endpoint: ShuttleRequestEndpoint.arrivals, + stopId: stopId, + requestContext: requestContext, + ); + + /// Builds the request [Uri] for [path], attaching the API key as the + /// standard OneBusAway `key` query parameter. + Uri _buildUri(String path) { + final String base = _config.apiEndpoint.endsWith('/') + ? _config.apiEndpoint.substring(0, _config.apiEndpoint.length - 1) + : _config.apiEndpoint; + return Uri.parse('$base$path').replace(queryParameters: {'key': _config.apiKey}); + } + + Future> _get( + String path, { + required ShuttleRequestEndpoint endpoint, + String? stopId, + ShuttleRequestContext? requestContext, + }) { + final context = + requestContext ?? const ShuttleRequestContext(operationId: 0, trigger: ShuttleRequestTrigger.unspecified); + final logicalRequestId = ++_logicalRequestSequence; + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.logicalRequestStarted, + context: context, + endpoint: endpoint, + stopId: stopId, + logicalRequestId: logicalRequestId, + ), + ); + return _getAttempt( + path, + endpoint: endpoint, + stopId: stopId, + context: context, + logicalRequestId: logicalRequestId, + retryAttempt: 0, + ); + } + + Future> _getAttempt( + String path, { + required ShuttleRequestEndpoint endpoint, + required ShuttleRequestContext context, + required int logicalRequestId, + required int retryAttempt, + String? stopId, + }) async { + if (!_config.isConfigured) { + throw const OneBusAwayException( + 'The OneBusAway API is not configured. Set the ONE_BUS_AWAY_API and ' + 'ONE_BUS_AWAY_API_KEY in .env, environment variables, or --dart-define.', + ); + } + final attempt = retryAttempt + 1; + final stopwatch = Stopwatch()..start(); + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.httpAttemptStarted, + context: context, + endpoint: endpoint, + stopId: stopId, + logicalRequestId: logicalRequestId, + attempt: attempt, + ), + ); + try { + final Response response = await _dio.getUri(_buildUri(path)); + stopwatch.stop(); + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.httpAttemptSucceeded, + context: context, + endpoint: endpoint, + stopId: stopId, + logicalRequestId: logicalRequestId, + attempt: attempt, + statusCode: response.statusCode, + elapsed: stopwatch.elapsed, + ), + ); + final dynamic body = response.data; + final dynamic decoded = body is String ? jsonDecode(body) : body; + if (decoded is! Map) { + throw const OneBusAwayException('OneBusAway returned an unexpected JSON response shape.'); + } + final dynamic responseCode = decoded['code']; + if (responseCode is! num) { + throw const OneBusAwayException('OneBusAway response is missing a numeric status code.'); + } + final int code = responseCode.toInt(); + if (code != 200) { + throw OneBusAwayException('OneBusAway returned error code $code.'); + } + return decoded; + } on OneBusAwayException { + rethrow; + } on FormatException { + throw const OneBusAwayException('OneBusAway returned invalid JSON.'); + } on DioException catch (e) { + // Never surface the request URI: it contains the API key. + final int? status = e.response?.statusCode; + stopwatch.stop(); + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.httpAttemptFailed, + context: context, + endpoint: endpoint, + stopId: stopId, + logicalRequestId: logicalRequestId, + attempt: attempt, + statusCode: status, + elapsed: stopwatch.elapsed, + ), + ); + if (status == 429 && retryAttempt < 2) { + final retryDelay = _rateLimitRetryDelay(e.response, retryAttempt); + _emit( + ShuttleRequestTraceEvent( + kind: ShuttleRequestTraceKind.retryScheduled, + context: context, + endpoint: endpoint, + stopId: stopId, + logicalRequestId: logicalRequestId, + attempt: attempt, + statusCode: status, + retryDelay: retryDelay, + ), + ); + await Future.delayed(retryDelay); + return _getAttempt( + path, + endpoint: endpoint, + stopId: stopId, + context: context, + logicalRequestId: logicalRequestId, + retryAttempt: retryAttempt + 1, + ); + } + throw OneBusAwayException( + status == null ? 'Failed to reach the OneBusAway API.' : 'Failed to reach the OneBusAway API (HTTP $status).', + ); + } catch (_) { + // Deliberately discard the original error: network/parsing error text + // can embed the full request URL, which contains the API key. + throw const OneBusAwayException('Failed to process OneBusAway data.'); + } + } + + void _emit(ShuttleRequestTraceEvent event) => _requestTraceObserver?.call(event); + + Duration _rateLimitRetryDelay(Response? response, int retryAttempt) { + final String? retryAfter = response?.headers.value(HttpHeaders.retryAfterHeader); + final int? seconds = int.tryParse(retryAfter ?? ''); + if (seconds != null && seconds >= 0) return Duration(seconds: seconds); + if (retryAfter != null) { + try { + final delay = HttpDate.parse(retryAfter).difference(DateTime.now().toUtc()); + return delay.isNegative ? Duration.zero : delay; + } on FormatException { + // Use a short backoff when the server's retry instruction is invalid. + } + } + return Duration(seconds: 2 * (retryAttempt + 1)); + } +} diff --git a/lib/core/services/shuttle.dart b/lib/core/services/shuttle.dart index 511eb4f2e..40e40f4eb 100644 --- a/lib/core/services/shuttle.dart +++ b/lib/core/services/shuttle.dart @@ -1,75 +1,86 @@ -import 'dart:async'; -import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/shuttle_arrival.dart'; import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:campus_mobile_experimental/core/services/one_bus_away_client.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle_request_trace.dart'; + +/// Fetches campus transit data from the OneBusAway API (MA-685). +/// +/// Catalog failures remain available through [error]. Arrival failures are +/// returned with their stop's [ShuttleArrivalResult] instead of shared state: +/// - [fetchData] populates [data] with the available shuttle stops. +/// - [getArrivingInformation] returns arrivals and any stop-specific error +/// together. +class ShuttleArrivalResult { + const ShuttleArrivalResult({required this.arrivals, this.error}); + + final List arrivals; + final String? error; +} class ShuttleService { - ShuttleService(); + ShuttleService({OneBusAwayClient? client, ShuttleRequestTraceObserver? requestTraceObserver}) + : _client = client ?? OneBusAwayClient(requestTraceObserver: requestTraceObserver); /// STATES bool _isLoading = false; DateTime? _lastUpdated; - String? _error; - final Map headers = {"accept": "application/json"}; - - /// add state related things for view model here - /// add any type of data manipulation here so it can be accessed via provider + String? _catalogError; /// MODELS List _data = []; - Future fetchData() async { - _error = null; + /// Maps the integer stop ids used by the UI to the raw OneBusAway stop ids + /// (e.g. `10772` -> `UCSD_10772`) needed by the arrivals endpoint. + final Map _oneBusAwayStopIds = {}; + + final OneBusAwayClient _client; + + Future fetchData({ShuttleRequestContext? requestContext}) async { + _catalogError = null; _isLoading = true; try { - /// fetch data - String _response = await (NetworkHelper.authorizedFetch(dotenv.get('SHUTTLE_API_ENDPOINT'), headers)); + /// fetch data: all stops served by the campus shuttle agency + final Map envelope = await _client.fetchStopsForAgency(requestContext: requestContext); + // print('\x1B[32mstops-for-agency response:\n${const JsonEncoder.withIndent(' ').convert(envelope)}\x1B[0m'); /// parse data - var data = shuttleStopModelFromJson(_response); - _data = data; - // print fetched data to terminal in green (one line per stop with reset) - // for (var stop in _data) { - // print('\x1B[32mShuttleStop(id: ${stop.id}, name: ${stop.name}, lat: ${stop.lat}, lon: ${stop.lon})\x1B[0m'); - // } + _data = shuttleStopsFromOneBusAwayEnvelope(envelope); + _oneBusAwayStopIds.clear(); + for (final ShuttleStopModel stop in _data) { + final String? oneBusAwayId = stop.oneBusAwayId; + if (oneBusAwayId != null) _oneBusAwayStopIds[stop.id] = oneBusAwayId; + } return true; } catch (e) { - /// if the authorized fetch failed we know we have to refresh the - /// token for this service - if (e.toString().contains("401")) if (await NetworkHelper.getNewToken(headers)) return await fetchData(); - _error = e.toString(); + /// OneBusAway failures are wrapped in [OneBusAwayException] with + /// sanitized messages, so this is safe to expose to the UI. + _catalogError = e.toString(); return false; } finally { _isLoading = false; } } - Future> getArrivingInformation(stopId) async { - _error = null; + Future getArrivingInformation(stopId, {ShuttleRequestContext? requestContext}) async { _isLoading = true; + final String oneBusAwayStopId = _oneBusAwayStopIds[stopId] ?? stopId.toString(); try { - /// fetch data - String _response = await (NetworkHelper.authorizedFetch( - dotenv.get('SHUTTLE_API_ENDPOINT') + "/$stopId/arrivals", - headers, - )); + /// fetch data: arrivals for the raw OneBusAway stop id when known + final Map envelope = await _client.fetchArrivalsAndDeparturesForStop( + oneBusAwayStopId, + requestContext: requestContext, + ); + // print('\x1B[32marrivals-and-departures-for-stop ($oneBusAwayStopId) response:\n${const JsonEncoder.withIndent(' ').convert(envelope)}\x1B[0m',); - /// parse data - final arrivingData = getArrivingShuttles(_response); - // print arriving data to terminal in pink (one line per arrival with reset) - // for (var arrival in arrivingData) { - // print( - // '\x1B[35mArrivingShuttle(stopId: ${arrival.routeStopId}, routeId: ${arrival.routeId}, routeName: ${arrival.routeName}, routeColor: ${arrival.routeColor}, minutesToArrival: ${arrival.secondsToArrival / 60})\x1B[0m'); - // } - return arrivingData; + /// parse data: keep only the campus shuttle agency's routes, matching + /// the scope of the previous shuttle feed + return ShuttleArrivalResult( + arrivals: arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: OneBusAwayClient.defaultAgencyId), + ); } catch (e) { - /// if the authorized fetch failed we know we have to refresh the - /// token for this service - if (e.toString().contains("401")) - if (await NetworkHelper.getNewToken(headers)) return await getArrivingInformation(stopId); - _error = e.toString(); - return []; + /// OneBusAway failures are wrapped in [OneBusAwayException] with + /// sanitized messages, so this is safe to expose to the UI. + return ShuttleArrivalResult(arrivals: const [], error: e.toString()); } finally { _isLoading = false; } @@ -77,7 +88,7 @@ class ShuttleService { /// SIMPLE GETTERS get isLoading => _isLoading; - get error => _error; + get error => _catalogError; get lastUpdated => _lastUpdated; List get data => _data; } diff --git a/lib/core/services/shuttle_request_trace.dart b/lib/core/services/shuttle_request_trace.dart new file mode 100644 index 000000000..ff016faa3 --- /dev/null +++ b/lib/core/services/shuttle_request_trace.dart @@ -0,0 +1,69 @@ +import 'package:flutter/foundation.dart'; + +enum ShuttleRequestTrigger { startup, selectionChange, manualReload, unspecified } + +enum ShuttleRequestEndpoint { catalog, arrivals } + +enum ShuttleRequestTraceKind { + providerOperationStarted, + providerRequestStarted, + providerRequestJoined, + providerRequestSkipped, + providerResultDiscarded, + logicalRequestStarted, + httpAttemptStarted, + httpAttemptSucceeded, + httpAttemptFailed, + retryScheduled, +} + +class ShuttleRequestContext { + const ShuttleRequestContext({required this.operationId, required this.trigger}); + + final int operationId; + final ShuttleRequestTrigger trigger; +} + +class ShuttleRequestTraceEvent { + const ShuttleRequestTraceEvent({ + required this.kind, + required this.context, + this.endpoint, + this.stopId, + this.logicalRequestId, + this.attempt, + this.statusCode, + this.elapsed, + this.retryDelay, + }); + + final ShuttleRequestTraceKind kind; + final ShuttleRequestContext context; + final ShuttleRequestEndpoint? endpoint; + final String? stopId; + final int? logicalRequestId; + final int? attempt; + final int? statusCode; + final Duration? elapsed; + final Duration? retryDelay; + + @override + String toString() => + 'ShuttleRequestTraceEvent(' + 'kind: ${kind.name}, ' + 'operation: ${context.operationId}, ' + 'trigger: ${context.trigger.name}, ' + 'endpoint: ${endpoint?.name}, ' + 'stopId: $stopId, ' + 'logicalRequest: $logicalRequestId, ' + 'attempt: $attempt, ' + 'status: $statusCode, ' + 'elapsedMs: ${elapsed?.inMilliseconds}, ' + 'retryDelayMs: ${retryDelay?.inMilliseconds})'; +} + +typedef ShuttleRequestTraceObserver = void Function(ShuttleRequestTraceEvent event); + +void debugLogShuttleRequestTrace(ShuttleRequestTraceEvent event) { + if (kDebugMode) debugPrint(event.toString()); +} diff --git a/lib/core/utils/dining_search.dart b/lib/core/utils/dining_search.dart new file mode 100644 index 000000000..87a34ec06 --- /dev/null +++ b/lib/core/utils/dining_search.dart @@ -0,0 +1,127 @@ +import 'package:campus_mobile_experimental/core/models/dining.dart'; + +/// Searches [models] with the given [query] and returns the matching models in +/// relevance order. +/// +/// An empty or whitespace-only query returns [models] unchanged. This keeps the +/// provider's payment filtering and distance ordering intact. +List searchDiningModels(List models, String query) { + final String normalizedQuery = _normalizeText(query); + if (normalizedQuery.isEmpty) return models; + + final List queryTokens = normalizedQuery.split(' '); + final List<_ScoredDiningModel> scoredModels = []; + + for (final DiningModel model in models) { + final int? score = _scoreModel(model, queryTokens); + if (score != null) scoredModels.add(_ScoredDiningModel(model, score)); + } + + scoredModels.sort((a, b) { + final int scoreComparison = b.score.compareTo(a.score); + if (scoreComparison != 0) return scoreComparison; + + final int distanceComparison = _compareDistances(a.model, b.model); + if (distanceComparison != 0) return distanceComparison; + + return a.model.name.compareTo(b.model.name); + }); + + return scoredModels.map((scoredModel) => scoredModel.model).toList(); +} + +String _normalizeText(String? text) { + if (text == null || text.isEmpty) return ''; + + return text + .toLowerCase() + .replaceAll(RegExp(r'[^\p{L}\p{N}]+', unicode: true), ' ') + .trim() + .replaceAll(RegExp(r'\s+'), ' '); +} + +int? _scoreModel(DiningModel model, List queryTokens) { + final List<_SearchField> searchFields = _buildSearchFields(model); + int score = 0; + + for (final String queryToken in queryTokens) { + int tokenScore = 0; + + for (final _SearchField searchField in searchFields) { + if (_containsTokenPrefix(searchField.text, queryToken)) { + tokenScore = tokenScore < searchField.weight ? searchField.weight : tokenScore; + } + } + + if (tokenScore == 0) return null; + score += tokenScore; + } + + if (_containsPhrase(searchFields, queryTokens)) score += 1; + return score; +} + +List<_SearchField> _buildSearchFields(DiningModel model) => [ + _SearchField(_normalizeText(model.name), 4), + _SearchField(_normalizeText([...model.paymentOptions, model.paymentFilterTypes].join(' ')), 2), + _SearchField(_normalizeText(model.specialHours?.specialHoursEvent), 2), + _SearchField(_normalizeText(model.specials?.specialTitle), 2), + _SearchField(_normalizeText(model.location), 3), + _SearchField(_normalizeText(model.address), 3), + _SearchField(_normalizeText(model.meals == null ? null : mealsValues.reverse[model.meals!]), 3), + _SearchField(_normalizeText(model.description), 1), + _SearchField(_normalizeText(model.specialHours?.specialHoursEventDetails), 1), + _SearchField(_normalizeText(model.specials?.specialDescription), 1), +]; + +bool _containsTokenPrefix(String fieldText, String queryToken) { + if (fieldText.isEmpty) return false; + + for (final String fieldToken in fieldText.split(' ')) { + if (fieldToken.startsWith(queryToken)) return true; + } + return false; +} + +bool _containsPhrase(List<_SearchField> searchFields, List queryTokens) { + for (final _SearchField searchField in searchFields) { + final List fieldTokens = searchField.text.split(' '); + for (int start = 0; start + queryTokens.length <= fieldTokens.length; start++) { + bool matches = true; + + for (int offset = 0; offset < queryTokens.length; offset++) { + if (fieldTokens[start + offset] != queryTokens[offset]) { + matches = false; + break; + } + } + + if (matches) return true; + } + } + return false; +} + +int _compareDistances(DiningModel a, DiningModel b) { + final bool aHasDistance = a.distance != null; + final bool bHasDistance = b.distance != null; + + if (aHasDistance && bHasDistance) return a.distance!.compareTo(b.distance!); + if (aHasDistance) return -1; + if (bHasDistance) return 1; + return 0; +} + +class _ScoredDiningModel { + const _ScoredDiningModel(this.model, this.score); + + final DiningModel model; + final int score; +} + +class _SearchField { + const _SearchField(this.text, this.weight); + + final String text; + final int weight; +} diff --git a/lib/ui/availability/availability_card.dart b/lib/ui/availability/availability_card.dart index df3b69b20..e1d11e4a5 100644 --- a/lib/ui/availability/availability_card.dart +++ b/lib/ui/availability/availability_card.dart @@ -1,13 +1,17 @@ +import 'dart:async'; + import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/app_provider.dart'; import 'package:campus_mobile_experimental/app_styles.dart'; import 'package:campus_mobile_experimental/core/models/availability.dart'; import 'package:campus_mobile_experimental/core/providers/availability.dart'; +import 'package:campus_mobile_experimental/core/providers/bottom_nav.dart'; import 'package:campus_mobile_experimental/core/providers/cards.dart'; import 'package:campus_mobile_experimental/ui/availability/availability_constants.dart'; import 'package:campus_mobile_experimental/ui/availability/availability_display.dart'; import 'package:campus_mobile_experimental/ui/common/action_link.dart'; import 'package:campus_mobile_experimental/ui/common/card_container.dart'; +import 'package:campus_mobile_experimental/ui/common/last_updated_widget.dart'; import 'package:dots_indicator/dots_indicator.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -19,18 +23,76 @@ class AvailabilityCard extends StatefulWidget { _AvailabilityCardState createState() => _AvailabilityCardState(); } -class _AvailabilityCardState extends State { +class _AvailabilityCardState extends State with WidgetsBindingObserver { + static const _refreshInterval = Duration(seconds: 90); + /// PROVIDERS late AvailabilityDataProvider _availabilityDataProvider; + late CardsDataProvider _cardsDataProvider; + late BottomNavigationBarProvider _bottomNavigationBarProvider; /// SERVICES final _controller = PageController(); int _currentPage = 0; + Timer? _timer; + AppLifecycleState? _lifecycleState; + + @override + void initState() { + super.initState(); + _lifecycleState = WidgetsBinding.instance.lifecycleState; + WidgetsBinding.instance.addObserver(this); + } @override void didChangeDependencies() { super.didChangeDependencies(); _availabilityDataProvider = Provider.of(context); + _cardsDataProvider = Provider.of(context); + _bottomNavigationBarProvider = Provider.of(context); + _updatePolling(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + _lifecycleState = state; + _updatePolling(); + } + + bool get _isActive => + mounted && + (_cardsDataProvider.cardStates[cardId] ?? false) && + _bottomNavigationBarProvider.currentIndex == NavigatorConstants.HOME_TAB && + _lifecycleState == AppLifecycleState.resumed; + + void _updatePolling() { + if (!_isActive) { + _timer?.cancel(); + _timer = null; + return; + } + if (_timer != null) return; + final timer = _timer = Timer.periodic(_refreshInterval, (_) { + if (_isActive) _availabilityDataProvider.fetchAvailability(silent: true); + }); + + // Defer fetching until after build so provider notifications are safe. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!_isActive || _timer != timer) return; + final lastUpdated = _availabilityDataProvider.lastUpdated; + if (lastUpdated == null || DateTime.now().difference(lastUpdated) >= _refreshInterval) { + _availabilityDataProvider.fetchAvailability(silent: true); + } + }); + WidgetsBinding.instance.ensureVisualUpdate(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _timer?.cancel(); + _controller.dispose(); + super.dispose(); } @override @@ -53,14 +115,41 @@ class _AvailabilityCardState extends State { errorText: _availabilityDataProvider.error, child: () => buildAvailabilityCard(_availabilityDataProvider.availabilityModels), actionButtons: [ - ActionLink( - buttonText: 'MANAGE LOCATIONS', - onPressed: () { - analytics.logEvent(name: '${cardId}_card_action', parameters: {'action': 'manage'}); - Navigator.pushNamed(context, RoutePaths.MANAGE_AVAILABILITY_VIEW); - }, + Flexible( + child: ActionLink( + buttonText: 'MANAGE LOCATIONS', + onPressed: () { + analytics.logEvent(name: '${cardId}_card_action', parameters: {'action': 'manage'}); + Navigator.pushNamed(context, RoutePaths.MANAGE_AVAILABILITY_VIEW); + }, + ), ), ], + footer: _availabilityDataProvider.lastUpdated == null + ? null + : Padding( + padding: const EdgeInsets.only(left: 24, right: 24, bottom: 16), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LastUpdatedWidget(time: _availabilityDataProvider.lastUpdated!), + if (_availabilityDataProvider.refreshFailed) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + 'Unable to refresh. Showing last available data.', + style: Theme.of(context).brightness == Brightness.dark + ? descriptiveTextSmallDark + : descriptiveTextSmallLight, + ), + ), + ], + ), + ), + ), ); } diff --git a/lib/ui/classes/classes_card.dart b/lib/ui/classes/classes_card.dart index beeb8dacf..da4dacdb2 100644 --- a/lib/ui/classes/classes_card.dart +++ b/lib/ui/classes/classes_card.dart @@ -14,7 +14,18 @@ import 'package:campus_mobile_experimental/ui/common/action_button.dart'; const cardId = 'schedule'; -class ClassScheduleCard extends StatelessWidget { +class ClassScheduleCard extends StatefulWidget { + @override + State createState() => _ClassScheduleCardState(); +} + +class _ClassScheduleCardState extends State { + @override + void initState() { + super.initState(); + context.read().loadFromCache(); + } + @override Widget build(BuildContext context) { return CardContainer( @@ -26,9 +37,12 @@ class ClassScheduleCard extends StatelessWidget { if (isLoading) return null; else - Provider.of(context, listen: false).fetchData(); + Provider.of(context, listen: false).reload(cardId); }, - isLoading: Provider.of(context).isLoading, + isLoading: + Provider.of(context).isRefreshing(cardId) || + (Provider.of(context).isLoading && + !Provider.of(context).hasData), titleText: CardTitleConstants.TITLE_MAP[cardId]!, errorText: Provider.of(context).error, child: () => buildClassScheduleCard( diff --git a/lib/ui/common/card_container.dart b/lib/ui/common/card_container.dart index d03508a78..1a3588295 100644 --- a/lib/ui/common/card_container.dart +++ b/lib/ui/common/card_container.dart @@ -122,12 +122,7 @@ class CardContainer extends StatelessWidget { child: child(), ); } else if (titleText == "SHUTTLE") { - // web cards are still sized with static values - return Container( - width: double.infinity, - constraints: BoxConstraints(minHeight: cardMinHeight, maxHeight: 375), - child: child(), - ); + return Container(width: double.infinity, child: child()); } else if (titleText == "PARKING") { double _maxHeight = 320; if (MediaQuery.of(context).size.width > 600) _maxHeight = 800; @@ -151,37 +146,13 @@ class CardContainer extends StatelessWidget { ); } - Widget buildMenuOptions(Map menuOptions) { - List> menu = []; - - menuOptions.forEach((menuOption, func) { - Widget item = DropdownMenuItem( - value: menuOption, - child: Text( - menuOption, - textAlign: TextAlign.center, - style: TextStyle(color: dotsUnselectedColor), - ), - ); - menu.add(item as DropdownMenuItem); - }); - - return Semantics( - label: '$titleText Card Menu', - button: true, - child: DropdownButton( - items: menu, - iconSize: 36, - iconEnabledColor: dotsUnselectedColor, - underline: Container(), - icon: Transform.translate( - offset: Offset(6, -3), - child: Icon(Icons.more_vert, color: dotsUnselectedColor, semanticLabel: '$titleText Card Menu'), - ), - onChanged: (String? selectedMenuItem) => onMenuItemPressed(selectedMenuItem), - ), - ); - } + Widget buildMenuOptions(Map menuOptions) => PopupMenuButton( + tooltip: '$titleText Card Menu', + icon: Icon(Icons.more_vert, size: 36, color: dotsUnselectedColor), + onSelected: onMenuItemPressed, + itemBuilder: (_) => + menuOptions.keys.map((option) => PopupMenuItem(value: option, child: Text(option))).toList(), + ); void onMenuItemPressed(String? selectedMenuItem) { switch (selectedMenuItem) { diff --git a/lib/ui/common/card_header.dart b/lib/ui/common/card_header.dart index c8f0e6f77..f436fb6dc 100644 --- a/lib/ui/common/card_header.dart +++ b/lib/ui/common/card_header.dart @@ -16,30 +16,36 @@ class CardHeader extends StatelessWidget { Widget build(BuildContext context) { return Padding( padding: padding, - child: Semantics( - explicitChildNodes: true, - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - child: Align( - alignment: Alignment.centerLeft, - child: Focus( - child: Semantics( - container: true, - header: true, - focusable: true, - child: Text( - titleText, - style: Theme.of(context).textTheme.titleLarge, - semanticsLabel: '$titleText Card', + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 48), + child: Semantics( + explicitChildNodes: true, + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Focus( + child: Semantics( + container: true, + header: true, + focusable: true, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Text( + titleText, + style: Theme.of(context).textTheme.titleLarge, + semanticsLabel: '$titleText Card', + ), + ), ), ), ), ), - ), - trailing, - ], + trailing, + ], + ), ), ), ); diff --git a/lib/ui/common/last_updated_widget.dart b/lib/ui/common/last_updated_widget.dart index 8747da399..fb7866415 100644 --- a/lib/ui/common/last_updated_widget.dart +++ b/lib/ui/common/last_updated_widget.dart @@ -11,12 +11,12 @@ class LastUpdatedWidget extends StatelessWidget { Widget build(BuildContext context) { return Container( child: Text( - 'Last updated: ' + determineText(time), + 'Last Updated: ' + determineText(time), style: TextStyle( fontSize: 16.0, fontStyle: FontStyle.italic, fontWeight: FontWeight.w400, - color: descriptiveTextColorLight, + color: Theme.of(context).brightness == Brightness.dark ? descriptiveTextColorDark : descriptiveTextColorLight, ), ), ); diff --git a/lib/ui/dining/dining_list.dart b/lib/ui/dining/dining_list.dart index 6b56e828b..a2dcd0d4b 100644 --- a/lib/ui/dining/dining_list.dart +++ b/lib/ui/dining/dining_list.dart @@ -2,6 +2,7 @@ import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/app_styles.dart'; import 'package:campus_mobile_experimental/core/models/dining.dart' as dining_model; import 'package:campus_mobile_experimental/core/providers/dining.dart'; +import 'package:campus_mobile_experimental/core/utils/dining_search.dart'; import 'package:campus_mobile_experimental/ui/common/container_view.dart'; import 'package:campus_mobile_experimental/ui/common/directions_helper.dart'; import 'package:campus_mobile_experimental/ui/common/time_range_widget.dart'; @@ -9,15 +10,34 @@ import 'package:campus_mobile_experimental/ui/dining/payment_filter_button.dart' import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -class DiningList extends StatelessWidget { - const DiningList({Key? key, this.listSize}) : super(key: key); +class DiningList extends StatefulWidget { + const DiningList({Key? key, this.listSize, this.showSearch = false}) : super(key: key); final listSize; + final bool showSearch; + + @override + State createState() => _DiningListState(); +} + +class _DiningListState extends State { + final TextEditingController _searchController = TextEditingController(); + final FocusNode _searchFocus = FocusNode(); + String _searchQuery = ''; + + @override + void dispose() { + _searchController.dispose(); + _searchFocus.dispose(); + super.dispose(); + } @override Widget build(BuildContext context) { // Using Provider's filteredDiningModels so that the list respects the filters List data = Provider.of(context).filteredDiningModels; + List searchedData = searchDiningModels(data, _searchQuery); + if (data.isEmpty) { return ContainerView( child: ListView( @@ -34,7 +54,8 @@ class DiningList extends StatelessWidget { ), ); } - return buildDiningList(data, context); + + return buildDiningList(searchedData, context); } Widget buildDiningList(List listOfDiners, BuildContext context) { @@ -43,14 +64,14 @@ class DiningList extends StatelessWidget { /// check to see if we want to display only a limited number of elements /// if no constraint is given on the size of the list then all elements /// are rendered - var size = listSize ?? listOfDiners.length; + var size = widget.listSize ?? listOfDiners.length; for (var i = 0; i < size; i++) { final dining_model.DiningModel item = listOfDiners[i]; final tile = buildDiningTile(item, context); diningTiles.add(tile); } - return listSize != null + return widget.listSize != null ? ListView( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, @@ -68,13 +89,26 @@ class DiningList extends StatelessWidget { child: ListView( padding: const EdgeInsets.only(left: 16, right: 16), shrinkWrap: true, - children: ListTile.divideTiles( - tiles: diningTiles, - context: context, - color: Theme.of(context).brightness == Brightness.dark - ? listTileDividerColorDark - : listTileDividerColorLight, - ).toList(), + children: [ + if (widget.showSearch) buildSearchField(context), + if (listOfDiners.isEmpty) + Padding( + padding: const EdgeInsets.only(top: 16), + child: Text( + 'No dining locations match your search.', + style: Theme.of(context).textTheme.bodyLarge, + textAlign: TextAlign.center, + ), + ) + else + ...ListTile.divideTiles( + tiles: diningTiles, + context: context, + color: Theme.of(context).brightness == Brightness.dark + ? listTileDividerColorDark + : listTileDividerColorLight, + ), + ], ), ), Positioned(bottom: 24, right: 24, child: PaymentFilterButton()), @@ -82,6 +116,55 @@ class DiningList extends StatelessWidget { ); } + Widget buildSearchField(BuildContext context) => Padding( + padding: const EdgeInsets.only(bottom: 16, top: 16), + child: TextField( + controller: _searchController, + focusNode: _searchFocus, + textInputAction: TextInputAction.search, + decoration: InputDecoration( + hintText: 'Search dining locations', + prefixIcon: Icon( + Icons.search, + color: Theme.of(context).brightness == Brightness.dark ? listTileDividerColorDark : listTileDividerColorLight, + ), + suffixIcon: _searchQuery.isEmpty + ? null + : IconButton( + icon: Icon( + Icons.clear, + color: Theme.of(context).brightness == Brightness.dark + ? listTileDividerColorDark + : listTileDividerColorLight, + ), + tooltip: 'Clear search', + onPressed: () { + _searchController.clear(); + _updateSearchQuery(''); + }, + ), + border: WidgetStateInputBorder.resolveWith( + (states) => OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide( + color: Theme.of(context).brightness == Brightness.dark + ? listTileDividerColorDark + : listTileDividerColorLight, + ), + ), + ), + ), + onChanged: _updateSearchQuery, + ), + ); + + void _updateSearchQuery(String query) { + if (query == _searchQuery) return; + setState(() { + _searchQuery = query; + }); + } + Widget textClosed(BuildContext context, {String? nextOpenDay, String? nextOpenTime}) { String closedText = 'Closed'; if (nextOpenDay != null && nextOpenTime != null) closedText += '. Opens $nextOpenDay at $nextOpenTime.'; diff --git a/lib/ui/finals/finals_card.dart b/lib/ui/finals/finals_card.dart index 306f7d16f..9dccea648 100644 --- a/lib/ui/finals/finals_card.dart +++ b/lib/ui/finals/finals_card.dart @@ -11,7 +11,18 @@ import 'package:campus_mobile_experimental/app_styles.dart'; const cardId = 'finals'; -class FinalsCard extends StatelessWidget { +class FinalsCard extends StatefulWidget { + @override + State createState() => _FinalsCardState(); +} + +class _FinalsCardState extends State { + @override + void initState() { + super.initState(); + context.read().loadFromCache(); + } + @override Widget build(BuildContext context) { return CardContainer( @@ -23,10 +34,13 @@ class FinalsCard extends StatelessWidget { if (isLoading) { return null; } else { - Provider.of(context, listen: false).fetchData(); + Provider.of(context, listen: false).reload(cardId); } }, - isLoading: Provider.of(context).isLoading, + isLoading: + Provider.of(context).isRefreshing(cardId) || + (Provider.of(context).isLoading && + !Provider.of(context).hasData), titleText: CardTitleConstants.TITLE_MAP[cardId]!, errorText: Provider.of(context).error, child: () => buildFinalsCard( diff --git a/lib/ui/home/home.dart b/lib/ui/home/home.dart index d1ceefa30..013dbe504 100644 --- a/lib/ui/home/home.dart +++ b/lib/ui/home/home.dart @@ -16,6 +16,7 @@ import 'package:campus_mobile_experimental/ui/dining/dining_card.dart'; import 'package:campus_mobile_experimental/ui/employee_id/employee_id_card.dart'; import 'package:campus_mobile_experimental/ui/events/events_card.dart'; import 'package:campus_mobile_experimental/ui/finals/finals_card.dart'; +import 'package:campus_mobile_experimental/ui/home/home_background.dart'; import 'package:campus_mobile_experimental/ui/my_student_chart/my_student_chart_card.dart'; import 'package:campus_mobile_experimental/ui/my_ucsd_chart/my_ucsd_chart_card.dart'; import 'package:campus_mobile_experimental/ui/navigator/bottom.dart'; @@ -139,13 +140,17 @@ class _HomeState extends State { Widget build(BuildContext context) { // Provider.of(context).changeTitle(null); // reset title to logo (for dining) _connectivityProvider = Provider.of(context); - return Padding( - padding: const EdgeInsets.symmetric(horizontal: cardMargin, vertical: 0.0), - child: ListView( - controller: _controller, - padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: cardMargin + 2.0, left: 0.0), - children: createList(), - ), + return CustomScrollView( + controller: _controller, + slivers: [ + DecoratedSliver( + decoration: const HomeBackgroundDecoration(), + sliver: SliverPadding( + padding: const EdgeInsets.only(left: cardMargin, right: cardMargin, bottom: cardMargin + 2.0), + sliver: SliverList(delegate: SliverChildListDelegate(createList())), + ), + ), + ], ); } diff --git a/lib/ui/home/home_background.dart b/lib/ui/home/home_background.dart new file mode 100644 index 000000000..9bb1e3263 --- /dev/null +++ b/lib/ui/home/home_background.dart @@ -0,0 +1,105 @@ +import 'package:flutter/material.dart'; + +/// Paints the existing circles without adding height or mounting card widgets. +class HomeBackgroundDecoration extends Decoration { + const HomeBackgroundDecoration(); + + @override + BoxPainter createBoxPainter([VoidCallback? onChanged]) => _HomeBackgroundPainter(onChanged); +} + +class _HomeBackgroundPainter extends BoxPainter { + _HomeBackgroundPainter(super.onChanged); + + static const _circles = [ + ( + asset: 'assets/images/circles/circle-1-background.png', + top: 355.0, + x: -101.0, + fromRight: true, + size: Size(298.64, 280), + ), + ( + asset: 'assets/images/circles/circle-2-background.png', + top: 720.0, + x: -64.0, + fromRight: false, + size: Size(136, 136), + ), + ( + asset: 'assets/images/circles/circle-4-background.png', + top: 1065.0, + // Preserve the left: 190 crop at a 390-pixel reference width. + x: -199.7, + fromRight: true, + size: Size(399.7, 398), + ), + ( + asset: 'assets/images/circles/circle-5-background.png', + top: 1908.0, + x: -88.0, + fromRight: false, + size: Size(197, 197), + ), + ( + asset: 'assets/images/circles/circle-6-background.png', + top: 2585.0, + x: -21.0, + fromRight: true, + size: Size(188, 188), + ), + ( + asset: 'assets/images/circles/circle-3-background.png', + top: 3392.0, + x: -142.0, + fromRight: false, + size: Size(300, 298.6), + ), + ]; + + List _painters = []; + double? _devicePixelRatio; + + @override + void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { + final pixelRatio = configuration.devicePixelRatio ?? 1; + if (_devicePixelRatio != pixelRatio) { + for (final painter in _painters) { + painter.dispose(); + } + _devicePixelRatio = pixelRatio; + _painters = [ + for (final circle in _circles) + BoxDecoration( + image: DecorationImage( + image: ResizeImage( + AssetImage(circle.asset), + width: (circle.size.width * pixelRatio).ceil(), + height: (circle.size.height * pixelRatio).ceil(), + policy: ResizeImagePolicy.fit, + ), + fit: BoxFit.contain, + ), + ).createBoxPainter(onChanged), + ]; + } + final size = configuration.size!; + canvas.save(); + // The sliver supplies content bounds and a paint offset that follows scroll. + canvas.clipRect(offset & size); + for (var index = 0; index < _circles.length; index++) { + final circle = _circles[index]; + final left = circle.fromRight ? size.width - circle.x - circle.size.width : circle.x; + _painters[index].paint(canvas, offset + Offset(left, circle.top), configuration.copyWith(size: circle.size)); + } + canvas.restore(); + } + + @override + void dispose() { + for (final painter in _painters) { + painter.dispose(); + } + super.dispose(); + } +} diff --git a/lib/ui/map/map.dart b/lib/ui/map/map.dart index 2b53ca892..bd188dd66 100644 --- a/lib/ui/map/map.dart +++ b/lib/ui/map/map.dart @@ -12,7 +12,33 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:provider/provider.dart'; import 'package:app_links/app_links.dart'; -class Maps extends StatelessWidget { +class Maps extends StatefulWidget { + @override + State createState() => _MapsState(); +} + +class _MapsState extends State { + StreamSubscription? _linkSubscription; + bool _mapInitialized = false; + bool _mapReady = false; + + @override + void initState() { + super.initState(); + // Warm the native map after the app has laid out its full viewport. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + setState(() => _mapInitialized = true); + initUniLinks(); + }); + } + + @override + void dispose() { + _linkSubscription?.cancel(); + super.dispose(); + } + Widget resultsList(BuildContext context) => Provider.of(context).markers.isNotEmpty ? MoreResultsList() : const SizedBox.shrink(); @@ -33,53 +59,59 @@ class Maps extends StatelessWidget { ); } - Future initUniLinks(BuildContext context) async { + Future initUniLinks() async { final appLinks = AppLinks(); - StreamSubscription? _sub; - - Uri? initialUri = await appLinks.getInitialAppLink(); - String? initialLink = initialUri?.toString(); - final bool hasInitialLink = initialLink != null; - final bool isSearchMapLink = hasInitialLink && initialLink.contains("deeplinking.searchmap"); - if (hasInitialLink && isSearchMapLink) { - var uri = Uri.dataFromString(initialLink); - var query = uri.queryParameters['query']!; - Provider.of(context, listen: false).searchBarController.text = query; - Provider.of(context, listen: false).fetchLocations(); - Provider.of(context, listen: false).currentIndex = NavigatorConstants.MAP_TAB; - } + final initialUri = await appLinks.getInitialAppLink(); + if (!mounted) return; + _handleMapLink(initialUri); + _linkSubscription = appLinks.uriLinkStream.listen(_handleMapLink); + } - _sub = appLinks.uriLinkStream.listen((Uri? uri) async { - String? link = uri?.toString(); - final bool hasLink = link != null; - final bool isSearchMapLink = hasLink && link.contains("deeplinking.searchmap"); - if (hasLink && isSearchMapLink) { - var query = uri!.queryParameters['query']!; - Provider.of(context, listen: false).searchBarController.text = query; - Provider.of(context, listen: false).fetchLocations(); - Provider.of(context, listen: false).currentIndex = NavigatorConstants.MAP_TAB; - _sub?.cancel(); - } - }); + void _handleMapLink(Uri? uri) { + if (!mounted || uri == null || !uri.toString().contains('deeplinking.searchmap')) return; + final query = uri.queryParameters['query']; + if (query == null) return; + final mapsProvider = context.read(); + mapsProvider.searchBarController.text = query; + mapsProvider.fetchLocations(); + context.read().currentIndex = NavigatorConstants.MAP_TAB; } @override Widget build(BuildContext context) { - initUniLinks(context); + final isMapTab = context.select( + (provider) => provider.currentIndex == NavigatorConstants.MAP_TAB, + ); return Stack( + fit: StackFit.expand, children: [ - GoogleMap( - markers: Set.of(Provider.of(context).markers.values), - myLocationEnabled: true, - myLocationButtonEnabled: false, - mapToolbarEnabled: false, - zoomControlsEnabled: false, - onMapCreated: (controller) { - Provider.of(context, listen: false).mapController = controller; - }, - initialCameraPosition: CameraPosition(target: const LatLng(32.8801, -117.2341), zoom: 14.5), + // Reserve the full viewport even before the native map is created. + Positioned.fill( + child: _mapInitialized + ? GoogleMap( + markers: Set.of(Provider.of(context).markers.values), + myLocationEnabled: true, + myLocationButtonEnabled: false, + mapToolbarEnabled: false, + zoomControlsEnabled: false, + onMapCreated: (controller) { + if (!mounted) return; + final mapsProvider = context.read(); + mapsProvider.mapController = controller; + mapsProvider.updateMapPosition(); + setState(() => _mapReady = true); + }, + initialCameraPosition: CameraPosition(target: const LatLng(32.8801, -117.2341), zoom: 14.5), + ) + : const SizedBox.expand(), ), - MapSearchBarPlaceHolder(), + if (isMapTab && !_mapReady) + const Positioned.fill( + child: IgnorePointer( + child: Center(child: CircularProgressIndicator(semanticsLabel: 'Loading map')), + ), + ), + const Positioned(top: 0, left: 0, right: 0, child: MapSearchBarPlaceHolder()), buildButtons(context), resultsList(context), const MapSearchFeedback(), diff --git a/lib/ui/notices/notices_card.dart b/lib/ui/notices/notices_card.dart index d0abcb046..2b395ec27 100644 --- a/lib/ui/notices/notices_card.dart +++ b/lib/ui/notices/notices_card.dart @@ -36,7 +36,7 @@ class NoticesCard extends StatelessWidget { onTap: () { openLink(notice.link); }, - child: ImageLoader(url: notice.imageUrl, fullSize: true), + child: ImageLoader(url: notice.imageUrl, fullSize: true, fit: BoxFit.fitWidth), ), ); } diff --git a/lib/ui/notifications/notifications_freefood.dart b/lib/ui/notifications/notifications_freefood.dart index 8758c4089..eeec65a27 100644 --- a/lib/ui/notifications/notifications_freefood.dart +++ b/lib/ui/notifications/notifications_freefood.dart @@ -58,7 +58,7 @@ class _CheckBoxButtonState extends State { children: [ Expanded( child: Container( - height: 40, + constraints: const BoxConstraints(minHeight: 40), child: AnimatedCrossFade( duration: Duration(milliseconds: 300), crossFadeState: isOverCount ? CrossFadeState.showFirst : CrossFadeState.showSecond, @@ -84,7 +84,7 @@ class _CheckBoxButtonState extends State { ), ), ), - _checkBoxButton(), + Flexible(child: _checkBoxButton()), ], mainAxisAlignment: MainAxisAlignment.spaceBetween, ), @@ -94,7 +94,7 @@ class _CheckBoxButtonState extends State { Widget _checkBoxButton() { return Container( height: 23, - width: 100, + constraints: const BoxConstraints(maxWidth: 100), decoration: BoxDecoration( border: Border.all(width: 1.0, color: _borderColor), borderRadius: BorderRadius.all(Radius.circular(2.0)), @@ -133,7 +133,14 @@ class _CheckBoxButtonState extends State { ), ), ), - Text("I'm Going!", style: TextStyle(color: _textColor, fontSize: 12)), + Flexible( + child: Text( + "I'm Going!", + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: _textColor, fontSize: 12), + ), + ), ], ), ), diff --git a/lib/ui/onboarding/onboarding_login.dart b/lib/ui/onboarding/onboarding_login.dart index b5cf44e02..0bc52e479 100644 --- a/lib/ui/onboarding/onboarding_login.dart +++ b/lib/ui/onboarding/onboarding_login.dart @@ -1,3 +1,4 @@ +import 'dart:math' as math; import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/app_styles.dart'; import 'package:campus_mobile_experimental/core/providers/user.dart'; @@ -22,8 +23,28 @@ class _OnboardingLoginState extends State { final _emailTextFieldController = TextEditingController(); final _passwordTextFieldController = TextEditingController(); - late final _screenWidth = MediaQuery.sizeOf(context).width; - late final _screenHeight = MediaQuery.sizeOf(context).height; + static const _CONTENT_WIDTH_FACTOR = 0.74444444; + static const _SIGN_IN_BUTTON_WIDTH_FACTOR = 0.24111111; + static const _SIGN_IN_BUTTON_ASPECT = 2.29268293; + static const _HEADING_FONT_FLOOR = 34.5; + static const _HEADING_FONT_FACTOR = 0.077; + static const _BODY_FONT_FLOOR = 18.0; + static const _BODY_FONT_FACTOR = 0.0402; + static const _FOOTER_FONT_FLOOR = 15.5; + static const _FOOTER_FONT_FACTOR = 0.0346; + static const _SKIP_FONT_FLOOR = 16.5; + static const _SKIP_FONT_FACTOR = 0.0368; + + double _contentUnit(double width, double usableHeight) { + final cap = width < 600 + ? 480.0 + : width < 900 + ? 560.0 + : width < 1200 + ? 620.0 + : 680.0; + return math.min(width, math.min(usableHeight / 1.6, cap)); + } @override void didChangeDependencies() { @@ -43,6 +64,7 @@ class _OnboardingLoginState extends State { systemNavigationBarIconBrightness: Brightness.dark, ), child: Scaffold( + resizeToAvoidBottomInset: true, backgroundColor: lightOnboardingScreen, body: _userDataProvider.isLoading ? const Center( @@ -50,22 +72,36 @@ class _OnboardingLoginState extends State { valueColor: const AlwaysStoppedAnimation(darkAccentColor), ), ) - : SingleChildScrollView( - child: Container( - height: _screenHeight, - decoration: const BoxDecoration( - image: const DecorationImage( - image: const AssetImage("assets/images/login-background.png"), - fit: BoxFit.cover, // Ensure the image covers the entire screen + : MediaQuery.withClampedTextScaling( + maxScaleFactor: 1.3, + child: Stack( + children: [ + Positioned.fill(child: Image.asset('assets/images/login-background.png', fit: BoxFit.cover)), + SafeArea( + child: LayoutBuilder( + builder: (context, constraints) { + final size = MediaQuery.sizeOf(context); + final viewPadding = MediaQuery.viewPaddingOf(context); + final usableHeight = size.height - viewPadding.top - viewPadding.bottom; + final u = _contentUnit(constraints.maxWidth, usableHeight); + return SingleChildScrollView( + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight, maxWidth: u), + child: IntrinsicHeight(child: _buildLoginWidget(u)), + ), + ), + ); + }, + ), ), - ), - child: SafeArea(child: _buildLoginWidget()), + ], ), ), ), ); - Widget _buildLoginWidget() => Center( + Widget _buildLoginWidget(double u) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, // Align items at the top crossAxisAlignment: CrossAxisAlignment.center, // Center items horizontally @@ -80,19 +116,19 @@ class _OnboardingLoginState extends State { child: Image.asset('assets/images/UCSanDiegoLogo-Blue.png'), ), ), - const SizedBox(height: 44.0), + SizedBox(height: math.max(44.0, 0.0982 * u)), // Welcome Heading - const Flexible( + Flexible( flex: 0, - child: const FractionallySizedBox( + child: FractionallySizedBox( widthFactor: 0.725, - child: const Text( + child: Text( "WELCOME TO THE UC SAN DIEGO MOBILE APP", textAlign: TextAlign.center, - style: const TextStyle( + style: TextStyle( fontFamily: "Refrigerator Deluxe", - fontSize: 34.5, + fontSize: math.max(_HEADING_FONT_FLOOR, _HEADING_FONT_FACTOR * u), height: 0.9333, // line height: 20px fontWeight: FontWeight.w900, color: const Color(0xFF182B49), // Subheading color @@ -100,21 +136,21 @@ class _OnboardingLoginState extends State { ), ), ), - const SizedBox(height: 12.5), + SizedBox(height: math.max(12.5, 0.0279 * u)), // Description Text - const Flexible( + Flexible( flex: 0, - child: const FractionallySizedBox( + child: FractionallySizedBox( widthFactor: 0.64722222, - child: const Text( + child: Text( // TODO: the font here seems a bit light. Might need to swap that out later - December 2025 "Your personalized gateway to campus life, events, news and more.", textAlign: TextAlign.center, - style: const TextStyle( + style: TextStyle( fontFamily: 'Brix Sans', fontWeight: FontWeight.w400, - fontSize: 18, + fontSize: math.max(_BODY_FONT_FLOOR, _BODY_FONT_FACTOR * u), letterSpacing: 2.2, height: 1.2778, // line height: ~26px color: const Color(0xFF182B49), // Foreground body color @@ -122,22 +158,22 @@ class _OnboardingLoginState extends State { ), ), ), - const SizedBox(height: 35.0), + SizedBox(height: math.max(35.0, 0.0781 * u)), // UCSD Email Input - _buildEmailField(), - const SizedBox(height: 18.5), + _buildEmailField(u), + SizedBox(height: math.max(18.5, 0.0413 * u)), // Password Input - _buildPasswordField(), - const SizedBox(height: 20.0), + _buildPasswordField(u), + SizedBox(height: math.max(20.0, 0.0446 * u)), // SIGN IN and Forgot Password? Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( - padding: EdgeInsets.only(left: MediaQuery.of(context).size.width * ((1 - 0.74444444) / 2) + 6), + padding: EdgeInsets.only(left: u * ((1 - _CONTENT_WIDTH_FACTOR) / 2) + 6), child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFFFCD00), // Yellow Button @@ -145,19 +181,19 @@ class _OnboardingLoginState extends State { elevation: 0.0, fixedSize: () { // calculate width using scaling ratio, then calculate height from width using aspect ratio - final width = _screenWidth * 0.24111111; - final height = width / 2.29268293; + final width = u * _SIGN_IN_BUTTON_WIDTH_FACTOR; + final height = width / _SIGN_IN_BUTTON_ASPECT; return Size(width, height); }(), ), child: Semantics( button: true, hint: 'press to login with your information inputted in above textfields', - child: const Text( + child: Text( 'SIGN IN', - style: const TextStyle( + style: TextStyle( fontFamily: 'Brix Sans', - fontSize: 18.0, + fontSize: math.max(_BODY_FONT_FLOOR, _BODY_FONT_FACTOR * u), height: 1.195, color: Colors.black, // Text color on button fontWeight: FontWeight.bold, @@ -183,17 +219,17 @@ class _OnboardingLoginState extends State { // the spacer in between sign in and forgot password // SizedBox(width: _screenWidth * 0.202), Padding( - padding: EdgeInsets.only(right: MediaQuery.of(context).size.width * ((1 - 0.74444444) / 2) + 6), + padding: EdgeInsets.only(right: u * ((1 - _CONTENT_WIDTH_FACTOR) / 2) + 6), child: GestureDetector( child: Semantics( hint: 'press to be redirected to the UCSD Password reset page', - child: const Text( + child: Text( 'Forgot Password?', - style: const TextStyle( + style: TextStyle( color: const Color(0xFF00629B), height: 1.42857143, decoration: TextDecoration.underline, - fontSize: 18.0, + fontSize: math.max(_BODY_FONT_FLOOR, _BODY_FONT_FACTOR * u), ), // Light Blue ), ), @@ -215,28 +251,28 @@ class _OnboardingLoginState extends State { const Spacer(flex: 2), // Not affiliated text - const Text( + Text( "Not affiliated with UC San Diego?", textAlign: TextAlign.center, - style: const TextStyle( - fontSize: 15.5, + style: TextStyle( + fontSize: math.max(_FOOTER_FONT_FLOOR, _FOOTER_FONT_FACTOR * u), height: 1.42, // line height: 20px color: const Color(0xFF5D5E60), // Foreground body color ), ), - const SizedBox(height: 12.0), + SizedBox(height: math.max(12.0, 0.0268 * u)), // Skip This Step GestureDetector( child: Semantics( hint: 'press to skip the login process and use this app as a visitor', - child: const Text( + child: Text( "SKIP THIS STEP", - style: const TextStyle( + style: TextStyle( color: const Color(0xFF182B49), // Subheading color fontFamily: 'Brix Sans', fontWeight: FontWeight.w700, - fontSize: 16.5, + fontSize: math.max(_SKIP_FONT_FLOOR, _SKIP_FONT_FACTOR * u), height: 1.195, // line height: 16.73px decoration: TextDecoration.underline, ), @@ -256,6 +292,7 @@ class _OnboardingLoginState extends State { static Widget _buildInputField( InputDecoration decoration, TextEditingController controller, { + required double u, TextInputType? keyboardType, bool obscureText = false, }) => Padding( @@ -268,14 +305,14 @@ class _OnboardingLoginState extends State { ], ), child: FractionallySizedBox( - widthFactor: 0.74444444, + widthFactor: _CONTENT_WIDTH_FACTOR, child: TextField( - style: const TextStyle( + style: TextStyle( fontFamily: 'Brix Sans', textBaseline: TextBaseline.alphabetic, color: const Color(0xFF182B49), // Fixed color format with full opacity fontWeight: FontWeight.w400, - fontSize: 18.0, + fontSize: math.max(_BODY_FONT_FLOOR, _BODY_FONT_FACTOR * u), height: 1.277, // line height: 23px letterSpacing: 1.2, ), @@ -288,7 +325,7 @@ class _OnboardingLoginState extends State { ), ); - Widget _buildEmailField() => _buildInputField( + Widget _buildEmailField(double u) => _buildInputField( const InputDecoration( border: InputBorder.none, hintText: 'UCSD Email', @@ -310,10 +347,11 @@ class _OnboardingLoginState extends State { hintStyle: const TextStyle(color: Color(0xFF6A6B6D)), ), _emailTextFieldController, + u: u, keyboardType: TextInputType.emailAddress, ); - Widget _buildPasswordField() => _buildInputField( + Widget _buildPasswordField(double u) => _buildInputField( InputDecoration( border: InputBorder.none, hintText: 'Password', @@ -335,6 +373,7 @@ class _OnboardingLoginState extends State { hintStyle: const TextStyle(color: Color(0xFF6A6B6D)), ), _passwordTextFieldController, + u: u, obscureText: _passwordObscured, ); diff --git a/lib/ui/onboarding/onboarding_slide_template.dart b/lib/ui/onboarding/onboarding_slide_template.dart index 068539cbc..dc10e01b6 100644 --- a/lib/ui/onboarding/onboarding_slide_template.dart +++ b/lib/ui/onboarding/onboarding_slide_template.dart @@ -1,67 +1,134 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import 'package:campus_mobile_experimental/app_styles.dart'; class OnboardingSlideTemplate extends StatelessWidget { const OnboardingSlideTemplate({ super.key, - required this.width, - required this.height, + required this.u, + this.landscape = false, required this.heroImage, required this.heading, required this.description, }); - final double width; - final double height; + static const double heroAspectRatio = 984 / 900; + + final double u; + final bool landscape; final AssetImage heroImage; final String heading; final String description; + // Three body lines is the conservative estimate used by the outer column; + // scrolling is only a fallback when even the minimum sizes cannot fit. + static double contentHeight({ + required double unit, + required double textScale, + required bool landscape, + double photoFactor = 0.9, + }) { + final photoWidth = photoFactor * unit; + final photoHeight = photoWidth / heroAspectRatio; + final textHeight = + 2 * math.max(28.0, 0.12 * unit) * 1.1 * textScale + + 0.0595 * unit + + 3 * math.max(14.0, 0.041 * unit) * 1.3 * textScale; + return landscape ? math.max(photoHeight, textHeight) : photoHeight + 0.0945 * unit + textHeight; + } + @override Widget build(BuildContext context) { - return Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const SizedBox(height: 10.0), - // Hero Image - FractionallySizedBox( - child: Container( - height: height * .42, - width: width * .9, - decoration: BoxDecoration( - image: DecorationImage(image: heroImage, fit: BoxFit.fill), - ), - ), - ), - Expanded( - child: Container( - width: width * 0.8, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - // Heading - Text( - heading, - style: const TextStyle( - fontFamily: 'Refrigerator Deluxe', - color: ColorPrimary, - fontWeight: FontWeight.w900, - fontSize: 50, - ), - textAlign: TextAlign.left, - ), - SizedBox(height: height * 0.025), - // Description - Text( - description, - style: TextStyle(color: const Color(0xFF182B49), fontSize: 18), - textAlign: TextAlign.left, + final textScale = MediaQuery.textScalerOf(context).scale(14) / 14; + final basePhotoFactor = textScale > 1.15 ? 0.8 : 0.9; + final shrunkPhotoFactor = textScale > 1.15 ? 0.72 : 0.8; + final headingFontSize = math.max(28.0, 0.12 * u); + final bodyFontSize = math.max(14.0, 0.041 * u); + + Widget content(double photoFactor) { + final photoWidth = photoFactor * u; + final photoHeight = photoWidth / heroAspectRatio; + + final photo = SizedBox( + width: photoWidth, + height: photoHeight, + child: Image(image: heroImage, fit: BoxFit.contain), + ); + + final text = SizedBox( + width: 0.8 * u, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + FittedBox( + fit: BoxFit.scaleDown, + child: Text( + heading, + style: TextStyle( + fontFamily: 'Refrigerator Deluxe', + color: ColorPrimary, + fontWeight: FontWeight.w900, + fontSize: headingFontSize, + height: 1.1, ), - ], + textAlign: TextAlign.left, + ), ), - ), + SizedBox(height: 0.0595 * u), + Text( + description, + style: TextStyle(color: const Color(0xFF182B49), fontSize: bodyFontSize, height: 1.3), + textAlign: TextAlign.left, + ), + ], ), - ], + ); + + if (landscape) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + photo, + SizedBox(width: 0.10 * u), + text, + ], + ); + } + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + photo, + SizedBox(height: 0.0945 * u), + text, + ], + ); + } + + return LayoutBuilder( + builder: (context, constraints) { + final minHeight = contentHeight( + unit: u, + textScale: textScale, + landscape: landscape, + photoFactor: basePhotoFactor, + ); + var photoFactor = basePhotoFactor; + if (constraints.maxHeight < minHeight) { + final shrunkMinHeight = contentHeight( + unit: u, + textScale: textScale, + landscape: landscape, + photoFactor: shrunkPhotoFactor, + ); + if (constraints.maxHeight < shrunkMinHeight) { + return SingleChildScrollView(child: Center(child: content(basePhotoFactor))); + } + photoFactor = shrunkPhotoFactor; + } + return Center(child: content(photoFactor)); + }, ); } } diff --git a/lib/ui/onboarding/onboarding_slides.dart b/lib/ui/onboarding/onboarding_slides.dart index 545bfd7b5..bac153b8f 100644 --- a/lib/ui/onboarding/onboarding_slides.dart +++ b/lib/ui/onboarding/onboarding_slides.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:campus_mobile_experimental/app_styles.dart'; import 'package:dots_indicator/dots_indicator.dart'; import 'package:flutter/material.dart'; @@ -14,127 +16,229 @@ class _OnboardingSlidesState extends State with TickerProvider var currentIndex = 0; final _foregroundPageController = PageController(); final _backgroundPageController = PageController(); - late final _screenWidth = MediaQuery.sizeOf(context).width; - late final _screenHeight = MediaQuery.sizeOf(context).height; @override void initState() { super.initState(); _foregroundPageController.addListener(() { - _backgroundPageController.jumpTo(_foregroundPageController.page! * MediaQuery.of(context).size.width); + _backgroundPageController.jumpTo(_foregroundPageController.page! * MediaQuery.sizeOf(context).width); }); } + double _portraitUnit(double width, double usableHeight) { + final cap = width < 600 + ? double.infinity + : width < 900 + ? 520.0 + : width < 1200 + ? 600.0 + : 680.0; + return math.min(width, math.min(usableHeight / 1.8, cap)); + } + + double _landscapeUnit(double width, double usableHeight) { + final cap = width < 900 + ? double.infinity + : width < 1200 + ? 600.0 + : width < 1500 + ? 680.0 + : 760.0; + return math.min(0.77 * usableHeight, math.min(0.49 * width, cap)); + } + + double _stackHeight(double u, double textScale, bool landscape, {double? contentUnit}) { + final linkLine = math.max(14.0, 0.039 * u) * 1.195 * textScale; + final gapBL = math.max(0.084 * u, 50.0 - linkLine); + return 0.03 * u + + 0.03 * u + + OnboardingSlideTemplate.contentHeight( + unit: contentUnit ?? u, + textScale: textScale, + landscape: landscape, + photoFactor: textScale > 1.15 ? 0.8 : 0.9, + ) + + gapBL + + linkLine; + } + + double _boostedContentUnit(double u, double textScale, double baseSpare, double usableHeight) { + if (baseSpare <= 0) return u; + final photoFactor = textScale > 1.15 ? 0.8 : 0.9; + double content(double unit) => OnboardingSlideTemplate.contentHeight( + unit: unit, + textScale: textScale, + landscape: false, + photoFactor: photoFactor, + ); + final target = content(u) + 0.165 * baseSpare; + var unit = u; + for (var i = 0; i < 3; i++) { + final deficit = target - content(unit); + if (deficit <= 0.1) break; + final slope = content(unit + 1.0) - content(unit); + if (slope <= 0) break; + unit += deficit / slope; + } + // Bias the solve to undershoot: the PageView is sized to the modeled height. + unit = math.max(u, unit - 0.25); + final maxStackHeight = usableHeight - 0.835 * baseSpare; + while (unit > u && _stackHeight(u, textScale, false, contentUnit: unit) > maxStackHeight) { + unit = math.max(u, unit - 1.0); + } + return unit; + } + // Dot Indicator - Widget buildDotIndicator() => DotsIndicator( + Widget buildDotIndicator(double u) => DotsIndicator( dotsCount: 5, position: currentIndex.toDouble(), - decorator: const DotsDecorator( + decorator: DotsDecorator( activeColor: const Color(0xFF00619B), - activeSize: const Size(16.0, 16.0), // Bigger active dot + activeSize: Size.square(0.03 * u), + size: Size.square(0.02 * u), + spacing: const EdgeInsets.symmetric(horizontal: 6.0), ), ); @override - Widget build(BuildContext context) => Scaffold( - resizeToAvoidBottomInset: false, - backgroundColor: lightOnboardingScreen, - body: Stack( - alignment: Alignment.topCenter, - children: [ - // Background Image transitioning smoothly - PageView.builder( - controller: _backgroundPageController, - physics: const NeverScrollableScrollPhysics(), - pageSnapping: false, - itemCount: 5, - itemBuilder: (_, index) => Stack( - children: [ - Positioned( - left: -2.5, - right: -2.5, - top: 0, - bottom: 0, - child: Image.asset("assets/images/onboarding/slide-${index + 1}-background.jpg", fit: BoxFit.fitWidth), - ), - ], - ), - ), - Column( + Widget build(BuildContext context) { + final size = MediaQuery.sizeOf(context); + final padding = MediaQuery.paddingOf(context); + final usableHeight = size.height - padding.top - padding.bottom; + final landscape = size.width > size.height && size.shortestSide >= 600; + final u = landscape ? _landscapeUnit(size.width, usableHeight) : _portraitUnit(size.width, usableHeight); + final textScale = math.min(MediaQuery.textScalerOf(context).scale(14) / 14, 1.3); + final baseSpare = math.max(0.0, usableHeight - _stackHeight(u, textScale, landscape)); + final contentUnit = landscape ? u : _boostedContentUnit(u, textScale, baseSpare, usableHeight); + final linkFontSize = math.max(14.0, 0.039 * u); + final linkLineHeight = linkFontSize * 1.195 * textScale; + final gapBL = math.max(0.084 * u, 50.0 - linkLineHeight); + final linkPadding = math.max(0.0, math.min(48.0 - linkLineHeight, gapBL - 2.0)); + + return Scaffold( + resizeToAvoidBottomInset: false, + backgroundColor: lightOnboardingScreen, + body: MediaQuery.withClampedTextScaling( + maxScaleFactor: 1.3, + child: Stack( + alignment: Alignment.topCenter, children: [ - const SizedBox(height: 110.0), - buildDotIndicator(), - Expanded( - child: PageView( - controller: _foregroundPageController, - onPageChanged: (int page) { - setState(() { - currentIndex = page; - }); - }, - children: [buildPage1(), buildPage2(), buildPage3(), buildPage4(), buildPage5()], + // Background Image transitioning smoothly + PageView.builder( + controller: _backgroundPageController, + physics: const NeverScrollableScrollPhysics(), + pageSnapping: false, + itemCount: 5, + itemBuilder: (_, index) => Stack( + children: [ + Positioned( + left: -2.5, + right: -2.5, + top: 0, + bottom: 0, + child: Image.asset( + "assets/images/onboarding/slide-${index + 1}-background.jpg", + fit: BoxFit.fitWidth, + ), + ), + ], + ), + ), + Padding( + padding: EdgeInsets.only(top: padding.top, bottom: padding.bottom), + child: Column( + children: [ + if (!landscape) SizedBox(height: baseSpare * 0.385), + buildDotIndicator(u), + SizedBox(height: 0.03 * u), + Expanded( + child: PageView( + controller: _foregroundPageController, + onPageChanged: (int page) { + setState(() { + currentIndex = page; + }); + }, + children: [ + buildPage1(contentUnit, landscape), + buildPage2(contentUnit, landscape), + buildPage3(contentUnit, landscape), + buildPage4(contentUnit, landscape), + buildPage5(contentUnit, landscape), + ], + ), + ), + SizedBox(height: gapBL - linkPadding), + Transform.translate( + offset: Offset(0, landscape ? -math.min(0.1 * u, gapBL) : 0), + child: buildGoToTheAppButton(u, linkPadding), + ), + if (!landscape) SizedBox(height: baseSpare * 0.45), + ], ), ), - buildGoToTheAppButton(), - const SizedBox(height: 80.0), ], ), - ], - ), - ); + ), + ); + } - Widget buildPage1() => OnboardingSlideTemplate( - width: _screenWidth, - height: _screenHeight, + Widget buildPage1(double u, bool landscape) => OnboardingSlideTemplate( + u: u, + landscape: landscape, heroImage: const AssetImage('assets/images/onboarding/hero-1-campus-life.png'), - heading: "ONE-STOP ACCESS\nTO CAMPUS LIFE. ", + heading: "ONE-STOP ACCESS\nTO CAMPUS LIFE.", description: "Keep up to date with amazing events and stay connected to campus news.", ); - Widget buildPage2() => OnboardingSlideTemplate( - width: _screenWidth, - height: _screenHeight, + Widget buildPage2(double u, bool landscape) => OnboardingSlideTemplate( + u: u, + landscape: landscape, heroImage: const AssetImage('assets/images/onboarding/hero-2-schedule.png'), - heading: "YOUR SCHEDULE\nON THE GO. ", + heading: "YOUR SCHEDULE\nON THE GO.", description: "View your classes and finals schedule whenever you need.", ); - Widget buildPage3() => OnboardingSlideTemplate( - width: _screenWidth, - height: _screenHeight, + Widget buildPage3(double u, bool landscape) => OnboardingSlideTemplate( + u: u, + landscape: landscape, heroImage: const AssetImage('assets/images/onboarding/hero-3-parking.png'), - heading: "PARKING\nMADE EASIER. ", + heading: "PARKING\nMADE EASIER.", description: "Keep an eye on parking lot capacity to plan your day.", ); - Widget buildPage4() => OnboardingSlideTemplate( - width: _screenWidth, - height: _screenHeight, + Widget buildPage4(double u, bool landscape) => OnboardingSlideTemplate( + u: u, + landscape: landscape, heroImage: const AssetImage('assets/images/onboarding/hero-4-busyness.png'), - heading: "SPEND LESS\nTIME WAITING. ", + heading: "SPEND LESS\nTIME WAITING.", description: "Easily see how busy campus locations are before you arrive.", ); - Widget buildPage5() => OnboardingSlideTemplate( - width: _screenWidth, - height: _screenHeight, + Widget buildPage5(double u, bool landscape) => OnboardingSlideTemplate( + u: u, + landscape: landscape, heroImage: const AssetImage('assets/images/onboarding/hero-5-notifications.png'), - heading: "YOU'RE ALL SET. ", + heading: "YOU'RE ALL SET.", description: "We recommend turning on push notifications to receive campus and safety alerts.", ); - Widget buildGoToTheAppButton() => GestureDetector( + Widget buildGoToTheAppButton(double u, double topPadding) => GestureDetector( child: Semantics( hint: 'press to skip the login process and use this app as a visitor', - child: const Text( - "GO TO THE APP", - style: const TextStyle( - color: const Color(0xFF182B49), // Subheading color - fontWeight: FontWeight.w700, - fontSize: 16.5, - height: 1.195, // line height: 16.73px - decoration: TextDecoration.underline, - decorationColor: Color(0xFF00629B), + child: Padding( + padding: EdgeInsets.only(top: topPadding), + child: Text( + "GO TO THE APP", + style: TextStyle( + color: const Color(0xFF182B49), // Subheading color + fontWeight: FontWeight.w700, + fontSize: math.max(14.0, 0.039 * u), + height: 1.195, // line height: 16.73px + decoration: TextDecoration.underline, + decorationColor: const Color(0xFF00629B), + ), ), ), ), diff --git a/lib/ui/parking/circular_parking_indicator.dart b/lib/ui/parking/circular_parking_indicator.dart index d3001d352..b35355d76 100644 --- a/lib/ui/parking/circular_parking_indicator.dart +++ b/lib/ui/parking/circular_parking_indicator.dart @@ -9,46 +9,80 @@ import 'package:campus_mobile_experimental/app_constants.dart'; class CircularParkingIndicators extends StatelessWidget { const CircularParkingIndicators({Key? key, required this.model}) : super(key: key); + static const double baseGaugeSize = 90; + static const double gaugeHorizontalPadding = 16; + static const double phoneBodyReferenceHeight = 320; + static const double minScale = 0.5; + static const double maxScale = 2.5; + /// MODELS final ParkingModel model; @override Widget build(BuildContext context) { - return Column( - children: [ - buildLocationTitle(context), - buildLocationContext(context), - buildSpotsAvailableText(context), - buildHistoricInfo(context), - buildAllParkingAvailability(context), - ], + final parkingProvider = Provider.of(context); + final selectedSpots = []; + parkingProvider.spotTypesState.forEach((key, value) { + if (value && selectedSpots.length < 4) selectedSpots.add(key); + }); + + return LayoutBuilder( + builder: (context, constraints) { + final scale = computeScale( + constraints.maxWidth, + selectedSpots.length, + allowGrowth: MediaQuery.of(context).size.width > 600, + ); + return Column( + children: [ + buildLocationTitle(context, scale), + buildLocationContext(context, scale), + buildSpotsAvailableText(context, scale), + buildAllParkingAvailability(context, parkingProvider, selectedSpots, scale), + ], + ); + }, ); } - Widget buildAllParkingAvailability(BuildContext context) { - List listOfCircularParkingInfo = []; - List selectedSpots = []; - - Provider.of(context).spotTypesState.forEach((key, value) { - final bool hasValue = value; - final bool hasSpaceForMore = selectedSpots.length < 4; - if (hasValue && hasSpaceForMore) selectedSpots.add(key); - }); - for (String spot in selectedSpots) { - listOfCircularParkingInfo.add( - buildCircularParkingInfo( - Provider.of(context).spotTypeMap[spot], - model.availability[spot], - context, - ), - ); - } + Widget buildAllParkingAvailability( + BuildContext context, + ParkingDataProvider parkingProvider, + List selectedSpots, + double scale, + ) { return Expanded( - child: Row(mainAxisAlignment: MainAxisAlignment.start, children: listOfCircularParkingInfo), + child: Column( + children: [ + buildHistoricInfo(context, scale), + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + for (String spot in selectedSpots) + buildCircularParkingInfo(parkingProvider.spotTypeMap[spot], model.availability[spot], context, scale), + ], + ), + ), + ], + ), ); } - Widget buildCircularParkingInfo(Spot? spotType, dynamic locationData, BuildContext context) { + /// Phones stay at or below the 90px baseline; tablets grow until one gauge + /// cell runs out of width. The 600px gate matches CardContainer's tablet + /// body so one breakpoint decides both. + static double computeScale(double maxWidth, int spotCount, {required bool allowGrowth}) { + if (spotCount <= 0) return 1.0; + final widthScale = (maxWidth / spotCount) / (baseGaugeSize + 2 * gaugeHorizontalPadding); + if (!allowGrowth) return widthScale.clamp(minScale, 1.0).toDouble(); + return widthScale.clamp(1.0, maxScale).toDouble(); + } + + static double computeEmptyStateScale(BoxConstraints constraints) => + (constraints.maxHeight / phoneBodyReferenceHeight).clamp(1.0, maxScale).toDouble(); + + Widget buildCircularParkingInfo(Spot? spotType, dynamic locationData, BuildContext context, double scale) { int open, total; if (locationData != null) { open = locationData["Open"] is String @@ -62,130 +96,98 @@ class CircularParkingIndicators extends StatelessWidget { open = total = 0; } - return locationData != null - ? Expanded( - child: Semantics( - label: - 'For ${spotType?.name ?? "Unknown"} parking spots, ${((open / total).isNaN ? "Not applicable" : ((open / total) * 100).round().toString() + "% available")}', - excludeSemantics: true, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16.0), - child: Stack( - alignment: Alignment.center, - children: [ - Center( - child: SizedBox( - height: 90, - width: 90, - child: CircularPercentIndicator( - radius: 45, - animation: true, - animationDuration: 1000, - lineWidth: 9, - percent: (open / total).isNaN ? 0.0 : open / total, - center: Text( - (open / total).isNaN ? "N/A" : ((open / total) * 100).round().toString() + "%", - style: Theme.of(context).textTheme.titleMedium, - ), - circularStrokeCap: CircularStrokeCap.round, - backgroundColor: colorFromHex('#EDECEC'), - progressColor: getColor(open / total), - ), + final availability = open / total; + return buildGauge( + context: context, + spotType: spotType, + open: open, + total: total, + scale: scale, + animate: locationData != null, + semanticLabel: locationData != null + ? 'For ${spotType?.name ?? "Unknown"} parking spots, ${(availability.isNaN ? "Not applicable" : (availability * 100).round().toString() + "% available")}' + : 'For ${spotType?.name ?? "Unknown"} parking, Not applicable', + ); + } + + Widget buildGauge({ + required BuildContext context, + required Spot? spotType, + required int open, + required int total, + required double scale, + required bool animate, + required String semanticLabel, + }) { + final availability = open / total; + final percentStyle = Theme.of(context).textTheme.titleMedium; + return Expanded( + child: Semantics( + label: semanticLabel, + excludeSemantics: true, + child: ClipRect( + child: Column( + mainAxisAlignment: scale > 1.0 ? MainAxisAlignment.center : MainAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.symmetric(horizontal: gaugeHorizontalPadding * scale), + child: Stack( + alignment: Alignment.center, + children: [ + Center( + child: SizedBox( + height: baseGaugeSize * scale, + width: baseGaugeSize * scale, + child: CircularPercentIndicator( + radius: baseGaugeSize / 2 * scale, + animation: animate, + animationDuration: 1000, + lineWidth: baseGaugeSize / 10 * scale, + percent: availability.isNaN ? 0.0 : availability, + center: Text( + availability.isNaN ? "N/A" : (availability * 100).round().toString() + "%", + style: percentStyle?.copyWith(fontSize: (percentStyle.fontSize ?? 16) * scale), ), + circularStrokeCap: CircularStrokeCap.round, + backgroundColor: colorFromHex('#EDECEC'), + progressColor: getColor(availability), ), - ], + ), ), - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: spotType != null - ? CircleAvatar( - backgroundColor: colorFromHex(spotType.logoBackgroundColor), - child: spotType.logoText.startsWith('icon - ') - ? Icon( - ParkingConstants.STRING_TO_ICON_DATA[spotType.logoText] ?? Icons.error, - size: 25.0, - color: colorFromHex(spotType.logoTextColor), - ) - : (spotType.logoText.isNotEmpty - ? Text( - spotType.logoText, - style: TextStyle( - color: colorFromHex(spotType.logoTextColor), - fontFamily: 'Brix Sans', - fontSize: 28, - fontWeight: FontWeight.w700, - ), - ) - : SizedBox.shrink()), - ) - : Container(), - ), - ], + ], + ), ), - ), // close Semantics - ) // close Expanded - : Expanded( - child: Semantics( - label: 'For ${spotType?.name ?? "Unknown"} parking, Not applicable', - excludeSemantics: true, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16.0), - child: Stack( - alignment: Alignment.center, - children: [ - Center( - child: SizedBox( - height: 90, - width: 90, - child: CircularPercentIndicator( - radius: 45, - animation: false, - lineWidth: 9, - percent: 0.0, - center: Text("N/A", style: Theme.of(context).textTheme.titleMedium), - backgroundColor: colorFromHex('#EDECEC'), - ), - ), - ), - ], - ), - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: spotType != null - ? CircleAvatar( - backgroundColor: colorFromHex(spotType.logoBackgroundColor), - child: spotType.logoText.startsWith('icon - ') - ? Icon( - ParkingConstants.STRING_TO_ICON_DATA[spotType.logoText] ?? Icons.error, - size: 25.0, - color: colorFromHex(spotType.logoTextColor), - ) - : (spotType.logoText.isNotEmpty - ? Text( - spotType.logoText, - style: TextStyle( - color: colorFromHex(spotType.logoTextColor), - fontFamily: 'Brix Sans', - fontWeight: FontWeight.w700, - fontSize: 28, - ), - ) - : SizedBox.shrink()), - ) - : Container(), - ), - ], + Padding( + padding: EdgeInsets.all(8.0 * scale), + child: spotType != null + ? CircleAvatar( + radius: 20 * scale, + backgroundColor: colorFromHex(spotType.logoBackgroundColor), + child: spotType.logoText.startsWith('icon - ') + ? Icon( + ParkingConstants.STRING_TO_ICON_DATA[spotType.logoText] ?? Icons.error, + size: 25.0 * scale, + color: colorFromHex(spotType.logoTextColor), + ) + : (spotType.logoText.isNotEmpty + ? Text( + spotType.logoText, + style: TextStyle( + color: colorFromHex(spotType.logoTextColor), + fontFamily: 'Brix Sans', + fontSize: 28 * scale, + fontWeight: FontWeight.w700, + ), + ) + : SizedBox.shrink()), + ) + : Container(), ), - ), - ); + ], + ), + ), + ), + ); } static Color getColor(double value) { @@ -194,29 +196,28 @@ class CircularParkingIndicators extends StatelessWidget { return Color(0xFFBD1900); } - Widget buildLocationTitle(BuildContext context) { + Widget buildLocationTitle(BuildContext context, double scale) { + final style = Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.normal); return Semantics( label: 'Parking Name: ${model.locationName.toUpperCase()}', excludeSemantics: true, - child: Text( - model.locationName.toUpperCase(), - style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.normal), - ), + child: Text(model.locationName.toUpperCase(), style: style?.copyWith(fontSize: (style.fontSize ?? 16) * scale)), ); } - Widget buildLocationContext(BuildContext context) { + Widget buildLocationContext(BuildContext context, double scale) { + final style = Theme.of(context).textTheme.titleSmall; return Padding( - padding: const EdgeInsets.only(top: 6.0), + padding: EdgeInsets.only(top: 6.0 * scale), child: Text( model.locationContext.toUpperCase(), semanticsLabel: 'Located at: ${model.locationContext}', - style: Theme.of(context).textTheme.titleSmall, + style: style?.copyWith(fontSize: (style.fontSize ?? 14) * scale), ), ); } - Widget buildSpotsAvailableText(BuildContext context) { + Widget buildSpotsAvailableText(BuildContext context, double scale) { final openSpots = Provider.of( context, ).getApproxNumOfOpenSpots(model.locationName)["Open"].toString(); @@ -225,27 +226,34 @@ class CircularParkingIndicators extends StatelessWidget { ).getApproxNumOfOpenSpots(model.locationName)["Total"].toString(); final visualText = "~$openSpots of $totalSpots Spots Available"; final semanticText = "Approximately $openSpots of $totalSpots Spots Available"; + final style = Theme.of(context).textTheme.bodyMedium; return Padding( - padding: const EdgeInsets.only(top: 8.0), + padding: EdgeInsets.only(top: 8.0 * scale), child: Center( - child: Text(visualText, semanticsLabel: semanticText, style: Theme.of(context).textTheme.bodyMedium), + child: Text( + visualText, + semanticsLabel: semanticText, + style: style?.copyWith(fontSize: (style.fontSize ?? 14) * scale), + ), ), ); } - Widget buildHistoricInfo(BuildContext context) { + Widget buildHistoricInfo(BuildContext context, double scale) { if (model.locationProvider == "Historic") { return Padding( padding: const EdgeInsets.only(bottom: 8), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon(Icons.error_outline, color: Colors.black), + Icon(Icons.error_outline, color: Colors.black, size: 24 * scale), SizedBox(width: 4), - Text( - "No Live Data. Estimated availability shown.", - style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 16), + Flexible( + child: Text( + "No Live Data. Estimated availability shown.", + style: Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 16 * scale), + ), ), ], ), diff --git a/lib/ui/parking/parking_card.dart b/lib/ui/parking/parking_card.dart index 2e38a9089..18760076b 100644 --- a/lib/ui/parking/parking_card.dart +++ b/lib/ui/parking/parking_card.dart @@ -76,17 +76,22 @@ class _ParkingCardState extends State { } if (selectedLotsViews.isEmpty) { - return (Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text("No Lots to Display", style: TextStyle(fontSize: 24)), - Padding( - padding: const EdgeInsets.only(top: 5), - child: Text("Add a Lot via 'Manage Lots'", style: TextStyle(fontSize: 14)), - ), - ], - )); + return LayoutBuilder( + builder: (context, constraints) { + final scale = CircularParkingIndicators.computeEmptyStateScale(constraints); + return Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text("No Lots to Display", style: TextStyle(fontSize: 24 * scale)), + Padding( + padding: const EdgeInsets.only(top: 5), + child: Text("Add a Lot via 'Manage Lots'", style: TextStyle(fontSize: 14 * scale)), + ), + ], + ); + }, + ); } return Column( diff --git a/lib/ui/profile/login.dart b/lib/ui/profile/login.dart index a734c08c7..e87d7ee60 100644 --- a/lib/ui/profile/login.dart +++ b/lib/ui/profile/login.dart @@ -46,7 +46,7 @@ class _LoginState extends State { Widget buildLoggedInWidget(BuildContext context) { return Container( - padding: const EdgeInsets.fromLTRB(15.0, 15.0, 0, 0), + padding: const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -79,14 +79,20 @@ class _LoginState extends State { Widget buildUserProfileTile(BuildContext context) { return ListTile( + contentPadding: EdgeInsets.zero, + minLeadingWidth: 24, + horizontalTitleGap: 8, leading: Icon(Icons.check_circle, color: Colors.green), - title: Transform.translate( - offset: Offset(-24, 0), + title: FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, child: Text( _userDataProvider.userProfileModel.username != null ? parseUsername(_userDataProvider.userProfileModel.username!) : "", style: bodyMediumLight, + maxLines: 1, + softWrap: false, ), ), trailing: TextButton( diff --git a/lib/ui/shuttle/manage_shuttle_view.dart b/lib/ui/shuttle/manage_shuttle_view.dart index 4f19a3f36..1e8518d01 100644 --- a/lib/ui/shuttle/manage_shuttle_view.dart +++ b/lib/ui/shuttle/manage_shuttle_view.dart @@ -47,18 +47,11 @@ class _ManageShuttleViewState extends State { } void _onReorder(int oldIndex, int newIndex) { - List newOrder = _shuttleDataProvider.stopsToRender; - List toRemove = []; - - newOrder.removeWhere((element) => toRemove.contains(element)); - ShuttleStopModel? item = newOrder.removeAt(oldIndex); + final newOrder = _shuttleDataProvider.stopsToRender.toList(); + final item = newOrder.removeAt(oldIndex); newOrder.insert(newIndex, item); - List orderedStopNames = []; - for (ShuttleStopModel? item in newOrder) { - orderedStopNames.add(item!.id); - } - _shuttleDataProvider.reorderStops(orderedStopNames); + _shuttleDataProvider.reorderStops(newOrder.map((stop) => stop.id).toList()); } List createList(BuildContext context) { diff --git a/lib/ui/shuttle/shuttle_card.dart b/lib/ui/shuttle/shuttle_card.dart index 3b1f4e983..6f7a678f3 100644 --- a/lib/ui/shuttle/shuttle_card.dart +++ b/lib/ui/shuttle/shuttle_card.dart @@ -12,6 +12,7 @@ import 'package:campus_mobile_experimental/core/providers/shuttle.dart'; import 'package:campus_mobile_experimental/ui/common/action_link.dart'; import 'package:campus_mobile_experimental/ui/common/card_container.dart'; import 'package:campus_mobile_experimental/ui/shuttle/shuttle_display.dart'; + // import 'package:url_launcher/url_launcher.dart'; const String cardId = 'shuttle'; @@ -62,9 +63,6 @@ class _ShuttleCardState extends State { buttonText: 'MANAGE SHUTTLE STOPS', onPressed: () { analytics.logEvent(name: '${cardId}_card_action', parameters: {'action': 'manage_stops'}); - setState(() { - _currentPage = 0; - }); Navigator.pushNamed(context, RoutePaths.MANAGE_SHUTTLE_VIEW); }, ), @@ -102,8 +100,8 @@ class _ShuttleCardState extends State { // Initialize first shuttle display with arrival information if (stopsToRender.isEmpty) { return Padding( - padding: const EdgeInsets.only(bottom: 42.0), - child: Center(child: Text('Add a stop to view real-time bus arrivals.')), + padding: const EdgeInsets.only(left: 8.0, right: 8.0, bottom: 42.0, top: 160.0), + child: Column(children: const [Text('Add a stop to view real-time bus arrivals.')]), ); } @@ -121,21 +119,40 @@ class _ShuttleCardState extends State { ShuttleDisplay( stop: _shuttleCardDataProvider.stopsToRender[i], arrivingShuttles: arrivalsToRender[_shuttleCardDataProvider.stopsToRender[i].id], + arrivalError: _shuttleCardDataProvider.arrivalErrors[_shuttleCardDataProvider.stopsToRender[i].id], ), ); } return Column( + mainAxisSize: MainAxisSize.min, children: [ - Flexible( - child: PageView( - controller: _controller, - children: renderList, - onPageChanged: (index) { - setState(() { - _currentPage = index; - }); - }, - ), + Stack( + children: [ + // Size the swipe viewport to the selected stop's natural height. + ExcludeSemantics( + child: Opacity(opacity: 0, child: renderList[_currentPage.clamp(0, renderList.length - 1)]), + ), + Positioned.fill( + child: PageView( + controller: _controller, + children: renderList + .map( + (page) => OverflowBox( + minHeight: 0, + maxHeight: double.infinity, + alignment: Alignment.topCenter, + child: page, + ), + ) + .toList(), + onPageChanged: (index) { + setState(() { + _currentPage = index; + }); + }, + ), + ), + ], ), if (renderList.length > 1) DotsIndicator( diff --git a/lib/ui/shuttle/shuttle_display.dart b/lib/ui/shuttle/shuttle_display.dart index f49a6c83e..d5353d587 100644 --- a/lib/ui/shuttle/shuttle_display.dart +++ b/lib/ui/shuttle/shuttle_display.dart @@ -5,16 +5,29 @@ import 'package:flutter/material.dart'; import 'package:campus_mobile_experimental/app_styles.dart'; class ShuttleDisplay extends StatelessWidget { - ShuttleDisplay({Key? key, required this.stop, required this.arrivingShuttles}) : super(key: key); + ShuttleDisplay({Key? key, required this.stop, required this.arrivingShuttles, this.arrivalError}) : super(key: key); /// STATES final List? arrivingShuttles; + final String? arrivalError; /// MODELS final ShuttleStopModel stop; @override Widget build(BuildContext context) { + if (arrivalError != null) { + return Column( + children: [ + buildCircleStopRow(context), + const SizedBox(height: 16), + const Padding( + padding: EdgeInsets.fromLTRB(16, 0, 16, 16), + child: Text('Arrival information is temporarily unavailable. Please try again.'), + ), + ], + ); + } if (arrivingShuttles == null) { return Container( width: double.infinity, @@ -43,6 +56,7 @@ class ShuttleDisplay extends StatelessWidget { } Row buildCircleStopRow(BuildContext context) { + final bool hasArrivals = arrivingShuttles?.isNotEmpty ?? false; return Row( mainAxisAlignment: MainAxisAlignment.start, children: [ @@ -61,20 +75,16 @@ class ShuttleDisplay extends StatelessWidget { ), child: CircleAvatar( minRadius: 40, - backgroundColor: HexColor( - arrivingShuttles!.isEmpty ? noArrivalsFoundColor : arrivingShuttles![0].routeColor, - ), + backgroundColor: HexColor(hasArrivals ? arrivingShuttles![0].routeColor : noArrivalsFoundColor), foregroundColor: Colors.black, child: Builder( builder: (context) { - Color circleColor = HexColor( - arrivingShuttles!.isEmpty ? noArrivalsFoundColor : arrivingShuttles![0].routeColor, - ); + Color circleColor = HexColor(hasArrivals ? arrivingShuttles![0].routeColor : noArrivalsFoundColor); // Calculate luminance to determine the color of "?" final double luminance = circleColor.computeLuminance(); final Color textColor = luminance > 0.5 ? Colors.black : Colors.white; return Text( - arrivingShuttles!.isEmpty ? "?" : arrivingShuttles![0].routeName[0], + hasArrivals ? arrivingShuttles![0].routeName[0] : "?", style: TextStyle(fontSize: 50, color: textColor), ); }, @@ -104,14 +114,16 @@ class ShuttleDisplay extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.start, children: [ SizedBox(width: 16), - Text( - "No arrivals found.", - style: TextStyle( - fontSize: 23.0, - fontWeight: FontWeight.w700, - color: Theme.of(context).brightness == Brightness.light - ? descriptiveTextColorLight - : descriptiveTextColorDark, + Flexible( + child: Text( + "No arrivals found.", + style: TextStyle( + fontSize: 23.0, + fontWeight: FontWeight.w700, + color: Theme.of(context).brightness == Brightness.light + ? descriptiveTextColorLight + : descriptiveTextColorDark, + ), ), ), ], @@ -140,22 +152,25 @@ class ShuttleDisplay extends StatelessWidget { ], ), SizedBox(width: 8), - Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - SizedBox(width: 16), - Text( - "Arriving in: ", - style: TextStyle( - fontSize: 23.0, - fontWeight: FontWeight.w400, - color: Theme.of(context).brightness == Brightness.light - ? descriptiveTextColorLight - : descriptiveTextColorDark, - ), - ), - buildTimeToArrivalText(context), - ], + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + if (arrivingShuttles![0].secondsToArrival >= 60) + Text( + "Arriving in: ", + style: TextStyle( + fontSize: 23.0, + fontWeight: FontWeight.w400, + color: Theme.of(context).brightness == Brightness.light + ? descriptiveTextColorLight + : descriptiveTextColorDark, + ), + ), + buildTimeToArrivalText(context), + ], + ), ), ], ); @@ -165,7 +180,7 @@ class ShuttleDisplay extends StatelessWidget { Widget buildTimeToArrivalText(BuildContext context) { var minutesToArrival = arrivingShuttles![0].secondsToArrival ~/ 60; return Text( - "$minutesToArrival minutes", + minutesToArrival <= 0 ? 'Arriving Now' : "$minutesToArrival minutes", style: Theme.of(context).brightness == Brightness.light ? titleMediumLight : titleMediumDark, ); } @@ -176,12 +191,14 @@ class ShuttleDisplay extends StatelessWidget { return Row( mainAxisAlignment: MainAxisAlignment.start, children: [ - Padding( - padding: const EdgeInsets.only(left: 16.0), - child: Text( - "Next Arrivals", - textAlign: TextAlign.left, - style: Theme.of(context).brightness == Brightness.light ? titleMediumLight : titleMediumDark, + Flexible( + child: Padding( + padding: const EdgeInsets.only(left: 16.0), + child: Text( + "Next Arrivals", + textAlign: TextAlign.left, + style: Theme.of(context).brightness == Brightness.light ? titleMediumLight : titleMediumDark, + ), ), ), ], @@ -220,12 +237,15 @@ class ShuttleDisplay extends StatelessWidget { flex: 3, child: Text(shuttle.routeName, style: TextStyle(fontSize: 16), overflow: TextOverflow.ellipsis, maxLines: 1), ), - Expanded(flex: 1, child: Container()), - Padding( - padding: const EdgeInsets.all(8.0), - child: Text( - "$minutesToArrival min", - style: Theme.of(context).brightness == Brightness.light ? titleMediumLight : titleMediumDark, + Expanded( + flex: 5, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + "$minutesToArrival min", + textAlign: TextAlign.end, + style: Theme.of(context).brightness == Brightness.light ? titleMediumLight : titleMediumDark, + ), ), ), ], diff --git a/pubspec.yaml b/pubspec.yaml index 40778f107..319133ecf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -63,6 +63,7 @@ flutter: - assets/images/ - assets/images/onboarding/ - assets/images/tgpt/ + - assets/images/circles/ - .env fonts: - family: Refrigerator Deluxe diff --git a/test/core/models/shuttle_arrival_test.dart b/test/core/models/shuttle_arrival_test.dart new file mode 100644 index 000000000..9a01e379e --- /dev/null +++ b/test/core/models/shuttle_arrival_test.dart @@ -0,0 +1,271 @@ +import 'package:campus_mobile_experimental/core/models/shuttle_arrival.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Builds a minimal OneBusAway `arrivals-and-departures-for-stop` envelope +/// around [arrivals] and [routes]. +Map envelopeWith({ + List arrivals = const [], + List> routes = const [], + int currentTime = 1000000, +}) => { + 'code': 200, + 'currentTime': currentTime, + 'data': { + 'entry': {'stopId': 'UCSD_10772', 'arrivalsAndDepartures': arrivals, 'nearbyStopIds': [], 'situationIds': []}, + 'references': {'routes': routes, 'stops': [], 'trips': []}, + }, +}; + +Map ucsdRoute({ + String id = 'UCSD_1040', + String shortName = 'IL', + String longName = 'Inside Loop', + String color = 'ffcd00', +}) => { + 'agencyId': 'UCSD', + 'id': id, + 'shortName': shortName, + 'longName': longName, + 'color': color, + 'type': 3, +}; + +Map arrival({ + String routeId = 'UCSD_1040', + String? routeShortName, + bool predicted = false, + int? predictedArrivalTime, + int? scheduledArrivalTime, + int? predictedDepartureTime, + int? scheduledDepartureTime, + bool arrivalEnabled = true, + bool departureEnabled = true, + String stopId = 'UCSD_10772', + String? tripHeadsign, +}) => { + 'routeId': routeId, + 'routeShortName': routeShortName, + 'tripHeadsign': tripHeadsign, + 'predicted': predicted, + 'predictedArrivalTime': predictedArrivalTime, + 'scheduledArrivalTime': scheduledArrivalTime, + 'predictedDepartureTime': predictedDepartureTime, + 'scheduledDepartureTime': scheduledDepartureTime, + 'arrivalEnabled': arrivalEnabled, + 'departureEnabled': departureEnabled, + 'stopId': stopId, +}; + +void main() { + group('arrivingShuttlesFromOneBusAwayEnvelope', () { + test('maps OneBusAway arrivals onto the existing ArrivingShuttle shape', () { + final int now = 1000000; + final Map envelope = envelopeWith( + currentTime: now, + routes: [ucsdRoute()], + arrivals: [arrival(predicted: true, predictedArrivalTime: now + 60000, scheduledArrivalTime: now + 120000)], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles, hasLength(1)); + final ArrivingShuttle shuttle = shuttles.single; + expect(shuttle.routeId, 1040); + expect(shuttle.routeName, 'Inside Loop'); + expect(shuttle.routeColor, '#ffcd00'); + expect(shuttle.routeStopId, 10772); + expect(shuttle.secondsToArrival, 60); + }); + + test('drops arrivals from other agencies when an agency filter is given', () { + final Map envelope = envelopeWith( + routes: [ + ucsdRoute(), + ucsdRoute(id: 'MTS_201', shortName: '201', longName: 'Super Loop - Counterclockwise', color: 'CC0000'), + ], + arrivals: [ + arrival(routeId: 'UCSD_1040', scheduledArrivalTime: 1060000), + arrival(routeId: 'MTS_201', scheduledArrivalTime: 1030000), + arrival(routeId: 'NCTD_301', scheduledArrivalTime: 1040000), + ], + ); + + final List filtered = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + expect(filtered.map((s) => s.routeId), [1040]); + + final List unfiltered = arrivingShuttlesFromOneBusAwayEnvelope(envelope); + expect(unfiltered, hasLength(3)); + }); + + test('prefers real-time predictions over scheduled arrival times', () { + final int now = 1000000; + final Map envelope = envelopeWith( + currentTime: now, + arrivals: [arrival(predicted: true, predictedArrivalTime: now + 30000, scheduledArrivalTime: now + 300000)], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles.single.secondsToArrival, 30); + }); + + test('falls back to scheduled arrival time when not predicted', () { + final int now = 1000000; + final Map envelope = envelopeWith( + currentTime: now, + arrivals: [arrival(predicted: false, predictedArrivalTime: now + 30000, scheduledArrivalTime: now + 300000)], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles.single.secondsToArrival, 300); + }); + + test('uses departure time when arrival is disabled or missing', () { + final int now = 1000000; + final Map envelope = envelopeWith( + currentTime: now, + arrivals: [ + arrival(arrivalEnabled: false, scheduledDepartureTime: now + 120000), + arrival(scheduledArrivalTime: 0, scheduledDepartureTime: now + 180000), + ], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles, hasLength(2)); + expect(shuttles[0].secondsToArrival, 120); + expect(shuttles[1].secondsToArrival, 180); + }); + + test('clamps arrivals that are already at the stop to zero seconds', () { + final int now = 1000000; + final Map envelope = envelopeWith( + currentTime: now, + arrivals: [arrival(predicted: true, predictedArrivalTime: now - 30000)], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles.single.secondsToArrival, 0); + }); + + test('skips arrivals without any usable arrival or departure time', () { + final Map envelope = envelopeWith( + arrivals: [ + arrival(), + arrival(scheduledArrivalTime: 0, scheduledDepartureTime: 0), + arrival(arrivalEnabled: false, departureEnabled: false, scheduledArrivalTime: 1500000), + 'not-even-a-map', + null, + ], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles, isEmpty); + }); + + test('resolves the route name with a graceful fallback chain', () { + final Map envelope = envelopeWith( + routes: [ucsdRoute(longName: '', shortName: 'OL')], + arrivals: [ + // referenced route: prefer its short name when long name is empty + arrival(routeId: 'UCSD_1040', routeShortName: 'ignored', scheduledArrivalTime: 1060000), + // unreferenced route: fall back to the fields on the arrival + arrival(routeId: 'UCSD_9999', routeShortName: 'X9', scheduledArrivalTime: 1060000), + // no reference and no short name: fall back to the trip headsign + arrival(routeId: 'UCSD_8888', tripHeadsign: 'UTC', scheduledArrivalTime: 1060000), + ], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles[0].routeName, 'OL'); + expect(shuttles[1].routeName, 'X9'); + expect(shuttles[2].routeName, 'UTC'); + }); + + test('defaults the route name when nothing usable is available', () { + final Map envelope = envelopeWith( + arrivals: [arrival(routeId: 'UCSD_7777', scheduledArrivalTime: 1060000)], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles.single.routeName, 'Route'); + }); + + test('normalizes OneBusAway colors and defaults when unusable', () { + final Map envelope = envelopeWith( + routes: [ + ucsdRoute(id: 'UCSD_1040', color: '182b49'), + ucsdRoute(id: 'UCSD_1030', color: ''), + ucsdRoute(id: 'UCSD_1020', color: 'not-a-color'), + ], + arrivals: [ + arrival(routeId: 'UCSD_1040', scheduledArrivalTime: 1060000), + arrival(routeId: 'UCSD_1030', scheduledArrivalTime: 1060000), + arrival(routeId: 'UCSD_1020', scheduledArrivalTime: 1060000), + // no referenced route at all + arrival(routeId: 'UCSD_1010', scheduledArrivalTime: 1060000), + ], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope(envelope, agencyId: 'UCSD'); + + expect(shuttles[0].routeColor, '#182b49'); + expect(shuttles[1].routeColor, oneBusAwayDefaultRouteColor); + expect(shuttles[2].routeColor, oneBusAwayDefaultRouteColor); + expect(shuttles[3].routeColor, oneBusAwayDefaultRouteColor); + }); + + test('supports an injected reference time for deterministic mapping', () { + final Map envelope = envelopeWith( + currentTime: 500, + arrivals: [arrival(scheduledArrivalTime: 1000000)], + ); + + final List shuttles = arrivingShuttlesFromOneBusAwayEnvelope( + envelope, + agencyId: 'UCSD', + nowMs: 400000, + ); + + expect(shuttles.single.secondsToArrival, 600); + }); + + test('degrades gracefully when data or entry is missing', () { + expect(arrivingShuttlesFromOneBusAwayEnvelope({}), isEmpty); + expect(arrivingShuttlesFromOneBusAwayEnvelope({'data': null}), isEmpty); + expect(arrivingShuttlesFromOneBusAwayEnvelope({'data': {}}), isEmpty); + expect( + arrivingShuttlesFromOneBusAwayEnvelope({ + 'data': {'entry': {}}, + }), + isEmpty, + ); + }); + + test('keeps the legacy JSON parsing behavior intact', () { + const String legacyJson = ''' + [ + { + "routeId": 1040, + "routeName": "Inside Loop", + "routeStopId": 10772, + "routeColor": "#FFCD00", + "secondsToArrival": 120 + } + ] + '''; + + final List shuttles = getArrivingShuttles(legacyJson); + + expect(shuttles, hasLength(1)); + expect(shuttles.single.routeName, 'Inside Loop'); + expect(shuttles.single.routeColor, '#FFCD00'); + expect(shuttles.single.secondsToArrival, 120); + }); + }); +} diff --git a/test/core/models/shuttle_stop_test.dart b/test/core/models/shuttle_stop_test.dart new file mode 100644 index 000000000..c1d50fe4f --- /dev/null +++ b/test/core/models/shuttle_stop_test.dart @@ -0,0 +1,118 @@ +import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('oneBusAwayIdToInt', () { + test('parses the numeric part of an agency-prefixed id', () { + expect(oneBusAwayIdToInt('UCSD_1040'), 1040); + expect(oneBusAwayIdToInt('MTS_201'), 201); + }); + + test('parses an unprefixed numeric id', () { + expect(oneBusAwayIdToInt('1040'), 1040); + }); + + test('uses the segment after the last separator', () { + expect(oneBusAwayIdToInt('A_B_42'), 42); + }); + + test('falls back to a stable non-negative hash for non-numeric ids', () { + final int id = oneBusAwayIdToInt('UCSD_not-a-number'); + expect(id, isNonNegative); + expect(id, oneBusAwayIdToInt('UCSD_not-a-number')); + expect(id, isNot(oneBusAwayIdToInt('UCSD_another-one'))); + }); + }); + + group('shuttleStopsFromOneBusAwayEnvelope', () { + test('maps OneBusAway stops onto the existing ShuttleStopModel shape', () { + final Map envelope = { + 'code': 200, + 'currentTime': 1793245671045, + 'data': { + 'limitExceeded': false, + 'list': [ + { + 'id': 'UCSD_10378', + 'code': '10378', + 'name': 'UCSD Extended Studies Building (South)', + 'lat': 32.871524, + 'lon': -117.233241, + 'routeIds': ['UCSD_1050'], + }, + { + 'id': 'UCSD_10772', + 'code': '10772', + 'name': 'Gilman Transit Center (North)', + 'lat': 32.87719056969953, + 'lon': -117.23570826703958, + 'routeIds': ['UCSD_1040', 'UCSD_1050'], + }, + ], + }, + }; + + final List stops = shuttleStopsFromOneBusAwayEnvelope(envelope); + + expect(stops, hasLength(2)); + final ShuttleStopModel first = stops.first; + expect(first.id, 10378); + expect(first.name, 'UCSD Extended Studies Building (South)'); + expect(first.lat, 32.871524); + expect(first.lon, -117.233241); + expect(first.oneBusAwayId, 'UCSD_10378'); + // the raw id is kept so the arrivals endpoint can be queried with it + expect(stops[1].id, 10772); + expect(stops[1].oneBusAwayId, 'UCSD_10772'); + }); + + test('skips malformed entries instead of crashing', () { + final Map envelope = { + 'code': 200, + 'currentTime': 1793245671045, + 'data': { + 'list': [ + {'id': 'UCSD_10378', 'name': 'Good Stop', 'lat': 32.87, 'lon': -117.23}, + {'id': 'UCSD_BAD', 'name': 'Missing coordinates'}, + {'name': 'Missing id', 'lat': 32.87, 'lon': -117.23}, + 'not-even-a-map', + null, + {'id': '', 'name': 'Empty id', 'lat': 32.87, 'lon': -117.23}, + ], + }, + }; + + final List stops = shuttleStopsFromOneBusAwayEnvelope(envelope); + + expect(stops, hasLength(1)); + expect(stops.single.id, 10378); + }); + + test('degrades gracefully when data or list is missing', () { + expect(shuttleStopsFromOneBusAwayEnvelope({}), isEmpty); + expect(shuttleStopsFromOneBusAwayEnvelope({'data': null}), isEmpty); + expect(shuttleStopsFromOneBusAwayEnvelope({'data': {}}), isEmpty); + expect( + shuttleStopsFromOneBusAwayEnvelope({ + 'data': {'list': null}, + }), + isEmpty, + ); + }); + + test('keeps the legacy JSON parsing behavior intact', () { + const String legacyJson = ''' + { + "789": {"lat": 1.5, "lon": -2.5, "id": 789, "name": "Legacy Stop"} + } + '''; + + final List stops = shuttleStopModelFromJson(legacyJson); + + expect(stops, hasLength(1)); + expect(stops.single.id, 789); + expect(stops.single.name, 'Legacy Stop'); + expect(stops.single.oneBusAwayId, isNull); + }); + }); +} diff --git a/test/core/providers/availability_test.dart b/test/core/providers/availability_test.dart new file mode 100644 index 000000000..a84bb744b --- /dev/null +++ b/test/core/providers/availability_test.dart @@ -0,0 +1,169 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:campus_mobile_experimental/core/providers/availability.dart'; +import 'package:campus_mobile_experimental/core/providers/user.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + for (final silent in [false, true]) { + test('${silent ? 'silent' : 'manual'} refresh recovers from an earlier fetch error', () async { + await _withAvailability((fixture) async { + fixture.statusCode = 503; + await fixture.fetch(); + expect(fixture.provider.error, isNotNull); + expect(fixture.provider.lastUpdated, isNull); + + fixture.statusCode = 200; + await fixture.fetch(silent: silent); + expect(fixture.provider.error, isNull); + expect(fixture.provider.availabilityModels.single!.name, 'Geisel'); + expect(fixture.provider.locationViewState['Geisel'], isTrue); + expect(fixture.provider.lastUpdated, isNotNull); + expect(fixture.provider.isLoading, isFalse); + }); + }); + } + + test('failed silent refresh preserves the last successful data and existing error state', () async { + await _withAvailability((fixture) async { + await fixture.fetch(); + final lastUpdated = fixture.provider.lastUpdated; + final location = fixture.provider.availabilityModels.single; + + fixture.statusCode = 503; + await fixture.fetch(silent: true); + expect(fixture.provider.error, isNull); + expect(fixture.provider.availabilityModels.single, same(location)); + expect(fixture.provider.lastUpdated, lastUpdated); + + await fixture.fetch(); + final error = fixture.provider.error; + expect(error, isNotNull); + await fixture.fetch(silent: true); + expect(fixture.provider.error, error); + expect(fixture.provider.availabilityModels.single, same(location)); + expect(fixture.provider.lastUpdated, lastUpdated); + expect(fixture.provider.isLoading, isFalse); + }); + }); + + test('repeated background failures keep cached data until a successful refresh clears the failure state', () async { + await _withAvailability((fixture) async { + expect(fixture.provider.refreshFailed, isFalse); + await fixture.fetch(); + final lastUpdated = fixture.provider.lastUpdated; + final location = fixture.provider.availabilityModels.single; + + fixture.statusCode = 503; + for (var attempt = 0; attempt < 3; attempt++) { + await fixture.fetch(silent: true); + expect(fixture.provider.refreshFailed, isTrue); + expect(fixture.provider.error, isNull); + expect(fixture.provider.isLoading, isFalse); + expect(fixture.provider.lastUpdated, lastUpdated); + expect(fixture.provider.availabilityModels.single, same(location)); + } + + fixture.statusCode = 200; + fixture.locationName = 'Updated Geisel'; + await fixture.fetch(silent: true); + expect(fixture.provider.refreshFailed, isFalse); + expect(fixture.provider.availabilityModels.single!.name, 'Updated Geisel'); + expect(fixture.provider.lastUpdated!.isAfter(lastUpdated!), isTrue); + }); + }); + + for (final firstSilent in [false, true]) { + for (final secondSilent in [false, true]) { + test( + 'overlapping ${firstSilent ? 'silent' : 'manual'} and ${secondSilent ? 'silent' : 'manual'} refreshes use one request', + () async { + await _withAvailability((fixture) async { + fixture.requestStarted = Completer(); + fixture.responseGate = Completer(); + final first = fixture.fetch(silent: firstSilent); + await fixture.requestStarted!.future.timeout(const Duration(seconds: 5)); + + final second = fixture.fetch(silent: secondSilent); + final loadingBeforeResponse = fixture.provider.isLoading; + fixture.responseGate!.complete(); + await Future.wait([first, second]); + + expect(fixture.requestCount, 1); + expect(loadingBeforeResponse, !firstSilent); + expect(fixture.provider.isLoading, isFalse); + expect(fixture.provider.availabilityModels.single!.name, 'Geisel'); + + // Once the active request finishes, a new refresh must be accepted. + fixture.locationName = 'Updated Geisel'; + await fixture.fetch(silent: secondSilent); + expect(fixture.requestCount, 2); + expect(fixture.provider.availabilityModels.single!.name, 'Updated Geisel'); + }); + }, + ); + } + } +} + +// Use loopback HTTP to exercise the real service without production endpoints. +// Flutter otherwise blocks test HTTP. +class _LocalHttpOverrides extends HttpOverrides {} + +Future _withAvailability(Future Function(_AvailabilityFixture) verify) => HttpOverrides.runZoned(() async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + dotenv.testLoad( + fileInput: 'DEFAULT_TIMEOUT=5000\nAVAILABILITY_API_ENDPOINT=http://127.0.0.1:${server.port}/availability', + ); + final user = UserDataProvider(); + final fixture = _AvailabilityFixture(AvailabilityDataProvider()..userDataProvider = user); + server.listen((request) async { + fixture.requestCount++; + final statusCode = fixture.statusCode; + final locationName = fixture.locationName; + final started = fixture.requestStarted; + if (started != null && !started.isCompleted) started.complete(); + await fixture.responseGate?.future; + request.response.statusCode = statusCode; + request.response.headers.contentType = ContentType.json; + request.response.write( + statusCode == 200 + ? jsonEncode({ + 'status': 'success', + 'timestamp': '2026-10-30T12:00:00Z', + 'data': [ + {'id': 1, 'name': locationName, 'childCounts': []}, + ], + }) + : jsonEncode({'error': 'unavailable'}), + ); + await request.response.close(); + }); + try { + await verify(fixture); + } finally { + fixture.provider.dispose(); + user.dispose(); + await server.close(force: true); + dotenv.clean(); + } +}, createHttpClient: (context) => _LocalHttpOverrides().createHttpClient(context)); + +class _AvailabilityFixture { + _AvailabilityFixture(this.provider); + + final AvailabilityDataProvider provider; + int statusCode = 200; + int requestCount = 0; + String locationName = 'Geisel'; + Completer? requestStarted; + Completer? responseGate; + + Future fetch({bool silent = false}) => + provider.fetchAvailability(silent: silent).timeout(const Duration(seconds: 5)); +} diff --git a/test/core/providers/shuttle_provider_test.dart b/test/core/providers/shuttle_provider_test.dart new file mode 100644 index 000000000..b1479d85c --- /dev/null +++ b/test/core/providers/shuttle_provider_test.dart @@ -0,0 +1,470 @@ +import 'dart:async'; + +import 'package:campus_mobile_experimental/core/models/location.dart'; +import 'package:campus_mobile_experimental/core/models/shuttle_arrival.dart'; +import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; +import 'package:campus_mobile_experimental/core/models/user_profile.dart'; +import 'package:campus_mobile_experimental/core/providers/shuttle.dart'; +import 'package:campus_mobile_experimental/core/providers/user.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle_request_trace.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _ScriptedShuttleService extends ShuttleService { + final Map failures = {5000: 'OneBusAway returned invalid JSON.'}; + final List requestedStopIds = []; + int catalogRequestCount = 0; + String? catalogError; + String? _scriptedError; + + @override + String? get error => _scriptedError; + + @override + List get data => List.unmodifiable([ + ShuttleStopModel(id: 5000, name: 'Failing Stop', lat: 32.0, lon: -117.0), + ShuttleStopModel(id: 4006, name: 'Healthy Empty Stop', lat: 32.1, lon: -117.0), + ShuttleStopModel(id: 10772, name: 'Gilman Transit Center', lat: 32.2, lon: -117.0), + ShuttleStopModel(id: 6000, name: 'Sixth College', lat: 32.3, lon: -117.0), + ShuttleStopModel(id: 7000, name: 'Seventh College', lat: 32.4, lon: -117.0), + ShuttleStopModel(id: 8000, name: 'Eighth College', lat: 32.5, lon: -117.0), + ]); + + @override + Future fetchData({ShuttleRequestContext? requestContext}) async { + catalogRequestCount++; + _scriptedError = catalogError; + return catalogError == null; + } + + @override + Future getArrivingInformation(stopId, {ShuttleRequestContext? requestContext}) async { + requestedStopIds.add(stopId as int); + final error = failures[stopId]; + if (error != null) return ShuttleArrivalResult(arrivals: const [], error: error); + if (stopId != 10772) return const ShuttleArrivalResult(arrivals: []); + return ShuttleArrivalResult( + arrivals: List.unmodifiable([ + ArrivingShuttle(routeId: 1040, routeName: 'Inside Loop', routeColor: '#ffcd00', secondsToArrival: 60), + ]), + ); + } +} + +class _ControlledShuttleService extends _ScriptedShuttleService { + final List> catalogRequests = []; + + @override + Future fetchData({ShuttleRequestContext? requestContext}) async { + final request = Completer(); + catalogRequests.add(request); + final success = await request.future; + _scriptedError = success ? null : 'Failed to reach the OneBusAway API.'; + return success; + } +} + +class _ControlledArrivalShuttleService extends _ScriptedShuttleService { + final Map> arrivalRequests = {}; + + @override + Future getArrivingInformation(stopId, {ShuttleRequestContext? requestContext}) { + final id = stopId as int; + requestedStopIds.add(id); + _scriptedError = null; + final request = Completer(); + arrivalRequests[id] = request; + return request.future; + } + + void completeArrival(int stopId, [List arrivals = const []]) { + arrivalRequests.remove(stopId)!.complete(ShuttleArrivalResult(arrivals: arrivals)); + } +} + +class _TestUserDataProvider extends UserDataProvider { + int profilePosts = 0; + + @override + Future postUserProfile(UserProfileModel profile) async { + profilePosts++; + } +} + +ShuttleDataProvider _provider( + _ScriptedShuttleService service, + List selectedStops, { + ShuttleRequestTraceObserver? requestTraceObserver, +}) { + final user = _TestUserDataProvider(); + user.userProfileModel.selectedStops = selectedStops; + final provider = ShuttleDataProvider(shuttleService: service, requestTraceObserver: requestTraceObserver) + ..userDataProvider = user; + addTearDown(provider.dispose); + addTearDown(user.dispose); + return provider; +} + +void main() { + test('request trace records startup starts and identical-update skips', () async { + final events = []; + final service = _ScriptedShuttleService()..failures.clear(); + final provider = _provider(service, [10772], requestTraceObserver: events.add); + + await provider.fetchStops(true, refreshCatalog: false); + + expect( + events.where((event) => event.kind == ShuttleRequestTraceKind.providerOperationStarted).single.context.trigger, + ShuttleRequestTrigger.startup, + ); + expect( + events + .where((event) => event.kind == ShuttleRequestTraceKind.providerRequestStarted) + .map((event) => event.endpoint), + [ShuttleRequestEndpoint.catalog, ShuttleRequestEndpoint.arrivals], + ); + + events.clear(); + await provider.fetchStops(true, refreshCatalog: false); + + expect(events, hasLength(1)); + expect(events.single.kind, ShuttleRequestTraceKind.providerRequestSkipped); + expect(events.single.context.trigger, ShuttleRequestTrigger.selectionChange); + }); + + test('startup updates share one catalog request and use the latest selection', () async { + final service = _ControlledShuttleService(); + final provider = _provider(service, []); + + final first = provider.fetchStops(true, refreshCatalog: false); + provider.userDataProvider!.userProfileModel.selectedStops = [4006]; + final second = provider.fetchStops(true, refreshCatalog: false); + provider.userDataProvider!.userProfileModel.selectedStops = [10772]; + final third = provider.fetchStops(true, refreshCatalog: false); + + expect(service.catalogRequests, hasLength(1)); + expect(provider.isLoading, isTrue); + + service.catalogRequests.first.complete(true); + await Future.wait([first, second, third]); + + expect(service.catalogRequests, hasLength(1)); + expect(provider.error, isNull); + expect(provider.isLoading, isFalse); + expect(provider.stopsToRender.map((stop) => stop.id), [10772]); + expect(service.requestedStopIds, [10772]); + expect(provider.arrivalsToRender[10772], hasLength(1)); + }); + + test('one failed stop leaves successful arrivals and empty stops visible', () async { + final service = _ScriptedShuttleService(); + final provider = _provider(service, [5000, 4006, 10772]); + + await provider.fetchStops(true); + + expect(provider.error, isNull); + expect(provider.isLoading, isFalse); + expect(provider.stopsToRender.map((stop) => stop.id), [5000, 4006, 10772]); + expect(provider.arrivalErrors, {5000: 'OneBusAway returned invalid JSON.'}); + expect(provider.arrivalsToRender[4006], isEmpty); + expect(provider.arrivalsToRender[10772]!.single.routeName, 'Inside Loop'); + expect(service.error, isNull); + }); + + test('selected stops ignore nulls and duplicates while preserving first-seen order', () async { + final service = _ScriptedShuttleService(); + final provider = _provider(service, [10772, 4006]); + provider.userDataProvider!.userProfileModel.selectedStops = [10772, null, 10772, 4006, 4006]; + + await provider.fetchStops(true); + + expect(provider.stopsToRender.map((stop) => stop.id), [10772, 4006]); + expect(service.requestedStopIds, [10772, 4006]); + expect(provider.userDataProvider!.userProfileModel.selectedStops, [10772, null, 10772, 4006, 4006]); + }); + + test('selected stops ignore unknown ids and stop after five valid unique ids', () async { + final service = _ScriptedShuttleService()..failures.clear(); + final provider = _provider(service, [9999, 5000, 4006, 10772, 6000, 7000, 8000]); + + await provider.fetchStops(true); + + expect(provider.stopsToRender.map((stop) => stop.id), [5000, 4006, 10772, 6000, 7000]); + expect(service.requestedStopIds, [5000, 4006, 10772, 6000, 7000]); + expect(provider.userDataProvider!.userProfileModel.selectedStops, [9999, 5000, 4006, 10772, 6000, 7000, 8000]); + }); + + test('reordering normalizes nullable, duplicate, unknown, and over-limit ids', () async { + final service = _ScriptedShuttleService()..failures.clear(); + final provider = _provider(service, [10772, 4006, 6000, 7000, 8000]); + await provider.fetchStops(true); + service.requestedStopIds.clear(); + + provider.reorderStops([8000, null, 7000, 8000, 6000, 9999, 4006, 10772, 5000]); + await provider.fetchStops(true, refreshCatalog: false); + + expect(provider.userDataProvider!.userProfileModel.selectedStops, [8000, 7000, 6000, 4006, 10772]); + expect(provider.stopsToRender.map((stop) => stop.id), [8000, 7000, 6000, 4006, 10772]); + expect(service.requestedStopIds, isEmpty); + }); + + test('adding rejects duplicate, unknown, and sixth stops without mutation or requests', () async { + final service = _ScriptedShuttleService()..failures.clear(); + final provider = _provider(service, [5000, 4006, 10772, 6000, 7000]); + await provider.fetchStops(true); + service.requestedStopIds.clear(); + + await provider.addStop(5000); + await provider.addStop(9999); + await provider.addStop(8000); + + expect(provider.userDataProvider!.userProfileModel.selectedStops, [5000, 4006, 10772, 6000, 7000]); + expect(service.requestedStopIds, isEmpty); + }); + + test('adding a valid stop persists the normalized selection and requests only that stop', () async { + final service = _ScriptedShuttleService()..failures.clear(); + final provider = _provider(service, [10772]); + provider.userDataProvider!.userProfileModel.selectedStops = [10772, null, 10772, 9999]; + await provider.fetchStops(true); + service.requestedStopIds.clear(); + + await provider.addStop(4006); + + expect(provider.userDataProvider!.userProfileModel.selectedStops, [10772, 4006]); + expect(service.requestedStopIds, [4006]); + expect((provider.userDataProvider! as _TestUserDataProvider).profilePosts, 1); + }); + + test('removing a stop persists the remaining normalized selection', () async { + final service = _ScriptedShuttleService()..failures.clear(); + final provider = _provider(service, [5000, 4006]); + provider.userDataProvider!.userProfileModel.selectedStops = [5000, null, 5000, 9999, 4006]; + await provider.fetchStops(true); + service.requestedStopIds.clear(); + + await provider.removeStop(5000); + + expect(provider.userDataProvider!.userProfileModel.selectedStops, [4006]); + expect(provider.stopsToRender.map((stop) => stop.id), [4006]); + expect((provider.userDataProvider! as _TestUserDataProvider).profilePosts, 1); + expect(service.requestedStopIds, isEmpty); + }); + + test('overlapping notifications share one in-flight arrival request per stop', () async { + final events = []; + final service = _ControlledArrivalShuttleService(); + final provider = _provider(service, [], requestTraceObserver: events.add); + await provider.fetchStops(true, refreshCatalog: false); + provider.userDataProvider!.userProfileModel.selectedStops = [10772]; + + final first = provider.fetchStops(true, refreshCatalog: false); + await Future.delayed(Duration.zero); + final second = provider.fetchStops(true, refreshCatalog: false); + + expect(service.requestedStopIds, [10772]); + expect(events.where((event) => event.kind == ShuttleRequestTraceKind.providerRequestJoined), isNotEmpty); + service.completeArrival(10772); + await Future.wait([first, second]); + expect(service.requestedStopIds, [10772]); + }); + + test('add and profile notification join the same arrival request', () async { + final service = _ControlledArrivalShuttleService(); + final provider = _provider(service, []); + await provider.fetchStops(true, refreshCatalog: false); + + final add = provider.addStop(10772); + await Future.delayed(Duration.zero); + final notification = provider.fetchStops(true, refreshCatalog: false); + + expect(service.requestedStopIds, [10772]); + service.completeArrival(10772); + await Future.wait([add, notification]); + expect(service.requestedStopIds, [10772]); + }); + + test('an in-flight result cannot restore a stop removed during its request', () async { + final events = []; + final service = _ControlledArrivalShuttleService(); + final provider = _provider(service, [], requestTraceObserver: events.add); + await provider.fetchStops(true, refreshCatalog: false); + provider.userDataProvider!.userProfileModel.selectedStops = [10772]; + + final fetch = provider.fetchStops(true, refreshCatalog: false); + await Future.delayed(Duration.zero); + final remove = provider.removeStop(10772); + + service.completeArrival(10772, [ + ArrivingShuttle(routeId: 1040, routeName: 'Inside Loop', routeColor: '#ffcd00', secondsToArrival: 60), + ]); + await Future.wait([fetch, remove]); + + expect(provider.stopsToRender, isEmpty); + expect(provider.arrivalsToRender.containsKey(10772), isFalse); + expect(service.requestedStopIds, [10772]); + expect( + events + .where((event) => event.kind == ShuttleRequestTraceKind.providerResultDiscarded) + .map((event) => event.stopId), + ['10772'], + ); + }); + + test('request budgets match startup and selection lifecycle events', () async { + final events = []; + final service = _ScriptedShuttleService()..failures.clear(); + final provider = _provider(service, [10772, 4006], requestTraceObserver: events.add) + ..userCoords = Coordinates(lat: 32.0, lon: -117.0); + + await provider.fetchStops(true, refreshCatalog: false); + expect(service.catalogRequestCount, 1); + expect(service.requestedStopIds, [10772, 4006]); + + await provider.fetchStops(true, refreshCatalog: false); + expect(service.catalogRequestCount, 1); + expect(service.requestedStopIds, [10772, 4006]); + + provider.reorderStops([4006, 10772]); + await provider.fetchStops(true, refreshCatalog: false); + expect(service.catalogRequestCount, 1); + expect(service.requestedStopIds, [10772, 4006]); + + provider.userCoords = Coordinates(lat: 33.0, lon: -118.0); + await provider.fetchStops(true, refreshCatalog: false); + expect(service.catalogRequestCount, 1); + expect(service.requestedStopIds, [10772, 4006]); + + await provider.addStop(6000); + expect(service.catalogRequestCount, 1); + expect(service.requestedStopIds, [10772, 4006, 6000]); + + await provider.removeStop(4006); + expect(service.catalogRequestCount, 1); + expect(service.requestedStopIds, [10772, 4006, 6000]); + + await provider.fetchStops(true); + expect(service.catalogRequestCount, 2); + expect(service.requestedStopIds, [10772, 4006, 6000, 10772, 6000]); + expect( + events + .where((event) => event.kind == ShuttleRequestTraceKind.providerOperationStarted) + .map((event) => event.context.trigger), + contains(ShuttleRequestTrigger.manualReload), + ); + }); + + test('selection changes during arrivals request only newly needed stops', () async { + final service = _ControlledArrivalShuttleService(); + final provider = _provider(service, []); + await provider.fetchStops(true, refreshCatalog: false); + provider.userDataProvider!.userProfileModel.selectedStops = [10772]; + + final first = provider.fetchStops(true, refreshCatalog: false); + await Future.delayed(Duration.zero); + provider.userDataProvider!.userProfileModel.selectedStops = [10772, 4006]; + final second = provider.fetchStops(true, refreshCatalog: false); + + service.completeArrival(10772); + await Future.delayed(Duration.zero); + expect(service.requestedStopIds, [10772, 4006]); + + service.completeArrival(4006); + await Future.wait([first, second]); + expect(service.requestedStopIds, [10772, 4006]); + }); + + test('dependency updates reuse the catalog while manual reload refreshes it', () async { + final service = _ControlledShuttleService(); + final provider = _provider(service, [4006]); + final initial = provider.fetchStops(true, refreshCatalog: false); + service.catalogRequests.single.complete(true); + await initial; + + await provider.fetchStops(true, refreshCatalog: false); + expect(service.catalogRequests, hasLength(1)); + expect(service.requestedStopIds, [4006]); + + provider.userDataProvider!.userProfileModel.selectedStops = [10772]; + await provider.fetchStops(true, refreshCatalog: false); + expect(service.catalogRequests, hasLength(1)); + expect(provider.arrivalsToRender[10772], hasLength(1)); + expect(service.requestedStopIds, [4006, 10772]); + + final manualReload = provider.fetchStops(true); + expect(service.catalogRequests, hasLength(2)); + service.catalogRequests.last.complete(true); + await manualReload; + expect(provider.error, isNull); + expect(service.requestedStopIds, [4006, 10772, 10772]); + }); + + test('a successful retry clears the affected stop error', () async { + final service = _ScriptedShuttleService(); + final provider = _provider(service, [5000, 4006]); + await provider.fetchStops(true); + expect(provider.arrivalErrors.containsKey(5000), isTrue); + + service.failures.clear(); + await provider.fetchStops(true); + + expect(provider.error, isNull); + expect(provider.arrivalErrors, isEmpty); + expect(provider.arrivalsToRender[5000], isEmpty); + }); + + test('an unselected closest stop is calculated but not requested', () async { + final service = _ScriptedShuttleService(); + final provider = _provider(service, [10772])..userCoords = Coordinates(lat: 32.0, lon: -117.0); + + await provider.fetchStops(true); + + expect(provider.closestStop!.id, 5000); + expect(provider.error, isNull); + expect(provider.arrivalsToRender[10772], hasLength(1)); + expect(service.requestedStopIds, [10772]); + }); + + test('no selected stops makes no arrival requests even when a closest stop exists', () async { + final service = _ScriptedShuttleService(); + final provider = _provider(service, [])..userCoords = Coordinates(lat: 32.0, lon: -117.0); + + await provider.fetchStops(true); + + expect(provider.closestStop!.id, 5000); + expect(service.requestedStopIds, isEmpty); + }); + + test('coordinate-only changes make no catalog or arrival requests', () async { + final service = _ScriptedShuttleService(); + final provider = _provider(service, [10772])..userCoords = Coordinates(lat: 32.0, lon: -117.0); + await provider.fetchStops(true, refreshCatalog: false); + service.requestedStopIds.clear(); + + provider.userCoords = Coordinates(lat: 33.0, lon: -118.0); + await provider.fetchStops(true, refreshCatalog: false); + + expect(service.catalogRequestCount, 1); + expect(service.requestedStopIds, isEmpty); + }); + + test('a selected closest stop is requested only once', () async { + final service = _ScriptedShuttleService(); + final provider = _provider(service, [5000, 4006])..userCoords = Coordinates(lat: 32.0, lon: -117.0); + + await provider.fetchStops(true); + + expect(service.requestedStopIds, [5000, 4006]); + }); + + test('a stop catalog failure still reports a card error', () async { + final service = _ScriptedShuttleService()..catalogError = 'Failed to reach the OneBusAway API.'; + final provider = _provider(service, [4006]); + + await provider.fetchStops(true); + + expect(provider.error, 'Failed to reach the OneBusAway API.'); + expect(provider.isLoading, isFalse); + expect(service.requestedStopIds, isEmpty); + }); +} diff --git a/test/core/services/one_bus_away_client_test.dart b/test/core/services/one_bus_away_client_test.dart new file mode 100644 index 000000000..6572e99b3 --- /dev/null +++ b/test/core/services/one_bus_away_client_test.dart @@ -0,0 +1,374 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:campus_mobile_experimental/core/services/one_bus_away_client.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle_request_trace.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const String testEndpoint = 'https://onebusaway.example.test'; +const String testApiKey = 'unit-test-api-key'; + +/// Fake HTTP layer: replaces dio's [HttpClientAdapter] so no real requests +/// are made. Captures request URIs so URL construction (including the API +/// key parameter) can be asserted. +class _RecordingAdapter implements HttpClientAdapter { + Future Function(RequestOptions options)? handler; + final List requestedUris = []; + + @override + Future fetch(RequestOptions options, Stream? requestStream, Future? cancelFuture) async { + requestedUris.add(options.uri); + final Future Function(RequestOptions options)? configuredHandler = handler; + if (configuredHandler == null) throw StateError('no response handler configured'); + return configuredHandler(options); + } + + @override + void close({bool force = false}) {} +} + +ResponseBody _jsonResponse(Object body, {int status = 200}) => ResponseBody.fromString( + jsonEncode(body), + status, + headers: { + Headers.contentTypeHeader: ['application/json'], + }, +); + +/// Wires a real [OneBusAwayClient] to the fake HTTP adapter. +class _Harness { + _Harness({this.endpoint = testEndpoint, this.apiKey = testApiKey}) { + dio = Dio(); + dio.httpClientAdapter = adapter; + client = OneBusAwayClient( + config: OneBusAwayConfig(apiEndpoint: endpoint, apiKey: apiKey), + dio: dio, + requestTraceObserver: events.add, + ); + } + + final String endpoint; + final String apiKey; + final _RecordingAdapter adapter = _RecordingAdapter(); + final List events = []; + late final Dio dio; + late final OneBusAwayClient client; + + void respond(Object body, {int status = 200}) { + adapter.handler = (_) async => _jsonResponse(body, status: status); + } + + void failWith(Object error) { + adapter.handler = (_) async => throw error; + } +} + +void main() { + final Map stopsEnvelope = { + 'code': 200, + 'currentTime': 1793245671045, + 'data': { + 'limitExceeded': false, + 'list': [ + {'id': 'UCSD_10378', 'lat': 32.871524, 'lon': -117.233241, 'name': 'UCSD Extended Studies Building (South)'}, + {'id': 'UCSD_10772', 'lat': 32.87719, 'lon': -117.235708, 'name': 'Gilman Transit Center (North)'}, + ], + }, + }; + + final Map arrivalsEnvelope = { + 'code': 200, + 'currentTime': 1793245671045, + 'data': { + 'entry': {'stopId': 'UCSD_10772', 'arrivalsAndDepartures': [], 'nearbyStopIds': [], 'situationIds': []}, + 'references': {'routes': [], 'stops': [], 'trips': []}, + }, + }; + + group('OneBusAwayConfig', () { + late DotEnv originalDotEnv; + + setUp(() { + originalDotEnv = dotenv; + dotenv = DotEnv(); + }); + + tearDown(() { + dotenv = originalDotEnv; + }); + + test('reads settings from the app dotenv configuration', () { + dotenv.testLoad(fileInput: 'ONE_BUS_AWAY_API=$testEndpoint\nONE_BUS_AWAY_API_KEY=$testApiKey'); + + final OneBusAwayConfig config = OneBusAwayConfig(); + + expect(config.apiEndpoint, testEndpoint); + expect(config.apiKey, testApiKey); + expect(config.isConfigured, isTrue); + }); + + test('injected values override dotenv configuration, including empty values', () { + dotenv.testLoad(fileInput: 'ONE_BUS_AWAY_API=$testEndpoint\nONE_BUS_AWAY_API_KEY=$testApiKey'); + + final OneBusAwayConfig config = OneBusAwayConfig(apiEndpoint: '', apiKey: ''); + + expect(config.apiEndpoint, isEmpty); + expect(config.apiKey, isEmpty); + expect(config.isConfigured, isFalse); + }); + + test('can construct configuration before dotenv is initialized', () { + expect(dotenv.isInitialized, isFalse); + expect(() => OneBusAwayConfig(), returnsNormally); + }); + + test('injected values take precedence over machine environment', () { + final OneBusAwayConfig config = OneBusAwayConfig(apiEndpoint: testEndpoint, apiKey: testApiKey); + expect(config.apiEndpoint, testEndpoint); + expect(config.apiKey, testApiKey); + expect(config.isConfigured, isTrue); + }); + + test('injected empty values leave the config unconfigured', () { + final OneBusAwayConfig config = OneBusAwayConfig(apiEndpoint: '', apiKey: ''); + expect(config.isConfigured, isFalse); + }); + + test('toString never leaks the endpoint or the key', () { + final OneBusAwayConfig config = OneBusAwayConfig(apiEndpoint: testEndpoint, apiKey: testApiKey); + final String description = config.toString(); + expect(description.contains(testEndpoint), isFalse); + expect(description.contains(testApiKey), isFalse); + }); + }); + + group('OneBusAwayClient.fetchStopsForAgency', () { + test('requests the stops-for-agency endpoint with the key as a query parameter', () async { + final _Harness harness = _Harness()..respond(stopsEnvelope); + + final Map envelope = await harness.client.fetchStopsForAgency(); + + expect(envelope['code'], 200); + expect(envelope['data']['list'], hasLength(2)); + expect(harness.adapter.requestedUris, hasLength(1)); + final Uri uri = harness.adapter.requestedUris.first; + expect(uri.host, 'onebusaway.example.test'); + expect(uri.path, '/api/where/stops-for-agency/UCSD.json'); + expect(uri.queryParameters['key'], testApiKey); + }); + + test('tolerates a trailing slash on the configured endpoint', () async { + final _Harness harness = _Harness(endpoint: '$testEndpoint/')..respond(stopsEnvelope); + + final Map envelope = await harness.client.fetchStopsForAgency(); + + expect(envelope['code'], 200); + final Uri uri = harness.adapter.requestedUris.first; + expect(uri.path, '/api/where/stops-for-agency/UCSD.json'); + expect('//'.allMatches(uri.path), isEmpty); + }); + + test('requests stops for a custom agency when provided', () async { + final _Harness harness = _Harness()..respond(stopsEnvelope); + + await harness.client.fetchStopsForAgency(agencyId: 'MTS'); + + expect(harness.adapter.requestedUris.first.path, '/api/where/stops-for-agency/MTS.json'); + }); + }); + + group('OneBusAwayClient.fetchArrivalsAndDeparturesForStop', () { + test('requests arrivals for the given raw OneBusAway stop id', () async { + final _Harness harness = _Harness()..respond(arrivalsEnvelope); + + final Map envelope = await harness.client.fetchArrivalsAndDeparturesForStop('UCSD_10772'); + + expect(envelope['code'], 200); + expect(harness.adapter.requestedUris, hasLength(1)); + final Uri uri = harness.adapter.requestedUris.first; + expect(uri.path, '/api/where/arrivals-and-departures-for-stop/UCSD_10772.json'); + expect(uri.queryParameters['key'], testApiKey); + }); + + test('emits sanitized logical-request and HTTP-attempt events', () async { + final harness = _Harness()..respond(arrivalsEnvelope); + const context = ShuttleRequestContext(operationId: 42, trigger: ShuttleRequestTrigger.selectionChange); + + await harness.client.fetchArrivalsAndDeparturesForStop('UCSD_10772', requestContext: context); + + expect(harness.events.map((event) => event.kind), [ + ShuttleRequestTraceKind.logicalRequestStarted, + ShuttleRequestTraceKind.httpAttemptStarted, + ShuttleRequestTraceKind.httpAttemptSucceeded, + ]); + final completed = harness.events.last; + expect(completed.context.operationId, 42); + expect(completed.endpoint, ShuttleRequestEndpoint.arrivals); + expect(completed.stopId, 'UCSD_10772'); + expect(completed.logicalRequestId, 1); + expect(completed.attempt, 1); + expect(completed.statusCode, 200); + expect(completed.elapsed, isNotNull); + for (final event in harness.events) { + expect(event.toString(), isNot(contains(testEndpoint))); + expect(event.toString(), isNot(contains(testApiKey))); + } + }); + }); + + group('OneBusAwayClient error handling', () { + test('waits for Retry-After before retrying a rate-limited request', () async { + final harness = _Harness(); + var attempts = 0; + harness.adapter.handler = (_) async { + attempts++; + if (attempts == 1) { + return ResponseBody.fromString( + '{}', + 429, + headers: { + Headers.contentTypeHeader: ['application/json'], + 'retry-after': ['1'], + }, + ); + } + return _jsonResponse(stopsEnvelope); + }; + + final pending = harness.client.fetchStopsForAgency(); + await Future.delayed(const Duration(milliseconds: 50)); + expect(attempts, 1); + final envelope = await pending; + + expect(attempts, 2); + expect(envelope['code'], 200); + expect( + harness.events.where((event) => event.kind == ShuttleRequestTraceKind.logicalRequestStarted), + hasLength(1), + ); + expect( + harness.events + .where((event) => event.kind == ShuttleRequestTraceKind.httpAttemptStarted) + .map((event) => event.attempt), + [1, 2], + ); + expect(harness.events.where((event) => event.kind == ShuttleRequestTraceKind.retryScheduled), hasLength(1)); + }); + + test('stops retrying after repeated rate limiting', () async { + final harness = _Harness(); + var attempts = 0; + harness.adapter.handler = (_) async { + attempts++; + return ResponseBody.fromString( + '{}', + 429, + headers: { + Headers.contentTypeHeader: ['application/json'], + 'retry-after': ['0'], + }, + ); + }; + + await expectLater( + harness.client.fetchStopsForAgency(), + throwsA(isA().having((e) => e.message, 'message', contains('HTTP 429'))), + ); + expect(attempts, 3); + }); + + test('throws a sanitized error on HTTP failure', () async { + final _Harness harness = _Harness()..respond({'error': 'boom'}, status: 500); + + await expectLater( + harness.client.fetchStopsForAgency(), + throwsA( + isA() + .having((e) => e.message, 'message', contains('HTTP 500')) + .having((e) => e.message, 'message', isNot(contains(testEndpoint))) + .having((e) => e.message, 'message', isNot(contains(testApiKey))), + ), + ); + }); + + test('throws a sanitized error on connection failure', () async { + final _Harness harness = _Harness()..failWith(Exception('connection refused to $testEndpoint?key=$testApiKey')); + + await expectLater( + harness.client.fetchStopsForAgency(), + throwsA( + isA() + .having((e) => e.message, 'message', isNot(contains(testEndpoint))) + .having((e) => e.message, 'message', isNot(contains(testApiKey))), + ), + ); + }); + + test('throws a sanitized error when the response is not valid JSON', () async { + final _Harness harness = _Harness() + ..adapter.handler = (_) async => ResponseBody.fromString( + 'not json at all', + 200, + headers: { + Headers.contentTypeHeader: ['application/json'], + }, + ); + + await expectLater( + harness.client.fetchStopsForAgency(), + throwsA(isA().having((e) => e.message, 'message', 'OneBusAway returned invalid JSON.')), + ); + }); + + test('reports an unexpected JSON shape without echoing response contents', () async { + final _Harness harness = _Harness()..respond(['$testEndpoint?key=$testApiKey']); + + await expectLater( + harness.client.fetchArrivalsAndDeparturesForStop('UCSD_4006'), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'OneBusAway returned an unexpected JSON response shape.', + ), + ), + ); + }); + + test('reports a malformed status code without echoing its value', () async { + final _Harness harness = _Harness()..respond({'code': '$testEndpoint?key=$testApiKey'}); + + await expectLater( + harness.client.fetchArrivalsAndDeparturesForStop('UCSD_4006'), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'OneBusAway response is missing a numeric status code.', + ), + ), + ); + }); + + test('throws when the OneBusAway envelope reports a non-200 code', () async { + final _Harness harness = _Harness()..respond({'code': 404, 'data': null}); + + await expectLater( + harness.client.fetchStopsForAgency(), + throwsA(isA().having((e) => e.message, 'message', contains('404'))), + ); + }); + + test('throws without making a request when the API is not configured', () async { + final _Harness harness = _Harness(endpoint: '', apiKey: ''); + + await expectLater( + harness.client.fetchStopsForAgency(), + throwsA(isA().having((e) => e.message, 'message', contains('not configured'))), + ); + expect(harness.adapter.requestedUris, isEmpty); + }); + }); +} diff --git a/test/core/services/shuttle_service_test.dart b/test/core/services/shuttle_service_test.dart new file mode 100644 index 000000000..6540075a3 --- /dev/null +++ b/test/core/services/shuttle_service_test.dart @@ -0,0 +1,266 @@ +import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; +import 'package:campus_mobile_experimental/core/services/one_bus_away_client.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle.dart'; +import 'package:campus_mobile_experimental/core/services/shuttle_request_trace.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Fake OneBusAway client: stands in for the HTTP layer so the service is +/// tested without touching the live API. +class _FakeOneBusAwayClient extends OneBusAwayClient { + _FakeOneBusAwayClient({this.stopsEnvelope, this.arrivalsEnvelope, this.error}) + : super( + config: OneBusAwayConfig(apiEndpoint: '', apiKey: ''), + ); + + final Map? stopsEnvelope; + final Map? arrivalsEnvelope; + + /// Mutable so a single fake can script a failure followed by a success. + Object? error; + + final List requestedStopIds = []; + + @override + Future> fetchStopsForAgency({ + String agencyId = OneBusAwayClient.defaultAgencyId, + ShuttleRequestContext? requestContext, + }) async { + if (error != null) throw error!; + return stopsEnvelope!; + } + + @override + Future> fetchArrivalsAndDeparturesForStop( + String stopId, { + ShuttleRequestContext? requestContext, + }) async { + if (error != null) throw error!; + requestedStopIds.add(stopId); + return arrivalsEnvelope!; + } +} + +class _PerStopOneBusAwayClient extends _FakeOneBusAwayClient { + _PerStopOneBusAwayClient({required super.arrivalsEnvelope}); + + @override + Future> fetchArrivalsAndDeparturesForStop( + String stopId, { + ShuttleRequestContext? requestContext, + }) async { + requestedStopIds.add(stopId); + if (stopId == '5000') { + throw const OneBusAwayException('Failed to reach the OneBusAway API (HTTP 503).'); + } + return arrivalsEnvelope!; + } +} + +Map _stopsEnvelope() => { + 'code': 200, + 'currentTime': 1793245671045, + 'data': { + 'list': [ + {'id': 'UCSD_10772', 'name': 'Gilman Transit Center (North)', 'lat': 32.87719, 'lon': -117.235708}, + {'id': 'UCSD_10378', 'name': 'UCSD Extended Studies Building (South)', 'lat': 32.871524, 'lon': -117.233241}, + ], + }, +}; + +const int _now = 1000000; + +Map _arrivalsEnvelope() => { + 'code': 200, + 'currentTime': _now, + 'data': { + 'entry': { + 'stopId': 'UCSD_10772', + 'arrivalsAndDepartures': [ + { + 'routeId': 'UCSD_1040', + 'routeShortName': 'IL', + 'predicted': true, + 'predictedArrivalTime': _now + 60000, + 'scheduledArrivalTime': _now + 90000, + 'arrivalEnabled': true, + 'departureEnabled': true, + 'stopId': 'UCSD_10772', + }, + { + 'routeId': 'MTS_201', + 'routeShortName': '201', + 'predicted': true, + 'predictedArrivalTime': _now + 30000, + 'arrivalEnabled': true, + 'departureEnabled': true, + 'stopId': 'UCSD_10772', + }, + ], + }, + 'references': { + 'routes': [ + {'id': 'UCSD_1040', 'shortName': 'IL', 'longName': 'Inside Loop', 'color': 'ffcd00'}, + ], + }, + }, +}; + +void main() { + group('ShuttleService.fetchData', () { + test('populates the stop list from the OneBusAway stops feed', () async { + final ShuttleService service = ShuttleService(client: _FakeOneBusAwayClient(stopsEnvelope: _stopsEnvelope())); + + final bool success = await service.fetchData(); + + expect(success, isTrue); + expect(service.error, isNull); + expect(service.data, hasLength(2)); + expect(service.data.first.id, 10772); + expect(service.data.first.name, 'Gilman Transit Center (North)'); + expect(service.data.first.oneBusAwayId, 'UCSD_10772'); + }); + + test('reports a sanitized error when the client fails', () async { + const String endpoint = 'https://onebusaway.example.test'; + const String apiKey = 'unit-test-api-key'; + final ShuttleService service = ShuttleService( + client: _FakeOneBusAwayClient(error: OneBusAwayException('Failed to reach the OneBusAway API (HTTP 500).')), + ); + + final bool success = await service.fetchData(); + + expect(success, isFalse); + expect(service.error, contains('HTTP 500')); + // errors surfaced to the UI must never contain credentials + expect(service.error?.contains(endpoint), isFalse); + expect(service.error?.contains(apiKey), isFalse); + }); + + test('clears a previous error after a successful fetch', () async { + final _FakeOneBusAwayClient failingClient = _FakeOneBusAwayClient( + stopsEnvelope: _stopsEnvelope(), + error: const OneBusAwayException('Failed to reach the OneBusAway API.'), + ); + final ShuttleService service = ShuttleService(client: failingClient); + + expect(await service.fetchData(), isFalse); + expect(service.error, isNotNull); + + failingClient.error = null; + expect(await service.fetchData(), isTrue); + expect(service.error, isNull); + }); + }); + + group('ShuttleService.getArrivingInformation', () { + test('an empty arrivals response with MTS references succeeds', () async { + final ShuttleService service = ShuttleService( + client: _FakeOneBusAwayClient( + arrivalsEnvelope: { + 'code': 200, + 'currentTime': 1793993241998, + 'data': { + 'entry': { + 'arrivalsAndDepartures': [], + 'nearbyStopIds': ['MTS_99385'], + 'situationIds': [], + 'stopId': 'UCSD_4006', + }, + 'references': { + 'routes': [ + {'agencyId': 'MTS', 'id': 'MTS_43', 'longName': 'Balboa Av TC - Kearny Mesa', 'color': '000099'}, + ], + }, + }, + }, + ), + ); + + final result = await service.getArrivingInformation(4006); + + expect(result.arrivals, isEmpty); + expect(result.error, isNull); + expect(service.error, isNull); + expect(service.isLoading, isFalse); + }); + + test('queries arrivals with the raw OneBusAway stop id', () async { + final _FakeOneBusAwayClient client = _FakeOneBusAwayClient( + stopsEnvelope: _stopsEnvelope(), + arrivalsEnvelope: _arrivalsEnvelope(), + ); + final ShuttleService service = ShuttleService(client: client); + await service.fetchData(); + + final ShuttleArrivalResult result = await service.getArrivingInformation(10772); + + // the integer id used by the UI is translated back to UCSD_10772 + expect(client.requestedStopIds, ['UCSD_10772']); + expect(result.error, isNull); + expect(result.arrivals, hasLength(1)); + expect(result.arrivals.single.routeName, 'Inside Loop'); + expect(result.arrivals.single.routeColor, '#ffcd00'); + expect(result.arrivals.single.secondsToArrival, 60); + }); + + test('falls back to the stop id as-is when the stop was never fetched', () async { + final _FakeOneBusAwayClient client = _FakeOneBusAwayClient(arrivalsEnvelope: _arrivalsEnvelope()); + final ShuttleService service = ShuttleService(client: client); + + await service.getArrivingInformation(10772); + + expect(client.requestedStopIds, ['10772']); + }); + + test('returns an empty result with a stop-specific sanitized error when the client fails', () async { + final ShuttleService service = ShuttleService( + client: _FakeOneBusAwayClient(error: OneBusAwayException('Failed to reach the OneBusAway API (HTTP 404).')), + ); + + final ShuttleArrivalResult result = await service.getArrivingInformation(10772); + + expect(result.arrivals, isEmpty); + expect(result.error, contains('HTTP 404')); + expect(service.error, isNull); + }); + + test('concurrent stops keep success and failure results independent', () async { + final service = ShuttleService(client: _PerStopOneBusAwayClient(arrivalsEnvelope: _arrivalsEnvelope())); + + final results = await Future.wait([service.getArrivingInformation(5000), service.getArrivingInformation(10772)]); + + expect(results[0].arrivals, isEmpty); + expect(results[0].error, contains('HTTP 503')); + expect(results[1].arrivals, hasLength(1)); + expect(results[1].error, isNull); + expect(service.error, isNull); + }); + + test('keeps isLoading accurate around requests', () async { + final _FakeOneBusAwayClient client = _FakeOneBusAwayClient( + stopsEnvelope: _stopsEnvelope(), + arrivalsEnvelope: _arrivalsEnvelope(), + ); + final ShuttleService service = ShuttleService(client: client); + + expect(service.isLoading, isFalse); + final Future pending = service.fetchData(); + expect(service.isLoading, isTrue); + await pending; + expect(service.isLoading, isFalse); + }); + }); + + group('ShuttleService contract with the provider', () { + test('model getters used by the Transit UI remain available', () async { + final ShuttleService service = ShuttleService(client: _FakeOneBusAwayClient(stopsEnvelope: _stopsEnvelope())); + await service.fetchData(); + + // the provider relies on these members + expect(service.data, isA>()); + expect(service.error, isNull); + expect(service.lastUpdated, isNull); + expect(service.isLoading, isFalse); + }); + }); +} diff --git a/test/ui/availability/availability_card_test.dart b/test/ui/availability/availability_card_test.dart new file mode 100644 index 000000000..1170255a2 --- /dev/null +++ b/test/ui/availability/availability_card_test.dart @@ -0,0 +1,427 @@ +import 'package:campus_mobile_experimental/app_constants.dart'; +import 'package:campus_mobile_experimental/app_styles.dart'; +import 'package:campus_mobile_experimental/core/models/availability.dart'; +import 'package:campus_mobile_experimental/core/providers/availability.dart'; +import 'package:campus_mobile_experimental/core/providers/bottom_nav.dart'; +import 'package:campus_mobile_experimental/core/providers/cards.dart'; +import 'package:campus_mobile_experimental/ui/availability/availability_card.dart'; +import 'package:campus_mobile_experimental/ui/common/last_updated_widget.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() => TestWidgetsFlutterBinding.instance.handleAppLifecycleStateChanged(AppLifecycleState.resumed)); + + setUpAll(() async { + // Use the app's actual fonts so narrow-screen measurements are realistic. + final bodyFonts = FontLoader('Brix Sans') + ..addFont(rootBundle.load('assets/fonts/HVD Fonts - BrixSansMedium.otf')) + ..addFont(rootBundle.load('assets/fonts/HVD Fonts - BrixSansMedium-Italic.otf')) + ..addFont(rootBundle.load('assets/fonts/HVD Fonts - BrixSansBold.otf')); + final headingFonts = FontLoader('Refrigerator Deluxe') + ..addFont(rootBundle.load('assets/fonts/Refrigerator Deluxe Bold.otf')); + await bodyFonts.load(); + await headingFonts.load(); + }); + + for (final brightness in Brightness.values) { + for (final scale in [1.0, 2.0]) { + testWidgets('timestamp and action fit a 320px screen in ${brightness.name} mode at ${scale}x text', ( + tester, + ) async { + final availability = _AvailabilityProvider(DateTime.now().subtract(const Duration(minutes: 5)))..failed = true; + await _showCard(tester, brightness: brightness, scale: scale, provider: availability); + final timestamp = find.byWidgetPredicate( + (widget) => widget is Text && (widget.data?.contains('Updated') ?? false), + ); + final action = find.text('MANAGE LOCATIONS'); + final timestampParagraph = tester.renderObject(timestamp); + final actionParagraph = tester.renderObject(action); + + expect(timestampParagraph.didExceedMaxLines, isFalse); + expect(actionParagraph.didExceedMaxLines, isFalse); + expect(find.text('Unable to refresh. Showing last available data.'), findsOneWidget); + expect(tester.getRect(timestamp).top, greaterThanOrEqualTo(tester.getRect(action).bottom)); + expect(tester.getRect(timestamp).left, closeTo(tester.getRect(action).left, 0.1)); + expect(tester.takeException(), isNull); + }); + } + } + + testWidgets('does not show a timestamp before the first successful update', (tester) async { + await _showCard(tester, showTimestamp: false); + expect(find.textContaining('Updated'), findsNothing); + expect(find.text('MANAGE LOCATIONS'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('failed refreshes rebuild the cached age and show a note until recovery', (tester) async { + final lastUpdated = DateTime.now().subtract(const Duration(hours: 3)); + final availability = _AvailabilityProvider(lastUpdated); + await _showCard(tester, provider: availability); + const failureNote = 'Unable to refresh. Showing last available data.'; + expect(find.text(failureNote), findsNothing); + var previousLabel = tester.widget(find.byType(LastUpdatedWidget)); + + for (var attempt = 0; attempt < 3; attempt++) { + availability.failed = true; + availability.notifyListeners(); + await tester.pump(); + final label = tester.widget(find.byType(LastUpdatedWidget)); + expect(label.time, lastUpdated); + expect(label, isNot(same(previousLabel))); + expect(find.text('Last Updated: ${LastUpdatedWidget.determineText(lastUpdated)}'), findsOneWidget); + expect(find.text(failureNote), findsOneWidget); + expect(find.textContaining('Live'), findsNothing); + previousLabel = label; + } + + availability.failed = false; + availability.notifyListeners(); + await tester.pump(); + expect(find.text(failureNote), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('enabled card refreshes silently every 90 seconds', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + await _showCard(tester, provider: availability); + + await tester.pump(const Duration(seconds: 89)); + expect(availability.refreshModes, isEmpty); + await tester.pump(const Duration(seconds: 1)); + expect(availability.refreshModes, [true]); + await tester.pump(const Duration(seconds: 90)); + expect(availability.refreshModes, [true, true]); + }); + + testWidgets('hidden card does not start polling', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + final cards = CardsDataProvider()..cardStates[cardId] = false; + await _showCard(tester, provider: availability, cardsProvider: cards); + + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + }); + + testWidgets('hiding a mounted card cancels polling', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + final cards = CardsDataProvider(); + await _showCard(tester, provider: availability, cardsProvider: cards); + await tester.pump(const Duration(seconds: 90)); + expect(availability.refreshModes, [true]); + + cards.cardStates[cardId] = false; + cards.notifyListeners(); + await tester.pump(); + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, [true]); + }); + + for (final tab in [ + NavigatorConstants.MAP_TAB, + NavigatorConstants.AI_ASSISTANT_TAB, + NavigatorConstants.NOTIFICATIONS_TAB, + NavigatorConstants.PROFILE_TAB, + ]) { + testWidgets('card does not poll when tab $tab is initially selected', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + final navigation = BottomNavigationBarProvider()..currentIndex = tab; + await _showCard(tester, provider: availability, navigationProvider: navigation); + + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + }); + } + + testWidgets('switching tabs pauses polling and returning to Home resumes it', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + final navigation = BottomNavigationBarProvider(); + await _showCard(tester, provider: availability, navigationProvider: navigation); + await tester.pump(const Duration(seconds: 60)); + + navigation.currentIndex = NavigatorConstants.MAP_TAB; + // Advance through the old deadline before rebuilding to check live tab state. + await tester.pump(const Duration(seconds: 30)); + expect(availability.refreshModes, isEmpty); + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + + navigation.currentIndex = NavigatorConstants.HOME_TAB; + await tester.pump(); + await tester.pump(const Duration(seconds: 89)); + expect(availability.refreshModes, isEmpty); + await tester.pump(const Duration(seconds: 1)); + expect(availability.refreshModes, [true]); + }); + + for (final state in AppLifecycleState.values.where((state) => state != AppLifecycleState.resumed)) { + testWidgets('card does not start polling in ${state.name} lifecycle state', (tester) async { + tester.binding.handleAppLifecycleStateChanged(state); + final availability = _AvailabilityProvider(DateTime.now()); + await _showCard(tester, provider: availability); + + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + }); + + testWidgets('${state.name} pauses polling and resuming restarts it', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + await _showCard(tester, provider: availability); + await tester.pump(const Duration(seconds: 60)); + + tester.binding.handleAppLifecycleStateChanged(state); + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(const Duration(seconds: 89)); + expect(availability.refreshModes, isEmpty); + await tester.pump(const Duration(seconds: 1)); + expect(availability.refreshModes, [true]); + }); + } + + for (final age in [null, const Duration(seconds: 90), const Duration(minutes: 5)]) { + testWidgets('activation promptly refreshes ${age == null ? 'missing' : '$age old'} data', (tester) async { + final availability = _AvailabilityProvider(age == null ? null : DateTime.now().subtract(age)) + ..notifyOnFetch = true; + await _showCard(tester, provider: availability); + + expect(availability.refreshModes, [true]); + availability.notifyListeners(); + await tester.pump(); + expect(availability.refreshModes, [true]); + }); + } + + for (final activity in ['card', 'tab', 'app']) { + testWidgets('returning after $activity inactivity refreshes stale data promptly', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + final cards = CardsDataProvider(); + final navigation = BottomNavigationBarProvider(); + await _showCard(tester, provider: availability, cardsProvider: cards, navigationProvider: navigation); + + void setActive(bool active) { + switch (activity) { + case 'card': + cards.cardStates[cardId] = active; + cards.notifyListeners(); + break; + case 'tab': + navigation.currentIndex = active ? NavigatorConstants.HOME_TAB : NavigatorConstants.MAP_TAB; + break; + case 'app': + tester.binding.handleAppLifecycleStateChanged( + active ? AppLifecycleState.resumed : AppLifecycleState.paused, + ); + break; + } + } + + setActive(false); + await tester.pump(); + availability.updatedAt = DateTime.now().subtract(const Duration(minutes: 5)); + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + + setActive(true); + await tester.pump(); + expect(availability.refreshModes, [true]); + await tester.pump(const Duration(seconds: 90)); + expect(availability.refreshModes, [true, true]); + }); + } + + testWidgets('all activity conditions must hold before stale data refreshes', (tester) async { + final availability = _AvailabilityProvider(DateTime.now().subtract(const Duration(minutes: 5))); + final cards = CardsDataProvider()..cardStates[cardId] = false; + final navigation = BottomNavigationBarProvider()..currentIndex = NavigatorConstants.MAP_TAB; + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + await _showCard(tester, provider: availability, cardsProvider: cards, navigationProvider: navigation); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + cards.cardStates[cardId] = true; + cards.notifyListeners(); + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + navigation.currentIndex = NavigatorConstants.HOME_TAB; + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + expect(availability.refreshModes, [true]); + }); + + testWidgets('rapid lifecycle transitions discard obsolete activation callbacks', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + await _showCard(tester, provider: availability); + availability.updatedAt = DateTime.now().subtract(const Duration(minutes: 5)); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + await tester.pump(); + expect(availability.refreshModes, isEmpty); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + expect(availability.refreshModes, [true]); + await tester.pump(const Duration(seconds: 90)); + expect(availability.refreshModes, [true, true]); + }); + + testWidgets('activation checks freshness again after the frame', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + await _showCard(tester, provider: availability); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + availability.updatedAt = DateTime.now().subtract(const Duration(minutes: 5)); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + + // Another request completed before the deferred activation refresh. + availability.updatedAt = DateTime.now(); + availability.notifyListeners(); + await tester.pump(); + expect(availability.refreshModes, isEmpty); + await tester.pump(const Duration(seconds: 90)); + expect(availability.refreshModes, [true]); + }); + + testWidgets('repeated activity changes keep one timer and rebuilds preserve its deadline', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + final cards = CardsDataProvider(); + final navigation = BottomNavigationBarProvider(); + await _showCard(tester, provider: availability, cardsProvider: cards, navigationProvider: navigation); + + for (var cycle = 0; cycle < 3; cycle++) { + cards.cardStates[cardId] = false; + cards.notifyListeners(); + navigation.currentIndex = NavigatorConstants.MAP_TAB; + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + await tester.pump(); + + cards.cardStates[cardId] = true; + cards.notifyListeners(); + navigation.currentIndex = NavigatorConstants.HOME_TAB; + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + } + await tester.pump(const Duration(seconds: 60)); + availability.notifyListeners(); + cards.notifyListeners(); + navigation.currentIndex = NavigatorConstants.HOME_TAB; + await tester.pump(); + expect(availability.refreshModes, isEmpty); + await tester.pump(const Duration(seconds: 30)); + expect(availability.refreshModes, [true]); + await tester.pump(const Duration(seconds: 90)); + expect(availability.refreshModes, [true, true]); + }); + + testWidgets('disposal cancels polling, pending activation refreshes, and lifecycle observation', (tester) async { + final availability = _AvailabilityProvider(DateTime.now()); + await _showCard(tester, provider: availability); + availability.updatedAt = DateTime.now().subtract(const Duration(minutes: 5)); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 3)); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(const Duration(minutes: 3)); + expect(availability.refreshModes, isEmpty); + expect(tester.takeException(), isNull); + }); +} + +Future _showCard( + WidgetTester tester, { + Brightness brightness = Brightness.light, + double scale = 1, + bool showTimestamp = true, + _AvailabilityProvider? provider, + CardsDataProvider? cardsProvider, + BottomNavigationBarProvider? navigationProvider, +}) async { + tester.view.physicalSize = const Size(320, 640); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final availability = + provider ?? _AvailabilityProvider(showTimestamp ? DateTime.now().subtract(const Duration(minutes: 5)) : null); + final cards = cardsProvider ?? CardsDataProvider(); + final navigation = navigationProvider ?? BottomNavigationBarProvider(); + addTearDown(() async { + await tester.pumpWidget(const SizedBox()); + availability.dispose(); + cards.dispose(); + navigation.dispose(); + }); + final dark = brightness == Brightness.dark; + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: availability), + ChangeNotifierProvider.value(value: cards), + ChangeNotifierProvider.value(value: navigation), + ], + child: MaterialApp( + theme: ThemeData( + useMaterial3: false, + brightness: brightness, + fontFamily: 'Brix Sans', + textTheme: TextTheme( + titleLarge: dark ? cardTitleStyleDark : cardTitleStyleLight, + bodyMedium: dark ? bodyMediumDark : bodyMediumLight, + labelLarge: dark ? labelLargeStyleDark : labelLargeStyleLight, + ), + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(scale)), + child: child!, + ), + home: Scaffold( + body: SingleChildScrollView( + child: Padding(padding: const EdgeInsets.symmetric(horizontal: 8), child: AvailabilityCard()), + ), + ), + ), + ), + ); +} + +class _AvailabilityProvider extends AvailabilityDataProvider { + _AvailabilityProvider(this.updatedAt); + + DateTime? updatedAt; + bool failed = false; + bool notifyOnFetch = false; + final refreshModes = []; + + @override + Future fetchAvailability({bool silent = false}) async { + refreshModes.add(silent); + if (notifyOnFetch) notifyListeners(); + } + + @override + bool get refreshFailed => failed; + + @override + DateTime? get lastUpdated => updatedAt; + + @override + List get availabilityModels => []; +} diff --git a/test/ui/common/last_updated_widget_test.dart b/test/ui/common/last_updated_widget_test.dart new file mode 100644 index 000000000..18e484bb0 --- /dev/null +++ b/test/ui/common/last_updated_widget_test.dart @@ -0,0 +1,44 @@ +import 'package:campus_mobile_experimental/app_styles.dart'; +import 'package:campus_mobile_experimental/ui/common/last_updated_widget.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final staleAges = { + const Duration(minutes: 5): '5 minutes ago', + const Duration(hours: 3): '3 hours ago', + const Duration(days: 3): '3 days ago', + }; + for (final entry in staleAges.entries) { + test('stale timestamp displays ${entry.value}', () { + final lastUpdated = DateTime.now().subtract(entry.key); + expect(LastUpdatedWidget.determineText(lastUpdated), entry.value); + }); + } + + for (final brightness in Brightness.values) { + testWidgets('last updated text is readable in ${brightness.name} mode', (tester) async { + final background = brightness == Brightness.dark ? darkPrimaryBgColor : lightAccentColor; + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(brightness: brightness), + home: Scaffold( + body: Card( + color: background, + child: LastUpdatedWidget(time: DateTime.now().subtract(const Duration(minutes: 5))), + ), + ), + ), + ); + + final text = tester.widget(find.byType(Text)); + expect(text.data, 'Last Updated: 5 minutes ago'); + expect(text.style!.fontSize, greaterThanOrEqualTo(16)); + final foregroundLuminance = text.style!.color!.computeLuminance(); + final backgroundLuminance = background.computeLuminance(); + final lighter = foregroundLuminance > backgroundLuminance ? foregroundLuminance : backgroundLuminance; + final darker = foregroundLuminance < backgroundLuminance ? foregroundLuminance : backgroundLuminance; + expect((lighter + 0.05) / (darker + 0.05), greaterThanOrEqualTo(4.5)); + }); + } +} diff --git a/test/ui/common/shuttle_card_menu_test.dart b/test/ui/common/shuttle_card_menu_test.dart new file mode 100644 index 000000000..49552d459 --- /dev/null +++ b/test/ui/common/shuttle_card_menu_test.dart @@ -0,0 +1,59 @@ +import 'package:campus_mobile_experimental/ui/common/card_container.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + for (final width in [320.0, 412.0]) { + for (final scale in [1.0, 2.0]) { + testWidgets('shuttle menu labels and actions work at ${width}px with ${scale}x text', (tester) async { + await tester.binding.setSurfaceSize(Size(width, 800)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + var reloads = 0; + var hides = 0; + await tester.pumpWidget( + MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(scale)), + child: child!, + ), + home: Scaffold( + body: SingleChildScrollView( + child: CardContainer( + titleText: 'SHUTTLE', + active: true, + isLoading: false, + errorText: null, + reload: () => reloads++, + hide: () => hides++, + child: () => const Text('Shuttle stop'), + ), + ), + ), + ), + ); + + for (final label in ['reload card', 'hide card']) { + await tester.tap(find.byTooltip('SHUTTLE Card Menu')); + await tester.pumpAndSettle(); + expect(find.text('reload card'), findsOneWidget); + expect(find.text('hide card'), findsOneWidget); + expect(tester.takeException(), isNull); + + final text = find.text(label); + final item = find.ancestor(of: text, matching: find.byType(PopupMenuItem)); + final textRect = tester.getRect(text); + final itemRect = tester.getRect(item); + expect(textRect.left, greaterThanOrEqualTo(itemRect.left)); + expect(textRect.right, lessThanOrEqualTo(itemRect.right)); + expect(textRect.bottom, lessThanOrEqualTo(itemRect.bottom)); + + await tester.tap(text); + await tester.pumpAndSettle(); + } + expect(reloads, 1); + expect(hides, 1); + expect(tester.takeException(), isNull); + }); + } + } +} diff --git a/test/ui/home/home_background_test.dart b/test/ui/home/home_background_test.dart new file mode 100644 index 000000000..8a8560912 --- /dev/null +++ b/test/ui/home/home_background_test.dart @@ -0,0 +1,202 @@ +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:campus_mobile_experimental/ui/home/home_background.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _images = [ + (asset: 'circle-1-background.png', native: Size(1679, 1571), display: Size(298.64, 280)), + (asset: 'circle-3-background.png', native: Size(1404, 1398), display: Size(300, 298.6)), + (asset: 'circle-4-background.png', native: Size(1876, 1870), display: Size(399.7, 398)), + (asset: 'circle-2-background.png', native: Size(2401, 2401), display: Size(136, 136)), + (asset: 'circle-5-background.png', native: Size(2401, 2401), display: Size(197, 197)), + (asset: 'circle-6-background.png', native: Size(2401, 2401), display: Size(188, 188)), +]; + +void main() { + final binding = _ImageTestBinding(); + final cache = binding.imageCache as _RecordingImageCache; + + tearDown(() { + cache.clear(); + cache.clearLiveImages(); + }); + + for (final ratio in [1.0, 2.0, 2.5, 3.0, 4.0]) { + testWidgets('background decodes actual PNGs for pixel ratio $ratio', (tester) async { + final painter = const HomeBackgroundDecoration().createBoxPainter(() {}); + addTearDown(painter.dispose); + await tester.runAsync(() async { + final recorder = ui.PictureRecorder(); + cache.startBatch(); + painter.paint( + Canvas(recorder), + Offset.zero, + ImageConfiguration(bundle: rootBundle, devicePixelRatio: ratio, size: const Size(400, 3700)), + ); + recorder.endRecording().dispose(); + await cache.batch.future.timeout(const Duration(seconds: 10)); + }); + + expect(cache.images, hasLength(6)); + for (final spec in _images) { + final actual = cache.images.entries.singleWhere((entry) => entry.key.contains(spec.asset)).value; + expect(actual.width, lessThanOrEqualTo((spec.display.width * ratio).ceil()), reason: spec.asset); + expect(actual.height, lessThanOrEqualTo((spec.display.height * ratio).ceil()), reason: spec.asset); + final aspectRatio = spec.native.width / spec.native.height; + expect( + (actual.width - actual.height * aspectRatio).abs(), + lessThanOrEqualTo(1 + aspectRatio), + reason: '${spec.asset}: allow one physical pixel of rounding per axis', + ); + final alpha = cache.alpha.entries.singleWhere((entry) => entry.key.contains(spec.asset)).value; + expect(alpha, (min: 0, max: 255), reason: '${spec.asset}: retain transparent and opaque pixels'); + } + final bytes = cache.images.values.fold(0, (sum, size) => sum + size.width * size.height * 4); + print('Pixel ratio $ratio: ${(bytes / (1024 * 1024)).toStringAsFixed(2)} MiB of decoded RGBA pixels'); + }); + } + + testWidgets('the same painter updates decode sizes when pixel ratio changes', (tester) async { + final painter = const HomeBackgroundDecoration().createBoxPainter(() {}); + addTearDown(painter.dispose); + final widths = []; + for (final ratio in [1.0, 3.0]) { + await tester.runAsync(() async { + cache.startBatch(); + final recorder = ui.PictureRecorder(); + painter.paint( + Canvas(recorder), + Offset.zero, + ImageConfiguration(bundle: rootBundle, devicePixelRatio: ratio, size: const Size(400, 3700)), + ); + recorder.endRecording().dispose(); + await cache.batch.future.timeout(const Duration(seconds: 10)); + }); + widths.add( + cache.images.entries.singleWhere((entry) => entry.key.contains('circle-2-background.png')).value.width, + ); + } + expect(widths, [136, 408]); + }); + + for (final width in [320, 800]) { + testWidgets('right-edge circle keeps the 390-pixel reference crop at width $width', (tester) async { + final painter = const HomeBackgroundDecoration().createBoxPainter(() {}); + addTearDown(painter.dispose); + await tester.runAsync(() async { + cache.startBatch(); + final recorder = ui.PictureRecorder(); + painter.paint( + Canvas(recorder), + Offset.zero, + ImageConfiguration(bundle: rootBundle, devicePixelRatio: 1, size: const Size(390, 1600)), + ); + recorder.endRecording().dispose(); + await cache.batch.future.timeout(const Duration(seconds: 10)); + + Future rightEdge(int canvasWidth) async { + final recorder = ui.PictureRecorder(); + painter.paint( + Canvas(recorder), + const Offset(0, -1065), + ImageConfiguration(bundle: rootBundle, devicePixelRatio: 1, size: Size(canvasWidth.toDouble(), 1600)), + ); + final picture = recorder.endRecording(); + final image = await picture.toImage(canvasWidth, 398); + picture.dispose(); + final bytes = (await image.toByteData(format: ui.ImageByteFormat.rawRgba))!.buffer.asUint8List(); + image.dispose(); + final edge = Uint8List(200 * 398 * 4); + for (var row = 0; row < 398; row++) { + final source = (row * canvasWidth + canvasWidth - 200) * 4; + edge.setRange(row * 800, (row + 1) * 800, bytes, source); + expect( + bytes[(row * canvasWidth + canvasWidth - 201) * 4 + 3], + 0, + reason: 'circle should not extend left of its 200-pixel edge crop', + ); + } + return edge; + } + + final reference = await rightEdge(390); + expect( + [for (var index = 3; index < reference.length; index += 4) reference[index]].any((alpha) => alpha > 0), + isTrue, + reason: 'reference crop must contain visible circle pixels', + ); + final actual = await rightEdge(width); + var maxDifference = 0; + for (var index = 0; index < actual.length; index++) { + final difference = (actual[index] - reference[index]).abs(); + if (difference > maxDifference) maxDifference = difference; + } + // Fractional image bounds can round a channel by one byte when translated. + expect( + maxDifference, + lessThanOrEqualTo(1), + reason: 'retain the right-edge crop within 1/255 of raster rounding per channel', + ); + }); + }); + } +} + +class _ImageTestBinding extends AutomatedTestWidgetsFlutterBinding { + @override + ImageCache createImageCache() => _RecordingImageCache(); +} + +class _RecordingImageCache extends ImageCache { + final images = {}; + final alpha = {}; + late Completer batch; + + void startBatch() { + images.clear(); + alpha.clear(); + batch = Completer(); + } + + @override + ImageStreamCompleter? putIfAbsent(Object key, ImageStreamCompleter Function() loader, {ImageErrorListener? onError}) { + final stream = super.putIfAbsent(key, loader, onError: onError); + if (stream != null) { + late ImageStreamListener listener; + listener = ImageStreamListener( + (info, _) { + stream.removeListener(listener); + unawaited(_capture(stream.debugLabel ?? key.toString(), info)); + }, + onError: (Object error, StackTrace? stack) { + if (!batch.isCompleted) batch.completeError(error, stack); + }, + ); + stream.addListener(listener); + } + return stream; + } + + Future _capture(String label, ImageInfo info) async { + try { + final bytes = (await info.image.toByteData(format: ui.ImageByteFormat.rawRgba))!; + var minimum = 255; + var maximum = 0; + for (var index = 3; index < bytes.lengthInBytes; index += 4) { + final value = bytes.getUint8(index); + if (value < minimum) minimum = value; + if (value > maximum) maximum = value; + } + alpha[label] = (min: minimum, max: maximum); + images[label] = Size(info.image.width.toDouble(), info.image.height.toDouble()); + if (images.length == 6 && !batch.isCompleted) batch.complete(); + } catch (error, stack) { + if (!batch.isCompleted) batch.completeError(error, stack); + } finally { + info.dispose(); + } + } +} diff --git a/test/ui/home/home_scroll_test.dart b/test/ui/home/home_scroll_test.dart new file mode 100644 index 000000000..07cda6c16 --- /dev/null +++ b/test/ui/home/home_scroll_test.dart @@ -0,0 +1,360 @@ +import 'dart:ui' as ui; + +import 'package:campus_mobile_experimental/app_styles.dart'; +import 'package:campus_mobile_experimental/core/models/cards.dart'; +import 'package:campus_mobile_experimental/core/models/notices.dart'; +import 'package:campus_mobile_experimental/core/providers/cards.dart'; +import 'package:campus_mobile_experimental/core/providers/connectivity.dart'; +import 'package:campus_mobile_experimental/core/providers/notices.dart'; +import 'package:campus_mobile_experimental/ui/home/home.dart'; +import 'package:campus_mobile_experimental/ui/navigator/bottom.dart'; +import 'package:campus_mobile_experimental/ui/notices/notices_card.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:visibility_detector/visibility_detector.dart'; +import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart' as web; + +const _bannerUrl = 'https://example.invalid/home-scroll-test.png'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + resetHomeScrollOffset(); + final visibilityController = VisibilityDetectorController.instance; + final previousInterval = visibilityController.updateInterval; + visibilityController.updateInterval = Duration.zero; + addTearDown(() => visibilityController.updateInterval = previousInterval); + final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(const MethodChannel('com.llfbandit.app_links/messages'), (_) async => null); + messenger.setMockMethodCallHandler(const MethodChannel('com.llfbandit.app_links/events'), (_) async => null); + }); + + Future<_NoticesProvider> showHome( + WidgetTester tester, + int count, { + bool mockDecorations = false, + CardsDataProvider? cards, + }) async { + tester.view.physicalSize = const Size(400, 600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + // Cache a real banner image so the actual notice cards have deterministic + // dimensions without HTTP requests or application service initialization. + final image = await tester.runAsync(() async { + final recorder = ui.PictureRecorder(); + Canvas(recorder).drawRect(const Rect.fromLTWH(0, 0, 300, 120), Paint()..color = Colors.blue); + final picture = recorder.endRecording(); + final image = await picture.toImage(300, 120); + picture.dispose(); + return image; + }); + PaintingBinding.instance.imageCache.putIfAbsent( + const NetworkImage(_bannerUrl), + () => OneFrameImageStreamCompleter(Future.value(ImageInfo(image: image!))), + ); + + if (mockDecorations) { + final circleImage = await tester.runAsync(() async { + final recorder = ui.PictureRecorder(); + Canvas(recorder).drawRect(const Rect.fromLTWH(0, 0, 300, 300), Paint()..color = const Color(0xFFFF0000)); + final picture = recorder.endRecording(); + final image = await picture.toImage(300, 300); + picture.dispose(); + return image; + }); + for (final circle in [ + (asset: 'circle-1-background.png', size: Size(298.64, 280)), + (asset: 'circle-2-background.png', size: Size(136, 136)), + (asset: 'circle-4-background.png', size: Size(399.7, 398)), + (asset: 'circle-5-background.png', size: Size(197, 197)), + (asset: 'circle-6-background.png', size: Size(188, 188)), + (asset: 'circle-3-background.png', size: Size(300, 298.6)), + ]) { + final key = await ResizeImage( + AssetImage('assets/images/circles/${circle.asset}'), + width: circle.size.width.ceil(), + height: circle.size.height.ceil(), + policy: ResizeImagePolicy.fit, + ).obtainKey(const ImageConfiguration(devicePixelRatio: 1)); + PaintingBinding.instance.imageCache.evict(key); + PaintingBinding.instance.imageCache.putIfAbsent( + key, + () => OneFrameImageStreamCompleter(Future.value(ImageInfo(image: circleImage!.clone()))), + ); + } + circleImage!.dispose(); + } + + final notices = _NoticesProvider(count); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => cards ?? _EmptyCardsProvider()), + ChangeNotifierProvider(create: (_) => InternetConnectivityProvider()), + ChangeNotifierProvider.value(value: notices), + ], + child: MaterialApp( + home: Scaffold( + body: RepaintBoundary(key: const ValueKey('home capture'), child: Home()), + ), + ), + ), + ); + await tester.pumpAndSettle(); + addTearDown(() async { + await tester.pumpWidget(const SizedBox()); + notices.dispose(); + PaintingBinding.instance.imageCache.clear(); + PaintingBinding.instance.imageCache.clearLiveImages(); + }); + return notices; + } + + ScrollPosition position(WidgetTester tester) => tester.state(find.byType(Scrollable)).position; + + Finder emptyStatePadding() => find.ancestor( + of: find.text('All cards hidden.\nPlease enable them in\nProfile > Card Settings'), + matching: find.byWidgetPredicate((widget) => widget is Padding && widget.padding == const EdgeInsets.all(32)), + ); + + Future pixel(WidgetTester tester, int x, int y) async { + final boundary = tester.renderObject(find.byKey(const ValueKey('home capture'))); + return (await tester.runAsync(() async { + final image = await boundary.toImage(); + final bytes = (await image.toByteData(format: ui.ImageByteFormat.rawRgba))!; + final index = (y * image.width + x) * 4; + final color = Color.fromARGB( + bytes.getUint8(index + 3), + bytes.getUint8(index), + bytes.getUint8(index + 1), + bytes.getUint8(index + 2), + ); + image.dispose(); + return color; + }))!; + } + + testWidgets('empty home does not scroll for decorations', (tester) async { + await showHome(tester, 0); + expect(position(tester).maxScrollExtent, 0); + expect(tester.takeException(), isNull); + }); + + testWidgets('one short card does not scroll for decorations', (tester) async { + await showHome(tester, 1); + expect(find.byType(NoticesCard), findsOneWidget); + expect(tester.getSize(find.byType(NoticesCard)).height, greaterThan(120)); + expect(position(tester).maxScrollExtent, 0); + expect(tester.takeException(), isNull); + }); + + testWidgets('long home reaches the final card with normal bottom padding', (tester) async { + await showHome(tester, 32); + final scrollPosition = position(tester); + expect(scrollPosition.maxScrollExtent, greaterThan(0)); + scrollPosition.jumpTo(scrollPosition.maxScrollExtent); + await tester.pumpAndSettle(); + final lastCard = find.byWidgetPredicate((widget) => widget is NoticesCard && widget.notice.title == 'Notice 31'); + expect(lastCard, findsOneWidget); + expect(emptyStatePadding(), findsOneWidget); + expect(tester.getBottomLeft(lastCard).dy, closeTo(tester.getTopLeft(emptyStatePadding()).dy, 0.01)); + final contentBottom = tester.getBottomLeft(emptyStatePadding()).dy; + expect(contentBottom, closeTo(scrollPosition.viewportDimension - cardMargin - 2, 0.01)); + expect(tester.takeException(), isNull); + }); + + testWidgets('home mounts cards near the viewport and mounts later cards on scroll', (tester) async { + await showHome(tester, 32); + final initialCount = find.byType(NoticesCard).evaluate().length; + expect(initialCount, greaterThan(0)); + expect(initialCount, lessThan(32)); + expect( + find.byWidgetPredicate((widget) => widget is NoticesCard && widget.notice.title == 'Notice 31'), + findsNothing, + ); + + final scrollPosition = position(tester); + scrollPosition.jumpTo(scrollPosition.maxScrollExtent); + await tester.pumpAndSettle(); + expect( + find.byWidgetPredicate((widget) => widget is NoticesCard && widget.notice.title == 'Notice 31'), + findsOneWidget, + ); + expect(find.byType(NoticesCard).evaluate().length, lessThan(32)); + expect(tester.takeException(), isNull); + }); + + testWidgets('home restores a saved scroll offset', (tester) async { + setHomeScrollOffset(1000); + await showHome(tester, 32); + expect(position(tester).pixels, closeTo(1000, 0.01)); + expect(tester.takeException(), isNull); + }); + + testWidgets('offscreen WebView controller is created and loads only when approached', (tester) async { + final previousPlatform = web.WebViewPlatform.instance; + final platform = _WebViewPlatform(); + web.WebViewPlatform.instance = platform; + addTearDown(() => web.WebViewPlatform.instance = previousPlatform ?? _WebViewPlatform()); + await showHome(tester, 32, cards: _WebCardsProvider()); + expect(platform.controllers, isEmpty); + position(tester).jumpTo(position(tester).maxScrollExtent); + await tester.pumpAndSettle(); + expect(platform.controllers, hasLength(1)); + expect(platform.controllers.single.requests, contains('https://example.invalid/web-card')); + expect(tester.takeException(), isNull); + }); + + testWidgets('shortening the list clamps the existing scroll offset', (tester) async { + final notices = await showHome(tester, 32); + final scrollPosition = position(tester); + scrollPosition.jumpTo(scrollPosition.maxScrollExtent); + await tester.pump(); + notices.setCount(1); + await tester.pumpAndSettle(); + expect(position(tester).maxScrollExtent, 0); + expect(position(tester).pixels, 0); + expect(tester.getTopLeft(find.byType(NoticesCard)).dy, closeTo(0, 0.01)); + expect(tester.takeException(), isNull); + }); + + testWidgets('decorations are clipped to the card content and bottom padding bounds', (tester) async { + await showHome(tester, 1, mockDecorations: true); + final sliver = tester.renderObject(find.byType(DecoratedSliver)); + final cardHeight = tester.getSize(find.byType(NoticesCard)).height; + expect(emptyStatePadding(), findsOneWidget); + final emptyStateHeight = tester.getSize(emptyStatePadding()).height; + expect(sliver.geometry!.scrollExtent, closeTo(cardHeight + emptyStateHeight + cardMargin + 2, 0.01)); + expect(await pixel(tester, 398, 500), Colors.transparent); + expect(tester.takeException(), isNull); + }); + + testWidgets('decorations cover bottom padding at the end of scrolling', (tester) async { + // Two notices plus the empty-state message end within circle 1's bounds. + await showHome(tester, 2, mockDecorations: true); + tester.view.physicalSize = const Size(400, 400); + await tester.pumpAndSettle(); + final scrollPosition = position(tester); + expect(scrollPosition.maxScrollExtent, greaterThan(0)); + scrollPosition.jumpTo(scrollPosition.maxScrollExtent); + await tester.pumpAndSettle(); + expect(emptyStatePadding(), findsOneWidget); + final contentBottom = tester.getBottomLeft(emptyStatePadding()).dy; + expect(contentBottom, closeTo(scrollPosition.viewportDimension - cardMargin - 2, 0.01)); + // Circle 1 intersects the content end. Check continuity into the final + // padding and through the last visible row, outside the cards horizontally. + expect(await pixel(tester, 398, 389), const Color(0xFFFF0000)); + expect(await pixel(tester, 398, 399), const Color(0xFFFF0000)); + expect(tester.takeException(), isNull); + }); + + testWidgets('circles remain behind the cards and move with scrolling', (tester) async { + await showHome(tester, 32, mockDecorations: true); + expect(await pixel(tester, 398, 500), const Color(0xFFFF0000)); + expect(await pixel(tester, 100, 60), const Color(0xFF2196F3)); + position(tester).jumpTo(100); + await tester.pumpAndSettle(); + expect(await pixel(tester, 398, 400), const Color(0xFFFF0000)); + expect(tester.takeException(), isNull); + }); +} + +class _EmptyCardsProvider extends CardsDataProvider { + @override + List get cardOrder => []; +} + +class _NoticesProvider extends NoticesDataProvider { + _NoticesProvider(this.count); + + int count; + + void setCount(int value) { + count = value; + notifyListeners(); + } + + @override + List get noticesModel => + List.generate(count, (index) => NoticesModel(title: 'Notice $index', imageUrl: _bannerUrl, link: '')); +} + +class _WebCardsProvider extends CardsDataProvider { + @override + List get cardOrder => ['review_web']; + + @override + Map get cardStates => {'review_web': true}; + + @override + Map get webCards => { + 'review_web': CardsModel( + cardActive: true, + initialURL: 'https://example.invalid/web-card', + isWebCard: true, + requireAuth: false, + titleText: 'Test web card', + ), + }; +} + +class _WebViewPlatform extends web.WebViewPlatform { + final controllers = <_WebViewController>[]; + + @override + web.PlatformWebViewController createPlatformWebViewController(web.PlatformWebViewControllerCreationParams params) { + final controller = _WebViewController(params); + controllers.add(controller); + return controller; + } + + @override + web.PlatformNavigationDelegate createPlatformNavigationDelegate( + web.PlatformNavigationDelegateCreationParams params, + ) => _NavigationDelegate(params); + + @override + web.PlatformWebViewWidget createPlatformWebViewWidget(web.PlatformWebViewWidgetCreationParams params) => + _WebViewWidget(params); +} + +class _WebViewController extends web.PlatformWebViewController { + _WebViewController(super.params) : super.implementation(); + + final requests = []; + + @override + Future setJavaScriptMode(web.JavaScriptMode mode) async {} + + @override + Future addJavaScriptChannel(web.JavaScriptChannelParams params) async {} + + @override + Future setPlatformNavigationDelegate(web.PlatformNavigationDelegate delegate) async {} + + @override + Future loadRequest(web.LoadRequestParams params) async => requests.add(params.uri.toString()); + + @override + Future currentUrl() async => requests.isEmpty ? null : requests.last; +} + +class _NavigationDelegate extends web.PlatformNavigationDelegate { + _NavigationDelegate(super.params) : super.implementation(); + + @override + Future setOnPageFinished(web.PageEventCallback callback) async {} +} + +class _WebViewWidget extends web.PlatformWebViewWidget { + _WebViewWidget(super.params) : super.implementation(); + + @override + Widget build(BuildContext context) => const SizedBox.expand(); +} diff --git a/test/ui/map/map_layout_test.dart b/test/ui/map/map_layout_test.dart new file mode 100644 index 000000000..3574b95e1 --- /dev/null +++ b/test/ui/map/map_layout_test.dart @@ -0,0 +1,246 @@ +import 'package:campus_mobile_experimental/app_constants.dart'; +import 'package:campus_mobile_experimental/core/providers/bottom_nav.dart'; +import 'package:campus_mobile_experimental/core/providers/map.dart'; +import 'package:campus_mobile_experimental/ui/map/map.dart'; +import 'package:campus_mobile_experimental/ui/map/map_search_bar_ph.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:google_maps_flutter/google_maps_flutter.dart'; +import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; +import 'package:provider/provider.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const messagesChannel = MethodChannel('com.llfbandit.app_links/messages'); + const eventsChannel = MethodChannel('com.llfbandit.app_links/events'); + late GoogleMapsFlutterPlatform originalPlatform; + late _MapPlatform platform; + late BottomNavigationBarProvider navigation; + late _MapsDataProvider maps; + int initialLinkReads = 0; + int linkSubscriptions = 0; + int linkCancellations = 0; + + setUp(() { + originalPlatform = GoogleMapsFlutterPlatform.instance; + platform = _MapPlatform(); + GoogleMapsFlutterPlatform.instance = platform; + navigation = BottomNavigationBarProvider(); + maps = _MapsDataProvider(); + initialLinkReads = 0; + linkSubscriptions = 0; + linkCancellations = 0; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(messagesChannel, ( + call, + ) async { + if (call.method == 'getInitialAppLink') initialLinkReads++; + return null; + }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(eventsChannel, ( + call, + ) async { + if (call.method == 'listen') linkSubscriptions++; + if (call.method == 'cancel') linkCancellations++; + return null; + }); + }); + + tearDown(() { + GoogleMapsFlutterPlatform.instance = originalPlatform; + navigation.dispose(); + maps.dispose(); + }); + + for (final screenSize in [const Size(320, 568), const Size(430, 932)]) { + testWidgets('map warms up at full viewport size before opening its tab at $screenSize', (tester) async { + await tester.binding.setSurfaceSize(screenSize); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget(_app(navigation, maps)); + expect(platform.viewIds, isEmpty); + final viewportSize = tester.getSize(find.byKey(const Key('viewport'))); + await tester.pump(); + expect(platform.viewIds, hasLength(1)); + expect(platform.constraints.last, BoxConstraints.tight(viewportSize)); + + navigation.currentIndex = NavigatorConstants.MAP_TAB; + await tester.pump(); + expect(tester.getSize(find.byType(Maps)), viewportSize); + expect(platform.viewIds, hasLength(1)); + expect(platform.constraints.last, BoxConstraints.tight(viewportSize)); + expect(tester.getSize(find.byType(GoogleMap)), viewportSize); + expect(tester.getSize(find.byType(MapSearchBarPlaceHolder)).height, lessThan(viewportSize.height / 2)); + final mapState = tester.state(find.byType(GoogleMap)); + + navigation.currentIndex = NavigatorConstants.HOME_TAB; + await tester.pump(); + maps.notifyListeners(); + await tester.pump(); + navigation.currentIndex = NavigatorConstants.MAP_TAB; + await tester.pump(); + expect(tester.state(find.byType(GoogleMap)), same(mapState)); + expect(platform.viewIds, hasLength(1)); + expect(platform.constraints.every((value) => value == BoxConstraints.tight(viewportSize)), isTrue); + expect(initialLinkReads, 1); + expect(linkSubscriptions, 1); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect(linkCancellations, 1); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('starting directly on the map waits for its first layout', (tester) async { + navigation.currentIndex = NavigatorConstants.MAP_TAB; + await tester.pumpWidget(_app(navigation, maps)); + expect(platform.viewIds, isEmpty); + final viewportSize = tester.getSize(find.byType(Maps)); + await tester.pump(); + expect(platform.viewIds, hasLength(1)); + expect(platform.constraints.last, BoxConstraints.tight(viewportSize)); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + testWidgets('loading feedback appears only on the map and clears when the native view is ready', (tester) async { + await tester.pumpWidget(_app(navigation, maps)); + await tester.pump(); + expect(find.byType(CircularProgressIndicator, skipOffstage: false), findsNothing); + + navigation.currentIndex = NavigatorConstants.MAP_TAB; + await tester.pump(); + final viewportSize = tester.getSize(find.byType(Maps)); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect( + tester.widget(find.byType(CircularProgressIndicator)).semanticsLabel, + 'Loading map', + ); + + final controller = _MapController(); + tester.widget(find.byType(GoogleMap)).onMapCreated!(controller); + await tester.pump(); + expect(maps.mapController, same(controller)); + expect(find.byType(CircularProgressIndicator, skipOffstage: false), findsNothing); + expect(tester.getSize(find.byType(Maps)), viewportSize); + expect(platform.viewIds, hasLength(1)); + + navigation.currentIndex = NavigatorConstants.HOME_TAB; + await tester.pump(); + navigation.currentIndex = NavigatorConstants.MAP_TAB; + await tester.pump(); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(platform.viewIds, hasLength(1)); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + testWidgets('map ready callback is safe if the page was removed during initialization', (tester) async { + await tester.pumpWidget(_app(navigation, maps)); + await tester.pump(); + final onMapCreated = tester.widget(find.byType(GoogleMap, skipOffstage: false)).onMapCreated!; + await tester.pumpWidget(const SizedBox.shrink()); + onMapCreated(_MapController()); + await tester.pump(); + expect(maps.mapController, isNull); + expect(tester.takeException(), isNull); + }); + + testWidgets('a map warmed up on Home opens without showing loading feedback', (tester) async { + await tester.pumpWidget(_app(navigation, maps)); + await tester.pump(); + tester.widget(find.byType(GoogleMap, skipOffstage: false)).onMapCreated!(_MapController()); + await tester.pump(); + + navigation.currentIndex = NavigatorConstants.MAP_TAB; + await tester.pump(); + expect(find.byType(GoogleMap), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(platform.viewIds, hasLength(1)); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + testWidgets('a startup search link opens the map without repeating the search on rebuild', (tester) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(messagesChannel, ( + call, + ) async { + if (call.method == 'getInitialAppLink') { + initialLinkReads++; + return 'https://mobile.ucsd.edu/deeplinking.searchmap?query=Price%20Center'; + } + return null; + }); + await tester.pumpWidget(_app(navigation, maps)); + await tester.pump(); + await tester.pump(); + expect(navigation.currentIndex, NavigatorConstants.MAP_TAB); + expect(maps.searchBarController.text, 'Price Center'); + expect(maps.searches, 1); + expect(platform.viewIds, hasLength(1)); + + maps.notifyListeners(); + await tester.pump(); + expect(maps.searches, 1); + expect(initialLinkReads, 1); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect(tester.takeException(), isNull); + }); +} + +Widget _app(BottomNavigationBarProvider navigation, MapsDataProvider maps) => MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: navigation), + ChangeNotifierProvider.value(value: maps), + ], + child: MaterialApp( + home: Scaffold( + appBar: AppBar(toolbarHeight: 57), + body: Consumer( + builder: (context, provider, _) => SizedBox.expand( + key: const Key('viewport'), + child: IndexedStack(index: provider.currentIndex, children: [const SizedBox.expand(), Maps()]), + ), + ), + bottomNavigationBar: const SizedBox(height: 73), + ), + ), +); + +class _MapPlatform extends GoogleMapsFlutterPlatform { + final Set viewIds = {}; + final List constraints = []; + + @override + Widget buildViewWithConfiguration( + int creationId, + PlatformViewCreatedCallback onPlatformViewCreated, { + required MapWidgetConfiguration widgetConfiguration, + MapConfiguration mapConfiguration = const MapConfiguration(), + MapObjects mapObjects = const MapObjects(), + }) { + viewIds.add(creationId); + // Measure the bounds passed to the native view without loading a Maps SDK. + return LayoutBuilder( + builder: (context, bounds) { + constraints.add(bounds); + return const SizedBox.expand(); + }, + ); + } +} + +class _MapsDataProvider extends MapsDataProvider { + int searches = 0; + + @override + void fetchLocations() { + searches++; + } +} + +class _MapController extends Fake implements GoogleMapController {} diff --git a/test/ui/shuttle/manage_shuttle_view_test.dart b/test/ui/shuttle/manage_shuttle_view_test.dart new file mode 100644 index 000000000..c871d2a12 --- /dev/null +++ b/test/ui/shuttle/manage_shuttle_view_test.dart @@ -0,0 +1,46 @@ +import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; +import 'package:campus_mobile_experimental/core/providers/shuttle.dart'; +import 'package:campus_mobile_experimental/ui/navigator/top.dart'; +import 'package:campus_mobile_experimental/ui/shuttle/manage_shuttle_view.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; + +class _ManageShuttleProvider extends ShuttleDataProvider { + final List stops = [ + ShuttleStopModel(id: 1, name: 'First stop', lat: 32.0, lon: -117.0), + ShuttleStopModel(id: 2, name: 'Second stop', lat: 32.1, lon: -117.1), + ]; + List? reorderedIds; + + @override + List get stopsToRender => stops.toList(growable: false); + + @override + void reorderStops(List? order) { + reorderedIds = order; + } +} + +void main() { + testWidgets('reordering stops copies the fixed provider list before mutation', (tester) async { + final provider = _ManageShuttleProvider(); + addTearDown(provider.dispose); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: provider), + ChangeNotifierProvider(create: (_) => CustomAppBar()), + ], + child: MaterialApp(home: Scaffold(body: ManageShuttleView())), + ), + ); + + final list = tester.widget(find.byType(ReorderableListView)); + list.onReorderItem!(0, 1); + await tester.pump(); + + expect(provider.reorderedIds, [2, 1]); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/ui/shuttle/shuttle_card_layout_test.dart b/test/ui/shuttle/shuttle_card_layout_test.dart new file mode 100644 index 000000000..c8e464454 --- /dev/null +++ b/test/ui/shuttle/shuttle_card_layout_test.dart @@ -0,0 +1,150 @@ +import 'package:campus_mobile_experimental/app_constants.dart'; +import 'package:campus_mobile_experimental/core/models/shuttle_arrival.dart'; +import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; +import 'package:campus_mobile_experimental/core/providers/cards.dart'; +import 'package:campus_mobile_experimental/core/providers/shuttle.dart'; +import 'package:campus_mobile_experimental/ui/shuttle/shuttle_card.dart'; +import 'package:dots_indicator/dots_indicator.dart'; +import 'package:firebase_analytics_platform_interface/firebase_analytics_platform_interface.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/test.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; + +class _LayoutShuttleProvider extends ShuttleDataProvider { + _LayoutShuttleProvider() { + arrivalsToRender[1] = [ + ArrivingShuttle(routeId: 1040, routeName: 'Inside Loop', routeColor: '#ffcd00', secondsToArrival: 420), + ArrivingShuttle(routeId: 1041, routeName: 'SIO Shuttle', routeColor: '#8fa9d2', secondsToArrival: 540), + ArrivingShuttle(routeId: 1041, routeName: 'SIO Shuttle', routeColor: '#8fa9d2', secondsToArrival: 1080), + ]; + arrivalsToRender[2] = []; + } + + @override + List get stopsToRender => [ + ShuttleStopModel(id: 1, name: 'Eighth College / Theatre District (North)', lat: 32.0, lon: -117.0), + ShuttleStopModel(id: 2, name: 'Gilman', lat: 32.0, lon: -117.0), + ]; +} + +class _FakeFirebaseAnalyticsPlatform extends FirebaseAnalyticsPlatform { + _FakeFirebaseAnalyticsPlatform({super.appInstance}); + + @override + FirebaseAnalyticsPlatform delegateFor({required FirebaseApp app, Map? webOptions}) => + _FakeFirebaseAnalyticsPlatform(appInstance: app); + + @override + Future logEvent({ + required String name, + Map? parameters, + AnalyticsCallOptions? callOptions, + }) async {} +} + +Future _pumpCard(WidgetTester tester, Size size, double textScale) async { + await tester.binding.setSurfaceSize(size); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => _LayoutShuttleProvider()), + ChangeNotifierProvider(create: (_) => CardsDataProvider()), + ], + child: MaterialApp( + routes: { + RoutePaths.MANAGE_SHUTTLE_VIEW: (_) => const Scaffold(body: Text('Manage shuttle stops')), + }, + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ), + home: Scaffold( + body: SingleChildScrollView( + child: Padding(padding: const EdgeInsets.symmetric(horizontal: 8), child: ShuttleCard()), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setupFirebaseCoreMocks(); + + setUpAll(() async { + FirebaseAnalyticsPlatform.instance = _FakeFirebaseAnalyticsPlatform(); + await Firebase.initializeApp(); + }); + + for (final size in [const Size(320, 568), const Size(412, 892), const Size(600, 960), const Size(1024, 768)]) { + for (final scale in [1.0, 1.5, 2.0]) { + testWidgets('shuttle card fits ${size.width.toInt()}px width at ${scale}x text scale', (tester) async { + await _pumpCard(tester, size, scale); + + expect(tester.takeException(), isNull); + final pager = find.byType(PageView); + final page = tester.widget(pager); + final content = find.descendant(of: pager, matching: find.text('18 min')); + expect(content, findsOneWidget); + expect(tester.getRect(content).bottom, lessThanOrEqualTo(tester.getRect(pager).bottom)); + expect(page.controller!.page, 0); + }); + } + } + + testWidgets('swiping between stops shrinks and grows the card to fit the content', (tester) async { + await _pumpCard(tester, const Size(412, 892), 1.5); + final pager = find.byType(PageView); + final controller = tester.widget(pager).controller!; + final populatedHeight = tester.getSize(pager).height; + expect(populatedHeight, greaterThan(375)); + + controller.animateToPage(1, duration: const Duration(milliseconds: 200), curve: Curves.linear); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(tester.getSize(pager).height, lessThan(populatedHeight)); + expect(find.descendant(of: pager, matching: find.text('No arrivals found.')), findsOneWidget); + + controller.animateToPage(0, duration: const Duration(milliseconds: 200), curve: Curves.linear); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(tester.getSize(pager).height, closeTo(populatedHeight, 0.01)); + }); + + testWidgets('returning from manage stops keeps the page, dots, and arrivals synchronized', (tester) async { + await _pumpCard(tester, const Size(412, 892), 1.0); + final pager = find.byType(PageView); + final controller = tester.widget(pager).controller!; + final provider = Provider.of(tester.element(pager), listen: false); + final populatedArrivals = provider.arrivalsToRender[1]!; + provider.arrivalsToRender[1] = []; + provider.arrivalsToRender[2] = populatedArrivals; + provider.notifyListeners(); + await tester.pumpAndSettle(); + + controller.jumpToPage(1); + await tester.pumpAndSettle(); + expect(controller.page, 1); + expect(tester.widget(find.byType(DotsIndicator)).position, 1); + final nextArrivals = find.descendant(of: pager, matching: find.text('Next Arrivals')); + expect(nextArrivals, findsOneWidget); + expect(tester.getRect(nextArrivals).bottom, lessThanOrEqualTo(tester.getRect(pager).bottom)); + + await tester.tap(find.text('MANAGE SHUTTLE STOPS')); + await tester.pumpAndSettle(); + expect(find.text('Manage shuttle stops'), findsOneWidget); + + Navigator.of(tester.element(find.text('Manage shuttle stops'))).pop(); + await tester.pumpAndSettle(); + + expect(controller.page, 1); + expect(tester.widget(find.byType(DotsIndicator)).position, 1); + expect(nextArrivals, findsOneWidget); + expect(tester.getRect(nextArrivals).bottom, lessThanOrEqualTo(tester.getRect(pager).bottom)); + }); +} diff --git a/test/ui/shuttle/shuttle_display_test.dart b/test/ui/shuttle/shuttle_display_test.dart new file mode 100644 index 000000000..c1b087d8b --- /dev/null +++ b/test/ui/shuttle/shuttle_display_test.dart @@ -0,0 +1,59 @@ +import 'package:campus_mobile_experimental/core/models/shuttle_arrival.dart'; +import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; +import 'package:campus_mobile_experimental/ui/shuttle/shuttle_display.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final stop = ShuttleStopModel(id: 4006, name: 'UCSD Stop', lat: 32.0, lon: -117.0); + + testWidgets('an empty arrivals response displays the stop and no arrivals message', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ShuttleDisplay(stop: stop, arrivingShuttles: const []), + ), + ), + ); + + expect(find.text('UCSD Stop'), findsOneWidget); + expect(find.text('No arrivals found.'), findsOneWidget); + expect(find.textContaining('temporarily unavailable'), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('a failed stop displays its name and an availability message', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ShuttleDisplay(stop: stop, arrivingShuttles: null, arrivalError: 'OneBusAway returned invalid JSON.'), + ), + ), + ); + + expect(find.text('UCSD Stop'), findsOneWidget); + expect(find.textContaining('temporarily unavailable'), findsOneWidget); + expect(find.text('No arrivals found.'), findsNothing); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('successful arrivals display the route and arrival time', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ShuttleDisplay( + stop: stop, + arrivingShuttles: [ + ArrivingShuttle(routeId: 1040, routeName: 'Inside Loop', routeColor: '#ffcd00', secondsToArrival: 60), + ], + ), + ), + ), + ); + + expect(find.text('Inside Loop'), findsOneWidget); + expect(find.text('1 minutes'), findsOneWidget); + expect(tester.takeException(), isNull); + }); +}