diff --git a/.github/workflows/pre_commit_check.yml b/.github/workflows/pre_commit_check.yml index a35a92c035..c02ac7d682 100644 --- a/.github/workflows/pre_commit_check.yml +++ b/.github/workflows/pre_commit_check.yml @@ -13,8 +13,14 @@ env: jobs: precommit: - runs-on: ubuntu-latest + # ArcGIS Maps' native build hook rejects Linux before Flutter tests start. + # Its test-host hook supports Windows, while production builds remain + # limited to the Android and iOS targets declared by the package. + runs-on: windows-latest timeout-minutes: 20 + defaults: + run: + shell: bash steps: - name: Check out code uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index 52b9332cdf..d6ddc6ffec 100644 --- a/.gitignore +++ b/.gitignore @@ -125,3 +125,6 @@ android/app/google-services.json !**/ios/**/default.pbxuser !**/ios/**/default.perspectivev3 !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages + +# ESRI Map +arcgis_maps_core diff --git a/android/app/build.gradle b/android/app/build.gradle index f190221d5e..5488c54bcf 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -16,7 +16,7 @@ if (keystorePropertiesFile.exists()) { android { namespace = "edu.ucsd" compileSdk = 36 - ndkVersion = "27.0.12077973" + ndkVersion = "28.2.13676358" compileOptions { sourceCompatibility = JavaVersion.VERSION_17 @@ -34,7 +34,7 @@ android { defaultConfig { applicationId = "edu.ucsd" - minSdkVersion = flutter.minSdkVersion + minSdkVersion = 28 targetSdk = 36 versionCode = flutter.versionCode versionName = flutter.versionName diff --git a/assets/esri_map_assets/Center-Trident.svg b/assets/esri_map_assets/Center-Trident.svg new file mode 100644 index 0000000000..b27fc3844c --- /dev/null +++ b/assets/esri_map_assets/Center-Trident.svg @@ -0,0 +1,119 @@ + + + + + + + + diff --git a/assets/esri_map_assets/construction-thumbnail.png b/assets/esri_map_assets/construction-thumbnail.png new file mode 100644 index 0000000000..61830070a3 Binary files /dev/null and b/assets/esri_map_assets/construction-thumbnail.png differ diff --git a/assets/esri_map_assets/dark-thumbnail.png b/assets/esri_map_assets/dark-thumbnail.png new file mode 100644 index 0000000000..a075c06460 Binary files /dev/null and b/assets/esri_map_assets/dark-thumbnail.png differ diff --git a/assets/esri_map_assets/default-thumbnail.png b/assets/esri_map_assets/default-thumbnail.png new file mode 100644 index 0000000000..d0f788b91e Binary files /dev/null and b/assets/esri_map_assets/default-thumbnail.png differ diff --git a/assets/esri_map_assets/districts-thumbnail.png b/assets/esri_map_assets/districts-thumbnail.png new file mode 100644 index 0000000000..148916efac Binary files /dev/null and b/assets/esri_map_assets/districts-thumbnail.png differ diff --git a/assets/esri_map_assets/light-thumbnail.png b/assets/esri_map_assets/light-thumbnail.png new file mode 100644 index 0000000000..36b5e8643d Binary files /dev/null and b/assets/esri_map_assets/light-thumbnail.png differ diff --git a/assets/esri_map_assets/mapConfig.json b/assets/esri_map_assets/mapConfig.json new file mode 100644 index 0000000000..684b2dd455 --- /dev/null +++ b/assets/esri_map_assets/mapConfig.json @@ -0,0 +1,170 @@ +{ + "portals": { + "age": "https://admin-enterprise-gis.ucsd.edu/portal", + "ago": "https://www.arcgis.com" + }, + + "serviceUrls": { + "hillshade": "https://services.arcgisonline.com/arcgis/rest/services/Elevation/World_Hillshade/MapServer", + "lightGrayBase": "https://services.arcgisonline.com/arcgis/rest/services/Canvas/World_Light_Gray_Base/MapServer", + "darkGrayBase": "https://services.arcgisonline.com/arcgis/rest/services/Canvas/World_Dark_Gray_Base/MapServer", + "nearmap": "https://admin-enterprise-gis.ucsd.edu/server/rest/services/Campus_Imagery_Nearmap_9in_2025_0423_0514/MapServer", + "worldImagery": "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer" + }, + + "basemaps": { + "defaultMap": { + "label": "Default", + "thumbnailAsset": "https://dvsbke0idzv4u.cloudfront.net/thumbnails/default-thumbnail.png", + "baseLayers": [ + { + "type": "arcgisVectorTiled", + "portalKey": "ago", + "itemId": "291da5eab3a0412593b66d384379f89f" + }, + { + "type": "arcgisVectorTiled", + "portalKey": "age", + "itemId": "e19f33d2c1f44967aef673306c483913" + } + ] + }, + "light": { + "label": "Light", + "thumbnailAsset": "https://dvsbke0idzv4u.cloudfront.net/thumbnails/light-thumbnail.png", + "baseLayers": [ + { + "type": "arcgisVectorTiled", + "portalKey": "ago", + "itemId": "291da5eab3a0412593b66d384379f89f" + }, + { + "type": "arcgisVectorTiled", + "portalKey": "age", + "itemId": "6643ee62af494f5bafe7dfdb8eb3f857" + } + ] + }, + "dark": { + "label": "Dark", + "thumbnailAsset": "https://dvsbke0idzv4u.cloudfront.net/thumbnails/dark-thumbnail.png", + "baseLayers": [ + { + "type": "arcgisVectorTiled", + "portalKey": "ago", + "itemId": "5e9b3685f4c24d8781073dd928ebda50" + }, + { + "type": "arcgisVectorTiled", + "portalKey": "age", + "itemId": "09d7b3934b6c4c2cad8380c04e08c1b1" + } + ] + }, + "satellite": { + "label": "Satellite", + "thumbnailAsset": "https://dvsbke0idzv4u.cloudfront.net/thumbnails/satellite-thumbnail.png", + "baseLayers": [ + { + "type": "arcgisTiled", + "serviceKey": "worldImagery" + } + ] + } + }, + + "layers": { + "tritonTransit": { + "label": "Transit", + "thumbnailAsset": "https://dvsbke0idzv4u.cloudfront.net/thumbnails/shuttles-thumbnail.png", + "source": "portalItem", + "portalKey": "ago", + "itemId": "ea5cdd8987414942b62178726120d5c7", + "refreshInterval": 0, + "popup": false + }, + "campusDistricts": { + "label": "Districts", + "thumbnailAsset": "https://dvsbke0idzv4u.cloudfront.net/thumbnails/districts-thumbnail.png", + "source": "url", + "url": "https://admin-enterprise-gis.ucsd.edu/server/rest/services/AdministrationServices/Areas_and_Boundaries/MapServer/4", + "refreshInterval": 0, + "popup": false + }, + "construction": { + "label": "Construction", + "thumbnailAsset": "https://dvsbke0idzv4u.cloudfront.net/thumbnails/construction-thumbnail.png", + "source": "url", + "sublayers": [ + { + "source": "url", + "url": "https://admin-enterprise-gis.ucsd.edu/server/rest/services/Construction/Construction_Alert_Approved/MapServer/0", + "refreshInterval": 0 + }, + { + "source": "url", + "url": "https://admin-enterprise-gis.ucsd.edu/server/rest/services/Construction/Construction_Alert_Approved/MapServer/1", + "refreshInterval": 0 + }, + { + "source": "url", + "url": "https://admin-enterprise-gis.ucsd.edu/server/rest/services/Construction/Construction_Alert_Approved/MapServer/2", + "refreshInterval": 0 + } + ], + "refreshInterval": 0, + "popup": false + } + }, + + "scenes": { + "default": { + "label": "Default", + "type": "2d" + }, + "building3d": { + "label": "3D Building", + "type": "scene", + "portalKey": "ago", + "itemId": "b6931d8c429c4138afd9dd936ee7bcd1" + }, + "droneView": { + "label": "Drone View", + "type": "scene", + "portalKey": "age", + "itemId": "0ffe293479844ce49ff5c30ffc0a0b67" + } + }, + + "features": { + "aiSearch": true, + "scenes": true + }, + + "searchCategories": [ + { + "label": "Dining", + "poiClass": "Dining and Beverage", + "icon": "restaurant", + "color": "#00C6D7" + }, + { + "label": "Library", + "poiClass": "Library", + "icon": "menu_book", + "color": "#D462AD" + }, + { + "label": "Parking", + "poiClass": "Parking", + "icon": "local_parking", + "color": "#6E963B" + }, + { + "label": "Recreation", + "poiClass": "Recreation Facilities", + "icon": "fitness_center", + "color": "#FC8900" + } + ] +} diff --git a/assets/esri_map_assets/satellite-thumbnail.png b/assets/esri_map_assets/satellite-thumbnail.png new file mode 100644 index 0000000000..d66c7b6834 Binary files /dev/null and b/assets/esri_map_assets/satellite-thumbnail.png differ diff --git a/assets/esri_map_assets/shuttles-thumbnail.png b/assets/esri_map_assets/shuttles-thumbnail.png new file mode 100644 index 0000000000..977d2bb51c Binary files /dev/null and b/assets/esri_map_assets/shuttles-thumbnail.png differ diff --git a/assets/esri_map_assets/tgpt-dark.svg b/assets/esri_map_assets/tgpt-dark.svg new file mode 100644 index 0000000000..59a5767677 --- /dev/null +++ b/assets/esri_map_assets/tgpt-dark.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/assets/esri_map_assets/tgpt-light.svg b/assets/esri_map_assets/tgpt-light.svg new file mode 100644 index 0000000000..10d9304a8c --- /dev/null +++ b/assets/esri_map_assets/tgpt-light.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist index 86343d8600..f32f270dc1 100644 --- a/ios/Flutter/AppFrameworkInfo.plist +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -21,6 +21,6 @@ CFBundleVersion 1.0 MinimumOSVersion - 16.0 + 17.0 diff --git a/ios/Podfile b/ios/Podfile index 755467ccd7..824c74203c 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -platform :ios, '16.0' +platform :ios, '17.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' @@ -31,6 +31,9 @@ target 'Runner' do use_frameworks! use_modular_headers! + pod 'Runtimecore', :podspec => '../arcgis_maps_core/ios/Runtimecore.podspec' + pod 'arcgis_maps_ffi', :podspec => '../arcgis_maps_core/ios/arcgis_maps_ffi.podspec' + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end @@ -38,7 +41,7 @@ post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |config| - config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '16.0' + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '17.0' end end end diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index a7c9c228c9..97565cab2f 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -158,6 +158,7 @@ 3B06AD1E1E4923F5004D2608 /* Thin Binary */, 348EE9E2258A901800712F2E /* ShellScript */, B19D24E1170B60724162B13B /* [CP] Embed Pods Frameworks */, + F3660986D315CC3D0C38923C /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -241,7 +242,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n\"${BUILD_DIR%Build/*}/SourcePackages/checkouts/firebase-ios-sdk/Crashlytics/run\"\n"; + shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n\"${PODS_ROOT}/FirebaseCrashlytics/run\"\n"; }; 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; @@ -281,13 +282,69 @@ ); inputPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/FirebaseCore/FirebaseCore.framework", + "${BUILT_PRODUCTS_DIR}/FirebaseCoreExtension/FirebaseCoreExtension.framework", + "${BUILT_PRODUCTS_DIR}/FirebaseCoreInternal/FirebaseCoreInternal.framework", + "${BUILT_PRODUCTS_DIR}/FirebaseCrashlytics/FirebaseCrashlytics.framework", + "${BUILT_PRODUCTS_DIR}/FirebaseInstallations/FirebaseInstallations.framework", + "${BUILT_PRODUCTS_DIR}/FirebaseMessaging/FirebaseMessaging.framework", + "${BUILT_PRODUCTS_DIR}/FirebaseRemoteConfigInterop/FirebaseRemoteConfigInterop.framework", + "${BUILT_PRODUCTS_DIR}/FirebaseSessions/FirebaseSessions.framework", + "${BUILT_PRODUCTS_DIR}/GoogleDataTransport/GoogleDataTransport.framework", + "${BUILT_PRODUCTS_DIR}/GoogleUtilities/GoogleUtilities.framework", + "${BUILT_PRODUCTS_DIR}/PromisesObjC/FBLPromises.framework", + "${BUILT_PRODUCTS_DIR}/PromisesSwift/Promises.framework", "${BUILT_PRODUCTS_DIR}/app_links/app_links.framework", + "${BUILT_PRODUCTS_DIR}/arcgis_maps/arcgis_maps.framework", + "${BUILT_PRODUCTS_DIR}/connectivity_plus/connectivity_plus.framework", + "${BUILT_PRODUCTS_DIR}/device_info_plus/device_info_plus.framework", + "${BUILT_PRODUCTS_DIR}/flutter_local_notifications/flutter_local_notifications.framework", + "${BUILT_PRODUCTS_DIR}/flutter_secure_storage_darwin/flutter_secure_storage_darwin.framework", + "${BUILT_PRODUCTS_DIR}/flutter_web_auth_2/flutter_web_auth_2.framework", + "${BUILT_PRODUCTS_DIR}/geolocator_apple/geolocator_apple.framework", + "${BUILT_PRODUCTS_DIR}/haptic_feedback/haptic_feedback.framework", + "${BUILT_PRODUCTS_DIR}/nanopb/nanopb.framework", + "${BUILT_PRODUCTS_DIR}/package_info_plus/package_info_plus.framework", + "${BUILT_PRODUCTS_DIR}/path_provider_foundation/path_provider_foundation.framework", + "${BUILT_PRODUCTS_DIR}/shared_preferences_foundation/shared_preferences_foundation.framework", + "${BUILT_PRODUCTS_DIR}/url_launcher_ios/url_launcher_ios.framework", + "${BUILT_PRODUCTS_DIR}/webview_flutter_wkwebview/webview_flutter_wkwebview.framework", "${BUILT_PRODUCTS_DIR}/wifi_connection/wifi_connection.framework", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/Runtimecore/Runtimecore.framework/Runtimecore", + "${PODS_XCFRAMEWORKS_BUILD_DIR}/arcgis_maps_ffi/arcgis_maps_ffi.framework/arcgis_maps_ffi", ); name = "[CP] Embed Pods Frameworks"; outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FirebaseCore.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FirebaseCoreExtension.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FirebaseCoreInternal.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FirebaseCrashlytics.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FirebaseInstallations.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FirebaseMessaging.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FirebaseRemoteConfigInterop.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FirebaseSessions.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GoogleDataTransport.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GoogleUtilities.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FBLPromises.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Promises.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/app_links.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/arcgis_maps.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/connectivity_plus.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/device_info_plus.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_local_notifications.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_secure_storage_darwin.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_web_auth_2.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/geolocator_apple.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/haptic_feedback.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/nanopb.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/package_info_plus.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/path_provider_foundation.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/shared_preferences_foundation.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/url_launcher_ios.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/webview_flutter_wkwebview.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/wifi_connection.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Runtimecore.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/arcgis_maps_ffi.framework", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; @@ -316,6 +373,30 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; + F3660986D315CC3D0C38923C /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh", + "${PODS_CONFIGURATION_BUILD_DIR}/GoogleMaps/GoogleMapsResources.bundle", + "${PODS_CONFIGURATION_BUILD_DIR}/firebase_messaging/firebase_messaging_Privacy.bundle", + "${PODS_CONFIGURATION_BUILD_DIR}/google_maps_flutter_ios_sdk10/google_maps_flutter_ios_sdk10_privacy.bundle", + "${PODS_CONFIGURATION_BUILD_DIR}/permission_handler_apple/permission_handler_apple_privacy.bundle", + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/GoogleMapsResources.bundle", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/firebase_messaging_Privacy.bundle", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/google_maps_flutter_ios_sdk10_privacy.bundle", + "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/permission_handler_apple_privacy.bundle", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -416,7 +497,7 @@ "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 16.0; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -558,7 +639,7 @@ "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 16.0; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -595,7 +676,7 @@ "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 16.0; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved deleted file mode 100644 index c47cc29630..0000000000 --- a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ /dev/null @@ -1,149 +0,0 @@ -{ - "pins" : [ - { - "identity" : "abseil-cpp-binary", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/abseil-cpp-binary.git", - "state" : { - "revision" : "bbe8b69694d7873315fd3a4ad41efe043e1c07c5", - "version" : "1.2024072200.0" - } - }, - { - "identity" : "app-check", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/app-check.git", - "state" : { - "revision" : "3e33dd27dd4c69bd81c7c81fe61d8ccf58846902", - "version" : "11.3.1" - } - }, - { - "identity" : "firebase-ios-sdk", - "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/firebase-ios-sdk", - "state" : { - "revision" : "9ab4a7e6e5d6d3df2a2aa002a11d25e078c8d6e5", - "version" : "12.16.0" - } - }, - { - "identity" : "flutterfire", - "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/flutterfire", - "state" : { - "revision" : "39bdb5b1ef392e8c31c60209e333b45e408099e8", - "version" : "4.3.0-firebase-core-swift" - } - }, - { - "identity" : "google-ads-on-device-conversion-ios-sdk", - "kind" : "remoteSourceControl", - "location" : "https://github.com/googleads/google-ads-on-device-conversion-ios-sdk", - "state" : { - "revision" : "dc39082d8881109d35b94b1c122164c0e8d08a55", - "version" : "3.6.1" - } - }, - { - "identity" : "google-maps-ios-utils", - "kind" : "remoteSourceControl", - "location" : "https://github.com/googlemaps/google-maps-ios-utils", - "state" : { - "revision" : "1727a5e25036cecc07296569b8ad3f85d4baca4b", - "version" : "6.1.3" - } - }, - { - "identity" : "googleappmeasurement", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/GoogleAppMeasurement.git", - "state" : { - "revision" : "ce606e3768abddff0510783e1a6d2f270b943b35", - "version" : "12.16.0" - } - }, - { - "identity" : "googledatatransport", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/GoogleDataTransport.git", - "state" : { - "revision" : "617af071af9aa1d6a091d59a202910ac482128f9", - "version" : "10.1.0" - } - }, - { - "identity" : "googleutilities", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/GoogleUtilities.git", - "state" : { - "revision" : "9f183ae842be978784f2963a343682e0c46d8fb3", - "version" : "8.1.2" - } - }, - { - "identity" : "grpc-binary", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/grpc-binary.git", - "state" : { - "revision" : "75b31c842f664a0f46a2e590a570e370249fd8f6", - "version" : "1.69.1" - } - }, - { - "identity" : "gtm-session-fetcher", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/gtm-session-fetcher.git", - "state" : { - "revision" : "c0ac7575d70050c2973ba2318bd5af47f8e8153a", - "version" : "5.3.0" - } - }, - { - "identity" : "interop-ios-for-google-sdks", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/interop-ios-for-google-sdks.git", - "state" : { - "revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe", - "version" : "101.0.0" - } - }, - { - "identity" : "ios-maps-sdk", - "kind" : "remoteSourceControl", - "location" : "https://github.com/googlemaps/ios-maps-sdk", - "state" : { - "revision" : "a951b24ac0ca7720f87d4be3d5bd539552d13882", - "version" : "10.15.0" - } - }, - { - "identity" : "leveldb", - "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/leveldb.git", - "state" : { - "revision" : "a0bc79961d7be727d258d33d5a6b2f1023270ba1", - "version" : "1.22.5" - } - }, - { - "identity" : "nanopb", - "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/nanopb.git", - "state" : { - "revision" : "3851d94a41890dea16dc3db34caf60e585cb4163", - "version" : "2.30910.1" - } - }, - { - "identity" : "promises", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/promises.git", - "state" : { - "revision" : "f4a19a3c313dc2616c70bb49d29a799fb16be837", - "version" : "2.4.1" - } - } - ], - "version" : 2 -} diff --git a/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved deleted file mode 100644 index c47cc29630..0000000000 --- a/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ /dev/null @@ -1,149 +0,0 @@ -{ - "pins" : [ - { - "identity" : "abseil-cpp-binary", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/abseil-cpp-binary.git", - "state" : { - "revision" : "bbe8b69694d7873315fd3a4ad41efe043e1c07c5", - "version" : "1.2024072200.0" - } - }, - { - "identity" : "app-check", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/app-check.git", - "state" : { - "revision" : "3e33dd27dd4c69bd81c7c81fe61d8ccf58846902", - "version" : "11.3.1" - } - }, - { - "identity" : "firebase-ios-sdk", - "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/firebase-ios-sdk", - "state" : { - "revision" : "9ab4a7e6e5d6d3df2a2aa002a11d25e078c8d6e5", - "version" : "12.16.0" - } - }, - { - "identity" : "flutterfire", - "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/flutterfire", - "state" : { - "revision" : "39bdb5b1ef392e8c31c60209e333b45e408099e8", - "version" : "4.3.0-firebase-core-swift" - } - }, - { - "identity" : "google-ads-on-device-conversion-ios-sdk", - "kind" : "remoteSourceControl", - "location" : "https://github.com/googleads/google-ads-on-device-conversion-ios-sdk", - "state" : { - "revision" : "dc39082d8881109d35b94b1c122164c0e8d08a55", - "version" : "3.6.1" - } - }, - { - "identity" : "google-maps-ios-utils", - "kind" : "remoteSourceControl", - "location" : "https://github.com/googlemaps/google-maps-ios-utils", - "state" : { - "revision" : "1727a5e25036cecc07296569b8ad3f85d4baca4b", - "version" : "6.1.3" - } - }, - { - "identity" : "googleappmeasurement", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/GoogleAppMeasurement.git", - "state" : { - "revision" : "ce606e3768abddff0510783e1a6d2f270b943b35", - "version" : "12.16.0" - } - }, - { - "identity" : "googledatatransport", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/GoogleDataTransport.git", - "state" : { - "revision" : "617af071af9aa1d6a091d59a202910ac482128f9", - "version" : "10.1.0" - } - }, - { - "identity" : "googleutilities", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/GoogleUtilities.git", - "state" : { - "revision" : "9f183ae842be978784f2963a343682e0c46d8fb3", - "version" : "8.1.2" - } - }, - { - "identity" : "grpc-binary", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/grpc-binary.git", - "state" : { - "revision" : "75b31c842f664a0f46a2e590a570e370249fd8f6", - "version" : "1.69.1" - } - }, - { - "identity" : "gtm-session-fetcher", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/gtm-session-fetcher.git", - "state" : { - "revision" : "c0ac7575d70050c2973ba2318bd5af47f8e8153a", - "version" : "5.3.0" - } - }, - { - "identity" : "interop-ios-for-google-sdks", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/interop-ios-for-google-sdks.git", - "state" : { - "revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe", - "version" : "101.0.0" - } - }, - { - "identity" : "ios-maps-sdk", - "kind" : "remoteSourceControl", - "location" : "https://github.com/googlemaps/ios-maps-sdk", - "state" : { - "revision" : "a951b24ac0ca7720f87d4be3d5bd539552d13882", - "version" : "10.15.0" - } - }, - { - "identity" : "leveldb", - "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/leveldb.git", - "state" : { - "revision" : "a0bc79961d7be727d258d33d5a6b2f1023270ba1", - "version" : "1.22.5" - } - }, - { - "identity" : "nanopb", - "kind" : "remoteSourceControl", - "location" : "https://github.com/firebase/nanopb.git", - "state" : { - "revision" : "3851d94a41890dea16dc3db34caf60e585cb4163", - "version" : "2.30910.1" - } - }, - { - "identity" : "promises", - "kind" : "remoteSourceControl", - "location" : "https://github.com/google/promises.git", - "state" : { - "revision" : "f4a19a3c313dc2616c70bb49d29a799fb16be837", - "version" : "2.4.1" - } - } - ], - "version" : 2 -} diff --git a/lib/app_networking.dart b/lib/app_networking.dart index f7026077a2..bce80e2a46 100644 --- a/lib/app_networking.dart +++ b/lib/app_networking.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/app_styles.dart'; import 'package:dio/dio.dart'; diff --git a/lib/app_router.dart b/lib/app_router.dart index 78058c8507..ca1b56b968 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -35,6 +35,7 @@ import 'package:campus_mobile_experimental/ui/shuttle/add_shuttle_stops_view.dar import 'package:campus_mobile_experimental/ui/shuttle/manage_shuttle_view.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esrimap.dart'; class Router { static Route generateRoute(RouteSettings settings) { @@ -53,7 +54,7 @@ class Router { }, ); case RoutePaths.MAP: - return MaterialPageRoute(builder: (_) => prefix0.Maps()); + return MaterialPageRoute(builder: (_) => EsriMap()); case RoutePaths.MAP_SEARCH: return MaterialPageRoute(builder: (_) => MapSearchView()); case RoutePaths.NOTIFICATIONS: diff --git a/lib/app_styles.dart b/lib/app_styles.dart index 5abe3fcbc6..26e35b1ea5 100644 --- a/lib/app_styles.dart +++ b/lib/app_styles.dart @@ -304,7 +304,7 @@ const IconThemeData darkIconTheme = IconThemeData(color: darkPrimaryColor2); // Unselected / inactive colors const Color unselectedIconLightColor = Color(0xFF6A6B6D); -const Color unselectedIconDarkColor = Color(0xFF6A6B6D); +const Color unselectedIconDarkColor = Color(0xFF909193); const noArrivalsFoundColor = "#747678"; // Colors for text on buttons using light theme @@ -351,7 +351,7 @@ const Color c3 = Color.fromARGB(255, 0, 0, 255); // List Tile Theme Data const lightListTileTheme = ListTileThemeData(selectedColor: const Color(0xFF00629B)); -const darkListTileTheme = ListTileThemeData(selectedColor: const Color(0xFF00C6D7)); +const darkListTileTheme = ListTileThemeData(selectedColor: secondaryColorDark); // New Onboarding Screen Colors const lightOnboardingScreen = Color.fromARGB(255, 245, 240, 228); diff --git a/lib/core/models/authentication.dart b/lib/core/models/authentication.dart index a5eca9aac5..844e98c925 100644 --- a/lib/core/models/authentication.dart +++ b/lib/core/models/authentication.dart @@ -1,4 +1,5 @@ import 'dart:convert'; + import 'package:hive/hive.dart'; part 'authentication.g.dart'; diff --git a/lib/core/models/dining.dart b/lib/core/models/dining.dart index e9373afd3f..ec1621a88c 100644 --- a/lib/core/models/dining.dart +++ b/lib/core/models/dining.dart @@ -1,4 +1,5 @@ import 'dart:convert'; + import 'package:campus_mobile_experimental/core/models/location.dart'; // To parse this JSON data, do diff --git a/lib/core/models/esri_map_models/esrimap_ai_search_model.dart b/lib/core/models/esri_map_models/esrimap_ai_search_model.dart new file mode 100644 index 0000000000..e68cbc0637 --- /dev/null +++ b/lib/core/models/esri_map_models/esrimap_ai_search_model.dart @@ -0,0 +1,105 @@ +/// ============================================================================ +/// File: esrimap_ai_search_model.dart +/// Description: Data models for AI natural language search queries, including +/// location search results, route stops, and response wrappers. +/// ============================================================================ + +/// Location search result returned by AI search endpoint. +class AiSearchResult { + /// Name or title of location. + final String name; + + /// Subtitle / category tag. + final String subtitle; + + /// Physical address string. + final String address; + + /// Latitude coordinate. + final double latitude; + + /// Longitude coordinate. + final double longitude; + + /// Optional distance in feet. + final int? distanceFeet; + + /// Optional formatted distance string (e.g. "0.3 mi"). + final String? distanceFormatted; + + /// Constructs an [AiSearchResult] instance. + const AiSearchResult({ + required this.name, + required this.subtitle, + required this.address, + required this.latitude, + required this.longitude, + this.distanceFeet, + this.distanceFormatted, + }); + + /// Factory constructor to deserialize [AiSearchResult] from a JSON map. + factory AiSearchResult.fromJson(Map j) => AiSearchResult( + name: j['name'] as String, + subtitle: j['subtitle'] as String? ?? '', + address: j['address'] as String? ?? '', + latitude: (j['latitude'] as num).toDouble(), + longitude: (j['longitude'] as num).toDouble(), + distanceFeet: j['distanceFeet'] as int?, + distanceFormatted: j['distanceFormatted'] as String?, + ); +} + +/// Geographical coordinate stop along a multi-stop AI route. +class AiSearchRouteStop { + /// Latitude coordinate. + final double lat; + + /// Longitude coordinate. + final double lon; + + /// Constructs an [AiSearchRouteStop] instance. + const AiSearchRouteStop({required this.lat, required this.lon}); + + /// Factory constructor to deserialize [AiSearchRouteStop] from a JSON map. + factory AiSearchRouteStop.fromJson(Map j) => + AiSearchRouteStop(lat: (j['lat'] as num).toDouble(), lon: (j['lon'] as num).toDouble()); +} + +/// Response payload returned from AI search REST API endpoint. +class AiSearchResponse { + /// Explanatory text or response message. + final String message; + + /// List of matching location search results. + final List results; + + /// Optional list of stop names for suggested routes. + final List? routeStopNames; + + /// Optional list of stop coordinates for suggested routes. + final List? routeStopCoords; + + /// Constructs an [AiSearchResponse] instance. + const AiSearchResponse({required this.message, required this.results, this.routeStopNames, this.routeStopCoords}); + + /// Factory constructor to deserialize [AiSearchResponse] from a JSON map. + factory AiSearchResponse.fromJson(Map j) { + List? stopNames; + List? stopCoords; + final route = j['suggestedRoute']; + final hasRoute = route != null; + if (hasRoute) { + stopNames = (route['stops'] as List).cast(); + stopCoords = (route['stopCoords'] as List) + .map((s) => AiSearchRouteStop.fromJson(s as Map)) + .toList(); + } + return AiSearchResponse( + message: j['message'] as String, + results: (j['results'] as List).map((r) => AiSearchResult.fromJson(r as Map)).toList(), + routeStopNames: stopNames, + routeStopCoords: stopCoords, + ); + } +} diff --git a/lib/core/models/esri_map_models/esrimap_basemaps.dart b/lib/core/models/esri_map_models/esrimap_basemaps.dart new file mode 100644 index 0000000000..b79cde4b1d --- /dev/null +++ b/lib/core/models/esri_map_models/esrimap_basemaps.dart @@ -0,0 +1,50 @@ +/// ============================================================================ +/// File: esrimap_basemaps.dart +/// Description: Enum models and conversion utilities for basemap types +/// (Default, Light, Dark, Satellite). +/// ============================================================================ + +/// Enumeration representing available basemap styles on the map view. +enum BasemapType { + /// Default standard campus vector map basemap. + defaultMap, + + /// Light neutral canvas basemap. + light, + + /// Dark slate mode basemap. + dark, + + /// Satellite imagery basemap. + satellite, +} + +/// Converts a [BasemapType] enum value into its corresponding configuration string key. +String basemapKey(BasemapType type) { + switch (type) { + case BasemapType.defaultMap: + return 'defaultMap'; + case BasemapType.light: + return 'light'; + case BasemapType.dark: + return 'dark'; + case BasemapType.satellite: + return 'satellite'; + } +} + +/// Converts a raw string key into a matching [BasemapType] enum, or null if unmapped. +BasemapType? basemapTypeFromKey(String key) { + switch (key) { + case 'defaultMap': + return BasemapType.defaultMap; + case 'light': + return BasemapType.light; + case 'dark': + return BasemapType.dark; + case 'satellite': + return BasemapType.satellite; + default: + return null; + } +} diff --git a/lib/core/models/esri_map_models/esrimap_config.dart b/lib/core/models/esri_map_models/esrimap_config.dart new file mode 100644 index 0000000000..6fa66a6532 --- /dev/null +++ b/lib/core/models/esri_map_models/esrimap_config.dart @@ -0,0 +1,300 @@ +/// ============================================================================ +/// File: esrimap_config.dart +/// Description: Data models for parsing backend map configuration JSON, +/// including portals, basemaps, operational layers, scenes, and feature flags. +/// ============================================================================ + +/// Specification for a base map layer. +class BaseLayerSpec { + /// Layer type identifier ('arcgisTiled', 'arcgisVectorTiled', 'arcgisMapImage'). + final String type; + + /// Service key resolving to a URL in [EsriMapConfig.serviceUrls]. + final String? serviceKey; + + /// Portal key resolving to a portal URI in [EsriMapConfig.portals]. + final String? portalKey; + + /// Optional item ID for portal items. + final String? itemId; + + /// Constructs a [BaseLayerSpec] instance. + const BaseLayerSpec({required this.type, this.serviceKey, this.portalKey, this.itemId}); + + /// Factory constructor to deserialize [BaseLayerSpec] from a JSON map. + factory BaseLayerSpec.fromJson(Map json) => BaseLayerSpec( + type: json['type'] as String, + serviceKey: json['serviceKey'] as String?, + portalKey: json['portalKey'] as String?, + itemId: json['itemId'] as String?, + ); +} + +/// Configuration structure for a basemap option. +class BasemapConfig { + /// Display label for the basemap tile in UI. + final String label; + + /// Asset path or URL for the basemap thumbnail image. + final String thumbnailAsset; + + /// List of underlying base layers constituting the basemap. + final List baseLayers; + + /// Constructs a [BasemapConfig] instance. + const BasemapConfig({required this.label, required this.thumbnailAsset, required this.baseLayers}); + + /// Factory constructor to deserialize [BasemapConfig] from a JSON map. + factory BasemapConfig.fromJson(Map json) => BasemapConfig( + label: json['label'] as String, + thumbnailAsset: json['thumbnailAsset'] as String, + baseLayers: (json['baseLayers'] as List).map((e) => BaseLayerSpec.fromJson(e as Map)).toList(), + ); +} + +/// Configuration structure for a sublayer inside a map image layer. +class SublayerEntry { + /// Display name of the sublayer. + final String name; + + /// Data source classification ('url', etc.). + final String source; + + /// REST service URL for the sublayer. + final String? url; + + /// Key resolving to a portal URI in [EsriMapConfig.portals]. + final String? portalKey; + + /// Optional item ID for portal items. + final String? itemId; + + /// Refresh timer interval in seconds (0 = disabled). + final int refreshInterval; + + /// Whether popup feature information is enabled for this sublayer. + final bool popup; + + /// Optional template string for feature popups. + final String? popupTemplate; + + /// Constructs a [SublayerEntry] instance. + const SublayerEntry({ + required this.name, + required this.source, + this.url, + this.portalKey, + this.itemId, + required this.refreshInterval, + required this.popup, + this.popupTemplate, + }); + + /// Factory constructor to deserialize [SublayerEntry] from a JSON map. + factory SublayerEntry.fromJson(Map json) => SublayerEntry( + name: json['name'] as String? ?? '', + source: json['source'] as String? ?? '', + url: json['url'] as String?, + portalKey: json['portalKey'] as String?, + itemId: json['itemId'] as String?, + refreshInterval: (json['refreshInterval'] as num?)?.toInt() ?? 0, + popup: json['popup'] as bool? ?? false, + popupTemplate: json['popupTemplate'] as String?, + ); +} + +/// Configuration structure for an operational layer toggle. +class LayerEntry { + /// Display label for the layer in UI. + final String label; + + /// Asset path or URL for the layer thumbnail image. + final String thumbnailAsset; + + /// Data source type string. + final String? source; + + /// REST service URL for the layer. + final String? url; + + /// Key resolving to a portal URI in [EsriMapConfig.portals]. + final String? portalKey; + + /// Optional item ID for portal items. + final String? itemId; + + /// Refresh timer interval in seconds (0 = disabled). + final int refreshInterval; + + /// Whether popup feature information is enabled. + final bool popup; + + /// Optional template string for feature popups. + final String? popupTemplate; + + /// Optional list of sublayers if this is a composite layer. + final List? sublayers; + + /// Constructs a [LayerEntry] instance. + const LayerEntry({ + required this.label, + required this.thumbnailAsset, + this.source, + this.url, + this.portalKey, + this.itemId, + this.refreshInterval = 0, + this.popup = false, + this.popupTemplate, + this.sublayers, + }); + + /// Returns true if sublayers list is non-null and not empty. + bool get hasSublayers { + final hasSub = sublayers != null && sublayers!.isNotEmpty; + return hasSub; + } + + /// Factory constructor to deserialize [LayerEntry] from a JSON map. + factory LayerEntry.fromJson(Map json) { + final sublayersJson = json['sublayers']; + final hasSublayersJson = sublayersJson != null; + + return LayerEntry( + label: json['label'] as String, + thumbnailAsset: json['thumbnailAsset'] as String, + source: json['source'] as String?, + url: json['url'] as String?, + portalKey: json['portalKey'] as String?, + itemId: json['itemId'] as String?, + refreshInterval: (json['refreshInterval'] as num?)?.toInt() ?? 0, + popup: json['popup'] as bool? ?? false, + popupTemplate: json['popupTemplate'] as String?, + sublayers: hasSublayersJson + ? (sublayersJson as List).map((e) => SublayerEntry.fromJson(e as Map)).toList() + : null, + ); + } +} + +/// Configuration structure for a 3D scene mode. +class SceneConfig { + /// Display label for the scene option. + final String label; + + /// Scene view type ('2d' or 'scene'). + final String type; + + /// Key resolving to a portal URI in [EsriMapConfig.portals]. + final String? portalKey; + + /// Item ID for the 3D WebScene item in ArcGIS Online / Enterprise. + final String? itemId; + + /// Constructs a [SceneConfig] instance. + const SceneConfig({required this.label, required this.type, this.portalKey, this.itemId}); + + /// Factory constructor to deserialize [SceneConfig] from a JSON map. + factory SceneConfig.fromJson(Map json) => SceneConfig( + label: json['label'] as String, + type: json['type'] as String, + portalKey: json['portalKey'] as String?, + itemId: json['itemId'] as String?, + ); +} + +/// Feature flags controlling availability of experimental app capabilities remotely. +class FeaturesConfig { + /// Whether AI natural language search sheet is enabled. + final bool aiSearch; + + /// Whether 3D scene modes are enabled. + final bool scenes; + + /// Constructs a [FeaturesConfig] instance. + const FeaturesConfig({required this.aiSearch, required this.scenes}); + + /// Factory constructor to deserialize [FeaturesConfig] from a JSON map. + factory FeaturesConfig.fromJson(Map json) => + FeaturesConfig(aiSearch: json['aiSearch'] as bool? ?? false, scenes: json['scenes'] as bool? ?? false); +} + +/// Configuration structure for a search category quick-filter chip. +class SearchCategoryConfig { + /// Display label for the category. + final String label; + + /// POI class string used to query backend server. + final String poiClass; + + /// Icon name key mapped via [iconDataForName]. + final String icon; + + /// Hexadecimal color string (e.g. "#F5F0E6"). + final String? color; + + /// Constructs a [SearchCategoryConfig] instance. + const SearchCategoryConfig({required this.label, required this.poiClass, required this.icon, this.color}); + + /// Factory constructor to deserialize [SearchCategoryConfig] from a JSON map. + factory SearchCategoryConfig.fromJson(Map json) => SearchCategoryConfig( + label: json['label'] as String, + poiClass: json['poiClass'] as String, + icon: json['icon'] as String, + color: json['color'] as String?, + ); +} + +/// Root configuration container object holding all map settings. +class EsriMapConfig { + /// Map of portal keys to portal endpoint URIs. + final Map portals; + + /// Map of service keys to ArcGIS REST endpoint URLs. + final Map serviceUrls; + + /// Map of basemap keys to basemap configuration objects. + final Map basemaps; + + /// Map of layer keys to operational layer entries. + final Map layers; + + /// Map of scene keys to 3D scene mode configurations. + final Map scenes; + + /// Remote feature flags config. + final FeaturesConfig features; + + /// Quick-search category entries. + final List searchCategories; + + /// Constructs an [EsriMapConfig] instance. + const EsriMapConfig({ + required this.portals, + required this.serviceUrls, + required this.basemaps, + required this.layers, + required this.scenes, + required this.features, + required this.searchCategories, + }); + + /// Factory constructor to deserialize root [EsriMapConfig] from a JSON map. + factory EsriMapConfig.fromJson(Map json) => EsriMapConfig( + portals: (json['portals'] as Map).cast(), + serviceUrls: (json['serviceUrls'] as Map).cast(), + basemaps: (json['basemaps'] as Map).map( + (k, v) => MapEntry(k, BasemapConfig.fromJson(v as Map)), + ), + layers: (json['layers'] as Map).map( + (k, v) => MapEntry(k, LayerEntry.fromJson(v as Map)), + ), + scenes: (json['scenes'] as Map).map( + (k, v) => MapEntry(k, SceneConfig.fromJson(v as Map)), + ), + features: FeaturesConfig.fromJson(json['features'] as Map), + searchCategories: (json['searchCategories'] as List) + .map((e) => SearchCategoryConfig.fromJson(e as Map)) + .toList(), + ); +} diff --git a/lib/core/models/esri_map_models/esrimap_search_category.dart b/lib/core/models/esri_map_models/esrimap_search_category.dart new file mode 100644 index 0000000000..66773dd103 --- /dev/null +++ b/lib/core/models/esri_map_models/esrimap_search_category.dart @@ -0,0 +1,58 @@ +/// ============================================================================ +/// File: esrimap_search_category.dart +/// Description: Model and utility helpers representing search categories +/// (e.g., Dining, Parking, Library) shown in suggestions. +/// ============================================================================ + +import 'package:flutter/material.dart'; + +/// Data class representing a quick search category chip shown on the map UI. +class EsriSearchCategory { + /// Display label for the category (e.g. "Dining", "Parking"). + final String label; + + /// Icon visual representation for the category. + final IconData icon; + + /// Underlying POI class string value used for filtering server queries. + final String poiClassValue; + + /// Accent or background color associated with the category. + final Color color; + + /// Constructs an [EsriSearchCategory] instance. + const EsriSearchCategory({ + required this.label, + required this.icon, + required this.poiClassValue, + this.color = const Color(0xFFF5F0E6), + }); +} + +/// Utility function mapping string icon names from config to [IconData] constants. +IconData iconDataForName(String name) { + switch (name) { + case 'restaurant': + return Icons.restaurant; + case 'menu_book': + return Icons.menu_book; + case 'local_parking': + return Icons.local_parking; + case 'fitness_center': + return Icons.fitness_center; + case 'directions_bus': + return Icons.directions_bus; + default: + return Icons.place; + } +} + +/// Utility function converting hexadecimal color strings (e.g., "#FFCD00") to Flutter [Color] objects. +Color colorFromHex(String? hex) { + final isHexEmpty = hex == null || hex.isEmpty; + if (isHexEmpty) return const Color(0xFFF5F0E6); + final stripped = hex.replaceFirst('#', ''); + final value = int.tryParse(stripped, radix: 16); + if (value == null) return const Color(0xFFF5F0E6); + return Color(0xFF000000 | value); +} diff --git a/lib/core/models/esri_map_models/map_search_result.dart b/lib/core/models/esri_map_models/map_search_result.dart new file mode 100644 index 0000000000..b70f12dd4f --- /dev/null +++ b/lib/core/models/esri_map_models/map_search_result.dart @@ -0,0 +1,96 @@ +/// ============================================================================ +/// File: map_search_result.dart +/// Description: Represents a unified search result for both campus buildings +/// and points of interest (POIs) in the Esri Map widget. +/// ============================================================================ + +/// Identifies the origin/type of search result. +enum MapSearchSource { + /// Result represents a physical building on campus. + building, + + /// Result represents a Point of Interest (POI) such as dining, parking, etc. + poi, +} + +/// Unified search result model encapsulating location details, coordinates, +/// description, and serialization logic for recent search persistence. +class MapSearchResult { + /// Name or title of the building or POI. + final String name; + + /// Subtitle or secondary detail string (e.g. building code or category). + final String subtitle; + + /// Latitude coordinate of the location. + final double latitude; + + /// Longitude coordinate of the location. + final double longitude; + + /// Source classification indicating whether this is a building or a POI. + final MapSearchSource source; + + /// Physical address string of the location. + final String address; + + /// Detailed textual description or additional metadata. + final String description; + + /// Optional website URL associated with this location. + final String? websiteUrl; + + /// Optional polygon geometry for the building footprint. Not serialized to JSON. + final dynamic footprint; + + /// Optional raw geometry dictionary for regenerating the footprint. + final Map? rawGeometry; + + /// Optional timestamp (milliseconds since epoch) indicating when this result was fetched. + final int? fetchedAt; + + /// Constructs a [MapSearchResult] instance. + const MapSearchResult({ + required this.name, + required this.subtitle, + required this.latitude, + required this.longitude, + required this.source, + this.address = '', + this.description = '', + this.websiteUrl, + this.footprint, + this.rawGeometry, + this.fetchedAt, + }); + + /// Serializes the search result into a JSON-compatible map for storage in SharedPreferences. + Map toJson() => { + 'name': name, + 'subtitle': subtitle, + 'latitude': latitude, + 'longitude': longitude, + 'source': source.index, + 'address': address, + 'description': description, + 'websiteUrl': websiteUrl, + if (rawGeometry != null) 'rawGeometry': rawGeometry, + if (fetchedAt != null) 'fetchedAt': fetchedAt, + }; + + /// Factory constructor to deserialize a [MapSearchResult] from a JSON map. + factory MapSearchResult.fromJson(Map json) { + return MapSearchResult( + name: json['name'] as String? ?? '', + subtitle: json['subtitle'] as String? ?? '', + latitude: (json['latitude'] as num?)?.toDouble() ?? 0.0, + longitude: (json['longitude'] as num?)?.toDouble() ?? 0.0, + source: MapSearchSource.values[json['source'] as int? ?? 0], + address: json['address'] as String? ?? '', + description: json['description'] as String? ?? '', + websiteUrl: json['websiteUrl'] as String?, + rawGeometry: json['rawGeometry'] as Map?, + fetchedAt: json['fetchedAt'] as int?, + ); + } +} diff --git a/lib/core/models/speed_test.dart b/lib/core/models/speed_test.dart index dd4f0d2c4d..dd029f8120 100644 --- a/lib/core/models/speed_test.dart +++ b/lib/core/models/speed_test.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:io'; + import 'package:wifi_connection/WifiInfo.dart'; class SpeedTestModel { diff --git a/lib/core/models/user_profile.dart b/lib/core/models/user_profile.dart index 5ed3f258c4..419bf575e2 100644 --- a/lib/core/models/user_profile.dart +++ b/lib/core/models/user_profile.dart @@ -1,4 +1,5 @@ import 'dart:convert'; + import 'package:hive/hive.dart'; part 'user_profile.g.dart'; diff --git a/lib/core/providers/dining.dart b/lib/core/providers/dining.dart index 6a91f22dfe..d8fb80faac 100644 --- a/lib/core/providers/dining.dart +++ b/lib/core/providers/dining.dart @@ -1,4 +1,5 @@ import 'dart:math'; + import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/core/models/dining.dart'; import 'package:campus_mobile_experimental/core/models/location.dart'; diff --git a/lib/core/providers/location.dart b/lib/core/providers/location.dart index 947f523a53..bb07223196 100644 --- a/lib/core/providers/location.dart +++ b/lib/core/providers/location.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/core/models/location.dart'; import 'package:flutter/cupertino.dart'; diff --git a/lib/core/providers/map.dart b/lib/core/providers/map.dart index 79bc2d5794..3f1d5b2f5c 100644 --- a/lib/core/providers/map.dart +++ b/lib/core/providers/map.dart @@ -1,4 +1,5 @@ import 'dart:math'; + import 'package:campus_mobile_experimental/core/models/location.dart'; import 'package:campus_mobile_experimental/core/models/map.dart'; import 'package:campus_mobile_experimental/core/services/map.dart'; diff --git a/lib/core/providers/notifications_freefood.dart b/lib/core/providers/notifications_freefood.dart index fc30b9208d..d7d78862cc 100644 --- a/lib/core/providers/notifications_freefood.dart +++ b/lib/core/providers/notifications_freefood.dart @@ -1,4 +1,5 @@ import 'dart:collection'; + import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/core/models/notifications.dart'; import 'package:campus_mobile_experimental/core/models/notifications_freefood.dart'; diff --git a/lib/core/providers/shuttle.dart b/lib/core/providers/shuttle.dart index aae9b53657..adcec697d5 100644 --- a/lib/core/providers/shuttle.dart +++ b/lib/core/providers/shuttle.dart @@ -1,4 +1,5 @@ import 'dart:math' as Math; + import 'package:campus_mobile_experimental/core/models/location.dart'; import 'package:campus_mobile_experimental/core/models/shuttle_arrival.dart'; import 'package:campus_mobile_experimental/core/models/shuttle_stop.dart'; diff --git a/lib/core/providers/speed_test.dart b/lib/core/providers/speed_test.dart index cff4116510..a556fc00ad 100644 --- a/lib/core/providers/speed_test.dart +++ b/lib/core/providers/speed_test.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:io'; + import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/location.dart'; diff --git a/lib/core/providers/user.dart b/lib/core/providers/user.dart index 321cf3c9eb..4ec29adb52 100644 --- a/lib/core/providers/user.dart +++ b/lib/core/providers/user.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:typed_data'; + import 'package:campus_mobile_experimental/app_provider.dart'; import 'package:campus_mobile_experimental/core/models/authentication.dart'; import 'package:campus_mobile_experimental/core/models/user_profile.dart'; diff --git a/lib/core/services/availability.dart b/lib/core/services/availability.dart index e14899b1f4..bac3853886 100644 --- a/lib/core/services/availability.dart +++ b/lib/core/services/availability.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/availability.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/classes.dart b/lib/core/services/classes.dart index 48be5dad47..859e64c980 100644 --- a/lib/core/services/classes.dart +++ b/lib/core/services/classes.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/classes.dart'; import 'package:campus_mobile_experimental/core/models/term.dart'; diff --git a/lib/core/services/dining.dart b/lib/core/services/dining.dart index 3091732412..370d639753 100644 --- a/lib/core/services/dining.dart +++ b/lib/core/services/dining.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/dining.dart'; import 'package:campus_mobile_experimental/core/models/dining_menu.dart'; diff --git a/lib/core/services/employee_id.dart b/lib/core/services/employee_id.dart index 2132f081d0..602a52e229 100644 --- a/lib/core/services/employee_id.dart +++ b/lib/core/services/employee_id.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/employee_id.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/esri_map_services/esrimap_auth_handler.dart b/lib/core/services/esri_map_services/esrimap_auth_handler.dart new file mode 100644 index 0000000000..46e39b8c8b --- /dev/null +++ b/lib/core/services/esri_map_services/esrimap_auth_handler.dart @@ -0,0 +1,103 @@ +/// ============================================================================ +/// File: esrimap_auth_handler.dart +/// Description: Custom ArcGIS Authentication Challenge Handler that fetches and +/// caches access tokens for secure ArcGIS Online / Enterprise services. +/// ============================================================================ + +import 'dart:convert'; + +import 'package:arcgis_maps/arcgis_maps.dart'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; + +/// Challenge handler implementation for authenticating protected ArcGIS REST services. +class AgeAuthChallengeHandler implements ArcGISAuthenticationChallengeHandler { + /// Endpoint URL used to retrieve authorization tokens. + final String tokensUrl; + + /// Cached token for ArcGIS Enterprise server hosts. + String? _cachedAgeToken; + DateTime? _ageTokenExpiry; + + /// Cached token for ArcGIS Online (arcgis.com) hosts. + String? _cachedAgoToken; + DateTime? _agoTokenExpiry; + + /// Creates an instance of [AgeAuthChallengeHandler] with the specified [tokensUrl]. + AgeAuthChallengeHandler(this.tokensUrl); + + /// Internal helper to retrieve an active token for the requested [host], reusing cached tokens if valid. + Future<(String?, DateTime?)> _getTokenForHost(String host) async { + final isAgo = host.contains('arcgis.com'); + + // Return cached token if valid and not expiring within 5 minutes + if (isAgo) { + final isAgoCachedValid = + _cachedAgoToken != null && + _agoTokenExpiry != null && + DateTime.now().isBefore(_agoTokenExpiry!.subtract(const Duration(minutes: 5))); + if (isAgoCachedValid) return (_cachedAgoToken, _agoTokenExpiry); + } else { + final isAgeCachedValid = + _cachedAgeToken != null && + _ageTokenExpiry != null && + DateTime.now().isBefore(_ageTokenExpiry!.subtract(const Duration(minutes: 5))); + if (isAgeCachedValid) return (_cachedAgeToken, _ageTokenExpiry); + } + + // Request fresh authentication tokens from server endpoint + final response = await http.get(Uri.parse(tokensUrl)); + final isTokenFetchNotOk = response.statusCode != 200; + if (isTokenFetchNotOk) throw Exception('Token fetch failed: ${response.statusCode}'); + final data = jsonDecode(response.body) as Map; + + // Cache Enterprise token + _cachedAgeToken = data['age']?['token'] as String?; + final ageExpiresIn = data['age']?['expires_in'] as int? ?? 7200; + _ageTokenExpiry = DateTime.now().add(Duration(seconds: ageExpiresIn)); + + // Cache ArcGIS Online token + _cachedAgoToken = data['ago']?['token'] as String?; + final agoExpiresIn = data['ago']?['expires_in'] as int? ?? 7200; + _agoTokenExpiry = DateTime.now().add(Duration(seconds: agoExpiresIn)); + + return isAgo ? (_cachedAgoToken, _agoTokenExpiry) : (_cachedAgeToken, _ageTokenExpiry); + } + + /// Handles incoming ArcGIS authentication challenges by attaching pregenerated token credentials. + @override + Future handleArcGISAuthenticationChallenge(ArcGISAuthenticationChallenge challenge) async { + final host = challenge.requestUri.host; + int maxRetries = 5; + int retryDelaySeconds = 2; + + for (int attempt = 1; attempt <= maxRetries; attempt++) { + try { + final (token, expiry) = await _getTokenForHost(host); + if (token == null || expiry == null) { + challenge.continueAndFail(); + return; + } + + final tokenInfo = TokenInfo.create(accessToken: token, expirationDate: expiry, isSslRequired: true); + if (tokenInfo == null) { + challenge.continueAndFail(); + return; + } + + final credential = PregeneratedTokenCredential(uri: challenge.requestUri, tokenInfo: tokenInfo, referer: ''); + challenge.continueWithCredential(credential); + return; // Success, exit the loop + } catch (e) { + debugPrint('Auth challenge failed on attempt $attempt: $e'); + if (attempt == maxRetries) { + challenge.continueAndFail(); + return; + } + // Wait before retrying (exponential backoff) + await Future.delayed(Duration(seconds: retryDelaySeconds)); + retryDelaySeconds *= 2; + } + } + } +} diff --git a/lib/core/services/esri_map_services/esrimap_basemap_factory.dart b/lib/core/services/esri_map_services/esrimap_basemap_factory.dart new file mode 100644 index 0000000000..fdbfb0db49 --- /dev/null +++ b/lib/core/services/esri_map_services/esrimap_basemap_factory.dart @@ -0,0 +1,88 @@ +/// ============================================================================ +/// File: esrimap_basemap_factory.dart +/// Description: Factory service constructing ArcGIS [Basemap] instances from +/// [EsriMapConfig] layer specifications. +/// ============================================================================ + +import 'dart:async'; + +import 'package:arcgis_maps/arcgis_maps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_basemaps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_config.dart'; + +void _setupPersistentRetry(Layer layer) { + layer.onLoadStatusChanged.listen((status) async { + if (status == LoadStatus.failedToLoad) { + await Future.delayed(const Duration(seconds: 2)); + layer.retryLoad(); + } + }); +} + +/// Constructs an ArcGIS [Basemap] for the requested [type] using configuration settings in [config]. +/// +/// To provide complete geographical background (coastlines, ocean, islands, regional streets) +/// without ever displaying "Map data not yet available" raster watermarks or requiring API keys: +/// 1. Public Esri Living Atlas Vector Tile base layers are used as the foundation (Light Gray / Dark Gray Canvas Base). +/// Vector tiles scale seamlessly to building/room level (Level 22+) without tile cutoff watermarks. +/// 2. Custom UC San Diego campus vector tile layers are layered directly on top to display campus-specific facilities. +Basemap buildBasemap(BasemapType type, EsriMapConfig config) { + // 1. Satellite Basemap: Use modern BasemapStyle for optimized CDN routing and faster raster loading. + var isSatellite = type == BasemapType.satellite; + if (isSatellite) return Basemap.withStyle(BasemapStyle.arcGISImagery); + + final basemap = Basemap(); + + // 2. Global Public Vector Tile Base (Coastlines, ocean, off-campus streets, islands) + // Living Atlas Item IDs (100% public, keyless vector tile services hosted by Esri): + // - Light Gray Canvas Base: 291da5eab3a0412593b66d384379f89f + // - Dark Gray Canvas Base: 5e9b3685f4c24d8781073dd928ebda50 + final globalBaseItemId = switch (type) { + BasemapType.dark => '5e9b3685f4c24d8781073dd928ebda50', + _ => '291da5eab3a0412593b66d384379f89f', + }; + + final globalLayer = ArcGISVectorTiledLayer.withItem( + PortalItem.withPortalAndItemId(portal: Portal.arcGISOnline(), itemId: globalBaseItemId), + ); + _setupPersistentRetry(globalLayer); + basemap.baseLayers.add(globalLayer); + + // 3. Custom UC San Diego Campus Vector Tile Layer (campus buildings, walkways, landscaping) + final entry = config.basemaps[basemapKey(type)]; + final portalUrl = config.portals['age'] ?? 'https://admin-enterprise-gis.ucsd.edu/portal'; + final vectorLayers = entry?.baseLayers.where((l) => l.type == 'arcgisVectorTiled').toList() ?? []; + + // Filter out any duplicate reference to the global base item ID + final campusVectorLayers = vectorLayers.where((l) => l.itemId != globalBaseItemId).toList(); + + if (campusVectorLayers.isNotEmpty) { + for (final layer in campusVectorLayers) { + final pUrl = layer.portalKey != null ? config.portals[layer.portalKey!] : portalUrl; + var hasValidUrlAndId = pUrl != null && layer.itemId != null; + if (hasValidUrlAndId) { + final portal = pUrl.contains('arcgis.com') ? Portal.arcGISOnline() : Portal(Uri.parse(pUrl)); + final campusLayer = ArcGISVectorTiledLayer.withItem( + PortalItem.withPortalAndItemId(portal: portal, itemId: layer.itemId!), + ); + _setupPersistentRetry(campusLayer); + basemap.baseLayers.add(campusLayer); + } + } + } else { + // Fallback: Append known UCSD campus vector tile layer IDs + final fallbackItemId = switch (type) { + BasemapType.light => '6643ee62af494f5bafe7dfdb8eb3f857', + BasemapType.dark => '09d7b3934b6c4c2cad8380c04e08c1b1', + _ => 'e19f33d2c1f44967aef673306c483913', + }; + + final fallbackLayer = ArcGISVectorTiledLayer.withItem( + PortalItem.withPortalAndItemId(portal: Portal(Uri.parse(portalUrl)), itemId: fallbackItemId), + ); + _setupPersistentRetry(fallbackLayer); + basemap.baseLayers.add(fallbackLayer); + } + + return basemap; +} diff --git a/lib/core/services/esri_map_services/esrimap_config_service.dart b/lib/core/services/esri_map_services/esrimap_config_service.dart new file mode 100644 index 0000000000..735f0a1c96 --- /dev/null +++ b/lib/core/services/esri_map_services/esrimap_config_service.dart @@ -0,0 +1,64 @@ +/// ============================================================================ +/// File: esrimap_config_service.dart +/// Description: Service singleton fetching and caching backend EsriMapConfig +/// JSON data and authentication token endpoints, with offline +/// asset bundle fallback logic. +/// ============================================================================ + +import 'dart:convert'; + +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_config.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart' show rootBundle; +import 'package:http/http.dart' as http; + +/// Service managing remote map configuration loading and token URL lookup. +class EsriMapConfigService { + /// Singleton instance accessor. + static final EsriMapConfigService instance = EsriMapConfigService._(); + EsriMapConfigService._(); + + /// Base API endpoint URL. + static const String BASE_URL = 'https://appzxi70zi.execute-api.us-west-2.amazonaws.com/test/ArcGIS-Map'; + + /// Asset bundle path for offline fallback map configuration JSON. + static const String ASSET_FALLBACK_PATH = 'assets/esri_map_assets/mapConfig.json'; + + EsriMapConfig? _config; + Future? _pending; + + /// Fetches [EsriMapConfig], reusing existing or in-flight Future tasks. + Future fetch() { + _pending ??= _doFetch(); + return _pending!; + } + + /// Returns cached [EsriMapConfig], or null if not yet loaded. + EsriMapConfig? get cached => _config; + + /// Returns backend tokens URL for authentication challenge handlers. + String get tokensUrl => '$BASE_URL/tokens'; + + /// Fetches map configuration over network, falling back to local asset bundle if offline or failed. + Future _doFetch() async { + // 1. Instantly load local configuration JSON from app asset bundle so map opens immediately + final fallbackJson = await rootBundle.loadString(ASSET_FALLBACK_PATH); + _config = EsriMapConfig.fromJson(jsonDecode(fallbackJson) as Map); + + // 2. Fire background network fetch to seamlessly update the cache for later + _fetchRemoteAndUpdateCache(); + + return _config!; + } + + /// Silently fetches configuration over network in the background to update the cache. + Future _fetchRemoteAndUpdateCache() async { + try { + final response = await http.get(Uri.parse('$BASE_URL/config')).timeout(const Duration(seconds: 5)); + if (response.statusCode == 200) + _config = EsriMapConfig.fromJson(jsonDecode(response.body) as Map); + } catch (e) { + debugPrint('Background remote map config fetch failed: $e'); + } + } +} diff --git a/lib/core/services/esri_map_services/esrimap_route_service.dart b/lib/core/services/esri_map_services/esrimap_route_service.dart new file mode 100644 index 0000000000..9d462d4e8d --- /dev/null +++ b/lib/core/services/esri_map_services/esrimap_route_service.dart @@ -0,0 +1,102 @@ +/// ============================================================================ +/// File: esrimap_route_service.dart +/// Description: Service handling route calculation via the ArcGIS Campus +/// Wayfinding Network NAServer. +/// ============================================================================ + +import 'package:arcgis_maps/arcgis_maps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:flutter/material.dart'; + +/// Result data structure holding the outcome of a solved route calculation. +class EsriRouteResult { + /// Travel duration in minutes. + final double travelTimeMinutes; + + /// List of direction maneuver instructions (turn-by-turn steps). + final List directionManeuvers; + + /// Visual geometry polyline representing the calculated route. + final Geometry? routeGeometry; + + /// Envelope bounding box centered with padding for map viewpoint framing. + final Envelope? paddedExtent; + + /// Constructs an [EsriRouteResult] instance. + const EsriRouteResult({ + required this.travelTimeMinutes, + required this.directionManeuvers, + this.routeGeometry, + this.paddedExtent, + }); +} + +/// Service class encapsulating ArcGIS Route Task execution. +class EsriMapRouteService { + /// Endpoint URL for the UCSD Campus Wayfinding Network service. + static const String ROUTE_SERVICE_URL = + 'https://admin-enterprise-gis.ucsd.edu/server/rest/services/' + 'Wayfinding/Campus_Wayfinding_Network/NAServer/Route'; + + /// Solves a network route between [originLatLng] and [destination] for the given [travelMode]. + static Future solveRoute({ + required (double lat, double lng) originLatLng, + required MapSearchResult destination, + required String travelMode, + }) async { + try { + final routeTask = RouteTask.withUri(Uri.parse(ROUTE_SERVICE_URL)); + await routeTask.load(); + + final params = await routeTask.createDefaultParameters(); + params.returnDirections = true; + + // Match requested travel mode ('Walking', 'Accessible', etc.) + final taskInfo = routeTask.getRouteTaskInfo(); + final matchingMode = taskInfo.travelModes.where((m) => m.name == travelMode).firstOrNull; + if (matchingMode != null) params.travelMode = matchingMode; + + // Configure origin and destination stops + final origin = Stop( + ArcGISPoint(x: originLatLng.$2, y: originLatLng.$1, spatialReference: SpatialReference.wgs84), + ); + final dest = Stop( + ArcGISPoint(x: destination.longitude, y: destination.latitude, spatialReference: SpatialReference.wgs84), + ); + params.setStops([origin, dest]); + + // Solve route + final result = await routeTask.solveRoute(params); + final isResultEmpty = result.routes.isEmpty; + if (isResultEmpty) return null; + + final route = result.routes.first; + final routeGeometry = route.routeGeometry; + final isGeometryNull = routeGeometry == null; + if (isGeometryNull) return null; + + // Compute padded extent so the route line stays visible above bottom sheets + final extent = routeGeometry.extent; + final dx = extent.width * 0.2; + final dyTop = extent.height * 0.5; + final dyBottom = extent.height * 0.75; + final paddedExtent = Envelope.fromXY( + xMin: extent.xMin - dx, + yMin: extent.yMin - dyBottom, + xMax: extent.xMax + dx, + yMax: extent.yMax + dyTop, + spatialReference: extent.spatialReference, + ); + + return EsriRouteResult( + travelTimeMinutes: route.totalTime, + directionManeuvers: route.directionManeuvers, + routeGeometry: routeGeometry, + paddedExtent: paddedExtent, + ); + } catch (e) { + debugPrint('Route solve error: $e'); + return null; + } + } +} diff --git a/lib/core/services/esri_map_services/esrimap_search_service.dart b/lib/core/services/esri_map_services/esrimap_search_service.dart new file mode 100644 index 0000000000..8c9ec9f4b0 --- /dev/null +++ b/lib/core/services/esri_map_services/esrimap_search_service.dart @@ -0,0 +1,397 @@ +/// ============================================================================ +/// File: esrimap_search_service.dart +/// Description: Service handling REST API requests for campus buildings & POIs, +/// as well as persisting recent search history to SharedPreferences. +/// ============================================================================ + +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:arcgis_maps/arcgis_maps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Service class managing location queries, POI class lookup, and local search history. +class EsriMapSearchService { + /// Base API URL endpoint. + static const String BASE_URL = 'https://appzxi70zi.execute-api.us-west-2.amazonaws.com/test/ArcGIS-Map'; + + /// SharedPreferences key used to persist recent searches. + static const String RECENT_SEARCHES_KEY = 'esri_map_recent_searches'; + + /// SharedPreferences key used to persist cached building footprints. + static const String _CACHED_BUILDINGS_KEY = 'esrimap_cached_buildings'; + + static List _searches = []; + static List _cachedBuildings = []; + + /// Maximum number of recent searches retained. + static const int MAX_RECENT_SEARCHES = 5; + + // --------------------------------------------------------------------------- + // REST API Helpers + // --------------------------------------------------------------------------- + + /// Performs an HTTP GET request to the specified [path] with optional query [params]. + static Future> apiGet(String path, [Map? params]) async { + final uri = Uri.parse('$BASE_URL/$path').replace(queryParameters: params); + final response = await http.get(uri); + final isResNotOk = response.statusCode != 200; + if (isResNotOk) throw Exception('API error ${response.statusCode}: ${response.body}'); + return jsonDecode(response.body) as Map; + } + + /// Performs an HTTP POST request to the specified [path] with a JSON [body]. + static Future> apiPost(String path, Map body) async { + final response = await http.post( + Uri.parse('$BASE_URL/$path'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode(body), + ); + final isResNotOk = response.statusCode != 200; + if (isResNotOk) throw Exception('API error ${response.statusCode}: ${response.body}'); + return jsonDecode(response.body) as Map; + } + + // --------------------------------------------------------------------------- + // Queries + // --------------------------------------------------------------------------- + + /// Queries campus buildings matching the search string [query]. + static Future> queryBuildings(String query) async { + final data = await apiGet('buildings', {'q': query}); + return (data['results'] as List? ?? []) + .map((r) { + return MapSearchResult( + name: r['name'] as String? ?? 'Unknown Building', + subtitle: r['subtitle'] as String? ?? 'Building', + latitude: (r['latitude'] as num?)?.toDouble() ?? 0.0, + longitude: (r['longitude'] as num?)?.toDouble() ?? 0.0, + source: MapSearchSource.building, + address: r['address'] as String? ?? '', + ); + }) + .where((r) => r.latitude != 0.0 && r.longitude != 0.0) + .toList(); + } + + /// Fetches all available POI class strings from the backend. + static Future> fetchAllPoiClasses() async { + try { + final data = await apiGet('poi/classes'); + return (data['classes'] as List? ?? []).map((c) => c as String).toList(); + } catch (e) { + debugPrint('Failed to fetch POI classes: $e'); + return []; + } + } + + /// Queries POIs matching the search string [query]. + static Future> queryPOIs(String query) async { + final data = await apiGet('poi', {'q': query}); + return parsePOIResults(data); + } + + /// Queries POIs belonging to a specific [classValue] (e.g. "Dining", "Parking"). + static Future> queryPOIsByClass(String classValue) async { + final data = await apiGet('poi', {'class': classValue, 'limit': '100'}); + return parsePOIResults(data); + } + + /// Parses raw JSON response maps into a list of [MapSearchResult] objects. + static List parsePOIResults(Map data) { + return (data['results'] as List? ?? []) + .map((r) { + return MapSearchResult( + name: r['name'] as String? ?? 'Unknown POI', + subtitle: r['subtitle'] as String? ?? '', + latitude: (r['latitude'] as num?)?.toDouble() ?? 0.0, + longitude: (r['longitude'] as num?)?.toDouble() ?? 0.0, + source: MapSearchSource.poi, + description: r['description'] as String? ?? '', + websiteUrl: r['websiteUrl'] as String?, + ); + }) + .where((r) => r.latitude != 0.0 && r.longitude != 0.0) + .toList(); + } + + /// Loads cached building footprints from SharedPreferences. + static Future loadCachedBuildings() async { + final prefs = await SharedPreferences.getInstance(); + final jsonStr = prefs.getString(_CACHED_BUILDINGS_KEY); + if (jsonStr != null) { + try { + final list = jsonDecode(jsonStr) as List; + _cachedBuildings = list.map((e) { + final result = MapSearchResult.fromJson(e as Map); + // Reconstruct the Polygon footprint if rawGeometry is available + dynamic footprintPolygon; + if (result.rawGeometry != null) { + final rings = result.rawGeometry!['rings'] as List?; + if (rings != null) { + try { + final builder = PolygonBuilder(spatialReference: SpatialReference.wgs84); + for (final ring in rings) { + final part = MutablePart(spatialReference: SpatialReference.wgs84); + for (final point in (ring as List)) { + final coords = point as List; + part.addPointXY(x: (coords[0] as num).toDouble(), y: (coords[1] as num).toDouble()); + } + builder.parts.addPart(part); + } + footprintPolygon = builder.toGeometry(); + } catch (_) {} + } + } + return MapSearchResult( + name: result.name, + subtitle: result.subtitle, + latitude: result.latitude, + longitude: result.longitude, + source: result.source, + address: result.address, + description: result.description, + websiteUrl: result.websiteUrl, + footprint: footprintPolygon, + rawGeometry: result.rawGeometry, + ); + }).toList(); + } catch (e) { + debugPrint('Failed to load cached buildings: $e'); + } + } + } + + /// Saves the current list of cached buildings to SharedPreferences. + static Future _saveCachedBuildings() async { + final prefs = await SharedPreferences.getInstance(); + final jsonList = _cachedBuildings.map((c) => c.toJson()).toList(); + await prefs.setString(_CACHED_BUILDINGS_KEY, jsonEncode(jsonList)); + } + + /// Identifies a building by performing a spatial intersection query at the given WGS84 coordinate. + static Future identifyBuildingAtCoordinate(double lat, double lng) async { + try { + final point = ArcGISPoint(x: lng, y: lat, spatialReference: SpatialReference.wgs84); + final now = DateTime.now().millisecondsSinceEpoch; + + for (int i = 0; i < _cachedBuildings.length; i++) { + final cached = _cachedBuildings[i]; + if (cached.footprint != null) { + final intersects = GeometryEngine.intersects(geometry1: point, geometry2: cached.footprint as Geometry); + if (intersects) { + // Check if cache is older than 30 days (30L * 24 * 60 * 60 * 1000) + final isExpired = cached.fetchedAt == null || (now - cached.fetchedAt!) > 2592000000; + if (!isExpired) { + return cached; + } else { + // Expired, remove it so we fetch a fresh one + _cachedBuildings.removeAt(i); + break; + } + } + } + } + + final uri = Uri.parse( + 'https://admin-enterprise-gis.ucsd.edu/server/rest/services/Buildings/Buildings_Campus_Map/MapServer/2/query', + ); + final response = await http.get( + uri.replace( + queryParameters: { + 'geometry': '$lng,$lat', + 'geometryType': 'esriGeometryPoint', + 'inSR': '4326', + 'spatialRel': 'esriSpatialRelIntersects', + 'distance': '15', + 'units': 'esriSRUnit_Foot', + 'outFields': '*', + 'returnGeometry': 'true', + 'outSR': '4326', + 'f': 'json', + }, + ), + ); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + final features = data['features'] as List?; + final hasFeatures = features != null && features.isNotEmpty; + if (hasFeatures) { + final attr = features.first['attributes'] as Map; + + final longName = attr['GIS.facTririgaBuildingInfo.FacilityLongName'] as String?; + final shortName = attr['GIS.facTririgaBuildingInfo.FacilityShortName'] as String?; + String name = (longName != null && longName.isNotEmpty) ? longName : (shortName ?? 'Unknown Building'); + String address = attr['GIS.facTririgaBuildingInfo.StreetAddress'] as String? ?? ''; + + // Try to extract center of geometry if it's returned, otherwise fallback to tap location + double resLat = lat; + double resLng = lng; + Polygon? footprintPolygon; + + final geom = features.first['geometry'] as Map?; + if (geom != null) { + final rings = geom['rings'] as List?; + final hasRings = rings != null && rings.isNotEmpty; + if (hasRings) { + final firstRing = rings.first as List?; + final hasFirstRing = firstRing != null && firstRing.isNotEmpty; + if (hasFirstRing) { + double minX = double.infinity, maxX = double.negativeInfinity; + double minY = double.infinity, maxY = double.negativeInfinity; + for (final point in firstRing) { + final coords = point as List; + final x = (coords[0] as num).toDouble(); + final y = (coords[1] as num).toDouble(); + if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; + } + resLng = (minX + maxX) / 2; + resLat = (minY + maxY) / 2; + } + + try { + final builder = PolygonBuilder(spatialReference: SpatialReference.wgs84); + for (final ring in rings) { + final part = MutablePart(spatialReference: SpatialReference.wgs84); + final ringPoints = ring as List; + for (final point in ringPoints) { + final coords = point as List; + part.addPointXY(x: (coords[0] as num).toDouble(), y: (coords[1] as num).toDouble()); + } + builder.parts.addPart(part); + } + footprintPolygon = builder.toGeometry() as Polygon?; + } catch (e) { + debugPrint('Failed to parse polygon geometry: $e'); + } + } + } + + if (name == 'Unknown Building') { + final fallbackUrl = Uri.parse( + 'https://admin-enterprise-gis.ucsd.edu/server/rest/services/Buildings/Buildings_Campus_Map/MapServer/0/query', + ); + try { + final fallbackRes = await http.get( + fallbackUrl.replace( + queryParameters: { + 'geometry': '$resLng,$resLat', + 'geometryType': 'esriGeometryPoint', + 'inSR': '4326', + 'spatialRel': 'esriSpatialRelIntersects', + 'distance': '100', // 100 feet from center of footprint + 'units': 'esriSRUnit_Foot', + 'outFields': '*', + 'returnGeometry': 'false', + 'f': 'json', + }, + ), + ); + if (fallbackRes.statusCode == 200) { + final fallbackData = jsonDecode(fallbackRes.body); + final fallbackFeatures = fallbackData['features'] as List?; + final hasFallbackFeatures = fallbackFeatures != null && fallbackFeatures.isNotEmpty; + if (hasFallbackFeatures) { + final fbAttr = fallbackFeatures.first['attributes'] as Map; + final fbLong = fbAttr['GIS.facTririgaBuildingInfo.FacilityLongName'] as String?; + final fbShort = fbAttr['GIS.facTririgaBuildingInfo.FacilityShortName'] as String?; + final hasFbLong = fbLong != null && fbLong.isNotEmpty; + final hasFbShort = fbShort != null && fbShort.isNotEmpty; + if (hasFbLong) { + name = fbLong; + } else if (hasFbShort) { + name = fbShort; + } + final fbAddr = fbAttr['GIS.facTririgaBuildingInfo.StreetAddress'] as String?; + final hasFbAddr = fbAddr != null && fbAddr.isNotEmpty; + if (hasFbAddr) address = fbAddr; + } + } + } catch (_) {} + } + + final newResult = MapSearchResult( + name: name, + subtitle: 'Building', + latitude: resLat, + longitude: resLng, + source: MapSearchSource.building, + address: address, + footprint: footprintPolygon, + rawGeometry: geom, + fetchedAt: DateTime.now().millisecondsSinceEpoch, + ); + + _cachedBuildings.add(newResult); + _saveCachedBuildings(); + + return newResult; + } + } + } catch (e) { + debugPrint('Failed to identify building at coordinate: $e'); + } + return null; + } + + // --------------------------------------------------------------------------- + // Viewport & Geographic Helpers + // --------------------------------------------------------------------------- + + /// Filters a list of [results] down to those located within the specified [envelope]. + static List filterToViewport(List results, Envelope? envelope) { + final isEnvelopeNull = envelope == null; + if (isEnvelopeNull) return results; + return results.where((r) { + return r.latitude >= envelope.yMin && + r.latitude <= envelope.yMax && + r.longitude >= envelope.xMin && + r.longitude <= envelope.xMax; + }).toList(); + } + + /// Calculates the Haversine distance in meters between two geographical WGS84 coordinates. + static double distanceMeters(double lat1, double lng1, double lat2, double lng2) { + const r = 6371000.0; // Earth radius in meters + final dLat = (lat2 - lat1) * math.pi / 180; + final dLng = (lng2 - lng1) * math.pi / 180; + final a = + math.sin(dLat / 2) * math.sin(dLat / 2) + + math.cos(lat1 * math.pi / 180) * math.cos(lat2 * math.pi / 180) * math.sin(dLng / 2) * math.sin(dLng / 2); + return r * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)); + } + + // --------------------------------------------------------------------------- + // Recent Searches Persistence + // --------------------------------------------------------------------------- + + /// Loads stored recent searches from [SharedPreferences]. + static Future> loadRecentSearches() async { + final prefs = await SharedPreferences.getInstance(); + final jsonStr = prefs.getString(RECENT_SEARCHES_KEY); + final hasJsonStr = jsonStr != null; + if (hasJsonStr) { + try { + final list = jsonDecode(jsonStr) as List; + return list.map((e) => MapSearchResult.fromJson(e as Map)).toList(); + } catch (_) { + // Return empty on corrupt stored data + } + } + return []; + } + + /// Saves the current list of [searches] to [SharedPreferences]. + static Future saveRecentSearches(List searches) async { + final prefs = await SharedPreferences.getInstance(); + final jsonStr = jsonEncode(searches.map((r) => r.toJson()).toList()); + await prefs.setString(RECENT_SEARCHES_KEY, jsonStr); + } +} diff --git a/lib/core/services/events.dart b/lib/core/services/events.dart index 4c51e63201..300d21d957 100644 --- a/lib/core/services/events.dart +++ b/lib/core/services/events.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/events.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/map.dart b/lib/core/services/map.dart index 27f8965d08..1a50002f0b 100644 --- a/lib/core/services/map.dart +++ b/lib/core/services/map.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/map.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/messages.dart b/lib/core/services/messages.dart index b3cf1717a8..d8e2fac09b 100644 --- a/lib/core/services/messages.dart +++ b/lib/core/services/messages.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/notifications.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/news.dart b/lib/core/services/news.dart index b1134cca1b..8cff63427c 100644 --- a/lib/core/services/news.dart +++ b/lib/core/services/news.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/news.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/notices.dart b/lib/core/services/notices.dart index edd7c50c5f..64e4d66384 100644 --- a/lib/core/services/notices.dart +++ b/lib/core/services/notices.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/notices.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/notifications.dart b/lib/core/services/notifications.dart index b104f9bb91..dc7f0b39e2 100644 --- a/lib/core/services/notifications.dart +++ b/lib/core/services/notifications.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/topics.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/speed_test.dart b/lib/core/services/speed_test.dart index 51c2e17727..bfe5498f3f 100644 --- a/lib/core/services/speed_test.dart +++ b/lib/core/services/speed_test.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:io'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/speed_test.dart'; import 'package:connectivity_plus/connectivity_plus.dart'; diff --git a/lib/core/services/spot_types.dart b/lib/core/services/spot_types.dart index d05329ee8f..90466da850 100644 --- a/lib/core/services/spot_types.dart +++ b/lib/core/services/spot_types.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/spot_types.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/services/tgpt_services/chat_persistence.dart b/lib/core/services/tgpt_services/chat_persistence.dart index 0a917705e4..ecbeb3bba7 100644 --- a/lib/core/services/tgpt_services/chat_persistence.dart +++ b/lib/core/services/tgpt_services/chat_persistence.dart @@ -1,4 +1,5 @@ import 'dart:convert'; + import 'package:hive/hive.dart'; import 'package:campus_mobile_experimental/core/models/tgpt_models/chat_message_persistent.dart'; import 'package:campus_mobile_experimental/core/models/tgpt_models/chat_history.dart'; diff --git a/lib/core/services/user.dart b/lib/core/services/user.dart index 44264d5348..38f52a6657 100644 --- a/lib/core/services/user.dart +++ b/lib/core/services/user.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_networking.dart'; import 'package:campus_mobile_experimental/core/models/user_profile.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; diff --git a/lib/core/utils/esri_map_feature_flags.dart b/lib/core/utils/esri_map_feature_flags.dart new file mode 100644 index 0000000000..cbbb879ace --- /dev/null +++ b/lib/core/utils/esri_map_feature_flags.dart @@ -0,0 +1,73 @@ +/// ============================================================================ +/// File: feature_flags.dart +/// Description: Centralized configuration for enabling/disabling app features +/// using static boolean variables. Because these are static const, +/// the Dart compiler will optimize away (tree-shake) dead code +/// when features are disabled, saving compute and memory resources. +/// ============================================================================ + +class FeatureFlags { + // --------------------------------------------------------------------------- + // Search & Navigation + // --------------------------------------------------------------------------- + + /// Controls the availability of the core Search Bar. + /// - `true`: The top search bar is rendered, allowing text search for buildings and places. + /// - `false`: The search bar is completely hidden. (Note: this effectively disables AI search and category chips too). + static const bool MAP_SEARCH_ENABLED = true; + + /// Controls the availability of the AI Search feature. + /// - `true`: Renders the AI search trigger button inside the search bar. + /// - `false`: Hides the AI search button and prevents instantiation of AI-related models. + static const bool MAP_AI_SEARCH_ENABLED = false; // No AI search for now. + + /// Controls the quick-filter category chips (Dining, Library, Parking, Recreation). + /// - `true`: Displays the quick-filter chips when the search bar is active. + /// - `false`: Hides the chips, saving UI rendering time. + static const bool MAP_SEARCH_CATEGORIES_ENABLED = true; + + /// Controls point-to-point routing and directions. + /// - `true`: Enables route calculation and displays "Directions" buttons in POI details. + /// - `false`: Disables route generation logic and hides related UI elements. + static const bool MAP_ROUTING_ENABLED = true; + + /// Controls device GPS location tracking. + /// - `true`: Starts the location data source to query GPS hardware and shows the re-center FAB. + /// - `false`: Prevents querying GPS hardware (saving battery) and hides location UI controls. + static const bool MAP_LOCATION_TRACKING_ENABLED = true; + + // --------------------------------------------------------------------------- + // Basemaps & Layers (inside the Map Display) + // --------------------------------------------------------------------------- + + /// Controls the availability of alternative basemaps like "Light" and "Dark". + /// - `true`: The UI will display buttons for these basemaps, and the map controller + /// will instantiate and pre-load them into memory. + /// - `false`: The UI buttons will be hidden, and the map controller will skip + /// creating these objects, saving significant memory. + static const bool MAP_ALTERNATE_BASEMAPS_ENABLED = false; // No Light and Dark basemaps for now. + + /// Master switch for all Operational Layers (Transit, Districts, Construction). + /// - `true`: Renders the "LAYERS" section in the map settings panel. + /// - `false`: Hides the entire "LAYERS" section and prevents layer preloading. + static const bool MAP_OPERATIONAL_LAYERS_ENABLED = true; + + // Fine-grained layer toggles (Only effective if MAP_OPERATIONAL_LAYERS_ENABLED is true) + static const bool TRANSIT_OPERATIONAL_LAYER_ENABLED = true; + static const bool DISTRICTS_OPERATIONAL_LAYER_ENABLED = true; + static const bool CONSTRUCTION_OPERATIONAL_LAYER_ENABLED = true; + + // --------------------------------------------------------------------------- + // SCENES Feature (inside the Map Display) + // --------------------------------------------------------------------------- + + /// Master switch for the 3D Scene View toggles. + /// - `true`: Renders the "SCENE" section in the map settings panel. + /// - `false`: Hides the entire "SCENE" section. + static const bool MAP_SCENES_ENABLED = false; + + // Fine-grained scene toggles (Only effective if MAP_SCENES_ENABLED is true) + static const bool DEFAULT_SCENE_ENABLED = false; + static const bool THREE_DIMENSIONAL_SCENE_ENABLED = false; + static const bool DRONE_VIEW_SCENE_ENABLED = false; +} diff --git a/lib/core/utils/webview.dart b/lib/core/utils/webview.dart index 273087f51c..03751f2091 100644 --- a/lib/core/utils/webview.dart +++ b/lib/core/utils/webview.dart @@ -1,4 +1,5 @@ import 'dart:core'; + import 'package:campus_mobile_experimental/app_styles.dart'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/main.dart b/lib/main.dart index d5be63fddd..404983d0ac 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -17,6 +17,7 @@ import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; +import 'package:arcgis_maps/arcgis_maps.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; @@ -39,6 +40,17 @@ void main() async { // dotenv loading await dotenv.load(isOptional: true); + // Uncomment to remove the "Licensed for Developer Use Only" watermark in the ESRI Map + // final esriApiKey = dotenv.env['ESRI_API_KEY']; + // if (esriApiKey != null && esriApiKey.isNotEmpty) { + // ArcGISEnvironment.apiKey = esriApiKey; + // } + // + // final esriLicenseKey = dotenv.env['ESRI_LICENSE_KEY']; + // if (esriLicenseKey != null && esriLicenseKey.isNotEmpty) { + // ArcGISEnvironment.setLicense(esriLicenseKey); + // } + /// Enable crash analytics - https://firebase.flutter.dev/docs/crashlytics/usage#toggle-crashlytics-collection await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true); diff --git a/lib/ui/common/directions_helper.dart b/lib/ui/common/directions_helper.dart index f799c5c04d..e438a4ab60 100644 --- a/lib/ui/common/directions_helper.dart +++ b/lib/ui/common/directions_helper.dart @@ -1,4 +1,5 @@ import 'dart:io'; + import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:url_launcher/url_launcher.dart'; diff --git a/lib/ui/common/webview_container.dart b/lib/ui/common/webview_container.dart index b896fa2bc8..fc000bd023 100644 --- a/lib/ui/common/webview_container.dart +++ b/lib/ui/common/webview_container.dart @@ -11,6 +11,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:campus_mobile_experimental/ui/home/home.dart'; import 'package:webview_flutter/webview_flutter.dart'; + import 'dart:async'; class WebViewContainer extends StatefulWidget { diff --git a/lib/ui/dining/dining_detail_view.dart b/lib/ui/dining/dining_detail_view.dart index 8bb21f2c2c..9d9a7f660f 100644 --- a/lib/ui/dining/dining_detail_view.dart +++ b/lib/ui/dining/dining_detail_view.dart @@ -8,6 +8,7 @@ import 'package:url_launcher/url_launcher.dart'; import 'package:provider/provider.dart'; import 'package:campus_mobile_experimental/core/models/availability.dart'; import 'package:campus_mobile_experimental/core/providers/availability.dart'; + import 'dining_busyness_bar.dart'; class DiningDetailView extends StatefulWidget { @@ -87,6 +88,15 @@ class _DiningDetailViewState extends State { width: 80, height: 80, semanticLabel: 'Location logo', + errorBuilder: (context, error, stackTrace) { + return Icon( + Icons.restaurant, + size: 56, + color: Theme.of(context).brightness == Brightness.light + ? lightPrimaryColor + : darkPrimaryColor2, + ); + }, ), ) : Icon( diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_ai_search_sheet.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_ai_search_sheet.dart new file mode 100644 index 0000000000..0d3d959d45 --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_ai_search_sheet.dart @@ -0,0 +1,292 @@ +/// ============================================================================ +/// File: esrimap_ai_search_sheet.dart +/// Description: Modal bottom sheet widget enabling AI natural language map queries +/// (e.g., "coffee spots near Geisel Library"). +/// ============================================================================ + +import 'dart:convert'; + +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_ai_search_model.dart'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; + +enum _AiSearchState { idle, loading, results, error } + +/// Modal bottom sheet widget for AI map search. +class EsriAiSearchSheet extends StatefulWidget { + /// Optional current user latitude coordinate. + final double? userLat; + + /// Optional current user longitude coordinate. + final double? userLon; + + /// Callback when a location result is selected. + final void Function(AiSearchResult result) onLocationSelected; + + /// Callback when a multi-stop route is requested. + final void Function(List stops) onRouteRequested; + + /// Constructs an [EsriAiSearchSheet] instance. + const EsriAiSearchSheet({ + Key? key, + this.userLat, + this.userLon, + required this.onLocationSelected, + required this.onRouteRequested, + }) : super(key: key); + + @override + State createState() => _EsriAiSearchSheetState(); +} + +class _EsriAiSearchSheetState extends State { + final _controller = TextEditingController(); + _AiSearchState _state = _AiSearchState.idle; + AiSearchResponse? _response; + + /// Base API URL endpoint. + static const String BASE_URL = 'https://appzxi70zi.execute-api.us-west-2.amazonaws.com/test/ArcGIS-Map'; + + Future _submit() async { + final query = _controller.text.trim(); + final isQueryEmpty = query.isEmpty; + if (isQueryEmpty) return; + + setState(() { + _state = _AiSearchState.loading; + _response = null; + }); + + try { + final body = {'query': query}; + final hasUserLat = widget.userLat != null; + final hasUserLon = widget.userLon != null; + if (hasUserLat) body['lat'] = widget.userLat; + if (hasUserLon) body['lon'] = widget.userLon; + + final res = await http.post( + Uri.parse('$BASE_URL/ai-search'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode(body), + ); + final isResNotOk = res.statusCode != 200; + if (isResNotOk) throw Exception('Request failed: ${res.statusCode}'); + + final data = jsonDecode(res.body) as Map; + setState(() { + _response = AiSearchResponse.fromJson(data); + _state = _AiSearchState.results; + }); + } catch (e) { + debugPrint('AI search error: $e'); + setState(() { + _state = _AiSearchState.error; + }); + } + } + + IconData _iconForSubtitle(String subtitle) { + final s = subtitle.toLowerCase(); + final isDining = s.contains('dining') || s.contains('food') || s.contains('coffee') || s.contains('cafe'); + if (isDining) return Icons.restaurant; + final isLibrary = s.contains('library') || s.contains('academic'); + if (isLibrary) return Icons.menu_book; + final isParking = s.contains('parking'); + if (isParking) return Icons.local_parking; + final isRec = s.contains('recreation') || s.contains('gym') || s.contains('fitness'); + if (isRec) return Icons.fitness_center; + final isTransit = s.contains('transit') || s.contains('shuttle'); + if (isTransit) return Icons.directions_bus; + return Icons.place; + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final bgColor = Theme.of(context).scaffoldBackgroundColor; + final textColor = isDark ? Colors.white : Colors.grey[900]!; + final subtitleColor = isDark ? Colors.grey[400]! : Colors.grey[600]!; + final accent = Theme.of(context).colorScheme.primary; + final bottomPad = MediaQuery.of(context).viewInsets.bottom; + + final isResultsState = _state == _AiSearchState.results; + final hasResponse = _response != null; + final hasResults = isResultsState && hasResponse; + final isLoading = _state == _AiSearchState.loading; + final isError = _state == _AiSearchState.error; + + return Container( + decoration: BoxDecoration( + color: bgColor, + borderRadius: const BorderRadius.vertical(top: Radius.circular(16)), + ), + padding: EdgeInsets.only(bottom: bottomPad), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Drag handle bar + Center( + child: Container( + margin: const EdgeInsets.only(top: 10, bottom: 6), + width: 36, + height: 4, + decoration: BoxDecoration( + color: isDark ? Colors.grey[700] : Colors.grey[300], + borderRadius: BorderRadius.circular(2), + ), + ), + ), + + // Header + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 12), + child: Row( + children: [ + Icon(Icons.auto_awesome, size: 18, color: accent), + const SizedBox(width: 8), + Text( + 'Ask the Map', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: textColor), + ), + ], + ), + ), + + // Search input + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 12), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _controller, + autofocus: true, + textInputAction: TextInputAction.search, + onSubmitted: (_) => _submit(), + style: TextStyle(color: textColor), + decoration: InputDecoration( + hintText: 'e.g. "good lunch spots near Price Center"', + hintStyle: TextStyle(color: subtitleColor, fontSize: 13), + filled: true, + fillColor: isDark ? Colors.grey[800] : Colors.grey[100], + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + ), + ), + ), + const SizedBox(width: 8), + Semantics( + button: true, + label: isLoading ? 'Searching' : 'Submit search', + child: ExcludeSemantics( + child: FilledButton( + onPressed: isLoading ? null : _submit, + style: FilledButton.styleFrom( + minimumSize: const Size(48, 48), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + child: isLoading + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), + ) + : const Icon(Icons.search), + ), + ), + ), + ], + ), + ), + + // Results section + if (hasResults) ...[ + if (_response!.message.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text(_response!.message, style: TextStyle(fontSize: 13, color: subtitleColor)), + ), + + if (_response!.results.isEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + child: Text( + 'No results found. Try a different query.', + style: TextStyle(fontSize: 13, color: subtitleColor), + ), + ), + + ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 280), + child: ListView.separated( + shrinkWrap: true, + itemCount: _response!.results.length, + separatorBuilder: (_, __) => + Divider(height: 1, indent: 56, color: isDark ? Colors.grey[800] : Colors.grey[200]), + itemBuilder: (context, i) { + final r = _response!.results[i]; + final hasDistance = r.distanceFormatted != null; + final subtitleStr = hasDistance ? '${r.subtitle} · ${r.distanceFormatted}' : r.subtitle; + + return ListTile( + leading: ExcludeSemantics( + child: CircleAvatar( + backgroundColor: accent.withValues(alpha: 0.12), + child: Icon(_iconForSubtitle(r.subtitle), color: accent, size: 18), + ), + ), + title: Text( + r.name, + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: textColor), + ), + subtitle: Text(subtitleStr, style: TextStyle(fontSize: 12, color: subtitleColor)), + onTap: () { + Navigator.pop(context); + widget.onLocationSelected(r); + }, + ); + }, + ), + ), + + // Multi-stop route button + if (_response!.routeStopNames != null) ...[ + const Divider(height: 1), + Padding( + padding: const EdgeInsets.all(12), + child: SizedBox( + width: double.infinity, + child: FilledButton.icon( + icon: const ExcludeSemantics(child: Icon(Icons.directions)), + label: Text('Route through ${_response!.routeStopNames!.length} stops'), + onPressed: () { + Navigator.pop(context); + widget.onRouteRequested(_response!.results); + }, + ), + ), + ), + ] else + const SizedBox(height: 16), + ], + + if (isError) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + child: Text( + 'Something went wrong. Please try again.', + style: TextStyle(fontSize: 13, color: Colors.redAccent), + ), + ), + ], + ), + ); + } +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_callout_content.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_callout_content.dart new file mode 100644 index 0000000000..fa1825fcd9 --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_callout_content.dart @@ -0,0 +1,309 @@ +import 'package:campus_mobile_experimental/core/models/availability.dart'; +import 'package:campus_mobile_experimental/core/models/dining.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:campus_mobile_experimental/core/models/parking.dart'; +import 'package:flutter/material.dart'; + +class EsriMapCalloutContent extends StatelessWidget { + final MapSearchResult result; + final String detail; + final bool isDark; + + final List diningModels; + final List parkingModels; + final List availabilityModels; + + const EsriMapCalloutContent({ + Key? key, + required this.result, + required this.detail, + required this.isDark, + required this.diningModels, + required this.parkingModels, + required this.availabilityModels, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final String queryName = result.name.toLowerCase().trim(); + + // 1. Try to match Dining + final diningMatch = _findDiningMatch(queryName, diningModels); + if (diningMatch != null) return _buildCalloutContainer(context, child: _buildDiningContent(context, diningMatch)); + + // 2. Try to match Parking + final parkingMatch = _findParkingMatch(queryName, parkingModels); + if (parkingMatch != null) + return _buildCalloutContainer(context, child: _buildParkingContent(context, parkingMatch)); + + // 3. Try to match Availability + final availabilityMatch = _findAvailabilityMatch(queryName, availabilityModels); + if (availabilityMatch != null) + return _buildCalloutContainer(context, child: _buildAvailabilityContent(context, availabilityMatch)); + + // 4. Fallback to generic subtitle if no contextual data is found + return _buildCalloutContainer(context, child: _buildFallbackContent(context)); + } + + // --- Matching Logic --- + + DiningModel? _findDiningMatch(String query, List models) { + if (query.isEmpty) return null; + for (var model in models) { + final name = model.name.toLowerCase().trim(); + final isExactMatch = name == query; + final queryContainsName = query.contains(name); + final nameContainsQuery = name.contains(query); + if (isExactMatch || queryContainsName || nameContainsQuery) return model; + } + return null; + } + + ParkingModel? _findParkingMatch(String query, List models) { + if (query.isEmpty) return null; + for (var model in models) { + final locName = model.locationName.toLowerCase().trim(); + // Use bidirectional containment to catch cases where the map says "Gilman Parking Structure" but the model says "Gilman" + final isExactMatch = locName == query; + final queryContainsLocName = query.contains(locName); + final locNameContainsQuery = locName.contains(query); + if (isExactMatch || queryContainsLocName || locNameContainsQuery) return model; + } + return null; + } + + SubLocations? _findAvailabilityMatch(String query, List models) { + if (query.isEmpty) return null; + for (var model in models) { + if (model != null) { + for (var sub in model.subLocations) { + final subName = sub.name.toLowerCase().trim(); + final isExactMatch = subName == query; + final queryContainsSubName = query.contains(subName); + final subNameContainsQuery = subName.contains(query); + if (isExactMatch || queryContainsSubName || subNameContainsQuery) return sub; + } + } + } + return null; + } + + // --- UI Builders --- + + Widget _buildCalloutContainer(BuildContext context, {required Widget child}) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + result.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: TextStyle( + color: isDark ? Colors.white : Colors.black87, + fontSize: 15, + fontWeight: FontWeight.w600, + height: 1.15, + ), + ), + const SizedBox(height: 4), + child, + ], + ); + } + + Widget _buildFallbackContent(BuildContext context) { + if (detail.isEmpty) return const SizedBox.shrink(); + final isBuilding = result.source == MapSearchSource.building; + return Semantics( + label: isBuilding ? 'Building Address: $detail' : null, + child: Text( + detail, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: TextStyle(color: isDark ? Colors.white70 : Colors.black54, fontSize: 12, height: 1.15), + ), + ); + } + + // --- Dining Content --- + + Widget _buildDiningContent(BuildContext context, DiningModel dining) { + try { + final isOpen = _isDiningOpen(dining.regularHours); + final statusColor = isOpen ? Colors.green : Colors.red; + final statusText = isOpen ? "Open" : "Closed"; + + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 8, + height: 8, + decoration: BoxDecoration(color: statusColor, shape: BoxShape.circle), + ), + const SizedBox(width: 4), + Text( + statusText, + style: TextStyle( + color: isDark ? Colors.white70 : Colors.black87, + fontSize: 12, + fontWeight: FontWeight.w500, + ), + ), + if (dining.distance != null) ...[ + const SizedBox(width: 6), + Container( + width: 4, + height: 4, + decoration: BoxDecoration(color: isDark ? Colors.white30 : Colors.black26, shape: BoxShape.circle), + ), + const SizedBox(width: 6), + Text( + "${dining.distance!.toStringAsFixed(1)} mi", + style: TextStyle(color: isDark ? Colors.white70 : Colors.black54, fontSize: 12), + ), + ], + ], + ); + } catch (e) { + return _buildFallbackContent(context); + } + } + + bool _isDiningOpen(RegularHours hours) { + int weekday = DateTime.now().weekday; + String? dayHours; + switch (weekday) { + case 1: + dayHours = hours.mon; + break; + case 2: + dayHours = hours.tue; + break; + case 3: + dayHours = hours.wed; + break; + case 4: + dayHours = hours.thu; + break; + case 5: + dayHours = hours.fri; + break; + case 6: + dayHours = hours.sat; + break; + case 7: + dayHours = hours.sun; + break; + } + + final isNull = dayHours == null; + final isClosed = dayHours == 'Closed-Closed'; + final isInvalid = dayHours == 'Invalid Date-Invalid Date'; + if (isNull || isClosed || isInvalid) return false; + + return true; + } + + // --- Parking Content --- + + Widget _buildParkingContent(BuildContext context, ParkingModel parking) { + try { + int totalOpen = 0; + int totalCapacity = 0; + + for (var spotData in parking.availability.values) { + if (spotData == null || spotData is! Map) continue; + + int open = spotData["Open"] is String ? (int.tryParse(spotData["Open"]) ?? 0) : (spotData["Open"] ?? 0); + + int total = spotData["Total"] is String ? (int.tryParse(spotData["Total"]) ?? 0) : (spotData["Total"] ?? 0); + + totalOpen += open; + totalCapacity += total; + } + + if (totalCapacity == 0) + return Text("No space data", style: TextStyle(color: isDark ? Colors.white70 : Colors.black54, fontSize: 12)); + + double percent = totalOpen / totalCapacity; + if (percent.isNaN) percent = 0.0; + + Color progressColor = Colors.green; + if (percent < 0.25) + progressColor = Colors.red; + else if (percent < 0.75) + progressColor = Colors.orange; + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + "$totalOpen / $totalCapacity Spaces", + style: TextStyle(color: isDark ? Colors.white70 : Colors.black87, fontSize: 12), + ), + const SizedBox(height: 4), + SizedBox( + width: 100, + child: ClipRRect( + borderRadius: BorderRadius.circular(4), + child: ExcludeSemantics( + child: LinearProgressIndicator( + value: percent, + backgroundColor: isDark ? Colors.white24 : Colors.black12, + valueColor: AlwaysStoppedAnimation(progressColor), + ), + ), + ), + ), + ], + ); + } catch (e) { + return _buildFallbackContent(context); + } + } + + // --- Availability Content --- + + Widget _buildAvailabilityContent(BuildContext context, SubLocations subLocation) { + try { + double percent = subLocation.percentage; + + Color progressColor = Color(0xFF109B00); // Green + if (percent >= 0.75) + progressColor = Color(0xFFBD1900); // Red + else if (percent >= 0.25) + progressColor = Color(0xFFFC8900); // Orange + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + "${(percent * 100).toInt()}% Busy", + style: TextStyle(color: isDark ? Colors.white70 : Colors.black87, fontSize: 12), + ), + const SizedBox(height: 4), + SizedBox( + width: 100, + child: ClipRRect( + borderRadius: BorderRadius.circular(4), + child: ExcludeSemantics( + child: LinearProgressIndicator( + value: percent <= 0.01 ? 0.01 : percent, + backgroundColor: isDark ? Colors.white24 : Colors.black12, + valueColor: AlwaysStoppedAnimation(progressColor), + ), + ), + ), + ), + ], + ); + } catch (e) { + return _buildFallbackContent(context); + } + } +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_category_list_panel.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_category_list_panel.dart new file mode 100644 index 0000000000..fa7626ce4d --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_category_list_panel.dart @@ -0,0 +1,208 @@ +/// ============================================================================ +/// File: esrimap_category_list_panel.dart +/// Description: Draggable scrollable bottom sheet displaying all plotted POI +/// results for an active category search, sorted by distance. +/// ============================================================================ + +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_search_category.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:campus_mobile_experimental/core/services/esri_map_services/esrimap_search_service.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_detail_slide_over.dart'; +import 'package:flutter/material.dart'; + +/// Bottom sheet widget rendering plotted category search results in a list. +class EsriMapCategoryListPanel extends StatelessWidget { + /// Controller managing draggable sheet height. + final DraggableScrollableController controller; + + /// Active search category being displayed. + final EsriSearchCategory? activeCategory; + + /// Unfiltered list of all results for this category. + final List allCategoryResults; + + /// Results currently within the visible map viewport. + final List viewportResults; + + /// User's current location coordinates for distance sorting, if available. + final (double lat, double lng)? userLocation; + + /// Callback to clear search and close panel. + final VoidCallback onClearSearch; + + /// Callback when "See all results" button is tapped. + final VoidCallback onSeeAllResults; + + /// Callback when a item in the list is tapped. + final void Function(MapSearchResult result) onSelectResult; + + /// Helper function mapping results to appropriate icon. + final IconData Function(MapSearchResult result) iconForResult; + + /// Constructs an [EsriMapCategoryListPanel] instance. + const EsriMapCategoryListPanel({ + Key? key, + required this.controller, + required this.activeCategory, + required this.allCategoryResults, + required this.viewportResults, + required this.userLocation, + required this.onClearSearch, + required this.onSeeAllResults, + required this.onSelectResult, + required this.iconForResult, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final label = activeCategory?.label ?? 'Results'; + + // Sort results by distance from user if position is available + final results = List.from(viewportResults); + final hasUserLocation = userLocation != null; + if (hasUserLocation) { + results.sort( + (a, b) => EsriMapSearchService.distanceMeters( + userLocation!.$1, + userLocation!.$2, + a.latitude, + a.longitude, + ).compareTo(EsriMapSearchService.distanceMeters(userLocation!.$1, userLocation!.$2, b.latitude, b.longitude)), + ); + } + + // Content-aware sizing calculation + final initialSize = 0.45; + final minSize = 0.15; + final maxSize = 0.90; + final snaps = [minSize, initialSize, maxSize]; + + return DraggableScrollableSheet( + controller: controller, + initialChildSize: initialSize, + minChildSize: minSize, + maxChildSize: maxSize, + snap: true, + snapSizes: snaps, + builder: (context, scrollController) { + final isResultsEmpty = results.isEmpty; + final headerTitle = isResultsEmpty ? '$label - None in view' : '$label - ${results.length} in view'; + final hasMoreTotalResults = allCategoryResults.length > results.length; + + return buildSlideOverContent( + context: context, + scrollController: scrollController, + headerTitle: headerTitle, + headerIcon: activeCategory?.icon ?? Icons.place, + onClose: onClearSearch, + onHeaderTap: () { + if (controller.isAttached) { + if (controller.size < 0.85) { + controller.animateTo(maxSize, duration: const Duration(milliseconds: 300), curve: Curves.easeOutCubic); + } else { + controller.animateTo( + initialSize, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOutCubic, + ); + } + } + }, + trailing: hasMoreTotalResults + ? TextButton.icon( + icon: ExcludeSemantics( + child: Icon(Icons.layers_outlined, size: 16, color: isDark ? Colors.white54 : Colors.grey[600]), + ), + label: Text( + 'See all ${allCategoryResults.length} results', + style: TextStyle(fontSize: 13, color: isDark ? Colors.white54 : Colors.grey[600]), + ), + style: TextButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + minimumSize: Size.zero, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + ), + onPressed: onSeeAllResults, + ) + : null, + sliverBody: isResultsEmpty + ? [ + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.location_off, size: 32, color: isDark ? Colors.grey[600] : Colors.grey[400]), + const SizedBox(height: 8), + Text( + 'No $label in current view.\nPan the map to see results.', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 16, color: isDark ? Colors.grey[500] : Colors.grey[600]), + ), + ], + ), + ), + ), + ] + : [ + SliverList( + delegate: SliverChildBuilderDelegate((context, index) { + final r = results[index]; + final dist = hasUserLocation + ? EsriMapSearchService.distanceMeters( + userLocation!.$1, + userLocation!.$2, + r.latitude, + r.longitude, + ) + : null; + final distFeet = dist != null ? dist * 3.28084 : null; + final distLabel = distFeet == null + ? null + : distFeet < 1000 + ? '${distFeet.round()} ft away' + : '${(distFeet / 5280).toStringAsFixed(1)} mi away'; + final isNotLastResult = index < results.length - 1; + return Column( + children: [ + ListTile( + splashColor: Colors.transparent, + leading: ExcludeSemantics( + child: Icon( + iconForResult(r), + size: 20, + color: isDark ? Colors.grey[400] : Colors.grey[600], + ), + ), + title: Text( + r.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 16), + ), + subtitle: distLabel != null + ? Text(distLabel, style: TextStyle(fontSize: 13, color: Colors.grey[500])) + : (r.subtitle.isNotEmpty + ? Text( + r.subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 13, color: Colors.grey[500]), + ) + : null), + dense: true, + onTap: () => onSelectResult(r), + ), + if (isNotLastResult) const Divider(height: 1), + ], + ); + }, childCount: results.length), + ), + ], + ); + }, + ); + } +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_detail_slide_over.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_detail_slide_over.dart new file mode 100644 index 0000000000..6a207821e9 --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_detail_slide_over.dart @@ -0,0 +1,618 @@ +import 'package:arcgis_maps/arcgis_maps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:campus_mobile_experimental/core/utils/esri_map_feature_flags.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +Widget buildSlideOverContent({ + required BuildContext context, + required ScrollController scrollController, + required String headerTitle, + IconData? headerIcon, + required VoidCallback onClose, + VoidCallback? onHeaderTap, + Widget? trailing, + required List sliverBody, + double headerHeight = 80.0, +}) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final bgColor = Theme.of(context).scaffoldBackgroundColor; + final hasHeaderIcon = headerIcon != null; + final hasTrailing = trailing != null; + + return Material( + elevation: 8, + color: bgColor, + borderRadius: const BorderRadius.vertical(top: Radius.circular(16)), + clipBehavior: Clip.antiAlias, + child: CustomScrollView( + controller: scrollController, + slivers: [ + SliverPersistentHeader( + pinned: true, + delegate: SlideOverHeaderDelegate( + height: headerHeight, + backgroundColor: bgColor, + child: InkWell( + onTap: onHeaderTap, + child: Column( + children: [ + Padding( + padding: const EdgeInsets.only(top: 10, bottom: 4), + child: Container( + width: 36, + height: 4, + decoration: BoxDecoration( + color: isDark ? Colors.grey[700] : Colors.grey[300], + borderRadius: BorderRadius.circular(2), + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(20, 6, 20, 8), + child: Row( + children: [ + if (hasHeaderIcon) ...[ + Icon(headerIcon, size: 18, color: isDark ? Colors.white70 : Colors.grey[700]), + const SizedBox(width: 8), + ], + Expanded( + child: Text( + headerTitle, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: isDark ? Colors.white : Colors.grey[900], + ), + ), + ), + if (hasTrailing) trailing, + Semantics( + button: true, + label: 'Close panel', + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: onClose, + customBorder: const CircleBorder(), + child: Container( + width: 34, + height: 34, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isDark ? Colors.grey[800] : Colors.grey[200], + ), + child: ExcludeSemantics( + child: Icon(Icons.close, size: 18, color: isDark ? Colors.white70 : Colors.grey[700]), + ), + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + const SliverToBoxAdapter(child: Divider(height: 1)), + ...sliverBody, + ], + ), + ); +} + +/// ============================================================================ +/// File: esrimap_detail_slide_over.dart +/// Description: Draggable slide-over sheet displaying building/POI details, +/// travel time, navigation buttons, and turn-by-turn directions. +/// ============================================================================ + +/// Persistent header delegate for pinned slide-over bottom sheet headers. +class SlideOverHeaderDelegate extends SliverPersistentHeaderDelegate { + /// Header widget content. + final Widget child; + + /// Fixed height of the persistent header. + final double height; + + /// Background color matching dark/light mode. + final Color backgroundColor; + + /// Constructs a [SlideOverHeaderDelegate] instance. + SlideOverHeaderDelegate({required this.child, required this.height, required this.backgroundColor}); + + @override + double get minExtent => height; + + @override + double get maxExtent => height; + + @override + Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { + final isTopPositioned = shrinkOffset == 0; + return Container( + height: height, + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: isTopPositioned ? const BorderRadius.vertical(top: Radius.circular(16)) : null, + ), + child: child, + ); + } + + @override + bool shouldRebuild(covariant SlideOverHeaderDelegate oldDelegate) => + child != oldDelegate.child || height != oldDelegate.height || backgroundColor != oldDelegate.backgroundColor; +} + +/// Helper function building a consistent DraggableScrollableSheet template with a pinned header. +Widget buildDetailSlideOverContent({ + required BuildContext context, + required String headerTitle, + IconData? headerIcon, + required VoidCallback onClose, + required VoidCallback onToggle, + VoidCallback? onShare, + required bool isMinimized, + Widget? trailing, + required List sliverBody, +}) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final bgColor = Theme.of(context).scaffoldBackgroundColor; + final hasHeaderIcon = headerIcon != null; + final hasTrailing = trailing != null; + + return Material( + color: bgColor, + borderRadius: const BorderRadius.vertical(top: Radius.circular(16)), + elevation: 16, + clipBehavior: Clip.antiAlias, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Header + GestureDetector( + onVerticalDragEnd: (details) { + var isSwipingDown = details.primaryVelocity != null && details.primaryVelocity! > 0; + var isSwipingUp = details.primaryVelocity != null && details.primaryVelocity! < 0; + if (isSwipingDown) { + if (!isMinimized) onToggle(); + } else if (isSwipingUp) { + if (isMinimized) onToggle(); + } + }, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 8, 8), + child: Row( + children: [ + Expanded( + child: InkWell( + onTap: onToggle, + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8), + child: Row( + children: [ + if (hasHeaderIcon) ...[ + ExcludeSemantics( + child: Icon(headerIcon, size: 18, color: isDark ? Colors.white70 : Colors.grey[700]), + ), + const SizedBox(width: 8), + ], + Expanded( + child: Text( + headerTitle, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: isDark ? Colors.white : Colors.grey[900], + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + ), + if (hasTrailing && !isMinimized) trailing, + if (onShare != null) ...[ + Material( + color: Colors.transparent, + child: InkWell( + customBorder: const CircleBorder(), + onTap: onShare, + child: Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: isDark ? Colors.grey[800] : Colors.grey[200], + shape: BoxShape.circle, + ), + child: Icon(Icons.share, size: 16, color: isDark ? Colors.white70 : Colors.grey[800]), + ), + ), + ), + const SizedBox(width: 12), + ], + Material( + color: Colors.transparent, + child: InkWell( + customBorder: const CircleBorder(), + onTap: onToggle, + child: Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: isDark ? Colors.grey[800] : Colors.grey[200], + shape: BoxShape.circle, + ), + child: Icon( + isMinimized ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down, + size: 20, + color: isDark ? Colors.white70 : Colors.grey[800], + ), + ), + ), + ), + const SizedBox(width: 12), + Material( + color: Colors.transparent, + child: InkWell( + customBorder: const CircleBorder(), + onTap: onClose, + child: Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: isDark ? Colors.grey[800] : Colors.grey[200], + shape: BoxShape.circle, + ), + child: Icon(Icons.close, size: 18, color: isDark ? Colors.white70 : Colors.grey[800]), + ), + ), + ), + ], + ), + ), + ), + if (!isMinimized) const Divider(height: 1), + if (!isMinimized) Flexible(child: CustomScrollView(shrinkWrap: true, slivers: sliverBody)), + ], + ), + ); +} + +class EsriMapDetailSlideOver extends StatelessWidget { + final ValueNotifier minimizedNotifier; + final double availableHeight; + final MapSearchResult result; + final IconData resultIcon; + final bool isRoutingMode; + final bool hasRoute; + final bool routeFailed; + final String travelMode; + final double routeTravelTimeMinutes; + final List routeManeuvers; + final (double, double)? fromLatLng; + final void Function(MapSearchResult result) onGetDirections; + final void Function(String mode) onTravelModeChanged; + final void Function(String url) onLaunchWebsite; + final VoidCallback onClose; + final VoidCallback onClearRoute; + + const EsriMapDetailSlideOver({ + Key? key, + required this.minimizedNotifier, + required this.availableHeight, + required this.result, + required this.resultIcon, + required this.isRoutingMode, + required this.hasRoute, + required this.routeFailed, + required this.travelMode, + required this.routeTravelTimeMinutes, + required this.routeManeuvers, + required this.fromLatLng, + required this.onGetDirections, + required this.onTravelModeChanged, + required this.onLaunchWebsite, + required this.onClose, + required this.onClearRoute, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final isRouting = isRoutingMode || hasRoute || routeFailed; + final isBuilding = result.source == MapSearchSource.building; + + String detailText = isBuilding ? result.address : result.description; + + if (!isBuilding) { + detailText = detailText.replaceAll(RegExp(r'https?://[^\s]+'), ''); + detailText = detailText.replaceAllMapped(RegExp(r'\.([A-Za-z])'), (m) => '. ${m.group(1)}'); + detailText = detailText.trim(); + } + + final categoryLabel = isBuilding ? 'Building' : result.subtitle; + + // Constrain height to a maximum of 50% of screen height + final maxHeight = availableHeight * 0.50; + + void handleShare() { + final googleMapsUrl = 'https://www.google.com/maps/search/?api=1&query=${result.latitude},${result.longitude}'; + Clipboard.setData(ClipboardData(text: googleMapsUrl)); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Link copied to clipboard!'), duration: Duration(seconds: 2))); + } + + return Align( + alignment: Alignment.bottomCenter, + child: ValueListenableBuilder( + valueListenable: minimizedNotifier, + builder: (context, isMinimized, child) { + final shouldShowDetailText = !isRouting && detailText.isNotEmpty; + final websiteUrl = result.websiteUrl?.trim(); + final hasWebsiteUrl = websiteUrl?.isNotEmpty == true; + final websiteHost = hasWebsiteUrl ? Uri.tryParse(websiteUrl!)?.host.replaceFirst('www.', '') : null; + + return ConstrainedBox( + constraints: BoxConstraints(maxHeight: maxHeight), + child: buildDetailSlideOverContent( + context: context, + headerTitle: isRouting ? 'Directions to ${result.name}' : result.name, + headerIcon: resultIcon, + onClose: isRouting ? onClearRoute : onClose, + onToggle: () => minimizedNotifier.value = !isMinimized, + onShare: handleShare, + isMinimized: isMinimized, + trailing: isRouting && !routeFailed + ? Padding( + padding: const EdgeInsets.only(right: 8), + child: TextButton.icon( + onPressed: () { + final originParam = fromLatLng != null ? '&origin=${fromLatLng!.$1},${fromLatLng!.$2}' : ''; + onLaunchWebsite( + 'https://www.google.com/maps/dir/?api=1' + '&destination=${result.latitude},${result.longitude}' + '&travelmode=walking&dirflg=w' + '$originParam', + ); + }, + icon: const Icon(Icons.map_outlined, size: 16), + label: const Text('Open Google Maps', style: TextStyle(fontSize: 12)), + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + minimumSize: Size.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + foregroundColor: isDark ? const Color(0xFFFFCD00) : Theme.of(context).primaryColor, + ), + ), + ) + : null, + sliverBody: [ + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(20, 16, 20, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isRouting) + Text( + categoryLabel, + style: TextStyle( + fontSize: 17, + fontWeight: FontWeight.w600, + color: isDark ? Colors.white : Colors.black87, + ), + ), + if (shouldShowDetailText) ...[ + const SizedBox(height: 10), + Semantics( + label: isBuilding ? 'Building Address: $detailText' : null, + child: Text( + detailText, + style: TextStyle( + fontSize: 15, + height: 1.4, + color: isDark ? Colors.grey[300] : Colors.grey[700], + ), + ), + ), + ], + if (!isRouting) const SizedBox(height: 20), + + if (routeFailed) ...[ + Text( + 'You are too far from campus for walking navigation.', + style: TextStyle(fontSize: 16, color: isDark ? Colors.grey[400] : Colors.grey[600]), + ), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: () { + final originParam = fromLatLng != null + ? '&origin=${fromLatLng!.$1},${fromLatLng!.$2}' + : ''; + onLaunchWebsite( + 'https://www.google.com/maps/dir/?api=1' + '&destination=${result.latitude},${result.longitude}' + '&travelmode=driving&dirflg=d' + '$originParam', + ); + }, + icon: const Icon(Icons.directions_car, size: 18), + label: const Text('Drive With Google Maps'), + style: OutlinedButton.styleFrom( + foregroundColor: isDark ? const Color(0xFFFFCD00) : Theme.of(context).primaryColor, + side: BorderSide( + color: isDark ? const Color(0xFFFFCD00) : Theme.of(context).primaryColor, + ), + padding: const EdgeInsets.symmetric(vertical: 12), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ), + ] else if (hasRoute) ...[ + Row( + children: [ + ExcludeSemantics( + child: Icon( + Icons.schedule, + size: 18, + color: isDark ? Colors.grey[400] : Colors.grey[600], + ), + ), + const SizedBox(width: 6), + Text( + routeTravelTimeMinutes < 1 ? '< 1 min' : '${routeTravelTimeMinutes.ceil()} min', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: isDark ? Colors.white : Colors.grey[900], + ), + ), + const SizedBox(width: 12), + Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6), + decoration: BoxDecoration( + color: isDark ? Colors.white : Colors.grey[900], + borderRadius: BorderRadius.circular(16), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + ExcludeSemantics( + child: Icon( + Icons.directions_walk, + size: 16, + color: isDark ? Colors.grey[900] : Colors.white, + ), + ), + const SizedBox(width: 6), + Text( + 'Walking', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w500, + color: isDark ? Colors.grey[900] : Colors.white, + ), + ), + ], + ), + ), + ], + ), + ] else + Row( + children: [ + if (hasWebsiteUrl) ...[ + Expanded( + child: OutlinedButton.icon( + onPressed: () => onLaunchWebsite(websiteUrl!), + icon: const Icon(Icons.language, size: 18), + label: websiteHost?.isNotEmpty == true + ? Text.rich( + TextSpan( + children: [ + const TextSpan(text: 'Visit Website\n'), + TextSpan(text: websiteHost, style: const TextStyle(fontSize: 11)), + ], + ), + textAlign: TextAlign.center, + ) + : const Text('View website'), + style: OutlinedButton.styleFrom( + foregroundColor: isDark ? const Color(0xFFFFCD00) : null, + side: isDark ? const BorderSide(color: Color(0xFFFFCD00)) : null, + padding: const EdgeInsets.symmetric(vertical: 12), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ), + const SizedBox(width: 12), + ], + if (FeatureFlags.MAP_ROUTING_ENABLED) + Expanded( + child: FilledButton.icon( + onPressed: isRoutingMode ? null : () => onGetDirections(result), + icon: isRoutingMode + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + semanticsLabel: 'Calculating route', + ), + ) + : const Icon(Icons.directions, size: 18), + label: Text(isRoutingMode ? 'Calculating...' : 'Get Directions'), + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 12), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ), + ], + ), + ], + ), + ), + ), + if (routeManeuvers.isNotEmpty) + SliverList( + delegate: SliverChildBuilderDelegate((context, index) { + final step = routeManeuvers[index]; + final distMeters = step.length; + final distLabel = distMeters < 1000 + ? '${distMeters.round()} m' + : '${(distMeters / 1000).toStringAsFixed(1)} km'; + final isNotLastManeuver = index < routeManeuvers.length - 1; + final isFirstIndex = index == 0; + + String directionText = step.directionText; + directionText = directionText.replaceAll('Location 1', 'My Location'); + directionText = directionText.replaceAll('Location 2', result.name); + + return Column( + children: [ + if (isFirstIndex) const Divider(height: 1), + ListTile( + leading: ExcludeSemantics( + child: Icon( + Icons.subdirectory_arrow_right, + size: 20, + color: isDark ? Colors.grey[400] : Colors.grey[600], + ), + ), + title: Text(directionText, style: const TextStyle(fontSize: 14)), + trailing: distMeters > 0 + ? Text( + distLabel, + style: TextStyle(fontSize: 13, color: isDark ? Colors.grey[500] : Colors.grey[500]), + ) + : null, + dense: true, + ), + if (isNotLastManeuver) const Divider(height: 1, indent: 56), + ], + ); + }, childCount: routeManeuvers.length), + ), + const SliverToBoxAdapter(child: SizedBox(height: 16)), + ], + ), + ); + }, + ), + ); + } +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_fab.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_fab.dart new file mode 100644 index 0000000000..dcc962359e --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_fab.dart @@ -0,0 +1,428 @@ +/// ============================================================================ +/// File: esrimap_fab.dart +/// Description: Floating Action Button (FAB) cluster widget containing the +/// compass needle, recenter on user/view, and layers toggle buttons. +/// ============================================================================ + +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; + +/// Floating action button cluster widget rendered in top-right of map view. +class EsriMapFabCluster extends StatelessWidget { + /// Whether dark theme mode is active. + final bool isDark; + + /// Whether a 3D scene mode is active. + final bool is3D; + + /// Map rotation heading in degrees. + final double mapRotation; + + /// Whether location tracking button is active. + final bool isLocationActive; + + /// Whether recenter button is active. + final bool isRecenterActive; + + /// Callback when layers panel button is pressed. + final VoidCallback onShowLayersPanel; + + /// Callback when recenter on view button is pressed. + final VoidCallback onRecenterOnView; + + /// Callback when recenter on user location button is pressed. + final VoidCallback onRecenterOnUser; + + /// Callback when compass snap-to-north button is pressed. + final VoidCallback onSnapToNorth; + + /// Callback when zoom in button is pressed. + final VoidCallback? onZoomIn; + + /// Callback when zoom out button is pressed. + final VoidCallback? onZoomOut; + + /// Constructs an [EsriMapFabCluster] instance. + const EsriMapFabCluster({ + Key? key, + required this.isDark, + this.is3D = false, + required this.mapRotation, + this.isLocationActive = false, + this.isRecenterActive = false, + required this.onShowLayersPanel, + required this.onRecenterOnView, + required this.onRecenterOnUser, + required this.onSnapToNorth, + this.onZoomIn, + this.onZoomOut, + }) : super(key: key); + + /// Active state highlight color. + static const Color ACTIVE_COLOR = Color(0xFFC69214); + + /// Fixed button diameter size. + static const double SIZE = 48.0; + + /// Height for individual pill button segments. + static const double BTN_HEIGHT = 44.0; + + @override + Widget build(BuildContext context) { + final bgColor = Theme.of(context).scaffoldBackgroundColor; + final fgColor = isDark ? Colors.white : Colors.grey[800]!; + + final recenterColor = isRecenterActive ? ACTIVE_COLOR : fgColor; + + final isAccessibleNav = MediaQuery.of(context).accessibleNavigation; + final hasZoomCallbacks = onZoomIn != null && onZoomOut != null; + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Compass needle button + if (mapRotation.abs() > 0.01) ...[ + Material( + elevation: 4, + color: bgColor, + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + child: Semantics( + button: true, + label: 'Snap to true north', + child: GestureDetector( + onTap: onSnapToNorth, + behavior: HitTestBehavior.opaque, + child: SizedBox( + width: SIZE, + height: SIZE, + child: Center( + child: ExcludeSemantics( + child: CustomPaint( + size: const Size(24, 24), + painter: _CompassNeedlePainter( + rotationDegrees: mapRotation, + southColor: fgColor.withValues(alpha: 0.35), + ), + ), + ), + ), + ), + ), + ), + ), + const SizedBox(height: 10), + ], + + // Center Map (Center on Campus) + _circleButton( + svgAsset: 'assets/esri_map_assets/Center-Trident.svg', + semanticsLabel: 'Center on campus', + color: recenterColor, + bgColor: bgColor, + onTap: onRecenterOnView, + ), + const SizedBox(height: 10), + + // Zoom Accessibility Buttons (Only shown when VoiceOver/TalkBack is active) + if (isAccessibleNav && hasZoomCallbacks) ...[ + _circleButton(icon: Icons.add, semanticsLabel: 'Zoom in', color: fgColor, bgColor: bgColor, onTap: onZoomIn!), + const SizedBox(height: 10), + _circleButton( + icon: Icons.remove, + semanticsLabel: 'Zoom out', + color: fgColor, + bgColor: bgColor, + onTap: onZoomOut!, + ), + const SizedBox(height: 10), + ], + + // Map displays (Layers) + _circleButton( + customIcon: CustomPaint( + size: const Size(20, 20), + painter: _MapDisplaysIconPainter(color: fgColor), + ), + semanticsLabel: 'Map layers and displays', + color: fgColor, + bgColor: bgColor, + onTap: onShowLayersPanel, + ), + ], + ); + } + + Widget _circleButton({ + IconData? icon, + String? svgAsset, + Widget? customIcon, + String? semanticsLabel, + required Color color, + required Color bgColor, + required VoidCallback onTap, + }) { + Widget iconWidget; + if (customIcon != null) { + iconWidget = customIcon; + } else if (svgAsset != null) { + iconWidget = SvgPicture.asset( + svgAsset, + width: 22, + height: 22, + colorFilter: ColorFilter.mode(color, BlendMode.srcIn), + ); + } else { + iconWidget = Icon(icon, size: 22, color: color); + } + + Widget accessibleIcon = ExcludeSemantics(child: iconWidget); + if (semanticsLabel != null) accessibleIcon = Semantics(label: semanticsLabel, child: accessibleIcon); + + return Material( + elevation: 4, + color: bgColor, + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onTap, + child: SizedBox( + width: SIZE, + height: SIZE, + child: Center(child: accessibleIcon), + ), + ), + ); + } +} + +class _MapDisplaysIconPainter extends CustomPainter { + final Color color; + _MapDisplaysIconPainter({required this.color}); + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 2.0 + ..strokeJoin = StrokeJoin.miter + ..strokeCap = StrokeCap.square; + + final double w = size.width; + final double h = size.height; + + final path = Path(); + + // Top Diamond + // Stop the diamond much earlier to leave a clear gap for the + sign + path.moveTo(w * 0.40, h * 0.20); // Start at top, slightly left + path.lineTo(w * 0.15, h * 0.40); // Down-left to left point + path.lineTo(w * 0.50, h * 0.65); // Down-right to bottom point + path.lineTo(w * 0.70, h * 0.50); // Up-right, stopping early + + // Bottom Diamond (V shape) + path.moveTo(w * 0.15, h * 0.60); // Left start + path.lineTo(w * 0.50, h * 0.85); // Bottom point + path.lineTo(w * 0.85, h * 0.60); // Right end + + canvas.drawPath(path, paint); + + // Plus sign + // Positioned solidly in the top right + final cx = w * 0.80; + final cy = h * 0.20; + final r = w * 0.14; + + final plusPaint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 2.0 + ..strokeCap = StrokeCap.square; + + canvas.drawLine(Offset(cx - r, cy), Offset(cx + r, cy), plusPaint); + canvas.drawLine(Offset(cx, cy - r), Offset(cx, cy + r), plusPaint); + } + + @override + bool shouldRepaint(covariant _MapDisplaysIconPainter oldDelegate) => oldDelegate.color != color; +} + +/// Floating action button for "Center on Me" rendered in bottom-right of map view. +class EsriMapLocationFab extends StatelessWidget { + final bool isDark; + final bool isLocationActive; + final bool isUserVisible; + final bool isLoading; + final double? bearingToUser; + final double mapRotation; + final VoidCallback onRecenterOnUser; + + const EsriMapLocationFab({ + Key? key, + required this.isDark, + this.isLocationActive = false, + this.isUserVisible = false, + this.isLoading = false, + this.bearingToUser, + this.mapRotation = 0.0, + required this.onRecenterOnUser, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final bgColor = Theme.of(context).scaffoldBackgroundColor; + final fgColor = isDark ? Colors.white : Colors.grey[800]!; + + final activeBgColor = isDark ? Colors.blue[900]!.withValues(alpha: 0.5) : const Color(0xFFE8F0FE); + + Widget iconWidget; + if (isLoading) { + iconWidget = SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator( + strokeWidth: 2.5, + valueColor: AlwaysStoppedAnimation(Colors.blue[600]!), + ), + ); + } else if (isLocationActive || isUserVisible || bearingToUser != null) { + double totalRotation = 0; + if (!isLocationActive && bearingToUser != null) totalRotation = bearingToUser!; + + iconWidget = Stack( + alignment: Alignment.center, + children: [ + // Light blue halo + Container( + width: 30, + height: 30, + decoration: BoxDecoration(shape: BoxShape.circle, color: activeBgColor), + ), + // Directional Triangle (only if inactive and user is not visible) + if (!isLocationActive && !isUserVisible && bearingToUser != null) + Transform.rotate( + angle: totalRotation.isNaN ? 0.0 : totalRotation, + child: Container( + width: 30, + height: 30, + alignment: Alignment.topCenter, + child: Padding( + padding: const EdgeInsets.only(top: 2.0), + child: CustomPaint( + size: const Size(10, 8), + painter: _DirectionArrowPainter(color: Colors.blue[600]!), + ), + ), + ), + ), + // The blue dot + Container( + width: 16, + height: 16, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.blue[600], + border: Border.all(color: Colors.white, width: 2.5), + boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.2), blurRadius: 2)], + ), + ), + ], + ); + } else { + iconWidget = Icon(Icons.explore_outlined, size: 26, color: fgColor); + } + + String semanticsLabel; + if (isLoading) { + semanticsLabel = 'Center on my location, acquiring GPS signal'; + } else if (isLocationActive) { + semanticsLabel = 'Tracking your location'; + } else { + semanticsLabel = 'Center on my location'; + } + + return Material( + elevation: 4, + color: bgColor, + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + child: Semantics( + button: true, + label: semanticsLabel, + child: InkWell( + onTap: onRecenterOnUser, + child: SizedBox( + width: EsriMapFabCluster.SIZE, + height: EsriMapFabCluster.SIZE, + child: Center(child: ExcludeSemantics(child: iconWidget)), + ), + ), + ), + ); + } +} + +class _DirectionArrowPainter extends CustomPainter { + final Color color; + _DirectionArrowPainter({required this.color}); + + @override + void paint(Canvas canvas, Size size) { + final path = Path() + ..moveTo(size.width / 2, 0) + ..lineTo(size.width, size.height) + ..lineTo(0, size.height) + ..close(); + canvas.drawPath(path, Paint()..color = color); + } + + @override + bool shouldRepaint(covariant _DirectionArrowPainter oldDelegate) => oldDelegate.color != color; +} + +class _CompassNeedlePainter extends CustomPainter { + final double rotationDegrees; + final Color southColor; + + const _CompassNeedlePainter({required this.rotationDegrees, required this.southColor}); + + @override + void paint(Canvas canvas, Size size) { + final cx = size.width / 2; + final cy = size.height / 2; + final tipDist = size.height * 0.46; + final halfWidth = size.width * 0.18; + + canvas.save(); + canvas.translate(cx, cy); + canvas.rotate(-rotationDegrees * math.pi / 180); + + final northPath = Path() + ..moveTo(0, -tipDist) + ..lineTo(halfWidth, 0) + ..lineTo(-halfWidth, 0) + ..close(); + + final southPath = Path() + ..moveTo(0, tipDist) + ..lineTo(halfWidth, 0) + ..lineTo(-halfWidth, 0) + ..close(); + + canvas.drawPath(northPath, Paint()..color = Colors.red); + canvas.drawPath(southPath, Paint()..color = southColor); + + canvas.restore(); + } + + @override + bool shouldRepaint(_CompassNeedlePainter old) { + final isRotationChanged = old.rotationDegrees != rotationDegrees; + final isColorChanged = old.southColor != southColor; + return isRotationChanged || isColorChanged; + } +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_layers_panel.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_layers_panel.dart new file mode 100644 index 0000000000..d5d56a30f7 --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_layers_panel.dart @@ -0,0 +1,336 @@ +/// ============================================================================ +/// File: esrimap_layers_panel.dart +/// Description: Floating panel widget allowing users to select basemaps (Default, +/// Light, Dark, Satellite), toggle operational layers, and switch 3D scenes. +/// ============================================================================ + +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_basemaps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_config.dart'; +import 'package:campus_mobile_experimental/core/utils/esri_map_feature_flags.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; + +/// Bottom sheet widget rendering basemap choices, layer toggles, and 3D scene mode chips. +class EsriMapLayersPanel extends StatelessWidget { + /// Map configuration containing basemap specs and layer definitions. + final EsriMapConfig config; + + /// Currently selected basemap type. + final BasemapType currentBasemapType; + + /// Currently selected scene mode key ('default', 'building3d', 'droneView'). + final String currentSceneKey; + + /// Visibility status map keyed by operational layer key. + final Map layerVisible; + + /// Loading status map keyed by operational layer key. + final Map layerLoading; + + /// Callback when a basemap option is selected. + final void Function(BasemapType type) onSwitchBasemap; + + /// Callback when a 3D scene mode chip is selected. + final void Function(String key) onSetSceneMode; + + /// Callback when an operational layer toggle is pressed. + final void Function(String key) onToggleLayer; + + /// Callback when panel close button is pressed. + final VoidCallback onClose; + + /// Whether to hide the 3D scene switcher section. + final bool hideSceneSwitcher; + + /// Constructs an [EsriMapLayersPanel] instance. + const EsriMapLayersPanel({ + Key? key, + required this.config, + required this.currentBasemapType, + required this.currentSceneKey, + required this.layerVisible, + required this.layerLoading, + required this.onSwitchBasemap, + required this.onSetSceneMode, + required this.onToggleLayer, + required this.onClose, + this.hideSceneSwitcher = false, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final bgColor = Theme.of(context).scaffoldBackgroundColor; + final textColor = isDark ? Colors.white : Colors.grey[900]!; + final subtitleColor = isDark ? Colors.grey[400]! : Colors.grey[600]!; + final accent = isDark ? const Color(0xFFFFCD00) : Colors.lightBlue[300]!; + + Widget sectionLabel(String text) => Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 8), + child: Text( + text, + style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: textColor), + ), + ); + + Widget imageTile({ + required String label, + required bool selected, + required VoidCallback onTap, + Widget? imageWidget, + bool loading = false, + }) { + return Semantics( + button: true, + selected: selected, + label: loading ? '$label, loading' : label, + child: ExcludeSemantics( + child: GestureDetector( + onTap: onTap, + child: SizedBox( + width: 86, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 68, + height: 68, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + border: selected + ? Border.all(color: accent, width: 2.5) + : Border.all(color: isDark ? Colors.grey[700]! : Colors.grey[300]!, width: 1), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(8.5), + child: loading + ? const Center( + child: SizedBox(width: 26, height: 26, child: CircularProgressIndicator(strokeWidth: 2)), + ) + : (imageWidget ?? Container(color: isDark ? Colors.grey[700] : Colors.grey[300])), + ), + ), + const SizedBox(height: 6), + Text( + label, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + fontWeight: selected ? FontWeight.w700 : FontWeight.w400, + color: selected ? accent : textColor, + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget networkImage(String url) => Image.network( + url, + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => Container(color: isDark ? Colors.grey[700] : Colors.grey[300]), + ); + + Widget sceneChip(String key, String label, bool selected) => Semantics( + button: true, + selected: selected, + label: label, + child: ExcludeSemantics( + child: GestureDetector( + onTap: () => onSetSceneMode(key), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + border: selected + ? Border.all(color: accent, width: 2) + : Border.all(color: isDark ? Colors.grey[700]! : Colors.grey[300]!, width: 1), + color: selected ? accent.withValues(alpha: 0.12) : (isDark ? Colors.grey[850] : Colors.grey[100]), + ), + child: Text( + label, + style: TextStyle( + fontSize: 13, + fontWeight: selected ? FontWeight.w700 : FontWeight.w400, + color: selected ? accent : textColor, + ), + ), + ), + ), + ), + ); + + final bottomPad = MediaQuery.of(context).padding.bottom; + final isDefault = currentSceneKey == 'default'; + // Hide SCENES entirely from the UI. SET to TRUE when ready to show drone view and 3D view to the user. + final showSceneSwitcher = FeatureFlags.MAP_SCENES_ENABLED && config.features.scenes && !hideSceneSwitcher; + + return Positioned( + left: 12, + right: 12, + bottom: bottomPad + 12, + child: Semantics( + sortKey: const OrdinalSortKey(1.8), + child: GestureDetector( + onVerticalDragEnd: (details) { + final isSwipeDown = details.velocity.pixelsPerSecond.dy > 200; + if (isSwipeDown) onClose(); + }, + child: Material( + elevation: 10, + color: bgColor, + borderRadius: BorderRadius.circular(16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Basemap + Layers — grayed out when not in default 2D scene + Opacity( + opacity: isDefault ? 1.0 : 0.35, + child: IgnorePointer( + ignoring: !isDefault, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Map Type Header (with Close Button) + Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 8), + child: Row( + children: [ + Expanded( + child: Text( + 'Map Type', + style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: textColor), + ), + ), + Material( + color: Colors.transparent, + child: InkWell( + customBorder: const CircleBorder(), + onTap: onClose, + child: Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: Theme.of(context).brightness == Brightness.dark + ? Colors.grey[800] + : Colors.grey[200], + shape: BoxShape.circle, + ), + child: Icon(Icons.close, size: 18, color: subtitleColor), + ), + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final entry in config.basemaps.entries.where((e) { + final t = basemapTypeFromKey(e.key); + var tIsNull = t == null; + if (tIsNull) return false; + var isAlt = FeatureFlags.MAP_ALTERNATE_BASEMAPS_ENABLED; + if (isAlt) return true; + var notLight = t != BasemapType.light; + var notDark = t != BasemapType.dark; + return notLight && notDark; + })) ...[ + imageTile( + label: entry.value.label, + selected: currentBasemapType == basemapTypeFromKey(entry.key), + onTap: () { + final t = basemapTypeFromKey(entry.key); + final isTypeNotNull = t != null; + if (isTypeNotNull) onSwitchBasemap(t); + }, + imageWidget: networkImage(entry.value.thumbnailAsset), + ), + const SizedBox(width: 8), + ], + ], + ), + ), + ), + + if (FeatureFlags.MAP_OPERATIONAL_LAYERS_ENABLED) ...[ + const Divider(height: 24, indent: 16, endIndent: 16), + + sectionLabel('Map Details'), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final entry in config.layers.entries.where((e) { + var key = e.key; + var isTransit = key == 'tritonTransit'; + if (isTransit) return FeatureFlags.TRANSIT_OPERATIONAL_LAYER_ENABLED; + var isDist = key == 'campusDistricts'; + if (isDist) return FeatureFlags.DISTRICTS_OPERATIONAL_LAYER_ENABLED; + var isConst = key == 'construction'; + if (isConst) return FeatureFlags.CONSTRUCTION_OPERATIONAL_LAYER_ENABLED; + return true; + })) ...[ + imageTile( + label: entry.value.label, + selected: layerVisible[entry.key] ?? false, + loading: layerLoading[entry.key] ?? false, + onTap: () => onToggleLayer(entry.key), + imageWidget: networkImage(entry.value.thumbnailAsset), + ), + const SizedBox(width: 8), + ], + ], + ), + ), + ), + ], + ], + ), + ), + ), + + // Scene chips — gated by features flag, hidden when slide-over is active + if (showSceneSwitcher) ...[ + const Divider(height: 24, indent: 16, endIndent: 16), + sectionLabel('Scene'), + Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 20), + child: Wrap( + spacing: 8, + children: [ + for (final entry in config.scenes.entries.where((e) { + var key = e.key; + var isDef = key == 'default'; + if (isDef) return FeatureFlags.DEFAULT_SCENE_ENABLED; + var is3d = key == 'building3d'; + if (is3d) return FeatureFlags.THREE_DIMENSIONAL_SCENE_ENABLED; + var isDrone = key == 'droneView'; + if (isDrone) return FeatureFlags.DRONE_VIEW_SCENE_ENABLED; + return true; + })) + sceneChip(entry.key, entry.value.label, currentSceneKey == entry.key), + ], + ), + ), + ] else + const SizedBox(height: 20), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_scale_bar.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_scale_bar.dart new file mode 100644 index 0000000000..c76f634a70 --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_scale_bar.dart @@ -0,0 +1,296 @@ +/// ============================================================================ +/// File: esrimap_scale_bar.dart +/// Description: Google Maps-style dynamic scale indicator widget displaying +/// dual Imperial and Metric distance scale brackets based on current +/// map zoom scale, with automatic fade-in on zoom and fade-out on stop. +/// ============================================================================ + +import 'dart:async'; + +import 'package:flutter/material.dart'; + +/// Dynamic scale bar widget modeled after Google Maps' scale indicator. +/// Appears when zooming in/out and automatically fades out when zooming stops. +class EsriMapScaleBar extends StatefulWidget { + /// Current map scale denominator (e.g. 24000 for 1:24,000 scale). + final double scale; + + /// Whether dark mode is active. + final bool isDark; + + /// Whether the scale bar automatically fades in on scale change and fades out when stopped. + final bool autoFade; + + /// Inactivity delay before fading out after zooming ceases. + final Duration fadeDelay; + + const EsriMapScaleBar({ + Key? key, + required this.scale, + this.isDark = false, + this.autoFade = true, + this.fadeDelay = const Duration(milliseconds: 1080), + }) : super(key: key); + + @override + State createState() => _EsriMapScaleBarState(); +} + +class _EsriMapScaleBarState extends State { + bool _isVisible = false; + Timer? _fadeTimer; + double _lastScale = 0.0; + + /// Standard round imperial distances in feet. + static const List _IMPERIAL_DISTANCES = [ + 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, + 5280, // 1 mi + 10560, // 2 mi + 26400, // 5 mi + 52800, // 10 mi + 105600, // 20 mi + 264000, // 50 mi + ]; + + /// Standard round metric distances in meters. + static const List _METRIC_DISTANCES = [ + 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, + 1000, // 1 km + 2000, // 2 km + 5000, // 5 km + 10000, // 10 km + 20000, // 20 km + 50000, // 50 km + 100000, // 100 km + ]; + + @override + void initState() { + super.initState(); + _lastScale = widget.scale; + if (!widget.autoFade) _isVisible = true; + } + + @override + void didUpdateWidget(covariant EsriMapScaleBar oldWidget) { + super.didUpdateWidget(oldWidget); + // Detect zoom/scale changes + var hasSignificantScaleChange = widget.scale > 0 && (widget.scale - _lastScale).abs() > 0.05; + if (hasSignificantScaleChange) { + _lastScale = widget.scale; + if (widget.autoFade) _triggerZoomFade(); + } + } + + void _triggerZoomFade() { + _fadeTimer?.cancel(); + if (!_isVisible) { + setState(() { + _isVisible = true; + }); + } + _fadeTimer = Timer(widget.fadeDelay, () { + if (mounted) { + setState(() { + _isVisible = false; + }); + } + }); + } + + @override + void dispose() { + _fadeTimer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (widget.scale <= 0) return const SizedBox.shrink(); + + // 1 logical pixel in meters at standard 96 DPI: (scale * 0.0254 / 96.0) + final metersPerPx = (widget.scale * 0.0254) / 96.0; + if (metersPerPx <= 0) return const SizedBox.shrink(); + + // Calculate imperial label for semantics + double chosenImperialFt = _IMPERIAL_DISTANCES.first; + double chosenWidthPx = 60.0; + for (final ft in _IMPERIAL_DISTANCES) { + final meters = ft * 0.3048; + final px = meters / metersPerPx; + if (px >= 40 && px <= 100) { + chosenImperialFt = ft; + chosenWidthPx = px; + break; + } + if (px > 100) { + chosenImperialFt = ft; + chosenWidthPx = px.clamp(40.0, 100.0); + break; + } + } + final String imperialLabel = chosenImperialFt >= 5280 + ? '${(chosenImperialFt / 5280).toStringAsFixed(chosenImperialFt % 5280 == 0 ? 0 : 1)} miles' + : '${chosenImperialFt.toInt()} feet'; + + final barMeters = chosenWidthPx * metersPerPx; + double chosenMetricMeters = _METRIC_DISTANCES.first; + for (final m in _METRIC_DISTANCES) { + if (m <= barMeters * 1.3) { + chosenMetricMeters = m; + } else { + break; + } + } + final String metricLabel = chosenMetricMeters >= 1000 + ? '${(chosenMetricMeters / 1000).toStringAsFixed(chosenMetricMeters % 1000 == 0 ? 0 : 1)} kilometers' + : (chosenMetricMeters < 1 + ? '${(chosenMetricMeters * 100).round()} centimeters' + : '${chosenMetricMeters % 1 == 0 ? chosenMetricMeters.toInt() : chosenMetricMeters.toStringAsFixed(1)} meters'); + + return Semantics( + label: 'Map scale is $imperialLabel or $metricLabel', + hidden: !_isVisible, + child: ExcludeSemantics( + child: AnimatedOpacity( + opacity: _isVisible ? 1.0 : 0.0, + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + child: _buildScaleContent(context), + ), + ), + ); + } + + Widget _buildScaleContent(BuildContext context) { + // 1 logical pixel in meters at standard 96 DPI: (scale * 0.0254 / 96.0) + final metersPerPx = (widget.scale * 0.0254) / 96.0; + if (metersPerPx <= 0) return const SizedBox.shrink(); + + // Target scale bar width between 40 and 100 logical pixels + double chosenImperialFt = _IMPERIAL_DISTANCES.first; + double chosenWidthPx = 60.0; + + for (final ft in _IMPERIAL_DISTANCES) { + final meters = ft * 0.3048; + final px = meters / metersPerPx; + if (px >= 40 && px <= 100) { + chosenImperialFt = ft; + chosenWidthPx = px; + break; + } + if (px > 100) { + chosenImperialFt = ft; + chosenWidthPx = px.clamp(40.0, 100.0); + break; + } + } + + // Format imperial label (e.g. "20 ft", "500 ft", "1 mi") + final String imperialLabel = chosenImperialFt >= 5280 + ? '${(chosenImperialFt / 5280).toStringAsFixed(chosenImperialFt % 5280 == 0 ? 0 : 1)} mi' + : '${chosenImperialFt.toInt()} ft'; + + // Find matching metric distance for the chosen width + final barMeters = chosenWidthPx * metersPerPx; + double chosenMetricMeters = _METRIC_DISTANCES.first; + for (final m in _METRIC_DISTANCES) { + if (m <= barMeters * 1.3) { + chosenMetricMeters = m; + } else { + break; + } + } + + // Format metric label (e.g. "5 m", "200 m", "1 km") + final String metricLabel = chosenMetricMeters >= 1000 + ? '${(chosenMetricMeters / 1000).toStringAsFixed(chosenMetricMeters % 1000 == 0 ? 0 : 1)} km' + : (chosenMetricMeters < 1 + ? '${(chosenMetricMeters * 100).round()} cm' + : '${chosenMetricMeters % 1 == 0 ? chosenMetricMeters.toInt() : chosenMetricMeters.toStringAsFixed(1)} m'); + + final textColor = widget.isDark ? Colors.white70 : const Color(0xFF3C4043); + final lineColor = widget.isDark ? Colors.white70 : const Color(0xFF5F6368); + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + decoration: BoxDecoration( + color: (widget.isDark ? Colors.black54 : Colors.white70).withOpacity(0.65), + borderRadius: BorderRadius.circular(4), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + // Imperial distance (Top) + Text( + imperialLabel, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: textColor, + letterSpacing: -0.2, + height: 1.1, + ), + ), + const SizedBox(height: 1), + + // Scale bracket bar: |___________| + SizedBox( + width: chosenWidthPx, + height: 6, + child: CustomPaint(painter: _ScaleBarBracketPainter(color: lineColor)), + ), + const SizedBox(height: 1), + + // Metric distance (Bottom) + Text( + metricLabel, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: textColor, + letterSpacing: -0.2, + height: 1.1, + ), + ), + ], + ), + ); + } +} + +/// Custom painter rendering the horizontal line with vertical tick marks on both ends. +class _ScaleBarBracketPainter extends CustomPainter { + final Color color; + + const _ScaleBarBracketPainter({required this.color}); + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..strokeWidth = 1.6 + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; + + final path = Path(); + // Left tick + path.moveTo(1, 0); + path.lineTo(1, size.height); + // Horizontal center bar + path.lineTo(size.width - 1, size.height); + // Right tick + path.lineTo(size.width - 1, 0); + + // Center tick + final midX = size.width / 2; + path.moveTo(midX, size.height); + path.lineTo(midX, size.height - 3); + + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(covariant _ScaleBarBracketPainter oldDelegate) => oldDelegate.color != color; +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_scene.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_scene.dart new file mode 100644 index 0000000000..d67ac6f775 --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_scene.dart @@ -0,0 +1,150 @@ +/// ============================================================================ +/// File: esrimap_scene.dart +/// Description: Widget wrapper for rendering 3D ArcGIS WebScene portals, +/// handling camera viewpoint controls, label scaling, and snap-to-north. +/// ============================================================================ + +import 'dart:async'; + +import 'package:arcgis_maps/arcgis_maps.dart'; +import 'package:flutter/material.dart'; + +/// Stateful widget encapsulating an [ArcGISSceneView] for 3D building and drone scene layers. +class EsriSceneWidget extends StatefulWidget { + /// Portal URI key. + final String portalUri; + + /// WebScene Portal Item ID. + final String itemId; + + /// Callback when camera rotation heading changes. + final void Function(double heading)? onHeadingChanged; + + /// Constructs an [EsriSceneWidget] instance. + const EsriSceneWidget({super.key, required this.portalUri, required this.itemId, this.onHeadingChanged}); + + @override + State createState() => EsriSceneWidgetState(); +} + +/// State object managing 3D camera controls and scene initialization. +class EsriSceneWidgetState extends State { + late final ArcGISSceneViewController _sceneViewController; + Camera? _initialCamera; + double _camToTargetLatOffset = 0.0; + StreamSubscription? _viewpointSubscription; + + @override + void initState() { + super.initState(); + _sceneViewController = ArcGISSceneView.createController(); + _sceneViewController.interactionOptions.rotateEnabled = true; + _sceneViewController.interactionOptions.panEnabled = true; + _sceneViewController.interactionOptions.flingEnabled = true; + _sceneViewController.interactionOptions.zoomFactor = 3.0; + _sceneViewController.atmosphereEffect = AtmosphereEffect.none; + _sceneViewController.spaceEffect = SpaceEffect.transparent; + } + + void _onSceneViewReady() { + final portal = Portal(Uri.parse(widget.portalUri)); + final portalItem = PortalItem.withPortalAndItemId(portal: portal, itemId: widget.itemId); + final scene = ArcGISScene.withItem(portalItem); + _sceneViewController.arcGISScene = scene; + + _initialCamera = Camera.withLatLong( + latitude: 32.86872066, + longitude: -117.23732235, + altitude: 1062.871, + heading: 0, + pitch: 53.261, + roll: 0, + ); + _sceneViewController.setViewpointCamera(_initialCamera!); + + // Capture camera to target offset once viewpoint stabilizes + Future.delayed(const Duration(milliseconds: 500), () { + final isNotMounted = !mounted; + if (isNotMounted) return; + final vp = _sceneViewController.getCurrentViewpoint(ViewpointType.centerAndScale); + final pt = vp?.targetGeometry; + final isPoint = pt is ArcGISPoint; + if (isPoint) _camToTargetLatOffset = pt.y - _initialCamera!.location.y; + }); + + _viewpointSubscription = _sceneViewController.onViewpointChanged.listen((_) { + final isNotMounted = !mounted; + if (isNotMounted) return; + final vp = _sceneViewController.getCurrentViewpoint(ViewpointType.centerAndScale); + final isVpNotNull = vp != null; + if (isVpNotNull) widget.onHeadingChanged?.call(vp.rotation); + }); + + _applyLabelScales(scene); + } + + // Restrict building labels to only appear when zoomed in close (scale <= 4000) + Future _applyLabelScales(ArcGISScene scene) async { + await scene.load(); + _applyLabelScalesToLayers(scene.operationalLayers); + } + + void _applyLabelScalesToLayers(List layers) { + for (final layer in layers) { + final isFeatureLayer = layer is FeatureLayer; + final isGroupLayer = layer is GroupLayer; + if (isFeatureLayer) { + for (final labelDef in layer.labelDefinitions) { + labelDef.minScale = 4000; + } + } else if (isGroupLayer) { + _applyLabelScalesToLayers(layer.layers); + } + } + } + + /// Resets 3D camera to initial campus view coordinates. + void resetCamera() { + final isInitialCameraNull = _initialCamera == null; + if (isInitialCameraNull) return; + _sceneViewController.setViewpointCamera(_initialCamera!); + } + + /// Snaps heading to north by rotating camera around current look-at target. + void snapToNorth() { + final isInitialCameraNull = _initialCamera == null; + if (isInitialCameraNull) return; + final vp = _sceneViewController.getCurrentViewpoint(ViewpointType.centerAndScale); + final target = vp?.targetGeometry; + final isNotPoint = target is! ArcGISPoint; + if (isNotPoint) { + resetCamera(); + return; + } + + final pivotLat = target.y; + final pivotLon = target.x; + final camAlt = _initialCamera!.location.z ?? 1062.871; + + _sceneViewController.setViewpointCamera( + Camera.withLatLong( + latitude: pivotLat - _camToTargetLatOffset, + longitude: pivotLon, + altitude: camAlt, + heading: 0, + pitch: _initialCamera!.pitch, + roll: 0, + ), + ); + } + + @override + void dispose() { + _viewpointSubscription?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => + ArcGISSceneView(controllerProvider: () => _sceneViewController, onSceneViewReady: _onSceneViewReady); +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_search_bar.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_search_bar.dart new file mode 100644 index 0000000000..8a243b4e97 --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_search_bar.dart @@ -0,0 +1,481 @@ +/// ============================================================================ +/// File: esrimap_search_bar.dart +/// Description: Floating search input bar and route field selector widget, +/// including AI search trigger and dropdown results list. +/// ============================================================================ + +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_config.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:campus_mobile_experimental/core/utils/esri_map_feature_flags.dart'; +import 'package:campus_mobile_experimental/app_styles.dart'; +import 'package:flutter/material.dart'; + +/// Search input bar and route directions header widget. +class EsriMapSearchBar extends StatelessWidget { + /// Map configuration object gating AI search features. + final EsriMapConfig? config; + + /// Whether route input fields ('From' and 'To') are active. + final bool showRouteFields; + + /// Main search input controller. + final TextEditingController searchController; + + /// Main search focus node. + final FocusNode focusNode; + + /// 'From' origin input controller. + final TextEditingController fromController; + + /// 'From' origin focus node. + final FocusNode fromFocusNode; + + /// 'To' destination input controller. + final TextEditingController toController; + + /// 'To' destination focus node. + final FocusNode toFocusNode; + + /// Whether search suggestions are currently visible. + final bool showSuggestions; + + /// Whether search results are currently visible. + final bool showResults; + + /// Whether a search operation is currently in progress. + final bool isSearching; + + /// Search results returned from backend query. + final List searchResults; + + /// Live matching POI class values. + final List matchingPoiClasses; + + /// Callback when main search text is submitted or changed. + final void Function(String query) onPerformSearch; + + /// Callback when a matching class category item is selected. + final void Function(String classValue) onPerformClassSearch; + + /// Callback when a search result is selected. + final void Function(MapSearchResult result) onSelectResult; + + /// Callback when search bar clear button is tapped. + final VoidCallback onClearSearch; + + /// Callback when route calculation fields are cleared. + final VoidCallback onClearRoute; + + /// Callback when 'From' and 'To' locations are swapped. + final VoidCallback onSwapRouteFields; + + /// Callback when search input field is tapped. + final VoidCallback onTapSearchField; + + /// Callback when 'From' input field focus/tap occurs. + final VoidCallback onTapFromField; + + /// Callback when 'To' input field focus/tap occurs. + final VoidCallback onTapToField; + + /// Callback when 'From' field text changes. + final void Function(String text) onChangedFromField; + + /// Callback when 'To' field text changes. + final void Function(String text) onChangedToField; + + /// Callback when 'From' field clear button is pressed. + final VoidCallback onClearFromField; + + /// Callback when 'To' field clear button is pressed. + final VoidCallback onClearToField; + + /// Callback when AI Search sheet trigger is pressed. + final VoidCallback onOpenAiSearch; + + /// Helper function getting icon for POI class. + final IconData Function(String classValue) iconForClass; + + /// Helper function getting label for POI class. + final String Function(String classValue) labelForClass; + + /// Helper function getting icon for MapSearchResult. + final IconData Function(MapSearchResult result) iconForResult; + + /// Constructs an [EsriMapSearchBar] instance. + const EsriMapSearchBar({ + Key? key, + required this.config, + required this.showRouteFields, + required this.searchController, + required this.focusNode, + required this.fromController, + required this.fromFocusNode, + required this.toController, + required this.toFocusNode, + required this.showSuggestions, + required this.showResults, + required this.isSearching, + required this.searchResults, + required this.matchingPoiClasses, + required this.onPerformSearch, + required this.onPerformClassSearch, + required this.onSelectResult, + required this.onClearSearch, + required this.onClearRoute, + required this.onSwapRouteFields, + required this.onTapSearchField, + required this.onTapFromField, + required this.onTapToField, + required this.onChangedFromField, + required this.onChangedToField, + required this.onClearFromField, + required this.onClearToField, + required this.onOpenAiSearch, + required this.iconForClass, + required this.labelForClass, + required this.iconForResult, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + var isAiSearchEnabled = FeatureFlags.MAP_AI_SEARCH_ENABLED && (config?.features.aiSearch ?? false); + const searchFontSize = 16.0; + final isDark = Theme.of(context).brightness == Brightness.dark; + final searchTextColor = isDark ? descriptiveTextColorDark : descriptiveTextColorLight; + final hasSearchResults = isSearching || searchResults.isNotEmpty; + final shouldShowResultsDivider = showResults && hasSearchResults; + + final isSearchNotEmpty = searchController.text.isNotEmpty; + final hasClassMatches = + FeatureFlags.MAP_SEARCH_CATEGORIES_ENABLED && + matchingPoiClasses.isNotEmpty && + isSearchNotEmpty && + !showSuggestions; + final shouldShowDropdown = isSearching ? showRouteFields && showResults : showResults || hasClassMatches; + + return Column( + children: [ + // Direction Route Fields ('From' + 'To') + if (showRouteFields) + Material( + elevation: 4, + borderRadius: BorderRadius.circular(8), + color: Theme.of(context).scaffoldBackgroundColor, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Left route connection indicator dots + Padding( + padding: const EdgeInsets.only(left: 14), + child: ExcludeSemantics( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.radio_button_checked, size: 16, color: Colors.blue[600]), + const SizedBox(height: 6), + Icon(Icons.circle, size: 4, color: isDark ? Colors.grey[600] : Colors.grey[400]), + const SizedBox(height: 4), + Icon(Icons.circle, size: 4, color: isDark ? Colors.grey[600] : Colors.grey[400]), + const SizedBox(height: 4), + Icon(Icons.circle, size: 4, color: isDark ? Colors.grey[600] : Colors.grey[400]), + const SizedBox(height: 6), + const Icon(Icons.location_on, size: 20, color: Colors.red), + ], + ), + ), + ), + // Text input fields column + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // 'From' field + Row( + children: [ + Expanded( + child: TextField( + controller: fromController, + focusNode: fromFocusNode, + style: const TextStyle(fontSize: 16), + decoration: const InputDecoration( + border: InputBorder.none, + contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 14), + hintText: 'From', + isDense: true, + ), + onTap: onTapFromField, + onChanged: onChangedFromField, + ), + ), + if (fromController.text.isNotEmpty) + Material( + color: Colors.transparent, + child: InkWell( + customBorder: const CircleBorder(), + onTap: onClearFromField, + child: Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: isDark ? Colors.grey[800] : Colors.grey[200], + shape: BoxShape.circle, + ), + child: Icon( + Icons.close, + size: 16, + color: isDark ? Colors.white70 : Colors.grey[800], + ), + ), + ), + ), + ], + ), + const Divider(height: 1, indent: 10, endIndent: 10), + // 'To' field + Row( + children: [ + Expanded( + child: TextField( + controller: toController, + focusNode: toFocusNode, + style: const TextStyle(fontSize: 16), + decoration: const InputDecoration( + border: InputBorder.none, + contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 14), + hintText: 'To', + isDense: true, + ), + onTap: onTapToField, + onChanged: onChangedToField, + ), + ), + if (toController.text.isNotEmpty) + Material( + color: Colors.transparent, + child: InkWell( + customBorder: const CircleBorder(), + onTap: onClearToField, + child: Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: isDark ? Colors.grey[800] : Colors.grey[200], + shape: BoxShape.circle, + ), + child: Icon( + Icons.close, + size: 16, + color: isDark ? Colors.white70 : Colors.grey[800], + ), + ), + ), + ), + ], + ), + ], + ), + ), + // Close route + Swap locations action buttons + Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 36, + height: 36, + child: IconButton( + padding: EdgeInsets.zero, + icon: const Icon(Icons.close, size: 20, color: Colors.redAccent), + onPressed: onClearRoute, + tooltip: 'Close routing', + ), + ), + SizedBox( + width: 36, + height: 36, + child: IconButton( + padding: EdgeInsets.zero, + icon: Icon(Icons.swap_vert, size: 20, color: isDark ? Colors.white70 : Colors.grey[600]), + onPressed: onSwapRouteFields, + tooltip: 'Swap starting and destination locations', + ), + ), + ], + ), + const SizedBox(width: 4), + ], + ), + ), + ) + else + // Single Search Bar + Material( + elevation: 4, + borderRadius: BorderRadius.circular(8), + color: Theme.of(context).scaffoldBackgroundColor, + child: Row( + children: [ + Padding( + padding: const EdgeInsets.only(left: 12), + child: SizedBox( + width: 24, + height: 24, + child: isSearching + ? CircularProgressIndicator(strokeWidth: 2, color: searchTextColor, semanticsLabel: 'Searching') + : ExcludeSemantics( + child: Icon(Icons.search, color: isDark ? Colors.white70 : Colors.grey[600]), + ), + ), + ), + Expanded( + child: TextField( + controller: searchController, + focusNode: focusNode, + textInputAction: TextInputAction.search, + onSubmitted: onPerformSearch, + onChanged: (text) { + final isTextEmpty = text.isEmpty; + if (isTextEmpty) { + onClearSearch(); + } else { + onPerformSearch(text); + } + }, + onTap: onTapSearchField, + style: TextStyle(fontSize: searchFontSize, color: searchTextColor), + decoration: InputDecoration( + border: InputBorder.none, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + hintText: 'Search buildings, places...', + hintStyle: TextStyle(fontSize: searchFontSize, color: searchTextColor), + ), + ), + ), + if (isSearchNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 10.0), + child: Material( + color: Colors.transparent, + child: InkWell( + customBorder: const CircleBorder(), + onTap: onClearSearch, + child: Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: isDark ? Colors.grey[800] : Colors.grey[200], + shape: BoxShape.circle, + ), + child: Icon(Icons.close, size: 18, color: isDark ? Colors.white70 : Colors.grey[800]), + ), + ), + ), + ), + if (isAiSearchEnabled) + IconButton( + icon: Icon( + Icons.auto_awesome, + color: isDark ? Colors.amber[300] : Theme.of(context).colorScheme.primary, + size: 20, + ), + onPressed: onOpenAiSearch, + tooltip: 'AI Location Search', + ), + ], + ), + ), + + // Search Results Dropdown List + if (shouldShowDropdown) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Material( + elevation: 4, + borderRadius: BorderRadius.circular(8), + color: Theme.of(context).scaffoldBackgroundColor, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Category matches + if (matchingPoiClasses.isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(16, 10, 16, 4), + child: Row( + children: [ + Icon(Icons.category_outlined, size: 13, color: isDark ? Colors.grey[500] : Colors.grey[500]), + const SizedBox(width: 6), + Text( + 'CATEGORIES', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 0.6, + color: isDark ? Colors.grey[500] : Colors.grey[500], + ), + ), + ], + ), + ), + ...matchingPoiClasses.map( + (classValue) => ListTile( + splashColor: Colors.transparent, + leading: Icon( + iconForClass(classValue), + size: 20, + color: isDark ? Colors.white70 : Colors.grey[700], + ), + title: Text(labelForClass(classValue)), + subtitle: Text( + classValue, + style: TextStyle(fontSize: 13, color: isDark ? Colors.grey[500] : Colors.grey[500]), + ), + dense: true, + onTap: () => onPerformClassSearch(classValue), + ), + ), + if (shouldShowResultsDivider) const Divider(height: 1), + ], + + // Building & POI results list + if (showResults) + isSearching + ? const Padding( + padding: EdgeInsets.all(16), + child: Center(child: CircularProgressIndicator()), + ) + : searchResults.isEmpty + ? (matchingPoiClasses.isEmpty + ? const Padding(padding: EdgeInsets.all(16), child: Text('No results found')) + : const SizedBox.shrink()) + : ConstrainedBox( + constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.4), + child: ListView.separated( + shrinkWrap: true, + padding: EdgeInsets.zero, + itemCount: searchResults.length, + separatorBuilder: (_, __) => const Divider(height: 1), + itemBuilder: (context, index) { + final result = searchResults[index]; + return ListTile( + splashColor: Colors.transparent, + leading: Icon(iconForResult(result)), + title: Text(result.name, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: result.subtitle.isNotEmpty + ? Text(result.subtitle, maxLines: 1, overflow: TextOverflow.ellipsis) + : null, + dense: true, + onTap: () => onSelectResult(result), + ); + }, + ), + ), + ], + ), + ), + ), + ], + ); + } +} diff --git a/lib/ui/esrimap/esri_map_widgets/esrimap_suggestions_panel.dart b/lib/ui/esrimap/esri_map_widgets/esrimap_suggestions_panel.dart new file mode 100644 index 0000000000..5c28419f4a --- /dev/null +++ b/lib/ui/esrimap/esri_map_widgets/esrimap_suggestions_panel.dart @@ -0,0 +1,250 @@ +/// ============================================================================ +/// File: esrimap_suggestions_panel.dart +/// Description: Dropdown card panel presenting suggested category quick-search +/// chips and recent search history items. +/// ============================================================================ + +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_search_category.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:flutter/material.dart'; + +class EsriMapSuggestionsPanel extends StatefulWidget { + final List categories; + final List recentSearches; + final bool showRouteFields; + final String? activeRouteField; + final VoidCallback onSelectCurrentLocation; + final void Function(EsriSearchCategory category) onSelectCategory; + final void Function(MapSearchResult result) onSelectRecent; + final void Function(int index) onRemoveRecent; + final VoidCallback onClearRecent; + + const EsriMapSuggestionsPanel({ + Key? key, + required this.categories, + required this.recentSearches, + required this.showRouteFields, + required this.activeRouteField, + required this.onSelectCurrentLocation, + required this.onSelectCategory, + required this.onSelectRecent, + required this.onRemoveRecent, + required this.onClearRecent, + }) : super(key: key); + + @override + State createState() => _EsriMapSuggestionsPanelState(); +} + +class _EsriMapSuggestionsPanelState extends State { + bool _isHistoryExpanded = false; + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + final bgColor = Theme.of(context).scaffoldBackgroundColor; + final isFromRouteFieldActive = widget.showRouteFields && widget.activeRouteField == 'from'; + final topPadding = isFromRouteFieldActive ? 0.0 : 12.0; + final availableHeight = MediaQuery.sizeOf(context).height - MediaQuery.viewInsetsOf(context).bottom; + + return Material( + elevation: 4, + borderRadius: BorderRadius.circular(8), + color: bgColor, + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: availableHeight * 0.55), + child: SingleChildScrollView( + padding: EdgeInsets.only(top: topPadding, bottom: 12), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (isFromRouteFieldActive) ...[ + ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + leading: ExcludeSemantics( + child: Icon( + Icons.my_location, + size: 20, + color: isDark ? Colors.grey[400] : Theme.of(context).colorScheme.primary, + ), + ), + title: Text( + 'Current Location', + semanticsLabel: 'Use my current location', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w500, + color: isDark ? Colors.white : Theme.of(context).colorScheme.primary, + ), + ), + onTap: widget.onSelectCurrentLocation, + ), + const Divider(height: 1), + const SizedBox(height: 12), + ], + if (widget.categories.isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + 'Quick search', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: isDark ? Colors.grey[400] : Colors.grey[600], + ), + ), + ), + const SizedBox(height: 8), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final category in widget.categories) Expanded(child: _buildCategoryChip(context, category)), + ], + ), + ), + ], + if (widget.recentSearches.isNotEmpty) ...[ + const SizedBox(height: 12), + const Divider(height: 1), + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 8, 0), + child: Row( + children: [ + Expanded( + child: Text( + 'Recently viewed', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: isDark ? Colors.grey[400] : Colors.grey[600], + ), + ), + ), + TextButton( + onPressed: widget.onClearRecent, + style: TextButton.styleFrom(foregroundColor: isDark ? Colors.grey[400] : Colors.grey[600]), + child: const Text('Clear', semanticsLabel: 'Clear recent searches'), + ), + ], + ), + ), + _buildRecentSearchesList(isDark), + ], + ], + ), + ), + ), + ); + } + + Widget _buildRecentSearchesList(bool isDark) { + final maxTotal = widget.recentSearches.length > 10 ? 10 : widget.recentSearches.length; + final displayCount = _isHistoryExpanded ? maxTotal : (maxTotal > 2 ? 2 : maxTotal); + + // ListTile height is approximately 64. 5 items = 320. + final double listHeight = _isHistoryExpanded && maxTotal > 5 ? (5 * 64.0) : (displayCount * 64.0); + + return Column( + children: [ + ConstrainedBox( + constraints: BoxConstraints(maxHeight: listHeight), + child: ListView.builder( + padding: EdgeInsets.zero, + physics: _isHistoryExpanded ? const ClampingScrollPhysics() : const NeverScrollableScrollPhysics(), + shrinkWrap: true, + itemCount: displayCount, + itemBuilder: (context, index) { + final recent = widget.recentSearches[index]; + final subtitle = recent.address.isNotEmpty ? recent.address : recent.subtitle; + return SizedBox( + height: 64, + child: ListTile( + contentPadding: const EdgeInsets.only(left: 16, right: 4), + leading: ExcludeSemantics( + child: CircleAvatar( + radius: 16, + backgroundColor: isDark ? Colors.grey[800] : Colors.grey[100], + child: Icon(Icons.history, size: 18, color: isDark ? Colors.grey[400] : Colors.grey[600]), + ), + ), + title: Text( + recent.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: isDark ? Colors.white : Colors.black87), + ), + subtitle: subtitle.isEmpty + ? null + : Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: isDark ? Colors.grey[400] : Colors.grey[600]), + ), + trailing: IconButton( + tooltip: 'Remove ${recent.name} from recents', + onPressed: () => widget.onRemoveRecent(index), + icon: Icon(Icons.close, size: 18, color: isDark ? Colors.grey[400] : Colors.grey[600]), + ), + onTap: () => widget.onSelectRecent(recent), + ), + ); + }, + ), + ), + if (maxTotal > 2) + TextButton( + style: TextButton.styleFrom(foregroundColor: isDark ? Colors.grey[400] : Colors.grey[600]), + onPressed: () { + setState(() { + _isHistoryExpanded = !_isHistoryExpanded; + }); + }, + child: Text( + _isHistoryExpanded ? 'Show Less' : 'Show More', + semanticsLabel: _isHistoryExpanded ? 'Show less recent searches' : 'Show more recent searches', + ), + ), + ], + ); + } + + Widget _buildCategoryChip(BuildContext context, EsriSearchCategory category) { + final isDark = Theme.of(context).brightness == Brightness.dark; + + return Semantics( + button: true, + label: 'Search ${category.label}', + child: Tooltip( + message: 'Search ${category.label}', + child: GestureDetector( + onTap: () => widget.onSelectCategory(category), + child: ExcludeSemantics( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 52, + height: 52, + decoration: BoxDecoration(color: category.color, shape: BoxShape.circle), + child: Icon(category.icon, size: 22, color: Theme.of(context).scaffoldBackgroundColor), + ), + const SizedBox(height: 6), + Text( + category.label, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: isDark ? Colors.grey[400] : Colors.grey[600]), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/ui/esrimap/esrimap.dart b/lib/ui/esrimap/esrimap.dart new file mode 100644 index 0000000000..cbe939a611 --- /dev/null +++ b/lib/ui/esrimap/esrimap.dart @@ -0,0 +1,2773 @@ +/// ============================================================================ +/// File: esrimap.dart +/// Description: Main campus Esri map screen widget. Integrates the 2D/3D map view, +/// location display, top search bar, floating action buttons, +/// basemap & operational layer controls, and bottom slide-over panels. +/// ============================================================================ + +import 'dart:async'; +import 'dart:math' as math; + +import 'package:arcgis_maps/arcgis_maps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_ai_search_model.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_basemaps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_config.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_search_category.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:campus_mobile_experimental/core/services/esri_map_services/esrimap_auth_handler.dart'; +import 'package:campus_mobile_experimental/core/services/esri_map_services/esrimap_basemap_factory.dart'; +import 'package:campus_mobile_experimental/core/services/esri_map_services/esrimap_config_service.dart'; +import 'package:campus_mobile_experimental/core/services/esri_map_services/esrimap_route_service.dart'; +import 'package:campus_mobile_experimental/core/services/esri_map_services/esrimap_search_service.dart'; +import 'package:campus_mobile_experimental/core/utils/esri_map_feature_flags.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_ai_search_sheet.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_category_list_panel.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_detail_slide_over.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_fab.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_layers_panel.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_scale_bar.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_scene.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_search_bar.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_suggestions_panel.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_callout_content.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; +import 'package:provider/provider.dart'; +import 'package:campus_mobile_experimental/core/providers/dining.dart'; +import 'package:campus_mobile_experimental/core/providers/parking.dart'; +import 'package:campus_mobile_experimental/core/providers/availability.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:hive/hive.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import 'dart:ui' as ui; + +// Re-export MapSearchResult so callers importing esrimap.dart retain access +export 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart' + show MapSearchResult, MapSearchSource; + +/// Primary StatefulWidget for the interactive Esri Campus Map screen. +class EsriMap extends StatefulWidget { + /// Constructs an [EsriMap] instance. + const EsriMap({Key? key}) : super(key: key); + + @override + State createState() => _EsriMapState(); +} + +class _EsriMapState extends State with AutomaticKeepAliveClientMixin { + // --------------------------------------------------------------------------- + // Controllers & Overlay Graphics + // --------------------------------------------------------------------------- + final _mapViewController = ArcGISMapView.createController(); + late final ArcGISMap _map; + final _graphicsOverlay = GraphicsOverlay(); + final _routeGraphicsOverlay = GraphicsOverlay(); + + final _searchController = TextEditingController(); + final _fromController = TextEditingController(); + final _toController = TextEditingController(); + + final _focusNode = FocusNode(); + final _fromFocusNode = FocusNode(); + final _toFocusNode = FocusNode(); + + final _categorySheetController = DraggableScrollableController(); + final _detailSheetMinimized = ValueNotifier(false); + + // --------------------------------------------------------------------------- + // Map State & Services + // --------------------------------------------------------------------------- + EsriMapConfig? _config; + var _locationDataSource = SystemLocationDataSource(); + + // Search State + static const _MINIMUM_SEARCH_LOADING_DURATION = Duration(milliseconds: 400); + List _searchResults = []; + List _allPoiClasses = []; + List _matchingPoiClasses = []; + bool _showResults = false; + bool _isSearching = false; + bool _showSuggestions = false; + List _recentSearches = []; + Timer? _searchDebounce; + int _searchRequestId = 0; + + // Active Category & Pin Plotting State + MapSearchResult? _selectedResultValue; + MapSearchResult? get _selectedResult => _selectedResultValue; + set _selectedResult(MapSearchResult? value) { + _selectedResultValue = value; + if (value != null) _detailSheetMinimized.value = false; + } + + MapSearchResult? _lastSelectedResult; + List _mappedResults = []; + List _allCategoryResults = []; + bool _showCategoryList = false; + EsriSearchCategory? _activeCategory; + + // FAB & Viewpoint State + // FAB & Viewpoint State + bool _isLocatingUser = false; + bool _isLocationActive = false; + bool _isRecenterActive = false; + bool _ignoreViewpointReset = false; + double _mapRotation = 0.0; + double _currentScale = 24000.0; + bool _isDisposed = false; + StreamSubscription? _viewpointChangedSubscription; + bool _hasNetworkError = false; + + // Routing State + bool _isRouting = false; + bool _hasRoute = false; + bool _routeFailed = false; + String _travelMode = 'Walking'; + double _routeTravelTimeMinutes = 0; + List _routeManeuvers = []; + bool _showRouteFields = false; + String? _activeRouteField; + (double, double)? _fromLatLng; + MapSearchResult? _routeDestination; + ArcGISPoint? _loadingLocation; + + // Basemaps & Operational Layers State + BasemapType _currentBasemapType = BasemapType.defaultMap; + final Map _basemaps = {}; + bool _showLayersPanel = false; + final Map _layerVisible = {}; + final Map _layerLoading = {}; + final Map> _layerInstances = {}; + final Map _layerTimers = {}; + + // Legend State + List _transitLegend = []; + Map _transitLegendSwatches = {}; + Map> _transitRouteLayers = {}; + Map _transitRouteVisibility = {}; + bool _isTransitLegendLoading = false; + bool _isTransitLegendMinimized = false; + + // 3D Scene Widgets & Keys + String _sceneMode = 'default'; + EsriSceneWidget? _scene3DWidget; + EsriSceneWidget? _sceneDroneWidget; + final _scene3DKey = GlobalKey(); + final _sceneDroneKey = GlobalKey(); + + var _mapReadyCompleter = Completer(); + + /// Returns list of mapped search categories constructed from server configuration. + List get _categories { + final isConfigNull = _config == null; + if (isConfigNull) return []; + return _config!.searchCategories + .map( + (c) => EsriSearchCategory( + label: c.label, + icon: iconDataForName(c.icon), + poiClassValue: c.poiClass, + color: colorFromHex(c.color), + ), + ) + .toList(); + } + + @override + bool get wantKeepAlive => true; + + // --------------------------------------------------------------------------- + // Lifecycle & Initialization + // --------------------------------------------------------------------------- + + @override + void initState() { + super.initState(); + _fetchConfigThenInit(); + _loadRecentSearches(); + _focusNode.addListener(_onFocusChanged); + _fromFocusNode.addListener(_onFromFocusChanged); + _toFocusNode.addListener(_onToFocusChanged); + } + + Future _fetchConfigThenInit() async { + setState(() => _hasNetworkError = false); + if (_mapReadyCompleter.isCompleted) _mapReadyCompleter = Completer(); + try { + final config = await EsriMapConfigService.instance.fetch(); + if (!mounted) return; + setState(() => _config = config); + _initMap(config); + _fetchAllPoiClasses(); + } catch (e) { + debugPrint('Config fetch failed: $e'); + if (mounted) setState(() => _hasNetworkError = true); + if (!_mapReadyCompleter.isCompleted) _mapReadyCompleter.completeError(e); + } + } + + /// Constructs initial basemaps and sets initial campus viewpoint. + void _initMap(EsriMapConfig config) { + for (final type in BasemapType.values) { + var shouldSkipBasemap = + !FeatureFlags.MAP_ALTERNATE_BASEMAPS_ENABLED && (type == BasemapType.light || type == BasemapType.dark); + if (shouldSkipBasemap) continue; + _basemaps[type] = buildBasemap(type, config); + } + + _map = ArcGISMap.withBasemap(_basemaps[_currentBasemapType]!); + _map.maxScale = 38.4; // Limit zoom in to scale 1:38.4 (~23.88 max zoom level) + _map.minScale = 70000000.0; // Limit zoom out to scale 1:70000000.0 (~3.08 min zoom level) + _map.maxExtent = Envelope.fromXY( + xMin: -180.0, + yMin: -55.0, + xMax: 180.0, + yMax: 55.0, + spatialReference: SpatialReference.wgs84, + ); + _map.initialViewpoint = Viewpoint.fromCenter( + ArcGISPoint(x: -117.2340, y: 32.8801, spatialReference: SpatialReference.wgs84), + scale: 24000, + ); + _mapReadyCompleter.complete(); + } + + /// Configures map view controller, auth handlers, graphics overlays, and viewpoint listeners when ready. + void _onMapViewReady() async { + await _mapReadyCompleter.future; + _setupAgeAuthChallengeHandler(); + _mapViewController.arcGISMap = _map; + _mapViewController.selectionProperties = SelectionProperties(color: const Color(0xFF34C759)); + _mapViewController.interactionOptions.rotateEnabled = true; + + final isGraphicsOverlayMissing = !_mapViewController.graphicsOverlays.contains(_graphicsOverlay); + if (isGraphicsOverlayMissing) _mapViewController.graphicsOverlays.add(_graphicsOverlay); + final isRouteOverlayMissing = !_mapViewController.graphicsOverlays.contains(_routeGraphicsOverlay); + if (isRouteOverlayMissing) _mapViewController.graphicsOverlays.add(_routeGraphicsOverlay); + + // Configure location display settings + _mapViewController.locationDisplay.dataSource = _locationDataSource; + _mapViewController.locationDisplay.autoPanMode = LocationDisplayAutoPanMode.off; + _mapViewController.locationDisplay.showLocation = true; + + _startLocationDisplay(); + _mapViewController.locationDisplay.onLocationChanged.listen((event) { + final pos = event.position; + final wgs = GeometryEngine.project(pos, outputSpatialReference: SpatialReference.wgs84) as ArcGISPoint?; + final isValidWgs = wgs != null && !wgs.x.isNaN && !wgs.y.isNaN; + if (isValidWgs) _saveLocationToHive(wgs.y, wgs.x); + }); + + _preloadAlternateBasemaps(); + _preloadHeavyLayers(); + + // Track map heading rotation and zoom level changes + DateTime? lastUpdateTime; + + _viewpointChangedSubscription = _mapViewController.onViewpointChanged.listen((_) { + final now = DateTime.now(); + var isRecentUpdate = lastUpdateTime != null && now.difference(lastUpdateTime!).inMilliseconds < 32; + if (isRecentUpdate) return; // Throttle to ~30 FPS to prevent heavy jitter + lastUpdateTime = now; + + final vp = _mapViewController.getCurrentViewpoint(ViewpointType.centerAndScale); + final isVpValid = vp != null && mounted; + if (isVpValid) { + final scale = vp.targetScale; + final centerPoint = vp.targetGeometry as ArcGISPoint?; + + setState(() { + _mapRotation = vp.rotation.isNaN ? 0.0 : vp.rotation; + _currentScale = scale; + final shouldResetVP = !_ignoreViewpointReset && (_isLocationActive || _isRecenterActive); + if (shouldResetVP) { + _isLocationActive = false; + _isRecenterActive = false; + } + }); + } + }); + } + + /// Silently preloads computationally expensive operational layers (e.g. portalItem Web Maps) + /// in the background to ensure instantaneous layer toggling later. + void _preloadHeavyLayers() async { + if (_config == null) return; + for (final entry in _config!.layers.entries) { + var needsPreload = entry.value.source == 'portalItem' && !_layerInstances.containsKey(entry.key); + if (needsPreload) { + final instances = await _buildLayerInstances(entry.key, entry.value); + _layerInstances[entry.key] = instances; + for (final layer in instances) { + if (layer != null) { + layer.isVisible = false; + _map.operationalLayers.add(layer); + } + } + try { + await Future.wait(instances.whereType().map((l) => l.load())); + _applyLayerSpecialCases(entry.key, instances); + } catch (e) { + debugPrint('Preload layer error: $e'); + } + } + } + } + + /// Sets authentication manager challenge handler for Enterprise token retrieval. + void _setupAgeAuthChallengeHandler() { + ArcGISEnvironment.authenticationManager.arcGISAuthenticationChallengeHandler = AgeAuthChallengeHandler( + EsriMapConfigService.instance.tokensUrl, + ); + } + + @override + void dispose() { + _searchDebounce?.cancel(); + _categorySheetController.dispose(); + _detailSheetMinimized.dispose(); + _searchController.dispose(); + _fromController.dispose(); + _toController.dispose(); + _fromFocusNode.dispose(); + _toFocusNode.dispose(); + _focusNode.dispose(); + for (final timer in _layerTimers.values) { + timer.cancel(); + } + _viewpointChangedSubscription?.cancel(); + super.dispose(); + } + + // --------------------------------------------------------------------------- + // Location & Basemaps Helpers + // --------------------------------------------------------------------------- + bool _isStartingLocationDataSource = false; + + /// Starts the device location data source. + Future _startLocationDisplay() async { + if (!FeatureFlags.MAP_LOCATION_TRACKING_ENABLED) return; + if (_isStartingLocationDataSource) return; + _isStartingLocationDataSource = true; + + try { + bool serviceEnabled = await Geolocator.isLocationServiceEnabled(); + if (!serviceEnabled) { + debugPrint('Location services are disabled.'); + return; + } + + LocationPermission permission = await Geolocator.checkPermission(); + if (permission == LocationPermission.denied) { + permission = await Geolocator.requestPermission(); + if (permission == LocationPermission.denied) { + debugPrint('Location permissions are denied'); + return; + } + } + + if (permission == LocationPermission.deniedForever) { + debugPrint('Location permissions are permanently denied'); + return; + } + + await _locationDataSource.start().timeout(const Duration(seconds: 5)); + } catch (e) { + debugPrint('Location DataSource Start Error: $e'); + final isTimeoutOrFail = e is TimeoutException || e.toString().toLowerCase().contains('fail'); + if (isTimeoutOrFail) { + _locationDataSource = SystemLocationDataSource(); + _mapViewController.locationDisplay.dataSource = _locationDataSource; + _locationDataSource.start().catchError((_) {}); + } + } finally { + _isStartingLocationDataSource = false; + } + } + + /// Efficiently fetches device location falling back from fastest to slowest + Future<(double, double)?> _getDeviceLocationEfficiently() async { + _startLocationDisplay(); + + // 1. Try internal ArcGIS cached position first + var gps = _getUserLatLng(); + if (gps != null) return gps; + + // 2. Try Fallback to Geolocator last known position + try { + final lastKnown = await Geolocator.getLastKnownPosition(); + if (lastKnown != null) return (lastKnown.latitude, lastKnown.longitude); + } catch (_) {} + + // 3. Try Hive cached location + final hiveLocation = await _loadLocationFromHive(); + if (hiveLocation != null) return hiveLocation; + + // 4. Fallback to a fresh fetch + try { + final pos = await Geolocator.getCurrentPosition( + locationSettings: const LocationSettings(timeLimit: Duration(seconds: 5)), + ); + return (pos.latitude, pos.longitude); + } catch (_) {} + + return null; + } + + /// Preloads non-active basemaps into memory. + void _preloadAlternateBasemaps() { + for (final entry in _basemaps.entries) { + final isCurrent = entry.key == _currentBasemapType; + if (isCurrent) continue; + entry.value.load().catchError((Object e) { + debugPrint('Failed to preload basemap ${entry.key}: $e'); + }); + } + } + + /// Switches active basemap without resetting viewpoint frame. + void _switchBasemap(BasemapType newType) { + final isSameType = newType == _currentBasemapType; + if (isSameType) return; + final newBasemap = _basemaps[newType]; + final isBasemapNull = newBasemap == null; + if (isBasemapNull) return; + + setState(() { + _map.basemap = newBasemap; + _map.maxScale = 38.4; + _map.minScale = 70000000.0; + _map.maxExtent = Envelope.fromXY( + xMin: -180.0, + yMin: -55.0, + xMax: 180.0, + yMax: 55.0, + spatialReference: SpatialReference.wgs84, + ); + _currentBasemapType = newType; + }); + } + + /// Switches between 2D map view and 3D portal scene views. + void _setSceneMode(String key) { + final isSameMode = key == _sceneMode; + if (isSameMode) return; + setState(() { + _sceneMode = key; + final isNotDefault = key != 'default'; + if (isNotDefault) _showLayersPanel = false; + final isConfigNull = _config == null; + if (isConfigNull) return; + + final scene = _config!.scenes[key]; + final isInvalidScene = scene == null || scene.type != 'scene'; + if (isInvalidScene) return; + + final portalUrl = scene.portalKey != null ? _config!.portals[scene.portalKey!] : null; + final isMissingPortalItem = portalUrl == null || scene.itemId == null; + if (isMissingPortalItem) return; + + final isBuilding3DMode = key == 'building3d' && _scene3DWidget == null; + final isDroneViewMode = key == 'droneView' && _sceneDroneWidget == null; + + if (isBuilding3DMode) { + _scene3DWidget = EsriSceneWidget( + key: _scene3DKey, + portalUri: portalUrl, + itemId: scene.itemId!, + onHeadingChanged: (h) => setState(() { + _mapRotation = h; + final shouldResetVP3D = !_ignoreViewpointReset && (_isLocationActive || _isRecenterActive); + if (shouldResetVP3D) { + _isLocationActive = false; + _isRecenterActive = false; + } + }), + ); + } else if (isDroneViewMode) { + _sceneDroneWidget = EsriSceneWidget( + key: _sceneDroneKey, + portalUri: portalUrl, + itemId: scene.itemId!, + onHeadingChanged: (h) => setState(() { + _mapRotation = h; + final shouldResetVPDrone = !_ignoreViewpointReset && (_isLocationActive || _isRecenterActive); + if (shouldResetVPDrone) { + _isLocationActive = false; + _isRecenterActive = false; + } + }), + ); + } + }); + } + + /// Toggles visibility of operational layers configured in map settings. + void _toggleLayer(String key) async { + final entry = _config?.layers[key]; + final isEntryNull = entry == null; + if (isEntryNull) return; + + final isAlreadyVisible = _layerVisible[key] == true; + if (isAlreadyVisible) { + _layerTimers[key]?.cancel(); + _layerTimers.remove(key); + + // Hide layers instead of destroying them to cache their loaded state + for (final layer in _layerInstances[key] ?? []) { + if (layer != null) layer.isVisible = false; + } + + setState(() => _layerVisible[key] = false); + return; + } + + setState(() => _layerLoading[key] = true); + + // Retrieve cached layers, or build them if they don't exist yet + List instances = _layerInstances[key] ?? []; + + if (instances.isEmpty) { + instances = await _buildLayerInstances(key, entry); + _layerInstances[key] = instances; + + for (final layer in instances) { + if (layer != null) _map.operationalLayers.add(layer); + } + + try { + await Future.wait(instances.whereType().map((l) => l.load())); + _applyLayerSpecialCases(key, instances); + } catch (e) { + debugPrint('Layer $key load error: $e'); + } + } else { + // Re-enable visibility for cached layers + for (final layer in instances) { + if (layer != null) layer.isVisible = true; + } + } + + _startLayerRefreshTimer(key, entry); + + if (key == 'tritonTransit') _fetchTransitLegendInfos(instances); + + setState(() { + _layerVisible[key] = true; + _layerLoading[key] = false; + }); + } + + void _toggleTransitRoute(String routeName, bool isVisible) { + setState(() { + _transitRouteVisibility[routeName] = isVisible; + }); + + final layers = _transitRouteLayers[routeName] ?? []; + for (final layer in layers) { + final allRoutesForLayer = _transitRouteLayers.entries + .where((e) => e.value.contains(layer)) + .map((e) => e.key) + .toList(); + + if (allRoutesForLayer.length <= 1) { + layer.isVisible = isVisible; + } else { + final visibleRoutes = allRoutesForLayer.where((r) => _transitRouteVisibility[r] ?? true).toList(); + + if (visibleRoutes.isEmpty) { + layer.isVisible = false; + try { + layer.definitionExpression = ''; + } catch (_) {} + } else if (visibleRoutes.length == allRoutesForLayer.length) { + layer.isVisible = true; + try { + layer.definitionExpression = ''; + } catch (_) {} + } else { + layer.isVisible = true; + try { + final renderer = layer.renderer; + if (renderer != null && renderer is UniqueValueRenderer) { + final fieldNames = renderer.fieldNames; + if (fieldNames.isNotEmpty) { + final fieldName = fieldNames.first; + final visibleValues = []; + + for (final uv in renderer.uniqueValues) { + String name = uv.label.trim(); + name = name.replaceAll('Institute of', 'Institution of'); + var isRouteVisible = visibleRoutes.contains(name); + var hasUvValues = uv.values.isNotEmpty; + if (isRouteVisible && hasUvValues) { + final val = uv.values.first; + if (val is String) { + visibleValues.add("'$val'"); + } else { + visibleValues.add("$val"); + } + } + } + + var hasVisibleValues = visibleValues.isNotEmpty; + if (hasVisibleValues) layer.definitionExpression = "$fieldName IN (${visibleValues.join(',')})"; + } + } + } catch (e) { + debugPrint('Failed to set definitionExpression: $e'); + } + } + } + } + } + + Future _fetchTransitLegendInfos(List instances) async { + if (_transitLegend.isNotEmpty) return; + if (mounted) setState(() => _isTransitLegendLoading = true); + + try { + final uniqueInfosMap = {}; + final routeLayers = >{}; + + Future processContent(dynamic content) async { + if (content is Loadable) { + try { + await (content as Loadable).load(); + } catch (_) {} + } + + bool processedSublayers = false; + + var isGroupLayerWithLayers = content is GroupLayer && content.layers.isNotEmpty; + var isMapImageLayerWithSublayers = content is ArcGISMapImageLayer && content.mapImageSublayers.isNotEmpty; + var isArcGISSublayerWithSublayers = content is ArcGISSublayer && content.sublayers.isNotEmpty; + var isLayerContentWithSublayers = content is LayerContent && content.subLayerContents.isNotEmpty; + + if (isGroupLayerWithLayers) { + for (final sub in content.layers) { + await processContent(sub); + } + processedSublayers = true; + } else if (isMapImageLayerWithSublayers) { + for (final sub in content.mapImageSublayers) { + await processContent(sub); + } + processedSublayers = true; + } else if (isArcGISSublayerWithSublayers) { + for (final sub in content.sublayers) { + await processContent(sub); + } + processedSublayers = true; + } else if (isLayerContentWithSublayers) { + for (final sub in content.subLayerContents) { + await processContent(sub); + } + processedSublayers = true; + } + + if (!processedSublayers && content is LayerContent) { + try { + final layerInfos = await content.fetchLegendInfos(); + for (final info in layerInfos) { + String name = info.name.trim(); + if (name.isEmpty) continue; + name = name.replaceAll('Institute of', 'Institution of'); + uniqueInfosMap[name] = info; + routeLayers.putIfAbsent(name, () => []).add(content); + } + } catch (e) { + debugPrint('Failed to fetch legend info for sub-content: $e'); + } + } + } + + for (final layer in instances.whereType()) { + await processContent(layer); + } + + final uniqueInfos = uniqueInfosMap.values.toList(); + + final swatches = {}; + for (final info in uniqueInfos) { + final swatchImage = await info.symbol?.createSwatch(screenScale: 2.0); + if (swatchImage != null) swatches[info.name] = await swatchImage.toImage(); + } + + if (mounted) { + setState(() { + _transitLegend = uniqueInfos.where((info) => swatches.containsKey(info.name)).toList(); + _transitLegendSwatches = swatches; + _transitRouteLayers = routeLayers; + _transitRouteVisibility = {for (var info in _transitLegend) info.name: true}; + }); + } + } catch (e) { + debugPrint('Failed to fetch transit legend: $e'); + } finally { + if (mounted) setState(() => _isTransitLegendLoading = false); + } + } + + Future> _buildLayerInstances(String key, LayerEntry entry) async { + // Intercept specific layers to forcefully inject vector sublayers, bypassing + // the remote backend config which still requests slow MapImageLayers. + if (key == 'campusDistricts') + return [ + FeatureLayer.withFeatureTable( + ServiceFeatureTable.withUri( + Uri.parse( + 'https://admin-enterprise-gis.ucsd.edu/server/rest/services/AdministrationServices/Areas_and_Boundaries/MapServer/4', + ), + ), + ), + ]; + if (key == 'construction') { + return [ + FeatureLayer.withFeatureTable( + ServiceFeatureTable.withUri( + Uri.parse( + 'https://admin-enterprise-gis.ucsd.edu/server/rest/services/Construction/Construction_Alert_Approved/MapServer/2', + ), + ), + ), + FeatureLayer.withFeatureTable( + ServiceFeatureTable.withUri( + Uri.parse( + 'https://admin-enterprise-gis.ucsd.edu/server/rest/services/Construction/Construction_Alert_Approved/MapServer/1', + ), + ), + ), + FeatureLayer.withFeatureTable( + ServiceFeatureTable.withUri( + Uri.parse( + 'https://admin-enterprise-gis.ucsd.edu/server/rest/services/Construction/Construction_Alert_Approved/MapServer/0', + ), + ), + ), + ]; + } + + var isPortalItem = entry.source == 'portalItem' && entry.portalKey != null && entry.itemId != null; + if (isPortalItem) { + final portalUrl = _config?.portals[entry.portalKey!]; + if (portalUrl != null) { + final portalItem = PortalItem.withPortalAndItemId(portal: Portal(Uri.parse(portalUrl)), itemId: entry.itemId!); + try { + await portalItem.load(); + if (portalItem.type == PortalItemType.webMap) { + final tempMap = ArcGISMap.withItem(portalItem); + await tempMap.load(); + final layers = tempMap.operationalLayers.toList(); + tempMap.operationalLayers.clear(); // Un-own the layers so they can be added to the main map + return layers; + } else { + return [FeatureLayer.withItem(item: portalItem, layerId: 0)]; + } + } catch (e) { + debugPrint('Portal item load error: $e'); + } + } + } + + var hasSub = entry.hasSublayers; + if (hasSub) return entry.sublayers!.map(_layerFromSublayer).toList(); + return [_layerFromEntry(entry)]; + } + + Layer? _layerFromSublayer(SublayerEntry sub) { + final isUrlSub = sub.source == 'url' && sub.url != null; + if (isUrlSub) { + final isVectorSource = sub.url!.contains('FeatureServer') || RegExp(r'MapServer\/\d+').hasMatch(sub.url!); + return isVectorSource + ? FeatureLayer.withFeatureTable(ServiceFeatureTable.withUri(Uri.parse(sub.url!))) + : ArcGISMapImageLayer.withUri(Uri.parse(sub.url!)); + } + return null; + } + + Layer? _layerFromEntry(LayerEntry entry) { + final isUrlEntry = entry.source == 'url' && entry.url != null; + if (isUrlEntry) { + final isVectorSource = entry.url!.contains('FeatureServer') || RegExp(r'MapServer\/\d+').hasMatch(entry.url!); + return isVectorSource + ? FeatureLayer.withFeatureTable(ServiceFeatureTable.withUri(Uri.parse(entry.url!))) + : ArcGISMapImageLayer.withUri(Uri.parse(entry.url!)); + } + return null; + } + + void _applyLayerSpecialCases(String key, List instances) { + final isCampusDistricts = + key == 'campusDistricts' && instances.isNotEmpty && instances.first is ArcGISMapImageLayer; + if (isCampusDistricts) { + final imageLayer = instances.first as ArcGISMapImageLayer; + for (final sub in imageLayer.mapImageSublayers) { + final isSublayerFour = sub.id == 4; + sub.isVisible = isSublayerFour; + } + } + } + + void _startLayerRefreshTimer(String key, LayerEntry entry) { + final subs = entry.sublayers; + final isSubsNull = subs == null; + if (isSubsNull) return; + + int? capturedIdx; + int? interval; + for (int i = 0; i < subs.length; i++) { + final hasRefresh = subs[i].refreshInterval > 0; + if (hasRefresh) { + capturedIdx = i; + interval = subs[i].refreshInterval; + break; + } + } + final isInvalidRefreshConfig = capturedIdx == null || interval == null; + if (isInvalidRefreshConfig) return; + + final idx = capturedIdx; + final sub = subs[idx]; + + _layerTimers[key] = Timer.periodic(Duration(seconds: interval), (_) async { + final isNotMounted = !mounted; + if (isNotMounted) return; + final instances = _layerInstances[key]; + final isInvalidInstances = instances == null || idx >= instances.length; + if (isInvalidInstances) return; + + final oldLayer = instances[idx]; + final isOldLayerNotNull = oldLayer != null; + if (isOldLayerNotNull) _map.operationalLayers.remove(oldLayer); + + final newLayer = _layerFromSublayer(sub); + instances[idx] = newLayer; + final isNewLayerNotNull = newLayer != null; + if (isNewLayerNotNull) { + _map.operationalLayers.add(newLayer); + try { + await newLayer.load(); + } catch (e) { + debugPrint('Refresh error $key[$idx]: $e'); + } + } + }); + } + + // --------------------------------------------------------------------------- + // Search & Recent History Operations + // --------------------------------------------------------------------------- + + Future _loadRecentSearches() async { + await EsriMapSearchService.loadCachedBuildings(); + final searches = await EsriMapSearchService.loadRecentSearches(); + if (mounted) setState(() => _recentSearches = searches); + } + + void _addToRecentSearches(MapSearchResult result) { + _recentSearches.removeWhere((r) => r.name == result.name && r.source == result.source); + _recentSearches.insert(0, result); + final isExceedingMax = _recentSearches.length > EsriMapSearchService.MAX_RECENT_SEARCHES; + if (isExceedingMax) _recentSearches = _recentSearches.sublist(0, EsriMapSearchService.MAX_RECENT_SEARCHES); + EsriMapSearchService.saveRecentSearches(_recentSearches); + } + + void _removeFromRecentSearches(int index) { + setState(() => _recentSearches.removeAt(index)); + EsriMapSearchService.saveRecentSearches(_recentSearches); + } + + void _clearRecentSearches() { + setState(_recentSearches.clear); + EsriMapSearchService.saveRecentSearches(_recentSearches); + } + + Future _fetchAllPoiClasses() async { + final classes = await EsriMapSearchService.fetchAllPoiClasses(); + if (mounted) setState(() => _allPoiClasses = classes); + } + + void _queueSearch(String query) { + _searchDebounce?.cancel(); + final requestId = ++_searchRequestId; + final trimmedQuery = query.trim(); + if (trimmedQuery.isEmpty) return; + _searchDebounce = Timer(const Duration(milliseconds: 250), () { + _searchDebounce = null; + _performSearch(trimmedQuery, requestId); + }); + } + + void _cancelPendingSearch() { + _searchDebounce?.cancel(); + _searchDebounce = null; + _searchRequestId++; + } + + Future _waitForMinimumSearchLoadingTime(Stopwatch stopwatch) async { + final remaining = _MINIMUM_SEARCH_LOADING_DURATION - stopwatch.elapsed; + if (remaining > Duration.zero) await Future.delayed(remaining); + } + + /// Text search: queries buildings and POIs concurrently. + Future _performSearch(String query, int requestId) async { + final loadingStopwatch = Stopwatch()..start(); + final q = query.toLowerCase(); + final matched = _allPoiClasses.where((c) => c.toLowerCase().contains(q)).toList(); + + for (final cat in _categories) { + final matchesCat = cat.poiClassValue.toLowerCase().contains(q) && !matched.contains(cat.poiClassValue); + if (matchesCat) matched.insert(0, cat.poiClassValue); + } + + setState(() { + _isSearching = true; + _showResults = _showRouteFields; + _showSuggestions = false; + _selectedResult = null; + _matchingPoiClasses = matched; + }); + + var merged = []; + try { + final results = await Future.wait([ + EsriMapSearchService.queryBuildings(query), + EsriMapSearchService.queryPOIs(query), + ]); + merged = [...results[0], ...results[1]]; + } catch (e) { + debugPrint('Search error: $e'); + } + await _waitForMinimumSearchLoadingTime(loadingStopwatch); + final isStale = !mounted || requestId != _searchRequestId; + if (isStale) return; + + if (_showRouteFields) { + setState(() { + _searchResults = merged; + _isSearching = false; + }); + } else { + final userLoc = _getUserLatLng(); + if (userLoc != null) { + merged.sort((a, b) { + final distA = EsriMapSearchService.distanceMeters(userLoc.$1, userLoc.$2, a.latitude, a.longitude); + final distB = EsriMapSearchService.distanceMeters(userLoc.$1, userLoc.$2, b.latitude, b.longitude); + return distA.compareTo(distB); + }); + } else { + merged.sort((a, b) => a.name.compareTo(b.name)); + } + + _plotResultsOnMap(merged); + + setState(() { + _searchResults = []; + _allCategoryResults = merged; + _showCategoryList = merged.isNotEmpty; + _showResults = false; + _activeCategory = null; + _isSearching = false; + }); + + final isSearchEmpty = merged.isEmpty && query.isNotEmpty; + if (isSearchEmpty) + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('No locations found.'))); + } + } + + /// Category search: queries matching locations and plots pins on the map. + Future _performCategorySearch(EsriSearchCategory category) async { + _cancelPendingSearch(); + final loadingStopwatch = Stopwatch()..start(); + final requestId = _searchRequestId; + setState(() { + _isSearching = true; + _showResults = false; + _showSuggestions = false; + _matchingPoiClasses = []; + _selectedResult = null; + _showCategoryList = false; + _activeCategory = category; + _searchController.text = category.label; + }); + _focusNode.unfocus(); + _fromFocusNode.unfocus(); + _toFocusNode.unfocus(); + + try { + var isRec = category.poiClassValue == 'Recreation Facilities'; + var allResults = []; + + if (isRec) { + final baseSearch = EsriMapSearchService.queryPOIsByClass(category.poiClassValue); + final extraSearches = >>[ + EsriMapSearchService.queryBuildings('gym'), + EsriMapSearchService.queryBuildings('rimac'), + EsriMapSearchService.queryBuildings('track'), + EsriMapSearchService.queryBuildings('canyonview'), + EsriMapSearchService.queryBuildings('pool'), + EsriMapSearchService.queryBuildings('natatorium'), + EsriMapSearchService.queryPOIs('park'), + EsriMapSearchService.queryPOIs('beach'), + EsriMapSearchService.queryPOIs('amphitheater'), + EsriMapSearchService.queryPOIs('amphitheatre'), + EsriMapSearchService.queryBuildings('amphitheater'), + EsriMapSearchService.queryBuildings('arena'), + EsriMapSearchService.queryPOIs('field'), + EsriMapSearchService.queryPOIs('court'), + EsriMapSearchService.queryBuildings('fitness'), + EsriMapSearchService.queryBuildings('athletic'), + EsriMapSearchService.queryBuildings('aquatic'), + EsriMapSearchService.queryBuildings('rec'), + EsriMapSearchService.queryBuildings('theater'), + EsriMapSearchService.queryPOIs('theater'), + EsriMapSearchService.queryBuildings('theatre'), + EsriMapSearchService.queryPOIs('theatre'), + EsriMapSearchService.queryBuildings('wellness'), + ]; + + final baseResults = await baseSearch; + final extraResultsLists = await Future.wait(extraSearches); + + final validTerms = [ + 'gym', + 'rimac', + 'track', + 'canyonview', + 'pool', + 'natatorium', + 'park', + 'beach', + 'amphitheater', + 'amphitheatre', + 'arena', + 'field', + 'court', + 'fitness', + 'athletic', + 'aquatic', + 'rec', + 'theater', + 'theatre', + 'wellness', + ]; + + final validExtraResults = extraResultsLists.expand((r) => r).where((r) { + final textLower = '${r.name} ${r.subtitle} ${r.description}'.toLowerCase(); + for (final term in validTerms) { + // Match word boundary to avoid substring matches (e.g. field in Gusfield) + if (RegExp(r'\b' + term).hasMatch(textLower)) return true; + } + return false; + }); + + allResults = [...baseResults, ...validExtraResults]; + } else { + allResults = await EsriMapSearchService.queryPOIsByClass(category.poiClassValue); + } + + // Deduplicate results by name to avoid showing the same place twice + final uniqueNames = {}; + allResults = allResults.where((r) { + if (!uniqueNames.add(r.name)) return false; + + // Filter out false positives for Recreation + if (isRec) { + final textLower = '${r.name} ${r.subtitle} ${r.description}'.toLowerCase(); + final excluded = [ + 'emergency', + 'restroom', + 'parking', + 'call box', + 'office', + 'elevator', + 'atm ', + ' atm', + 'conference', + 'room ', + ' room', + 'reception', + 'director', + 'academic', + 'admin', + 'lecture', + 'institute', + ]; + for (final term in excluded) { + if (textLower.contains(term)) return false; + } + } + return true; + }).toList(); + + await _waitForMinimumSearchLoadingTime(loadingStopwatch); + final isStale = !mounted || requestId != _searchRequestId; + if (isStale) return; + + final userLoc = _getUserLatLng(); + if (userLoc != null) { + allResults.sort((a, b) { + final distA = EsriMapSearchService.distanceMeters(userLoc.$1, userLoc.$2, a.latitude, a.longitude); + final distB = EsriMapSearchService.distanceMeters(userLoc.$1, userLoc.$2, b.latitude, b.longitude); + return distA.compareTo(distB); + }); + _plotResultsOnMap(allResults); + if (allResults.isNotEmpty) { + final closest = allResults.first; + final p = ArcGISPoint(x: closest.longitude, y: closest.latitude, spatialReference: SpatialReference.wgs84); + _showCalloutForGraphic(closest, _graphicsOverlay.graphics.first); + _mapViewController.setViewpointAnimated(Viewpoint.fromCenter(p, scale: 18000)); + } + } else { + allResults.sort((a, b) => a.name.compareTo(b.name)); + _plotResultsOnMap(allResults); + _zoomToResults(allResults); + } + + setState(() { + _allCategoryResults = allResults; + _showCategoryList = allResults.isNotEmpty; + _isSearching = false; + }); + if (allResults.isEmpty) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('No ${category.label.toLowerCase()} locations found.'))); + } + } catch (e) { + debugPrint('Category search error: $e'); + await _waitForMinimumSearchLoadingTime(loadingStopwatch); + final isStale = !mounted || requestId != _searchRequestId; + if (isStale) return; + setState(() { + _mappedResults = []; + _allCategoryResults = []; + _isSearching = false; + }); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text("Couldn't load ${category.label.toLowerCase()} locations."))); + } + } + + Future _performClassSearch(String classValue) async { + final category = EsriSearchCategory( + label: _labelForClass(classValue), + icon: _iconForClass(classValue), + poiClassValue: classValue, + ); + await _performCategorySearch(category); + } + + // --------------------------------------------------------------------------- + // Map Graphics & Pin Plotting + // --------------------------------------------------------------------------- + + void _plotResultsOnMap(List results) { + _dismissCallout(); + _graphicsOverlay.graphics.clear(); + _mappedResults = results; + for (int i = 0; i < results.length; i++) { + final result = results[i]; + final isBuilding = result.source == MapSearchSource.building; + + if (result.footprint is Polygon) { + final footprintGraphic = Graphic( + geometry: result.footprint as Polygon, + symbol: SimpleFillSymbol( + style: SimpleFillSymbolStyle.solid, + color: Colors.blue.withOpacity(0.3), + outline: SimpleLineSymbol(style: SimpleLineSymbolStyle.solid, color: Colors.blue, width: 2), + ), + ); + footprintGraphic.attributes['resultIndex'] = i; + _graphicsOverlay.graphics.add(footprintGraphic); + } + + final point = ArcGISPoint(x: result.longitude, y: result.latitude, spatialReference: SpatialReference.wgs84); + final graphic = Graphic( + geometry: point, + symbol: SimpleMarkerSymbol( + style: SimpleMarkerSymbolStyle.circle, + color: isBuilding ? Colors.blue : Colors.red, + size: 14, + ), + ); + graphic.attributes['resultIndex'] = i; + _graphicsOverlay.graphics.add(graphic); + } + } + + void _zoomToResults(List results) { + final isResultsEmpty = results.isEmpty; + if (isResultsEmpty) return; + + final isSingleResult = results.length == 1; + if (isSingleResult) { + final r = results.first; + _mapViewController.setViewpointAnimated( + Viewpoint.fromCenter( + ArcGISPoint(x: r.longitude, y: r.latitude, spatialReference: SpatialReference.wgs84), + scale: 18000, + ), + ); + return; + } + + // Find the median coordinate to locate the densest cluster, ignoring outliers + final lats = results.map((r) => r.latitude).toList()..sort(); + final lngs = results.map((r) => r.longitude).toList()..sort(); + + final medianLat = lats[lats.length ~/ 2]; + final medianLng = lngs[lngs.length ~/ 2]; + + _mapViewController.setViewpointAnimated( + Viewpoint.fromCenter( + ArcGISPoint(x: medianLng, y: medianLat, spatialReference: SpatialReference.wgs84), + scale: 24000, + ), + ); + } + + /// Dismisses the active map pin callout, if any. + void _dismissCallout() { + _mapViewController.callout.dismiss(); + _graphicsOverlay.clearSelection(); + } + + void _seeAllCategoryResults() { + final isAllCategoryResultsEmpty = _allCategoryResults.isEmpty; + if (isAllCategoryResultsEmpty) return; + _zoomToResults(_allCategoryResults); + } + + void _selectResult(MapSearchResult result) { + _cancelPendingSearch(); + _dismissCallout(); + final isRouteModeActive = _showRouteFields && _activeRouteField != null; + if (isRouteModeActive) { + final isFromActive = _activeRouteField == 'from'; + final isToActive = _activeRouteField == 'to'; + if (isFromActive) { + _fromController.text = result.name; + _fromLatLng = (result.latitude, result.longitude); + _graphicsOverlay.graphics.clear(); + setState(() { + _showResults = false; + _showSuggestions = false; + _mappedResults = []; + _allCategoryResults = []; + _showCategoryList = false; + _activeCategory = null; + }); + _fromFocusNode.unfocus(); + final hasRouteDestination = _routeDestination != null; + if (hasRouteDestination) _solveRoute(_routeDestination!, originLatLng: _fromLatLng); + } else if (isToActive) { + _toController.text = result.name; + _routeDestination = result; + _graphicsOverlay.graphics.clear(); + setState(() { + _selectedResult = result; + _lastSelectedResult = result; + _showResults = false; + _showSuggestions = false; + _mappedResults = []; + _allCategoryResults = []; + _showCategoryList = false; + _activeCategory = null; + }); + _toFocusNode.unfocus(); + _solveRoute(result, originLatLng: _fromLatLng); + } + _addToRecentSearches(result); + return; + } + + _graphicsOverlay.graphics.clear(); + final point = ArcGISPoint(x: result.longitude, y: result.latitude, spatialReference: SpatialReference.wgs84); + final isBuilding = result.source == MapSearchSource.building; + final graphic = Graphic( + geometry: point, + symbol: SimpleMarkerSymbol( + style: SimpleMarkerSymbolStyle.circle, + color: isBuilding ? Colors.blue : Colors.red, + size: 14, + ), + ); + _graphicsOverlay.graphics.add(graphic); + _showCalloutForGraphic(result, graphic); + _mapViewController.setViewpointAnimated(Viewpoint.fromCenter(point, scale: 5000)); + + setState(() { + _showResults = false; + _showSuggestions = false; + _searchController.text = result.name; + _selectedResult = result; + _lastSelectedResult = result; + }); + _focusNode.unfocus(); + _addToRecentSearches(result); + } + + Future _onMapTap(Offset screenPoint) async { + final hasClassMatches = _matchingPoiClasses.isNotEmpty && _searchController.text.isNotEmpty; + final isDropdownVisible = _showSuggestions || _showResults || hasClassMatches; + if (isDropdownVisible) { + setState(() { + _showSuggestions = false; + _showResults = false; + _matchingPoiClasses = []; + }); + _focusNode.unfocus(); + return; + } + + final mapPoint = _mapViewController.screenToLocation(screen: screenPoint); + + // Delay the loading indicator so fast responses (like empty taps) don't flash it + bool isRequestFinished = false; + Future.delayed(const Duration(milliseconds: 200), () { + if (!isRequestFinished && mounted) { + setState(() { + _loadingLocation = mapPoint; + }); + } + }); + + try { + final identifyResult = await _mapViewController.identifyGraphicsOverlay( + _graphicsOverlay, + screenPoint: screenPoint, + tolerance: 12.0, + maximumResults: 1, + ); + + final hasGraphics = identifyResult.graphics.isNotEmpty; + if (hasGraphics) { + isRequestFinished = true; + if (mounted) + setState(() { + _loadingLocation = null; + }); + final tappedGraphic = identifyResult.graphics.first; + final index = tappedGraphic.attributes['resultIndex'] as int?; + final isValidResultIndex = index != null && index >= 0 && index < _mappedResults.length; + if (isValidResultIndex) _handlePinTap(_mappedResults[index], tappedGraphic); + return; + } + } catch (e) { + debugPrint('Identify error: $e'); + } + + if (mapPoint != null) { + final wgs84Point = + GeometryEngine.project(mapPoint, outputSpatialReference: SpatialReference.wgs84) as ArcGISPoint?; + final isValidPoint = wgs84Point != null && !wgs84Point.x.isNaN && !wgs84Point.y.isNaN; + if (isValidPoint) { + final buildingResult = await EsriMapSearchService.identifyBuildingAtCoordinate(wgs84Point.y, wgs84Point.x); + isRequestFinished = true; + if (mounted) + setState(() { + _loadingLocation = null; + }); + if (buildingResult != null) { + if (_allCategoryResults.isNotEmpty) _clearSearch(); + _plotResultsOnMap([buildingResult]); + final hasGraphics = _graphicsOverlay.graphics.isNotEmpty; + if (hasGraphics) _handlePinTap(buildingResult, _graphicsOverlay.graphics.last); + return; + } else { + _dismissCallout(); + } + } + } + + isRequestFinished = true; + if (mounted) + setState(() { + _loadingLocation = null; + }); + _dismissCallout(); + final isSelectedResultNotNull = _selectedResult != null; + if (isSelectedResultNotNull) _closeDetail(); + } + + /// Shows a place name above a plotted map pin without changing the search. + + void _showCalloutForGraphic(MapSearchResult result, Graphic graphic) { + final isBuilding = result.source == MapSearchSource.building; + final detail = (isBuilding && result.address.isNotEmpty) ? result.address : result.subtitle; + final isDark = Theme.of(context).brightness == Brightness.dark; + + final diningProvider = Provider.of(context, listen: false); + final parkingProvider = Provider.of(context, listen: false); + final availabilityProvider = Provider.of(context, listen: false); + + _graphicsOverlay.clearSelection(); + graphic.isSelected = true; + _mapViewController.callout.showCalloutForGeoElement( + graphic, + leaderPosition: LeaderPosition.bottom, + style: CalloutStyle( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + borderColor: isDark ? Colors.white24 : Colors.black26, + borderRadius: 12, + borderWidth: 0.5, + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9), + minWidth: 96, + // Removed maxWidth to allow the callout to size dynamically based on contextual data without clipping + offset: const Offset(0, -10), + ), + contentBuilder: (_, __) => EsriMapCalloutContent( + result: result, + detail: detail, + isDark: isDark, + diningModels: diningProvider.diningModels, + parkingModels: parkingProvider.parkingModels, + availabilityModels: availabilityProvider.availabilityModels, + ), + ); + } + + void _handlePinTap(MapSearchResult result, Graphic graphic) { + if (_showRouteFields) { + _selectResultFromPin(result); + return; + } + + // Always show the callout when a pin is tapped, even if multiple results exist + _showCalloutForGraphic(result, graphic); + + _selectResultFromPin(result, updateSearchText: false); + } + + void _selectResultFromList(MapSearchResult result) { + final index = _mappedResults.indexOf(result); + var isOutOfBounds = index < 0 || index >= _graphicsOverlay.graphics.length; + if (isOutOfBounds) { + _selectResultFromPin(result); + return; + } + _handlePinTap(result, _graphicsOverlay.graphics[index]); + } + + void _selectResultFromPin(MapSearchResult result, {bool updateSearchText = true}) { + if (_showRouteFields) { + final isFromActive = _activeRouteField == 'from'; + if (isFromActive) { + _fromController.text = result.name; + _fromLatLng = (result.latitude, result.longitude); + _graphicsOverlay.graphics.clear(); + setState(() { + _showResults = false; + _showSuggestions = false; + _mappedResults = []; + _allCategoryResults = []; + _showCategoryList = false; + _activeCategory = null; + }); + _fromFocusNode.unfocus(); + final hasRouteDestination = _routeDestination != null; + if (hasRouteDestination) _solveRoute(_routeDestination!, originLatLng: _fromLatLng); + } else { + _toController.text = result.name; + _routeDestination = result; + _graphicsOverlay.graphics.clear(); + setState(() { + _selectedResult = result; + _lastSelectedResult = result; + _showResults = false; + _showSuggestions = false; + _mappedResults = []; + _allCategoryResults = []; + _showCategoryList = false; + _activeCategory = null; + }); + _toFocusNode.unfocus(); + _solveRoute(result, originLatLng: _fromLatLng); + } + _addToRecentSearches(result); + return; + } + + final point = ArcGISPoint(x: result.longitude, y: result.latitude, spatialReference: SpatialReference.wgs84); + _mapViewController.setViewpointAnimated(Viewpoint.fromCenter(point, scale: 5000)); + + setState(() { + _selectedResult = result; + _lastSelectedResult = result; + if (updateSearchText) _searchController.text = result.name; + _showResults = false; + _showSuggestions = false; + _showCategoryList = false; + }); + _focusNode.unfocus(); + _addToRecentSearches(result); + } + + void _closeDetail() { + _dismissCallout(); + final canShowCategoryResults = _allCategoryResults.isNotEmpty && !_showRouteFields && !_hasRoute && !_routeFailed; + if (canShowCategoryResults) { + setState(() { + _selectedResult = null; + _showCategoryList = true; + }); + } else { + _clearSearch(); + } + } + + Future _recenterOnUser() async { + if (_isLocatingUser) return; + setState(() => _isLocatingUser = true); + + try { + final gps = await _getDeviceLocationEfficiently(); + if (gps == null) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Unable to get your current location.'))); + } + return; + } + debugPrint('\x1B[32m[Center on Me] Coordinates obtained: Lat: ${gps.$1}, Lng: ${gps.$2}\x1B[0m'); + if (!mounted) return; + + _ignoreViewpointReset = true; + setState(() => _isLocationActive = true); + + // Do not await the animation, as it can occasionally hang and stall the UI spinner + _mapViewController + .setViewpointAnimated( + Viewpoint.fromCenter( + ArcGISPoint(x: gps.$2, y: gps.$1, spatialReference: SpatialReference.wgs84), + scale: 10000, + ), + ) + .then((_) { + if (mounted) { + setState(() { + _ignoreViewpointReset = false; + }); + } + }); + } catch (e) { + debugPrint('Location error: $e'); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Unable to get your current location.'))); + } finally { + if (mounted) setState(() => _isLocatingUser = false); + } + } + + void _recenterOnView() { + _ignoreViewpointReset = true; + setState(() { + _isRecenterActive = true; + _isLocationActive = false; + }); + Future.delayed(const Duration(milliseconds: 600), () { + if (mounted) { + setState(() { + _ignoreViewpointReset = false; + _isRecenterActive = false; + }); + } + }); + + final isNotDefaultScene = _sceneMode != 'default'; + if (isNotDefaultScene) { + final isBuilding3D = _sceneMode == 'building3d'; + if (isBuilding3D) { + _scene3DKey.currentState?.snapToNorth(); + } else { + _sceneDroneKey.currentState?.snapToNorth(); + } + return; + } + + final isSelectedResultNotNull = _selectedResult != null; + final hasLastResultNoMapped = _lastSelectedResult != null && _mappedResults.isEmpty; + final hasMappedResults = _mappedResults.isNotEmpty; + + if (isSelectedResultNotNull) { + _mapViewController.setViewpointAnimated( + Viewpoint.fromCenter( + ArcGISPoint( + x: _selectedResult!.longitude, + y: _selectedResult!.latitude, + spatialReference: SpatialReference.wgs84, + ), + scale: 5000, + ), + ); + } else if (hasLastResultNoMapped) { + _mapViewController.setViewpointAnimated( + Viewpoint.fromCenter( + ArcGISPoint( + x: _lastSelectedResult!.longitude, + y: _lastSelectedResult!.latitude, + spatialReference: SpatialReference.wgs84, + ), + scale: 5000, + ), + ); + } else if (hasMappedResults) { + _zoomToResults(_mappedResults); + } else { + _mapViewController.setViewpointAnimated( + Viewpoint.fromCenter( + ArcGISPoint(x: -117.2340, y: 32.8801, spatialReference: SpatialReference.wgs84), + scale: 24000, + ), + ); + } + } + + void _snapToNorth() { + final isNotDefaultScene = _sceneMode != 'default'; + if (isNotDefaultScene) { + final isBuilding3D = _sceneMode == 'building3d'; + if (isBuilding3D) { + _scene3DKey.currentState?.snapToNorth(); + } else { + _sceneDroneKey.currentState?.snapToNorth(); + } + return; + } + _mapViewController.setViewpointRotation(angleDegrees: 0); + } + + void _zoomIn() { + if (_sceneMode != 'default') return; // Not implemented for 3D yet + final vp = _mapViewController.getCurrentViewpoint(ViewpointType.centerAndScale); + final isValidPoint = vp != null && vp.targetGeometry is ArcGISPoint; + if (isValidPoint) { + _mapViewController.setViewpointAnimated( + Viewpoint.fromCenter(vp!.targetGeometry as ArcGISPoint, scale: _currentScale / 2.0), + ); + } + } + + void _zoomOut() { + if (_sceneMode != 'default') return; // Not implemented for 3D yet + final vp = _mapViewController.getCurrentViewpoint(ViewpointType.centerAndScale); + final isValidPoint = vp != null && vp.targetGeometry is ArcGISPoint; + if (isValidPoint) { + _mapViewController.setViewpointAnimated( + Viewpoint.fromCenter(vp!.targetGeometry as ArcGISPoint, scale: _currentScale * 2.0), + ); + } + } + + void _clearSearch() { + _cancelPendingSearch(); + _dismissCallout(); + _searchController.clear(); + _fromController.clear(); + _toController.clear(); + _graphicsOverlay.graphics.clear(); + _routeGraphicsOverlay.graphics.clear(); + setState(() { + _hasRoute = false; + _routeFailed = false; + _travelMode = 'Walking'; + _routeTravelTimeMinutes = 0; + _routeManeuvers = []; + _showRouteFields = false; + _searchResults = []; + _matchingPoiClasses = []; + _mappedResults = []; + _allCategoryResults = []; + _showResults = false; + _isSearching = false; + _showSuggestions = false; + _showCategoryList = false; + _activeCategory = null; + _selectedResult = null; + _lastSelectedResult = null; + _activeRouteField = null; + _fromLatLng = null; + _routeDestination = null; + }); + } + + void _clearRoute() { + _cancelPendingSearch(); + _dismissCallout(); + _routeGraphicsOverlay.graphics.clear(); + final destination = _selectedResult; + final isDestinationNotNull = destination != null; + if (isDestinationNotNull) { + final point = ArcGISPoint( + x: destination.longitude, + y: destination.latitude, + spatialReference: SpatialReference.wgs84, + ); + final isBuilding = destination.source == MapSearchSource.building; + _graphicsOverlay.graphics.clear(); + _graphicsOverlay.graphics.add( + Graphic( + geometry: point, + symbol: SimpleMarkerSymbol( + style: SimpleMarkerSymbolStyle.circle, + color: isBuilding ? Colors.blue : Colors.red, + size: 14, + ), + ), + ); + _mapViewController.setViewpointAnimated(Viewpoint.fromCenter(point, scale: 5000)); + } + + setState(() { + _isSearching = false; + _hasRoute = false; + _routeFailed = false; + _travelMode = 'Walking'; + _routeTravelTimeMinutes = 0; + _routeManeuvers = []; + _showRouteFields = false; + _activeRouteField = null; + _fromLatLng = null; + _routeDestination = null; + }); + } + + // --------------------------------------------------------------------------- + // Route Navigation Solver + // --------------------------------------------------------------------------- + + Future _solveRoute(MapSearchResult destination, {String? travelMode, (double, double)? originLatLng}) async { + if (!FeatureFlags.MAP_ROUTING_ENABLED) return; + + final mode = travelMode ?? _travelMode; + setState(() { + _isRouting = true; + _routeFailed = false; + _travelMode = mode; + }); + + var userLatLng = originLatLng; + if (userLatLng == null) userLatLng = await _getDeviceLocationEfficiently(); + + final isUserLatLngNull = userLatLng == null; + if (isUserLatLngNull) { + setState(() => _isRouting = false); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please enable location or manually enter starting location'), + duration: Duration(seconds: 3), + ), + ); + } + return; + } + + final routeRes = await EsriMapRouteService.solveRoute( + originLatLng: userLatLng, + destination: destination, + travelMode: mode, + ); + + final isRouteResNull = routeRes == null; + if (!isRouteResNull) { + _routeTravelTimeMinutes = routeRes.travelTimeMinutes; + _routeManeuvers = routeRes.directionManeuvers; + } + + _routeGraphicsOverlay.graphics.clear(); + + if (isRouteResNull) { + final builder = PolylineBuilder(spatialReference: SpatialReference.wgs84); + builder.addPoint(ArcGISPoint(x: userLatLng.$2, y: userLatLng.$1, spatialReference: SpatialReference.wgs84)); + builder.addPoint( + ArcGISPoint(x: destination.longitude, y: destination.latitude, spatialReference: SpatialReference.wgs84), + ); + + _routeGraphicsOverlay.graphics.add( + Graphic( + geometry: builder.toGeometry(), + symbol: SimpleLineSymbol(style: SimpleLineSymbolStyle.dash, color: Colors.blue, width: 3), + ), + ); + } else { + final hasRouteGeometry = routeRes.routeGeometry != null; + if (hasRouteGeometry) { + _routeGraphicsOverlay.graphics.add( + Graphic( + geometry: routeRes.routeGeometry!, + symbol: SimpleLineSymbol(style: SimpleLineSymbolStyle.solid, color: Colors.blue, width: 4), + ), + ); + } + } + + final whiteOutline = SimpleLineSymbol(style: SimpleLineSymbolStyle.solid, color: Colors.white, width: 2); + final destPoint = ArcGISPoint( + x: destination.longitude, + y: destination.latitude, + spatialReference: SpatialReference.wgs84, + ); + _routeGraphicsOverlay.graphics.add( + Graphic( + geometry: destPoint, + symbol: SimpleMarkerSymbol(style: SimpleMarkerSymbolStyle.circle, color: Colors.red, size: 12) + ..outline = whiteOutline, + ), + ); + _routeGraphicsOverlay.graphics.add( + Graphic( + geometry: destPoint, + symbol: TextSymbol(text: 'Destination', color: Colors.black, size: 14) + ..haloColor = Colors.white + ..haloWidth = 2 + ..offsetY = -15, + ), + ); + + final originPoint = ArcGISPoint(x: userLatLng.$2, y: userLatLng.$1, spatialReference: SpatialReference.wgs84); + _routeGraphicsOverlay.graphics.add( + Graphic( + geometry: originPoint, + symbol: SimpleMarkerSymbol(style: SimpleMarkerSymbolStyle.circle, color: Colors.green, size: 12) + ..outline = whiteOutline, + ), + ); + _routeGraphicsOverlay.graphics.add( + Graphic( + geometry: originPoint, + symbol: TextSymbol(text: 'Start', color: Colors.black, size: 14) + ..haloColor = Colors.white + ..haloWidth = 2 + ..offsetY = -15, + ), + ); + + if (isRouteResNull) { + final builder = PolylineBuilder(spatialReference: SpatialReference.wgs84); + builder.addPoint(originPoint); + builder.addPoint(destPoint); + final extent = builder.toGeometry().extent; + final padded = Envelope.fromXY( + xMin: extent.xMin - 0.005, + yMin: extent.yMin - 0.005, + xMax: extent.xMax + 0.005, + yMax: extent.yMax + 0.005, + spatialReference: SpatialReference.wgs84, + ); + _mapViewController.setViewpointAnimated(Viewpoint.fromTargetExtent(padded)); + } else { + final hasPaddedExtent = routeRes.paddedExtent != null; + if (hasPaddedExtent) _mapViewController.setViewpointAnimated(Viewpoint.fromTargetExtent(routeRes.paddedExtent!)); + } + + _graphicsOverlay.graphics.clear(); + _mappedResults = []; + _allCategoryResults = []; + + if (mounted) { + setState(() { + _isRouting = false; + _routeFailed = isRouteResNull; + _hasRoute = !isRouteResNull; + _showRouteFields = true; + _showCategoryList = false; + _activeCategory = null; + _selectedResult = destination; + _lastSelectedResult = destination; + }); + } + } + + // --------------------------------------------------------------------------- + // Helper getters & AI callbacks + // --------------------------------------------------------------------------- + + (double lat, double lng)? _getUserLatLng() { + final pos = _mapViewController.locationDisplay.location?.position; + final isPosNull = pos == null; + if (isPosNull) return null; + final wgs = GeometryEngine.project(pos, outputSpatialReference: SpatialReference.wgs84) as ArcGISPoint?; + final isWgsNull = wgs == null; + if (isWgsNull) return null; + final isWgsNaN = wgs.x.isNaN || wgs.y.isNaN; + if (isWgsNaN) return null; + return (wgs.y, wgs.x); + } + + Envelope? _getViewportEnvelopeWGS84() { + final vp = _mapViewController.getCurrentViewpoint(ViewpointType.boundingGeometry); + final geom = vp?.targetGeometry; + final isGeomNull = geom == null; + if (isGeomNull) return null; + final projected = GeometryEngine.project(geom, outputSpatialReference: SpatialReference.wgs84); + return projected as Envelope?; + } + + Future _saveLocationToHive(double lat, double lng) async { + try { + final box = await Hive.openBox('mapLocationCache'); + await box.put('lat', lat); + await box.put('lng', lng); + } catch (_) {} + } + + Future<(double, double)?> _loadLocationFromHive() async { + try { + final box = await Hive.openBox('mapLocationCache'); + final lat = box.get('lat') as double?; + final lng = box.get('lng') as double?; + if (lat != null && lng != null) return (lat, lng); + } catch (_) {} + return null; + } + + IconData _iconForResult(MapSearchResult result) { + final isBuilding = result.source == MapSearchSource.building; + return isBuilding ? Icons.business : Icons.place; + } + + IconData _iconForClass(String classValue) { + return _categories + .firstWhere( + (c) => c.poiClassValue.toLowerCase() == classValue.toLowerCase(), + orElse: () => const EsriSearchCategory(label: '', icon: Icons.place, poiClassValue: ''), + ) + .icon; + } + + String _labelForClass(String classValue) { + final match = _categories.where((c) => c.poiClassValue.toLowerCase() == classValue.toLowerCase()); + final hasMatch = match.isNotEmpty; + return hasMatch ? match.first.label : classValue; + } + + Future _launchWebsite(String url) async { + final uri = Uri.parse(url); + final canLaunch = await canLaunchUrl(uri); + if (canLaunch) await launchUrl(uri, mode: LaunchMode.externalApplication); + } + + void _onAiLocationSelected(AiSearchResult result) { + _searchController.text = result.name; + final point = ArcGISPoint(x: result.longitude, y: result.latitude, spatialReference: SpatialReference.wgs84); + _graphicsOverlay.graphics.clear(); + _graphicsOverlay.graphics.add( + Graphic( + geometry: point, + symbol: SimpleMarkerSymbol(style: SimpleMarkerSymbolStyle.circle, color: Colors.red, size: 14), + ), + ); + _mapViewController.setViewpointAnimated(Viewpoint.fromCenter(point, scale: 5000)); + final mapResult = MapSearchResult( + name: result.name, + subtitle: result.subtitle, + latitude: result.latitude, + longitude: result.longitude, + source: MapSearchSource.poi, + address: result.address, + ); + setState(() { + _showResults = false; + _showSuggestions = false; + _selectedResult = mapResult; + _lastSelectedResult = mapResult; + }); + _addToRecentSearches(mapResult); + } + + void _onAiRouteRequested(List stops) { + final isStopsEmpty = stops.isEmpty; + if (isStopsEmpty) return; + + final AiSearchResult destination = stops.last; + final hasMultipleStops = stops.length >= 2; + final AiSearchResult? origin = hasMultipleStops ? stops.first : null; + + final destResult = MapSearchResult( + name: destination.name, + subtitle: destination.subtitle, + latitude: destination.latitude, + longitude: destination.longitude, + source: MapSearchSource.poi, + address: destination.address, + ); + + final hasOrigin = origin != null; + if (hasOrigin) { + _fromController.text = origin.name; + _fromLatLng = (origin.latitude, origin.longitude); + } else { + final gps = _getUserLatLng(); + final hasGps = gps != null; + _fromController.text = hasGps ? 'My Location' : ''; + _fromLatLng = gps; + } + + _toController.text = destination.name; + _routeDestination = destResult; + _graphicsOverlay.graphics.clear(); + setState(() { + _showRouteFields = true; + _selectedResult = null; + _mappedResults = []; + _allCategoryResults = []; + _showCategoryList = false; + _activeCategory = null; + }); + _solveRoute(destResult, originLatLng: _fromLatLng); + } + + void _onFocusChanged() { + _hideSearchOverlayWhenUnfocused(); + if (_focusNode.hasFocus) { + _dismissCallout(); + setState(() { + _showLayersPanel = false; + _isTransitLegendMinimized = true; + }); + final isSearchFocusEmpty = _searchController.text.isEmpty; + if (isSearchFocusEmpty) { + setState(() { + _showSuggestions = true; + _showResults = false; + }); + } + } + } + + void _onFromFocusChanged() { + _hideSearchOverlayWhenUnfocused(); + final hasFromFocus = _fromFocusNode.hasFocus; + if (hasFromFocus) { + setState(() { + _showLayersPanel = false; + _isTransitLegendMinimized = true; + _activeRouteField = 'from'; + final isFromEmpty = _fromController.text.isEmpty; + if (isFromEmpty) { + _showSuggestions = true; + _showResults = false; + } + }); + _detailSheetMinimized.value = true; + } + } + + void _onToFocusChanged() { + _hideSearchOverlayWhenUnfocused(); + final hasToFocus = _toFocusNode.hasFocus; + if (hasToFocus) { + setState(() { + _showLayersPanel = false; + _isTransitLegendMinimized = true; + _activeRouteField = 'to'; + final isToEmpty = _toController.text.isEmpty; + if (isToEmpty) { + _showSuggestions = true; + _showResults = false; + } + }); + _detailSheetMinimized.value = true; + } + } + + void _hideSearchOverlayWhenUnfocused() { + var hasFocus = _focusNode.hasFocus || _fromFocusNode.hasFocus || _toFocusNode.hasFocus; + if (hasFocus) return; + setState(() { + _showSuggestions = false; + _showResults = false; + _matchingPoiClasses = []; + }); + } + + void _onMapPointerDown(PointerDownEvent _) { + if (_showLayersPanel) { + setState(() => _showLayersPanel = false); + return; + } + final isCategoryListOpen = _showCategoryList && _selectedResult == null; + if (isCategoryListOpen) { + final isAttached = _categorySheetController.isAttached; + if (isAttached) + _categorySheetController.animateTo(0.15, duration: const Duration(milliseconds: 250), curve: Curves.easeOut); + } + final isSelectedResultOpen = _selectedResult != null; + if (isSelectedResultOpen) _detailSheetMinimized.value = true; + } + + // --------------------------------------------------------------------------- + // Build Method + // --------------------------------------------------------------------------- + + Widget _buildTransitLegend() { + if (_isTransitLegendLoading) { + return Card( + color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.9), + elevation: 4, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + child: const Padding( + padding: EdgeInsets.all(12), + child: SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2)), + ), + ); + } + + if (_transitLegend.isEmpty) return const SizedBox.shrink(); + + return Card( + color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.9), + elevation: 4, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Semantics( + button: true, + label: _isTransitLegendMinimized ? 'Expand transit routes legend' : 'Collapse transit routes legend', + child: InkWell( + borderRadius: BorderRadius.circular(4), + onTap: () => setState(() => _isTransitLegendMinimized = !_isTransitLegendMinimized), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: ExcludeSemantics( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Transit Routes', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)), + const SizedBox(width: 8), + Icon(_isTransitLegendMinimized ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down, size: 18), + ], + ), + ), + ), + ), + ), + if (!_isTransitLegendMinimized) ...[ + const SizedBox(height: 6), + for (final info in _transitLegend) + InkWell( + onTap: () { + final isVisible = _transitRouteVisibility[info.name] ?? true; + _toggleTransitRoute(info.name, !isVisible); + }, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Opacity( + opacity: (_transitRouteVisibility[info.name] ?? true) ? 1.0 : 0.5, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + (_transitRouteVisibility[info.name] ?? true) + ? Icons.check_box + : Icons.check_box_outline_blank, + size: 16, + color: Theme.of(context).brightness == Brightness.dark + ? Colors.grey[400] + : Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + if (_transitLegendSwatches[info.name] != null) + ExcludeSemantics( + child: RawImage(image: _transitLegendSwatches[info.name], width: 16, height: 16), + ), + const SizedBox(width: 8), + Text(info.name, style: const TextStyle(fontSize: 12)), + ], + ), + ), + ), + ), + ], + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + super.build(context); + final isDark = Theme.of(context).brightness == Brightness.dark; + final keyboardVisible = MediaQuery.of(context).viewInsets.bottom > 0; + final shouldShowCatListPanel = _showCategoryList && _allCategoryResults.isNotEmpty; + + final isDefaultScene = _sceneMode == 'default'; + final isBuilding3dScene = _sceneMode == 'building3d'; + final isDroneViewScene = _sceneMode == 'droneView'; + + final indexedStackIndex = isBuilding3dScene ? 1 : (isDroneViewScene ? 2 : 0); + + final shouldShowScaleBar = _sceneMode == 'default' && _selectedResult == null && !shouldShowCatListPanel; + final isFabVisible = + !_hasNetworkError && + !keyboardVisible && + !_showLayersPanel && + _selectedResult == null && + !shouldShowCatListPanel && + !_showSuggestions && + !_showResults; + final isLayersPanelVisible = _showLayersPanel && _config != null; + final isSearchEnabledAndDefault = FeatureFlags.MAP_SEARCH_ENABLED && isDefaultScene && !_hasNetworkError; + final hasValidResults = _mappedResults.isNotEmpty && !_hasNetworkError; + + return Scaffold( + body: LayoutBuilder( + builder: (context, constraints) { + return Stack( + children: [ + // Map View Stack (2D Map View vs 3D Scene View) + Semantics( + sortKey: const OrdinalSortKey(3.0), + child: Column( + children: [ + Expanded( + child: _hasNetworkError + ? Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const ExcludeSemantics(child: Icon(Icons.wifi_off, size: 48, color: Colors.grey)), + const SizedBox(height: 16), + const Text('Network error. Please try again.', style: TextStyle(fontSize: 16)), + const SizedBox(height: 16), + ElevatedButton(onPressed: _fetchConfigThenInit, child: const Text('Reload')), + ], + ), + ) + : IndexedStack( + index: indexedStackIndex, + children: [ + Semantics( + label: 'Interactive 2D Campus Map', + hint: 'Double tap and hold, then drag to pan. Pinch to zoom.', + child: Listener( + onPointerDown: _onMapPointerDown, + child: ArcGISMapView( + controllerProvider: () => _mapViewController, + onMapViewReady: _onMapViewReady, + onTap: _onMapTap, + ), + ), + ), + Semantics( + label: 'Interactive 3D Campus Scene', + hint: 'Double tap and hold, then drag to pan. Pinch to zoom.', + child: _scene3DWidget ?? const SizedBox.shrink(), + ), + Semantics( + label: 'Interactive 3D Drone Scene', + hint: 'Double tap and hold, then drag to pan. Pinch to zoom.', + child: _sceneDroneWidget ?? const SizedBox.shrink(), + ), + ], + ), + ), + ], + ), + ), + + // Hidden Semantics nodes for Map Pins / Graphics + if (hasValidResults && isDefaultScene) + Builder( + builder: (context) { + final List semanticsNodes = []; + final vp = _mapViewController.getCurrentViewpoint(ViewpointType.boundingGeometry); + final mapSr = vp?.targetGeometry.spatialReference; + + for (int i = 0; i < _mappedResults.length; i++) { + final result = _mappedResults[i]; + var mapPoint = ArcGISPoint( + x: result.longitude, + y: result.latitude, + spatialReference: SpatialReference.wgs84, + ); + final hasValidSpatialReference = mapSr != null && mapPoint.spatialReference != null; + if (hasValidSpatialReference) { + try { + final proj = GeometryEngine.project(mapPoint, outputSpatialReference: mapSr); + mapPoint = proj as ArcGISPoint; + } catch (_) {} + } + + final screenPt = _mapViewController.locationToScreen(mapPoint: mapPoint); + // Keep within visible bounds roughly + final isWithinHorizontalBounds = screenPt.dx >= -50 && screenPt.dx <= constraints.maxWidth + 50; + final isWithinVerticalBounds = screenPt.dy >= -50 && screenPt.dy <= constraints.maxHeight + 50; + if (isWithinHorizontalBounds && isWithinVerticalBounds) { + semanticsNodes.add( + Positioned( + left: screenPt.dx - 24, + top: screenPt.dy - 48, + child: Semantics( + label: 'Map pin: ${result.name}', + hint: 'Double tap to view details.', + button: true, + onTap: () { + if (i < _graphicsOverlay.graphics.length) { + _handlePinTap(result, _graphicsOverlay.graphics[i]); + } else { + _selectResultFromPin(result); + } + }, + child: const SizedBox(width: 48, height: 48), + ), + ), + ); + } + } + return Semantics( + sortKey: const OrdinalSortKey(4.0), + child: Stack(children: semanticsNodes), + ); + }, + ), + + // Map controls stay behind search and slide-over panels. + if (isFabVisible) + Positioned( + top: MediaQuery.of(context).padding.top + 68, + right: 16, + child: Semantics( + sortKey: const OrdinalSortKey(5.0), + child: EsriMapFabCluster( + isDark: isDark, + is3D: _sceneMode != 'default', + mapRotation: _mapRotation, + isLocationActive: _isLocationActive, + isRecenterActive: _isRecenterActive, + onShowLayersPanel: () => setState(() => _showLayersPanel = true), + onRecenterOnView: _recenterOnView, + onRecenterOnUser: _recenterOnUser, + onSnapToNorth: _snapToNorth, + onZoomIn: _zoomIn, + onZoomOut: _zoomOut, + ), + ), + ), + + // Bottom-right center-on-me button + if (isFabVisible && _sceneMode == 'default') + Builder( + builder: (context) { + double? screenAngle; + bool isUserVisible = false; + + if (!_isLocationActive) { + try { + final pos = _mapViewController.locationDisplay.location?.position; + final vp = _mapViewController.getCurrentViewpoint(ViewpointType.boundingGeometry); + final geom = vp?.targetGeometry; + if (pos != null && geom != null) { + final projectedPos = GeometryEngine.project( + pos, + outputSpatialReference: geom.spatialReference!, + ); + isUserVisible = GeometryEngine.intersects(geometry1: projectedPos, geometry2: geom); + + if (!isUserVisible) { + final screenPoint = _mapViewController.locationToScreen( + mapPoint: projectedPos as ArcGISPoint, + ); + // FAB center is bottom: 100, right: 16, size: 48x48 -> center is 24px inwards + final fabX = constraints.maxWidth - 16 - 24; + final fabY = constraints.maxHeight - 100 - 24; + + final dx = screenPoint.dx - fabX; + final dy = screenPoint.dy - fabY; + // angle from UP (negative Y) + screenAngle = math.atan2(dx, -dy); + } + } + } catch (_) {} + } + + return Positioned( + bottom: 100, + right: 16, + child: Semantics( + sortKey: const OrdinalSortKey(6.0), + child: EsriMapLocationFab( + isDark: isDark, + isLocationActive: _isLocationActive, + isUserVisible: isUserVisible, + isLoading: _isLocatingUser, + bearingToUser: screenAngle, + mapRotation: _mapRotation, + onRecenterOnUser: _recenterOnUser, + ), + ), + ); + }, + ), + + if (_loadingLocation != null) + Builder( + builder: (context) { + final screenPt = _mapViewController.locationToScreen(mapPoint: _loadingLocation!); + return Positioned( + left: screenPt.dx - 12, + top: screenPt.dy - 12, + child: Semantics( + sortKey: const OrdinalSortKey(7.0), + child: Container( + width: 24, + height: 24, + decoration: BoxDecoration( + color: Theme.of(context).scaffoldBackgroundColor, + shape: BoxShape.circle, + boxShadow: const [BoxShadow(color: Colors.black26, blurRadius: 4, offset: Offset(0, 2))], + ), + padding: const EdgeInsets.all(4), + child: CircularProgressIndicator( + strokeWidth: 2, + color: isDark ? Colors.white : Theme.of(context).primaryColor, + ), + ), + ), + ); + }, + ), + + // Floating top search bar & suggestion panel + if (isSearchEnabledAndDefault) + Positioned( + top: 8, + left: 12, + right: 12, + child: Semantics( + sortKey: const OrdinalSortKey(1.0), + child: Column( + children: [ + EsriMapSearchBar( + config: _config, + showRouteFields: _showRouteFields, + searchController: _searchController, + focusNode: _focusNode, + fromController: _fromController, + fromFocusNode: _fromFocusNode, + toController: _toController, + toFocusNode: _toFocusNode, + showSuggestions: _showSuggestions, + showResults: _showResults, + isSearching: _isSearching, + searchResults: _searchResults, + matchingPoiClasses: _matchingPoiClasses, + onPerformSearch: _queueSearch, + onPerformClassSearch: _performClassSearch, + onSelectResult: _selectResult, + onClearSearch: _clearSearch, + onClearRoute: _clearRoute, + onSwapRouteFields: () { + final tmpText = _fromController.text; + final tmpLatLng = _fromLatLng; + _fromController.text = _toController.text; + _toController.text = tmpText; + setState(() { + final hasRouteDestination = _routeDestination != null; + _fromLatLng = hasRouteDestination + ? (_routeDestination!.latitude, _routeDestination!.longitude) + : null; + final hasTmpLatLng = tmpLatLng != null; + _routeDestination = hasTmpLatLng + ? MapSearchResult( + name: tmpText, + subtitle: '', + latitude: tmpLatLng.$1, + longitude: tmpLatLng.$2, + source: MapSearchSource.building, + ) + : null; + }); + final canSolveRoute = _routeDestination != null && _fromLatLng != null; + if (canSolveRoute) _solveRoute(_routeDestination!, originLatLng: _fromLatLng); + }, + onTapSearchField: () { + final hasSelectedResult = _selectedResult != null; + if (hasSelectedResult) setState(() => _selectedResult = null); + final isSearchTextEmpty = _searchController.text.isEmpty; + if (isSearchTextEmpty) { + setState(() { + _showSuggestions = true; + _showResults = false; + }); + } + }, + onTapFromField: () { + setState(() { + _activeRouteField = 'from'; + _showSuggestions = true; + _showResults = false; + }); + }, + onTapToField: () { + setState(() { + _activeRouteField = 'to'; + _showSuggestions = true; + _showResults = false; + }); + }, + onChangedFromField: (text) { + _fromLatLng = null; + final isLongEnough = text.length >= 3; + final isTextEmpty = text.isEmpty; + if (isLongEnough) { + _queueSearch(text); + } else if (isTextEmpty) { + _cancelPendingSearch(); + setState(() { + _isSearching = false; + _showResults = false; + _showSuggestions = true; + }); + } else { + _cancelPendingSearch(); + setState(() { + _isSearching = false; + _showResults = false; + _showSuggestions = false; + }); + } + }, + onChangedToField: (text) { + final isLongEnough = text.length >= 3; + final isTextEmpty = text.isEmpty; + if (isLongEnough) { + _queueSearch(text); + } else if (isTextEmpty) { + _cancelPendingSearch(); + setState(() { + _isSearching = false; + _showResults = false; + _showSuggestions = true; + }); + } else { + _cancelPendingSearch(); + setState(() { + _isSearching = false; + _showResults = false; + _showSuggestions = false; + }); + } + }, + onClearFromField: () { + _cancelPendingSearch(); + _fromController.clear(); + _fromLatLng = null; + setState(() { + _isSearching = false; + _showResults = false; + _showSuggestions = true; + }); + }, + onClearToField: () { + _cancelPendingSearch(); + _toController.clear(); + setState(() { + _isSearching = false; + _showResults = false; + _showSuggestions = true; + }); + }, + onOpenAiSearch: () => showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (_) => EsriAiSearchSheet( + userLat: _getUserLatLng()?.$1, + userLon: _getUserLatLng()?.$2, + onLocationSelected: _onAiLocationSelected, + onRouteRequested: _onAiRouteRequested, + ), + ), + iconForClass: _iconForClass, + labelForClass: _labelForClass, + iconForResult: _iconForResult, + ), + + // Suggestions panel (Category icons + Recent Search History) + if (_showSuggestions && !_showResults) + Padding( + padding: const EdgeInsets.only(top: 4), + child: EsriMapSuggestionsPanel( + categories: _categories, + recentSearches: _recentSearches, + showRouteFields: _showRouteFields, + activeRouteField: _activeRouteField, + onSelectCurrentLocation: () async { + (double, double)? gps = await _getDeviceLocationEfficiently(); + if (gps == null) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Unable to get your current location.')), + ); + } + return; + } + _fromController.text = 'My Location'; + _fromLatLng = gps; + if (mounted) { + setState(() { + _showSuggestions = false; + _showResults = false; + }); + } + _fromFocusNode.unfocus(); + final hasRouteDestination = _routeDestination != null; + if (hasRouteDestination) _solveRoute(_routeDestination!, originLatLng: _fromLatLng); + }, + onSelectCategory: _performCategorySearch, + onSelectRecent: _selectResult, + onRemoveRecent: _removeFromRecentSearches, + onClearRecent: _clearRecentSearches, + ), + ), + ], + ), + ), + ), + + // Category results list panel + if (shouldShowCatListPanel) + Semantics( + sortKey: const OrdinalSortKey(1.5), + child: EsriMapCategoryListPanel( + key: const Key('category_list_panel'), + controller: _categorySheetController, + activeCategory: _activeCategory, + allCategoryResults: _allCategoryResults, + viewportResults: EsriMapSearchService.filterToViewport( + _allCategoryResults, + _getViewportEnvelopeWGS84(), + ), + userLocation: _getUserLatLng(), + onClearSearch: _clearSearch, + onSeeAllResults: _seeAllCategoryResults, + onSelectResult: _selectResultFromList, + iconForResult: _iconForResult, + ), + ), + + // Dynamic Google Maps-style Scale Bar Indicator + if (shouldShowScaleBar) + Positioned( + bottom: 24, + right: 16, + child: Semantics( + sortKey: const OrdinalSortKey(8.0), + child: EsriMapScaleBar(scale: _currentScale, isDark: isDark), + ), + ), + + // Transit Legend + if (_layerVisible['tritonTransit'] == true && isFabVisible) + Positioned( + bottom: 16, + left: 8, + child: Semantics(sortKey: const OrdinalSortKey(9.0), child: _buildTransitLegend()), + ), + + // Selected Result Detail Slide-over + AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + switchInCurve: Curves.easeOutQuart, + switchOutCurve: Curves.easeInQuart, + transitionBuilder: (child, animation) { + final offsetAnimation = Tween( + begin: const Offset(0.0, 1.0), + end: Offset.zero, + ).animate(animation); + return SlideTransition(position: offsetAnimation, child: child); + }, + child: _selectedResult != null + ? Semantics( + key: ValueKey(_selectedResult!.name), + sortKey: const OrdinalSortKey(1.6), + child: LayoutBuilder( + builder: (context, constraints) => EsriMapDetailSlideOver( + minimizedNotifier: _detailSheetMinimized, + availableHeight: constraints.maxHeight, + result: _selectedResult!, + resultIcon: _iconForResult(_selectedResult!), + isRoutingMode: _isRouting, + hasRoute: _hasRoute, + routeFailed: _routeFailed, + travelMode: _travelMode, + routeTravelTimeMinutes: _routeTravelTimeMinutes, + routeManeuvers: _routeManeuvers, + fromLatLng: _fromLatLng, + onGetDirections: (res) { + final gps = _getUserLatLng(); + final hasGps = gps != null; + _fromController.text = hasGps ? 'My Location' : ''; + _toController.text = res.name; + _routeDestination = res; + _graphicsOverlay.graphics.clear(); + setState(() { + _showRouteFields = true; + _mappedResults = []; + _allCategoryResults = []; + _showCategoryList = false; + _activeCategory = null; + }); + _solveRoute(res); + }, + onTravelModeChanged: (mode) { + final hasSelectedResult = _selectedResult != null; + if (hasSelectedResult) + _solveRoute(_selectedResult!, travelMode: mode, originLatLng: _fromLatLng); + }, + onLaunchWebsite: _launchWebsite, + onClose: _closeDetail, + onClearRoute: _clearRoute, + ), + ), + ) + : const SizedBox.shrink(key: ValueKey('empty_detail')), + ), + + // Basemap & Operational Layer Selector Panel + if (isLayersPanelVisible) ...[ + Positioned.fill( + child: Semantics( + sortKey: const OrdinalSortKey(1.7), + button: true, + label: 'Close map displays menu', + child: GestureDetector( + onTap: () => setState(() => _showLayersPanel = false), + child: Container(color: const Color(0x80000000)), + ), + ), + ), + EsriMapLayersPanel( + config: _config!, + currentBasemapType: _currentBasemapType, + currentSceneKey: _sceneMode, + layerVisible: _layerVisible, + layerLoading: _layerLoading, + hideSceneSwitcher: _selectedResult != null || _showCategoryList, + onSwitchBasemap: _switchBasemap, + onSetSceneMode: _setSceneMode, + onToggleLayer: _toggleLayer, + onClose: () => setState(() => _showLayersPanel = false), + ), + ], + ], + ); + }, + ), + ); + } +} diff --git a/lib/ui/events/event_tile.dart b/lib/ui/events/event_tile.dart index d42fcfd956..c841cce0a1 100644 --- a/lib/ui/events/event_tile.dart +++ b/lib/ui/events/event_tile.dart @@ -139,6 +139,14 @@ Widget _eventImageLoader(String? url) { ), ); }, + errorBuilder: (context, error, stackTrace) { + return Image.asset( + 'assets/images/UCSDMobile_sharp.png', + height: 150, + width: EventTile.TILE_WIDTH, + fit: BoxFit.cover, + ); + }, height: 150, width: EventTile.TILE_WIDTH, fit: BoxFit.cover, diff --git a/lib/ui/map/map.dart b/lib/ui/map/map.dart index bd188dd660..c06aec512d 100644 --- a/lib/ui/map/map.dart +++ b/lib/ui/map/map.dart @@ -1,4 +1,5 @@ import 'dart:async'; + 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'; diff --git a/lib/ui/navigator/bottom.dart b/lib/ui/navigator/bottom.dart index f7cf358e7e..948954ec06 100644 --- a/lib/ui/navigator/bottom.dart +++ b/lib/ui/navigator/bottom.dart @@ -4,7 +4,8 @@ import 'package:campus_mobile_experimental/core/providers/bottom_nav.dart'; import 'package:campus_mobile_experimental/core/wrappers/push_notifications.dart'; import 'package:campus_mobile_experimental/ui/ai_assistant/ai_assistant.dart'; import 'package:campus_mobile_experimental/ui/home/home.dart'; -import 'package:campus_mobile_experimental/ui/map/map.dart' as prefix0; +// import 'package:campus_mobile_experimental/ui/map/map.dart' as prefix0; +import 'package:campus_mobile_experimental/ui/esrimap/esrimap.dart'; import 'package:campus_mobile_experimental/ui/navigator/top.dart'; import 'package:campus_mobile_experimental/ui/notifications/notifications_list_view.dart'; import 'package:campus_mobile_experimental/ui/profile/profile.dart'; @@ -29,7 +30,7 @@ class BottomTabBar extends StatefulWidget { } class _BottomTabBarState extends State { - var currentTab = [Home(), prefix0.Maps(), AIAssistantTab(), NotificationsListView(), Profile()]; + var currentTab = [Home(), EsriMap(), AIAssistantTab(), NotificationsListView(), Profile()]; @override Widget build(BuildContext context) { @@ -42,10 +43,11 @@ class _BottomTabBarState extends State { backgroundColor: provider.currentIndex == 0 ? lightPrimaryColor : theme.scaffoldBackgroundColor, appBar: isAssistantTab ? null - : PreferredSize(preferredSize: Size.fromHeight(57), child: Provider.of(context).appBar), + : PreferredSize(preferredSize: Size.fromHeight(50), child: Provider.of(context).appBar), body: PushNotificationWrapper( child: IndexedStack(index: provider.currentIndex, children: currentTab), ), + bottomNavigationBar: Container( decoration: BoxDecoration( color: theme.bottomNavigationBarTheme.backgroundColor, @@ -135,7 +137,15 @@ class _BottomTabBarState extends State { color: isSelected ? theme.listTileTheme.selectedColor : Colors.transparent, borderRadius: BorderRadius.circular(34), ), - child: Image.asset(iconAsset, width: 34, height: 34, filterQuality: FilterQuality.high), + child: Image.asset( + iconAsset, + width: 34, + height: 34, + filterQuality: FilterQuality.high, + color: isSelected + ? theme.bottomNavigationBarTheme.selectedItemColor + : theme.bottomNavigationBarTheme.unselectedItemColor, + ), ); } diff --git a/lib/ui/profile/cards.dart b/lib/ui/profile/cards.dart index 230eb1d292..52ade7e82b 100644 --- a/lib/ui/profile/cards.dart +++ b/lib/ui/profile/cards.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/app_styles.dart'; import 'package:campus_mobile_experimental/core/providers/cards.dart'; diff --git a/lib/ui/profile/profile.dart b/lib/ui/profile/profile.dart index 880bf6b922..f94bdbc984 100644 --- a/lib/ui/profile/profile.dart +++ b/lib/ui/profile/profile.dart @@ -1,4 +1,5 @@ import 'dart:async'; + import 'package:campus_mobile_experimental/app_constants.dart'; import 'package:campus_mobile_experimental/app_styles.dart'; import 'package:campus_mobile_experimental/core/providers/bottom_nav.dart'; diff --git a/pubspec.lock b/pubspec.lock index cea49646f1..913b933cdd 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -33,6 +33,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.5.1" + arcgis_maps: + dependency: "direct main" + description: + name: arcgis_maps + sha256: "6eda8e19a5580b40c58c39134edfa6e90b649d97298460b31f006457f6fbeaf5" + url: "https://pub.dev" + source: hosted + version: "300.0.0+4935" args: dependency: transitive description: @@ -169,6 +177,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" code_builder: dependency: transitive description: @@ -241,14 +257,22 @@ packages: url: "https://pub.dev" source: hosted version: "0.7.11" + desktop_webview_window: + dependency: transitive + description: + name: desktop_webview_window + sha256: "20c3ac0f0404f72a0ce76f6f729f4dc656c04747f42e0a38d9553855b1d6012e" + url: "https://pub.dev" + source: hosted + version: "0.3.2" device_info_plus: dependency: "direct main" description: name: device_info_plus - sha256: "98f28b42168cc509abc92f88518882fd58061ea372d7999aecc424345c7bff6a" + sha256: b4fed1b2835da9d670d7bed7db79ae2a94b0f5ad6312268158a9b5479abbacdd url: "https://pub.dev" source: hosted - version: "11.5.0" + version: "12.4.0" device_info_plus_platform_interface: dependency: transitive description: @@ -265,6 +289,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.9.0" + dio_cache_interceptor: + dependency: transitive + description: + name: dio_cache_interceptor + sha256: "9472f9f3dcaa384ae68e60606c1d04e6314dea5eab39f18d94ff9b0a300dbbe4" + url: "https://pub.dev" + source: hosted + version: "4.0.7" dio_web_adapter: dependency: transitive description: @@ -281,6 +313,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.1" + drift: + dependency: transitive + description: + name: drift + sha256: "3179e7323b36d1852b42997b92ac72e8abcb61b1d58cfa8c6da9b540ab02a540" + url: "https://pub.dev" + source: hosted + version: "2.35.3" encrypt: dependency: "direct main" description: @@ -548,6 +588,22 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_web_auth_2: + dependency: transitive + description: + name: flutter_web_auth_2 + sha256: a7655829251ee63aae64a748f8512f36670d8eba4657b0055cdf5ef304a9d164 + url: "https://pub.dev" + source: hosted + version: "5.1.0" + flutter_web_auth_2_platform_interface: + dependency: transitive + description: + name: flutter_web_auth_2_platform_interface + sha256: ba0fbba55bffb47242025f96852ad1ffba34bc451568f56ef36e613612baffab + url: "https://pub.dev" + source: hosted + version: "5.0.0" flutter_web_plugins: dependency: transitive description: flutter @@ -561,22 +617,30 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.0" + geoclue: + dependency: transitive + description: + name: geoclue + sha256: c2a998c77474fc57aa00c6baa2928e58f4b267649057a1c76738656e9dbd2a7f + url: "https://pub.dev" + source: hosted + version: "0.1.1" geolocator: dependency: "direct main" description: name: geolocator - sha256: f62bcd90459e63210bbf9c35deb6a51c521f992a78de19a1fe5c11704f9530e2 + sha256: "79939537046c9025be47ec645f35c8090ecadb6fe98eba146a0d25e8c1357516" url: "https://pub.dev" source: hosted - version: "13.0.4" + version: "14.0.2" geolocator_android: dependency: transitive description: name: geolocator_android - sha256: fcb1760a50d7500deca37c9a666785c047139b5f9ee15aa5469fae7dbbe3170d + sha256: "70880ea8f995eb1783896a001e257315cffa9fb84db487825806ff37101b61eb" url: "https://pub.dev" source: hosted - version: "4.6.2" + version: "5.0.4" geolocator_apple: dependency: transitive description: @@ -585,6 +649,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.13" + geolocator_linux: + dependency: transitive + description: + name: geolocator_linux + sha256: d64112a205931926f4363bb6bd48f14cb38e7326833041d170615586cd143797 + url: "https://pub.dev" + source: hosted + version: "0.2.4" geolocator_platform_interface: dependency: transitive description: @@ -689,6 +761,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.2" + gsettings: + dependency: transitive + description: + name: gsettings + sha256: "1b0ce661f5436d2db1e51f3c4295a49849f03d304003a7ba177d01e3a858249c" + url: "https://pub.dev" + source: hosted + version: "0.2.8" gtk: dependency: transitive description: @@ -697,6 +777,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.0" + haptic_feedback: + dependency: transitive + description: + name: haptic_feedback + sha256: c6b7ce370f17142cd6df1ed29add2cf50393aa967d9c5638e6fb7dbeff7414ec + url: "https://pub.dev" + source: hosted + version: "0.6.5" hive: dependency: "direct main" description: @@ -721,6 +809,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.3" + hooks: + dependency: transitive + description: + name: hooks + sha256: "025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e" + url: "https://pub.dev" + source: hosted + version: "1.0.3" html: dependency: transitive description: @@ -737,6 +833,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.5.0" + http_cache_core: + dependency: transitive + description: + name: http_cache_core + sha256: d6de4ca6680e70f4eacd79e073d6a73734eb1da86305409e495adfabf404eddf + url: "https://pub.dev" + source: hosted + version: "1.1.4" + http_cache_drift_store: + dependency: transitive + description: + name: http_cache_drift_store + sha256: "48449b49030b053eee7416643aee89cb1ec6c0d232a97b95a4845611b0bf8d03" + url: "https://pub.dev" + source: hosted + version: "7.0.1" http_multi_server: dependency: transitive description: @@ -825,6 +937,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.5.0" + logger: + dependency: transitive + description: + name: logger + sha256: "2a0dc097e7b01d942475bdd552356db2d0f768b05540bd4b2b53f1840f2239a7" + url: "https://pub.dev" + source: hosted + version: "2.8.0" logging: dependency: transitive description: @@ -881,6 +1001,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.0" + mutex: + dependency: transitive + description: + name: mutex + sha256: "8827da25de792088eb33e572115a5eb0d61d61a3c01acbc8bcbe76ed78f1a1f2" + url: "https://pub.dev" + source: hosted + version: "3.1.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "8aaead321425bd3f03bd5894aa27c8ea6993eab95531da7e59f5d39c6e5708ec" + url: "https://pub.dev" + source: hosted + version: "0.18.0" nested: dependency: transitive description: @@ -909,10 +1045,10 @@ packages: dependency: "direct main" description: name: package_info_plus - sha256: "16eee997588c60225bda0488b6dcfac69280a6b7a3cf02c741895dd370a02968" + sha256: "468c26b4254ab01979fa5e4a98cb343ea3631b9acee6f21028997419a80e1a20" url: "https://pub.dev" source: hosted - version: "8.3.1" + version: "9.0.1" package_info_plus_platform_interface: dependency: transitive description: @@ -993,6 +1129,54 @@ packages: url: "https://pub.dev" source: hosted version: "4.2.5" + permission_handler: + dependency: "direct main" + description: + name: permission_handler + sha256: fe54465bcc62a4564c6e4db337bbaded6c0c0fa6e10487414436d163114784f6 + url: "https://pub.dev" + source: hosted + version: "12.0.3" + permission_handler_android: + dependency: transitive + description: + name: permission_handler_android + sha256: "1e3bc410ca1bf84662104b100eb126e066cb55791b7451307f9708d4007350e6" + url: "https://pub.dev" + source: hosted + version: "13.0.1" + permission_handler_apple: + dependency: transitive + description: + name: permission_handler_apple + sha256: "82d31c9b321c45785ccd73bce9c63af17037116193b4000b998a4363059adb6e" + url: "https://pub.dev" + source: hosted + version: "9.6.5" + permission_handler_html: + dependency: transitive + description: + name: permission_handler_html + sha256: "6ea98b3f17f60d3b527f2647ed2ab4dc0f6bfe25b22cb1c363f5d8f62252f6ac" + url: "https://pub.dev" + source: hosted + version: "0.1.4+1" + permission_handler_platform_interface: + dependency: transitive + description: + name: permission_handler_platform_interface + sha256: ed86a61c190258fdd65de395ea0632822e3415c1faec38eae0c31b479c28a531 + url: "https://pub.dev" + source: hosted + version: "4.4.1" + permission_handler_windows: + dependency: transitive + description: + name: permission_handler_windows + sha256: "210031f00c32d61038fb4175d82dd874a426bfbae2c2af774bd4e5abb5cac755" + url: "https://pub.dev" + source: hosted + version: "0.2.4" petitparser: dependency: transitive description: @@ -1021,10 +1205,10 @@ packages: dependency: "direct main" description: name: pointycastle - sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe" + sha256: "92aa3841d083cc4b0f4709b5c74fd6409a3e6ba833ffc7dc6a8fee096366acf5" url: "https://pub.dev" source: hosted - version: "3.9.1" + version: "4.0.0" pool: dependency: transitive description: @@ -1065,6 +1249,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.2" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" sanitize_html: dependency: transitive description: @@ -1174,6 +1366,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.10.1" + sqlite3: + dependency: transitive + description: + name: sqlite3 + sha256: "4c7fe79840389aaeaf05fd093f795b631b5a98e2bd28d54e555c100f4a9c7a1c" + url: "https://pub.dev" + source: hosted + version: "3.5.2" stack_trace: dependency: transitive description: @@ -1463,6 +1663,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.0" + window_to_front: + dependency: transitive + description: + name: window_to_front + sha256: "14fad8984db4415e2eeb30b04bb77140b180e260d6cb66b26de126a8657a9241" + url: "https://pub.dev" + source: hosted + version: "0.0.4" xdg_directories: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 319133ecf5..eba0bff8e3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -33,11 +33,12 @@ dependencies: intl: ^0.20.2 liquid_progress_indicator_v2: 0.5.0 measured_size: 1.0.0 - geolocator: ^13.0.4 - package_info_plus: ^8.3.1 + geolocator: ^14.0.0 + package_info_plus: ^9.0.0 flutter_markdown: ^0.6.18 flutter_svg: ^2.2.0 percent_indicator: ^4.2.5 + permission_handler: ^12.0.1 pointycastle: ^3.9.0 provider: ^6.1.5+1 shared_preferences: ^2.5.3 @@ -49,20 +50,25 @@ dependencies: git: url: https://github.com/UCSD/wifi_connection.git ref: e0fb416f81daedeabb1eedef22041e67f30f792b - device_info_plus: ^11.5.0 + device_info_plus: ^12.1.0 + arcgis_maps: ^300.0.0 dependency_overrides: value_layout_builder: ^0.5.0 # Fix Flutter 3.32.0 compatibility + pointycastle: ^4.0.0 dev_dependencies: build_runner: 2.4.13 flutter_test: sdk: flutter hive_generator: 1.1.3 flutter: + config: + enable-swift-package-manager: false uses-material-design: true assets: - assets/images/ - assets/images/onboarding/ - assets/images/tgpt/ + - assets/esri_map_assets/ - assets/images/circles/ - .env fonts: diff --git a/scripts/codemagic-ci/Readme.md b/scripts/codemagic-ci/Readme.md index 25937a7db4..5f7b6dd840 100644 --- a/scripts/codemagic-ci/Readme.md +++ b/scripts/codemagic-ci/Readme.md @@ -36,7 +36,17 @@ ## iii. Post-Clone Script -1. Copy and paste the contents of `post-clone.sh` from `campus-mobile/scripts/codemagic-ci` +1. In Codemagic's Workflow Editor, set the Post-clone script to invoke the + checked-in script directly: + + ```sh + sh ./scripts/codemagic-ci/post-clone.sh + ``` + + Invoking the repository file ensures future script changes are used by + Codemagic without copying them into the Workflow Editor again. +2. Save the workflow and confirm the next build log contains + `Start: post-clone.sh` before dependency resolution begins. ## iv. Build for Platforms diff --git a/scripts/codemagic-ci/post-clone.sh b/scripts/codemagic-ci/post-clone.sh index e646b20ca9..e0cb92688a 100644 --- a/scripts/codemagic-ci/post-clone.sh +++ b/scripts/codemagic-ci/post-clone.sh @@ -53,7 +53,7 @@ fi # 7. BUILD_PLATFORM if [ -n "$BUILD_PLATFORM" ]; then - echo "BUILD_PLATFORM: Found" + echo "BUILD_PLATFORM: $BUILD_PLATFORM" else echo "Error: BUILD_PLATFORM not found, exiting." exit 1 @@ -82,4 +82,27 @@ else echo "$BUILD_ENV Environment Build (Branch: $FCI_BRANCH)" > ./release_notes.txt fi +# ArcGIS native iOS frameworks are downloaded outside the Git repository. +# Install them before CocoaPods resolves the local podspec paths in ios/Podfile. +# Normalize the value so both "IOS" and "iOS" select the iOS setup. +BUILD_PLATFORM_NORMALIZED=$(printf '%s' "$BUILD_PLATFORM" | tr '[:lower:]' '[:upper:]') +if [ "$BUILD_PLATFORM_NORMALIZED" = "IOS" ]; then + echo "Installing ArcGIS native SDK for iOS ..." + echo "Repository root: $(pwd)" + flutter pub get + dart run arcgis_maps install + + echo "Verifying ArcGIS CocoaPods podspecs ..." + for podspec in \ + ./arcgis_maps_core/ios/Runtimecore.podspec \ + ./arcgis_maps_core/ios/arcgis_maps_ffi.podspec + do + if [ ! -f "$podspec" ]; then + echo "Error: ArcGIS installation did not create $podspec" + exit 1 + fi + echo "Found: $podspec" + done +fi + echo "End: post-clone.sh" diff --git a/test/core/services/esrimap_basemap_factory_test.dart b/test/core/services/esrimap_basemap_factory_test.dart new file mode 100644 index 0000000000..553f7b708a --- /dev/null +++ b/test/core/services/esrimap_basemap_factory_test.dart @@ -0,0 +1,55 @@ +import 'dart:convert'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_basemaps.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_config.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('EsriMapConfig & Vector Basemaps', () { + test('mapConfig.json parses Living Atlas and UCSD vector tile basemap configurations correctly', () async { + final configString = await rootBundle.loadString('assets/esri_map_assets/mapConfig.json'); + final jsonMap = jsonDecode(configString) as Map; + final config = EsriMapConfig.fromJson(jsonMap); + + // Verify Default basemap includes Living Atlas Light Gray vector base and UCSD campus vector tile + final defaultBasemap = config.basemaps['defaultMap']; + expect(defaultBasemap, isNotNull); + expect(defaultBasemap!.baseLayers.length, 2); + expect(defaultBasemap.baseLayers.any((l) => l.itemId == '291da5eab3a0412593b66d384379f89f'), isTrue); + expect(defaultBasemap.baseLayers.any((l) => l.itemId == 'e19f33d2c1f44967aef673306c483913'), isTrue); + + // Verify Light basemap includes Living Atlas Light Gray vector base and UCSD campus vector tile + final lightBasemap = config.basemaps['light']; + expect(lightBasemap, isNotNull); + expect(lightBasemap!.baseLayers.length, 2); + expect(lightBasemap.baseLayers.any((l) => l.itemId == '291da5eab3a0412593b66d384379f89f'), isTrue); + expect(lightBasemap.baseLayers.any((l) => l.itemId == '6643ee62af494f5bafe7dfdb8eb3f857'), isTrue); + + // Verify Dark basemap includes Living Atlas Dark Gray vector base and UCSD campus vector tile + final darkBasemap = config.basemaps['dark']; + expect(darkBasemap, isNotNull); + expect(darkBasemap!.baseLayers.length, 2); + expect(darkBasemap.baseLayers.any((l) => l.itemId == '5e9b3685f4c24d8781073dd928ebda50'), isTrue); + expect(darkBasemap.baseLayers.any((l) => l.itemId == '09d7b3934b6c4c2cad8380c04e08c1b1'), isTrue); + + // Verify Satellite basemap uses worldImagery + final satelliteBasemap = config.basemaps['satellite']; + expect(satelliteBasemap, isNotNull); + expect(satelliteBasemap!.baseLayers.any((l) => l.serviceKey == 'worldImagery'), isTrue); + }); + + test('basemapKey and basemapTypeFromKey mapping', () { + expect(basemapKey(BasemapType.defaultMap), 'defaultMap'); + expect(basemapKey(BasemapType.light), 'light'); + expect(basemapKey(BasemapType.dark), 'dark'); + expect(basemapKey(BasemapType.satellite), 'satellite'); + + expect(basemapTypeFromKey('defaultMap'), BasemapType.defaultMap); + expect(basemapTypeFromKey('light'), BasemapType.light); + expect(basemapTypeFromKey('dark'), BasemapType.dark); + expect(basemapTypeFromKey('satellite'), BasemapType.satellite); + }); + }); +} diff --git a/test/ui/esrimap/esrimap_detail_slide_over_test.dart b/test/ui/esrimap/esrimap_detail_slide_over_test.dart new file mode 100644 index 0000000000..ba700b3c94 --- /dev/null +++ b/test/ui/esrimap/esrimap_detail_slide_over_test.dart @@ -0,0 +1,49 @@ +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_detail_slide_over.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('shows route calculation progress', (tester) async { + final minimized = ValueNotifier(false); + addTearDown(minimized.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: EsriMapDetailSlideOver( + minimizedNotifier: minimized, + availableHeight: 800, + result: const MapSearchResult( + name: 'Price Center', + subtitle: 'Building', + latitude: 32.8797, + longitude: -117.2362, + source: MapSearchSource.building, + ), + resultIcon: Icons.business, + isRoutingMode: true, + hasRoute: false, + routeFailed: false, + travelMode: 'Walking', + routeTravelTimeMinutes: 0, + routeManeuvers: const [], + fromLatLng: null, + onGetDirections: (_) {}, + onTravelModeChanged: (_) {}, + onLaunchWebsite: (_) {}, + onClose: () {}, + onClearRoute: () {}, + ), + ), + ), + ); + + expect( + tester.widget(find.byType(CircularProgressIndicator)).semanticsLabel, + 'Calculating route', + ); + expect(find.text('Calculating...'), findsOneWidget); + expect(tester.widget(find.byType(FilledButton)).onPressed, isNull); + }); +} diff --git a/test/ui/esrimap/esrimap_scale_bar_test.dart b/test/ui/esrimap/esrimap_scale_bar_test.dart new file mode 100644 index 0000000000..1d53c55257 --- /dev/null +++ b/test/ui/esrimap/esrimap_scale_bar_test.dart @@ -0,0 +1,78 @@ +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_scale_bar.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('EsriMapScaleBar Widget Tests', () { + testWidgets('renders imperial and metric units when autoFade is false', (tester) async { + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: EsriMapScaleBar(scale: 24000.0, isDark: false, autoFade: false))), + ); + + expect(find.byType(EsriMapScaleBar), findsOneWidget); + expect(find.byType(CustomPaint), findsWidgets); + }); + + testWidgets('renders close-up zoom scale (e.g. 500)', (tester) async { + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: EsriMapScaleBar(scale: 500.0, isDark: false, autoFade: false))), + ); + + expect(find.byType(EsriMapScaleBar), findsOneWidget); + expect(find.text('20 ft'), findsOneWidget); + expect(find.text('5 m'), findsOneWidget); + }); + + testWidgets('fades in on zoom change and fades out after delay', (tester) async { + double currentScale = 24000.0; + + await tester.pumpWidget( + StatefulBuilder( + builder: (context, setState) => MaterialApp( + home: Scaffold( + body: Column( + children: [ + EsriMapScaleBar(scale: currentScale, autoFade: true, fadeDelay: const Duration(milliseconds: 500)), + ElevatedButton(onPressed: () => setState(() => currentScale = 12000.0), child: const Text('Zoom')), + ], + ), + ), + ), + ), + ); + + // Initially opacity is 0.0 + final animatedOpacityFinder = find.byType(AnimatedOpacity); + expect(animatedOpacityFinder, findsOneWidget); + AnimatedOpacity opacityWidget = tester.widget(animatedOpacityFinder); + expect(opacityWidget.opacity, 0.0); + + // Trigger zoom/scale change + await tester.tap(find.text('Zoom')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + + // Now opacity is 1.0 (visible while zooming) + opacityWidget = tester.widget(animatedOpacityFinder); + expect(opacityWidget.opacity, 1.0); + + // Wait for fade delay + await tester.pump(const Duration(milliseconds: 600)); + await tester.pump(const Duration(milliseconds: 300)); + + // Now opacity has returned to 0.0 (faded out when zooming stopped) + opacityWidget = tester.widget(animatedOpacityFinder); + expect(opacityWidget.opacity, 0.0); + }); + + testWidgets('returns SizedBox.shrink when scale is 0 or negative', (tester) async { + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: EsriMapScaleBar(scale: 0.0, isDark: false, autoFade: false))), + ); + + expect(find.text('ft'), findsNothing); + }); + }); +} diff --git a/test/ui/esrimap/esrimap_search_bar_test.dart b/test/ui/esrimap/esrimap_search_bar_test.dart new file mode 100644 index 0000000000..dc6308eb3a --- /dev/null +++ b/test/ui/esrimap/esrimap_search_bar_test.dart @@ -0,0 +1,70 @@ +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_search_bar.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('shows one inline search progress indicator', (tester) async { + final searchController = TextEditingController(text: 'library'); + final fromController = TextEditingController(); + final toController = TextEditingController(); + final focusNode = FocusNode(); + final fromFocusNode = FocusNode(); + final toFocusNode = FocusNode(); + addTearDown(() { + searchController.dispose(); + fromController.dispose(); + toController.dispose(); + focusNode.dispose(); + fromFocusNode.dispose(); + toFocusNode.dispose(); + }); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: EsriMapSearchBar( + config: null, + showRouteFields: false, + searchController: searchController, + focusNode: focusNode, + fromController: fromController, + fromFocusNode: fromFocusNode, + toController: toController, + toFocusNode: toFocusNode, + showSuggestions: false, + showResults: true, + isSearching: true, + searchResults: const [], + matchingPoiClasses: const [], + onPerformSearch: (_) {}, + onPerformClassSearch: (_) {}, + onSelectResult: (_) {}, + onClearSearch: () {}, + onClearRoute: () {}, + onSwapRouteFields: () {}, + onTapSearchField: () {}, + onTapFromField: () {}, + onTapToField: () {}, + onChangedFromField: (_) {}, + onChangedToField: (_) {}, + onClearFromField: () {}, + onClearToField: () {}, + onOpenAiSearch: () {}, + iconForClass: (_) => Icons.category, + labelForClass: (value) => value, + iconForResult: (_) => Icons.place, + ), + ), + ), + ); + + final indicator = tester.widget(find.byType(CircularProgressIndicator)); + final searchField = tester.widget(find.byType(TextField)); + expect(indicator.semanticsLabel, 'Searching'); + expect(indicator.color, searchField.style?.color); + expect(searchField.decoration?.hintText, 'Search buildings, places...'); + expect(searchField.decoration?.hintStyle?.fontSize, searchField.style?.fontSize); + expect(find.byIcon(Icons.search), findsNothing); + expect(find.text('No results found'), findsNothing); + }); +} diff --git a/test/ui/esrimap/esrimap_suggestions_panel_test.dart b/test/ui/esrimap/esrimap_suggestions_panel_test.dart new file mode 100644 index 0000000000..15c524e321 --- /dev/null +++ b/test/ui/esrimap/esrimap_suggestions_panel_test.dart @@ -0,0 +1,72 @@ +import 'package:campus_mobile_experimental/core/models/esri_map_models/esrimap_search_category.dart'; +import 'package:campus_mobile_experimental/core/models/esri_map_models/map_search_result.dart'; +import 'package:campus_mobile_experimental/ui/esrimap/esri_map_widgets/esrimap_suggestions_panel.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('quick search and recent controls invoke their callbacks', (tester) async { + tester.view.physicalSize = const Size(320, 640); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + const category = EsriSearchCategory(label: 'Dining', icon: Icons.restaurant, poiClassValue: 'Dining and Beverage'); + const categories = [ + category, + EsriSearchCategory(label: 'Library', icon: Icons.menu_book, poiClassValue: 'Library'), + EsriSearchCategory(label: 'Parking', icon: Icons.local_parking, poiClassValue: 'Parking'), + EsriSearchCategory(label: 'Recreation', icon: Icons.fitness_center, poiClassValue: 'Recreation Facilities'), + ]; + const recent = MapSearchResult( + name: 'Starbucks', + subtitle: 'Dining and Beverage', + latitude: 32.880184, + longitude: -117.23642, + source: MapSearchSource.poi, + ); + EsriSearchCategory? selectedCategory; + MapSearchResult? selectedRecent; + int? removedIndex; + var clearCount = 0; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: EsriMapSuggestionsPanel( + categories: categories, + recentSearches: const [recent], + showRouteFields: false, + activeRouteField: null, + onSelectCurrentLocation: () {}, + onSelectCategory: (value) => selectedCategory = value, + onSelectRecent: (value) => selectedRecent = value, + onRemoveRecent: (index) => removedIndex = index, + onClearRecent: () => clearCount++, + ), + ), + ), + ); + + await tester.tap(find.byTooltip('Search Dining')); + expect(selectedCategory, same(category)); + expect( + find.byWidgetPredicate((widget) => widget is ListView && widget.scrollDirection == Axis.horizontal), + findsNothing, + ); + expect( + tester.getRect(find.byTooltip('Search Recreation')).right, + lessThanOrEqualTo(tester.getRect(find.byType(Scaffold)).right), + ); + + await tester.ensureVisible(find.text('Starbucks')); + await tester.tap(find.text('Starbucks')); + expect(selectedRecent, same(recent)); + + await tester.tap(find.byTooltip('Remove Starbucks from recents')); + expect(removedIndex, 0); + + await tester.tap(find.text('Clear')); + expect(clearCount, 1); + }); +} diff --git a/test_geom.dart b/test_geom.dart new file mode 100644 index 0000000000..f409898ac1 --- /dev/null +++ b/test_geom.dart @@ -0,0 +1 @@ +import 'package:arcgis_maps/arcgis_maps.dart'; void main() { print(Geometry.fromJsonString); }