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..66fe10c06 100644 --- a/lib/app_provider.dart +++ b/lib/app_provider.dart @@ -161,11 +161,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 +175,7 @@ List dependentServices = [ }, update: (_, userDataProvider, studentIdDataProvider) { studentIdDataProvider!.userDataProvider = userDataProvider; + userDataProvider.studentIdDataProvider = studentIdDataProvider; return studentIdDataProvider; }, ), 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/classes.dart b/lib/core/models/classes.dart index 807b0230e..dacb3e2cf 100644 --- a/lib/core/models/classes.dart +++ b/lib/core/models/classes.dart @@ -56,7 +56,7 @@ class ClassData { courseCode: json["course_code"] == null ? null : json["course_code"], units: (json["units"] as num?)?.toDouble(), courseLevel: json["course_level"] == null ? null : json["course_level"], - gradeOption: json["grade_option"] == null ? null : json["grade_option"], + gradeOption: json["grade_option"] ?? json["gradeOption"], grade: json["grade"] == null ? null : json["grade"], courseTitle: json["course_title"] == null ? null : json["course_title"], enrollmentStatus: json["enrollment_status"] == null ? null : json["enrollment_status"], diff --git a/lib/core/models/events.dart b/lib/core/models/events.dart index 12f059a81..8d8f0232a 100644 --- a/lib/core/models/events.dart +++ b/lib/core/models/events.dart @@ -51,8 +51,8 @@ class EventModel { Map toJson() => { "title": title, "description": description, - "startDate": startDate, - "endDate": endDate, + "startDate": startDate.toIso8601String(), + "endDate": endDate.toIso8601String(), "imageHQ": imageHQ, "imageThumb": imageThumb, "link": link, diff --git a/lib/core/models/scheduled_class.dart b/lib/core/models/scheduled_class.dart index cc154f02f..5fd49ac41 100644 --- a/lib/core/models/scheduled_class.dart +++ b/lib/core/models/scheduled_class.dart @@ -22,16 +22,29 @@ class ScheduledClass { return dayCodes.isEmpty ? days : dayCodes.join(', '); } - String get gradeOption { - switch (course.gradeOption) { - case 'L': + String? get gradeOption { + final raw = course.gradeOption?.trim(); + if (raw == null || raw.isEmpty) return null; + switch (raw.toLowerCase()) { + case 'l': + case 'letter grade': return 'Letter Grade'; - case 'P': + case 'p': + case 'pn': + case 'pnp': + case 'pass/no pass': + case 'pass/not pass': return 'Pass/No Pass'; - case 'S': + case 's': + case 'su': + case 's/u': + case 'sat/unsat': + case 'satisfactory/unsatisfactory': return 'Sat/Unsat'; default: - return 'Other'; + // Surface the raw value instead of a misleading "Other" when the + // TSS API adds new grade-option codes. + return raw; } } } 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/events.dart b/lib/core/providers/events.dart index 0b77ef86a..f443e02a4 100644 --- a/lib/core/providers/events.dart +++ b/lib/core/providers/events.dart @@ -1,10 +1,13 @@ import 'package:campus_mobile_experimental/core/models/events.dart'; import 'package:campus_mobile_experimental/core/services/events.dart'; import 'package:flutter/material.dart'; +import 'package:hive/hive.dart'; class EventsDataProvider extends ChangeNotifier { /// STATES bool _isLoading = false; + String? _refreshingCardId; + bool _modelInitialized = false; DateTime? _lastUpdated; String? _error; @@ -14,25 +17,110 @@ class EventsDataProvider extends ChangeNotifier { /// SERVICES var _eventsService = EventsService(); - void fetchEvents() async { + /// The single apply step for both the cache path and the network path. + /// An empty list is a valid applied model. + void _applyModels(List models) { + _eventsModels = models; + _modelInitialized = true; + + /// Re-derive the empty-state text on every apply; this also clears + /// whatever error an earlier state left behind. + _error = _eventsModels.isEmpty ? 'No events found.' : null; + } + + Future loadFromCache() async { + if (_modelInitialized) return; + + try { + final box = await Hive.openBox('EventsModel'); + final cachedJson = box.get('EventsModel') as String?; + + if (cachedJson == null || cachedJson.isEmpty) return; + + final cachedModels = eventModelFromJson(cachedJson); + + /// A fetch may have applied newer data while the box was opening; + /// never let stale cache overwrite it. + if (_modelInitialized) return; + + _applyModels(cachedModels); + notifyListeners(); + } catch (e) { + /// A cache miss or unreadable cache is not an error; + /// the network fetch remains the source of truth. + print('Failed to load events from cache: $e'); + } + } + + Future fetchEvents() async { + if (_isLoading) return; + _isLoading = true; - _error = null; + + /// Only clear a visible error when nothing is displayed behind it. + if (!_modelInitialized) _error = null; notifyListeners(); - if (await _eventsService.fetchData()) { - _eventsModels = _eventsService.eventsModels!; - _lastUpdated = DateTime.now(); - - /// check to see if the events feed returns nothing back - if (_eventsModels.isEmpty) _error = 'No events found.'; - } else { - _error = _eventsService.error; + + String? cacheJson; + try { + if (await _eventsService.fetchData()) { + final fetchedModels = _eventsService.eventsModels!; + final newJson = eventModelToJson(fetchedModels); + + /// Skip the redundant apply and cache write if the fresh data + /// matches what is already displayed. + if (_modelInitialized && newJson == eventModelToJson(_eventsModels)) { + return; + } + + /// Show fresh data immediately; persist to cache afterwards. + /// An empty fetch must not clobber cached events or block the + /// cache from applying afterwards. + if (fetchedModels.isNotEmpty) { + _applyModels(fetchedModels); + _lastUpdated = DateTime.now(); + cacheJson = newJson; + } else if (!_modelInitialized) { + _error = 'No events found.'; + } + } else { + /// Keep whatever is displayed; only surface an error when the card + /// has nothing to show. + if (!_modelInitialized) _error = _eventsService.error; + } + } catch (e) { + /// Never let an unexpected failure wedge the card in a loading state. + if (!_modelInitialized) _error = e.toString(); + } finally { + _isLoading = false; + notifyListeners(); + } + + /// A failed cache write must not discard the fresh UI update. + if (cacheJson != null) { + try { + final box = await Hive.openBox('EventsModel'); + await box.put('EventsModel', cacheJson); + } catch (_) {} + } + } + + Future reload(String cardId) async { + if (_isLoading || _refreshingCardId != null) return; + + _refreshingCardId = cardId; + try { + await fetchEvents(); + } finally { + _refreshingCardId = null; + notifyListeners(); } - _isLoading = false; - notifyListeners(); } ///SIMPLE GETTERS get isLoading => _isLoading; + bool isRefreshing(String cardId) => _refreshingCardId == cardId; + bool get hasData => _modelInitialized; get error => _error; get lastUpdated => _lastUpdated; List get eventsModels => _eventsModels; 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/events.dart b/lib/core/services/events.dart index 4c51e6320..55e47c3e8 100644 --- a/lib/core/services/events.dart +++ b/lib/core/services/events.dart @@ -4,10 +4,6 @@ import 'package:campus_mobile_experimental/core/models/events.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; class EventsService { - EventsService() { - fetchData(); - } - /// STATES bool _isLoading = false; DateTime? _lastUpdated; 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..425415a1d 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( @@ -87,7 +101,7 @@ class ClassScheduleCard extends StatelessWidget { buildLocationRow(context, section.room?.trim().isNotEmpty == true ? section.room!.trim() : 'TBD'), SizedBox(height: 8), // Evaluation Option: - buildGradeEvaluationRow(context, scheduledClass.gradeOption), + if (scheduledClass.gradeOption != null) buildGradeEvaluationRow(context, scheduledClass.gradeOption!), // "Last updated: A few seconds ago Padding( padding: const EdgeInsets.only(left: 4.0, top: 24.0), diff --git a/lib/ui/classes/classes_list.dart b/lib/ui/classes/classes_list.dart index e52112fc7..24e057ef5 100644 --- a/lib/ui/classes/classes_list.dart +++ b/lib/ui/classes/classes_list.dart @@ -166,7 +166,7 @@ class ClassList extends StatelessWidget { // Classroom Location: _detailRow(Icons.location_on_outlined, 'Location: ${_formatLocation(scheduledClass)}', detailStyle), // Evaluation Option: - if (!isMidterm) + if (!isMidterm && scheduledClass.gradeOption != null) _detailRow(Icons.check_box_outlined, 'Evaluation: ${scheduledClass.gradeOption}', detailStyle), ], ), 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/events/event_tile.dart b/lib/ui/events/event_tile.dart index d42fcfd95..e64d602a6 100644 --- a/lib/ui/events/event_tile.dart +++ b/lib/ui/events/event_tile.dart @@ -21,7 +21,7 @@ class EventTile extends StatelessWidget { @override Widget build(BuildContext context) { // Show loading indicator while data is loading - if (Provider.of(context).isLoading) { + if (Provider.of(context).isLoading && !Provider.of(context).hasData) { return Center(child: CircularProgressIndicator(color: Theme.of(context).colorScheme.secondary)); } return _buildEventTile(context); diff --git a/lib/ui/events/events_card.dart b/lib/ui/events/events_card.dart index 3497e1da2..1de0dd953 100644 --- a/lib/ui/events/events_card.dart +++ b/lib/ui/events/events_card.dart @@ -12,15 +12,31 @@ import 'package:provider/provider.dart'; const cardId = 'events'; // edit these files -class EventsCard extends StatelessWidget { +class EventsCard extends StatefulWidget { + @override + State createState() => _EventsCardState(); +} + +class _EventsCardState extends State { + @override + void initState() { + super.initState(); + + /// Render path: hydrate from the local cache immediately. + /// The silent refresh is owned by the provider's create-time fetch. + context.read().loadFromCache(); + } + @override Widget build(BuildContext context) { return CardContainer( cardId: cardId, active: context.select((CardsDataProvider p) => p.cardStates[cardId] ?? false), hide: () => Provider.of(context, listen: false).toggleCard(cardId), - reload: () => Provider.of(context, listen: false).fetchEvents(), - isLoading: Provider.of(context).isLoading, + reload: () => Provider.of(context, listen: false).reload(cardId), + 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: () => buildEventsCardList(Provider.of(context).eventsModels), diff --git a/lib/ui/events/events_card_list.dart b/lib/ui/events/events_card_list.dart index 5aa81e9f0..e36817e1d 100644 --- a/lib/ui/events/events_card_list.dart +++ b/lib/ui/events/events_card_list.dart @@ -12,9 +12,10 @@ class EventsCardList extends StatelessWidget { @override Widget build(BuildContext context) { - return Provider.of(context).isLoading + final provider = Provider.of(context); + return provider.isLoading && !provider.hasData ? Center(child: CircularProgressIndicator(color: Theme.of(context).colorScheme.secondary)) - : buildEventsList(Provider.of(context).eventsModels, context); + : buildEventsList(provider.eventsModels, context); } Widget buildEventsList(List listOfEvents, BuildContext context) { diff --git a/lib/ui/events/events_view_all.dart b/lib/ui/events/events_view_all.dart index aff7d1876..269c8acba 100644 --- a/lib/ui/events/events_view_all.dart +++ b/lib/ui/events/events_view_all.dart @@ -10,12 +10,10 @@ class EventsAll extends StatelessWidget { @override Widget build(BuildContext context) { - return Provider.of(context).isLoading + final provider = Provider.of(context); + return provider.isLoading && !provider.hasData ? Center(child: CircularProgressIndicator(color: Theme.of(context).colorScheme.secondary)) - : Padding( - padding: const EdgeInsets.only(top: 16.0), - child: buildEventsList(Provider.of(context).eventsModels, context), - ); + : Padding(padding: const EdgeInsets.only(top: 16.0), child: buildEventsList(provider.eventsModels, context)); } Widget buildEventsList(List listOfEvents, BuildContext context) { @@ -32,8 +30,8 @@ class EventsAll extends StatelessWidget { crossAxisCount: 2, crossAxisSpacing: 1, mainAxisSpacing: 8, + mainAxisExtent: 300, children: eventTiles, - childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height / 1.4), ); } else { return ContainerView(child: Center(child: Text('No events found.'))); 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/shuttle_card.dart b/lib/ui/shuttle/shuttle_card.dart index 3b1f4e983..562e1be79 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'; @@ -102,8 +103,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.')]), ); } 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/scheduled_class_test.dart b/test/core/models/scheduled_class_test.dart new file mode 100644 index 000000000..978eadbba --- /dev/null +++ b/test/core/models/scheduled_class_test.dart @@ -0,0 +1,50 @@ +import 'package:campus_mobile_experimental/core/models/classes.dart'; +import 'package:campus_mobile_experimental/core/models/scheduled_class.dart'; +import 'package:flutter_test/flutter_test.dart'; + +ScheduledClass scheduledFromJson(Map courseJson) => + ScheduledClass(course: ClassData.fromJson(courseJson), section: SectionData()); + +void main() { + group('ScheduledClass.gradeOption', () { + test('maps the legacy single-letter codes', () { + expect(scheduledFromJson({'grade_option': 'L'}).gradeOption, 'Letter Grade'); + expect(scheduledFromJson({'grade_option': 'P'}).gradeOption, 'Pass/No Pass'); + expect(scheduledFromJson({'grade_option': 'S'}).gradeOption, 'Sat/Unsat'); + }); + + test('maps real MyAcademicHistory Title Case values', () { + expect(scheduledFromJson({'grade_option': 'Letter Grade'}).gradeOption, 'Letter Grade'); + expect(scheduledFromJson({'grade_option': 'Pass/No Pass'}).gradeOption, 'Pass/No Pass'); + expect(scheduledFromJson({'grade_option': 'Sat/Unsat'}).gradeOption, 'Sat/Unsat'); + expect(scheduledFromJson({'grade_option': 'Satisfactory/Unsatisfactory'}).gradeOption, 'Sat/Unsat'); + }); + + test('maps grade-option spellings case-insensitively', () { + expect(scheduledFromJson({'grade_option': 'letter grade'}).gradeOption, 'Letter Grade'); + expect(scheduledFromJson({'grade_option': 'pass/not pass'}).gradeOption, 'Pass/No Pass'); + expect(scheduledFromJson({'grade_option': 's/u'}).gradeOption, 'Sat/Unsat'); + }); + + test('passes unrecognized non-empty values through verbatim', () { + expect(scheduledFromJson({'grade_option': 'Z'}).gradeOption, 'Z'); + expect(scheduledFromJson({'grade_option': 'credit'}).gradeOption, 'credit'); + }); + + test('returns null when the value is missing, null, or blank', () { + expect(scheduledFromJson({}).gradeOption, isNull); + expect(scheduledFromJson({'grade_option': null}).gradeOption, isNull); + expect(scheduledFromJson({'grade_option': ' '}).gradeOption, isNull); + }); + }); + + group('ClassData.fromJson grade_option parsing', () { + test('reads snake_case payloads', () { + expect(ClassData.fromJson({'grade_option': 'Letter Grade'}).gradeOption, 'Letter Grade'); + }); + + test('falls back to camelCase payloads', () { + expect(ClassData.fromJson({'gradeOption': 'Pass/No Pass'}).gradeOption, 'Pass/No Pass'); + }); + }); +} 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/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/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 {}