dawarich/app/javascript/controllers/maps_v2_controller.js

1376 lines
40 KiB
JavaScript
Raw Normal View History

2025-11-16 06:45:26 -05:00
import { Controller } from '@hotwired/stimulus'
import maplibregl from 'maplibre-gl'
import { ApiClient } from 'maps_v2/services/api_client'
2025-11-20 16:36:58 -05:00
import { SettingsManager } from 'maps_v2/utils/settings_manager'
2025-11-26 15:07:12 -05:00
import { SearchManager } from 'maps_v2/utils/search_manager'
2025-11-20 18:10:08 -05:00
import { Toast } from 'maps_v2/components/toast'
2025-11-25 14:27:18 -05:00
import { performanceMonitor } from 'maps_v2/utils/performance_monitor'
import { CleanupHelper } from 'maps_v2/utils/cleanup_helper'
import { getMapStyle } from 'maps_v2/utils/style_manager'
import { LayerManager } from './maps_v2/layer_manager'
import { DataLoader } from './maps_v2/data_loader'
import { EventHandlers } from './maps_v2/event_handlers'
import { FilterManager } from './maps_v2/filter_manager'
import { DateManager } from './maps_v2/date_manager'
import { lazyLoader } from 'maps_v2/utils/lazy_loader'
2025-11-16 06:45:26 -05:00
/**
* Main map controller for Maps V2
* Coordinates between different managers and handles UI interactions
2025-11-16 06:45:26 -05:00
*/
export default class extends Controller {
static values = {
apiKey: String,
startDate: String,
endDate: String
}
2025-11-26 13:40:12 -05:00
static targets = [
'container',
'loading',
'loadingText',
'monthSelect',
'clusterToggle',
'settingsPanel',
'visitsSearch',
'routeOpacityRange',
'placesFilters',
'enableAllPlaceTagsToggle',
2025-11-26 13:40:12 -05:00
'fogRadiusValue',
'fogThresholdValue',
'metersBetweenValue',
'minutesBetweenValue',
2025-11-26 15:07:12 -05:00
// Search
'searchInput',
'searchResults',
2025-11-26 13:40:12 -05:00
// Layer toggles
'pointsToggle',
'routesToggle',
'heatmapToggle',
'visitsToggle',
'photosToggle',
'areasToggle',
// 'tracksToggle',
'placesToggle',
2025-11-26 13:40:12 -05:00
'fogToggle',
2025-11-26 15:43:59 -05:00
'scratchToggle',
// Speed-colored routes
'routesOptions',
'speedColoredToggle',
'speedColorScaleContainer',
'speedColorScaleInput'
2025-11-26 13:40:12 -05:00
]
2025-11-16 06:45:26 -05:00
2025-11-25 14:27:18 -05:00
async connect() {
this.cleanup = new CleanupHelper()
// Initialize settings manager with API key for backend sync
SettingsManager.initialize(this.apiKeyValue)
// Sync settings from backend (will fall back to localStorage if needed)
await this.loadSettings()
2025-11-26 13:40:12 -05:00
// Sync toggle states with loaded settings
this.syncToggleStates()
2025-11-25 14:27:18 -05:00
await this.initializeMap()
2025-11-16 06:45:26 -05:00
this.initializeAPI()
// Initialize managers
this.layerManager = new LayerManager(this.map, this.settings, this.api)
this.dataLoader = new DataLoader(this.api, this.apiKeyValue)
this.eventHandlers = new EventHandlers(this.map)
this.filterManager = new FilterManager(this.dataLoader)
2025-11-21 13:46:51 -05:00
2025-11-26 15:07:12 -05:00
// Initialize search manager
this.initializeSearch()
// Listen for visit creation events
this.boundHandleVisitCreated = this.handleVisitCreated.bind(this)
this.cleanup.addEventListener(document, 'visit:created', this.boundHandleVisitCreated)
// Listen for place creation events
this.boundHandlePlaceCreated = this.handlePlaceCreated.bind(this)
this.cleanup.addEventListener(document, 'place:created', this.boundHandlePlaceCreated)
2025-11-21 13:46:51 -05:00
// Format initial dates from backend to match V1 API format
this.startDateValue = DateManager.formatDateForAPI(new Date(this.startDateValue))
this.endDateValue = DateManager.formatDateForAPI(new Date(this.endDateValue))
2025-11-21 13:46:51 -05:00
console.log('[Maps V2] Initial dates:', this.startDateValue, 'to', this.endDateValue)
2025-11-16 06:45:26 -05:00
this.loadMapData()
}
disconnect() {
2025-11-26 15:07:12 -05:00
this.searchManager?.destroy()
2025-11-25 14:27:18 -05:00
this.cleanup.cleanup()
2025-11-16 06:45:26 -05:00
this.map?.remove()
2025-11-25 14:27:18 -05:00
performanceMonitor.logReport()
2025-11-16 06:45:26 -05:00
}
2025-11-20 16:36:58 -05:00
/**
2025-11-25 14:27:18 -05:00
* Load settings (sync from backend and localStorage)
2025-11-20 16:36:58 -05:00
*/
2025-11-25 14:27:18 -05:00
async loadSettings() {
this.settings = await SettingsManager.sync()
console.log('[Maps V2] Settings loaded:', this.settings)
2025-11-20 16:36:58 -05:00
}
2025-11-26 13:40:12 -05:00
/**
* Sync UI controls with loaded settings
*/
syncToggleStates() {
// Sync layer toggles
const toggleMap = {
pointsToggle: 'pointsVisible',
routesToggle: 'routesVisible',
heatmapToggle: 'heatmapEnabled',
visitsToggle: 'visitsEnabled',
photosToggle: 'photosEnabled',
areasToggle: 'areasEnabled',
placesToggle: 'placesEnabled',
2025-11-26 13:40:12 -05:00
// tracksToggle: 'tracksEnabled',
fogToggle: 'fogEnabled',
2025-11-26 15:43:59 -05:00
scratchToggle: 'scratchEnabled',
speedColoredToggle: 'speedColoredRoutesEnabled'
2025-11-26 13:40:12 -05:00
}
Object.entries(toggleMap).forEach(([targetName, settingKey]) => {
const target = `${targetName}Target`
if (this[target]) {
this[target].checked = this.settings[settingKey]
}
})
// Show/hide visits search based on initial toggle state
if (this.hasVisitsToggleTarget && this.hasVisitsSearchTarget) {
if (this.visitsToggleTarget.checked) {
this.visitsSearchTarget.style.display = 'block'
} else {
this.visitsSearchTarget.style.display = 'none'
}
}
// Show/hide places filters based on initial toggle state
if (this.hasPlacesToggleTarget && this.hasPlacesFiltersTarget) {
if (this.placesToggleTarget.checked) {
this.placesFiltersTarget.style.display = 'block'
} else {
this.placesFiltersTarget.style.display = 'none'
}
}
2025-11-26 13:40:12 -05:00
// Sync route opacity slider
if (this.hasRouteOpacityRangeTarget) {
this.routeOpacityRangeTarget.value = (this.settings.routeOpacity || 1.0) * 100
}
// Sync map style dropdown
const mapStyleSelect = this.element.querySelector('select[name="mapStyle"]')
if (mapStyleSelect) {
mapStyleSelect.value = this.settings.mapStyle || 'light'
}
// Sync fog of war settings
const fogRadiusInput = this.element.querySelector('input[name="fogOfWarRadius"]')
if (fogRadiusInput) {
fogRadiusInput.value = this.settings.fogOfWarRadius || 1000
if (this.hasFogRadiusValueTarget) {
this.fogRadiusValueTarget.textContent = `${fogRadiusInput.value}m`
}
}
const fogThresholdInput = this.element.querySelector('input[name="fogOfWarThreshold"]')
if (fogThresholdInput) {
fogThresholdInput.value = this.settings.fogOfWarThreshold || 1
if (this.hasFogThresholdValueTarget) {
this.fogThresholdValueTarget.textContent = fogThresholdInput.value
}
}
// Sync route generation settings
const metersBetweenInput = this.element.querySelector('input[name="metersBetweenRoutes"]')
if (metersBetweenInput) {
metersBetweenInput.value = this.settings.metersBetweenRoutes || 500
if (this.hasMetersBetweenValueTarget) {
this.metersBetweenValueTarget.textContent = `${metersBetweenInput.value}m`
}
}
const minutesBetweenInput = this.element.querySelector('input[name="minutesBetweenRoutes"]')
if (minutesBetweenInput) {
minutesBetweenInput.value = this.settings.minutesBetweenRoutes || 60
if (this.hasMinutesBetweenValueTarget) {
this.minutesBetweenValueTarget.textContent = `${minutesBetweenInput.value}min`
}
}
2025-11-26 15:43:59 -05:00
// Sync speed-colored routes settings
if (this.hasSpeedColorScaleInputTarget) {
const colorScale = this.settings.speedColorScale || '0:#00ff00|15:#00ffff|30:#ff00ff|50:#ffff00|100:#ff3300'
this.speedColorScaleInputTarget.value = colorScale
}
if (this.hasSpeedColorScaleContainerTarget && this.hasSpeedColoredToggleTarget) {
const isEnabled = this.speedColoredToggleTarget.checked
this.speedColorScaleContainerTarget.classList.toggle('hidden', !isEnabled)
}
2025-11-26 13:40:12 -05:00
// Sync points rendering mode radio buttons
const pointsRenderingRadios = this.element.querySelectorAll('input[name="pointsRenderingMode"]')
pointsRenderingRadios.forEach(radio => {
radio.checked = radio.value === (this.settings.pointsRenderingMode || 'raw')
})
// Sync speed-colored routes toggle
const speedColoredRoutesToggle = this.element.querySelector('input[name="speedColoredRoutes"]')
if (speedColoredRoutesToggle) {
speedColoredRoutesToggle.checked = this.settings.speedColoredRoutes || false
}
console.log('[Maps V2] UI controls synced with settings')
}
2025-11-16 06:45:26 -05:00
/**
* Initialize MapLibre map
*/
2025-11-25 14:27:18 -05:00
async initializeMap() {
// Get map style from local files (async)
const style = await getMapStyle(this.settings.mapStyle)
2025-11-20 16:36:58 -05:00
2025-11-16 06:45:26 -05:00
this.map = new maplibregl.Map({
container: this.containerTarget,
2025-11-25 14:27:18 -05:00
style: style,
2025-11-16 06:45:26 -05:00
center: [0, 0],
zoom: 2
})
// Add navigation controls
this.map.addControl(new maplibregl.NavigationControl(), 'top-right')
}
/**
* Initialize API client
*/
initializeAPI() {
this.api = new ApiClient(this.apiKeyValue)
}
2025-11-26 15:07:12 -05:00
/**
* Initialize location search
*/
initializeSearch() {
if (!this.hasSearchInputTarget || !this.hasSearchResultsTarget) {
console.warn('[Maps V2] Search targets not found, search functionality disabled')
return
}
this.searchManager = new SearchManager(this.map, this.apiKeyValue)
this.searchManager.initialize(this.searchInputTarget, this.searchResultsTarget)
console.log('[Maps V2] Search manager initialized')
}
/**
* Handle visit creation event - reload visits and update layer
*/
async handleVisitCreated(event) {
console.log('[Maps V2] Visit created, reloading visits...', event.detail)
try {
// Fetch updated visits
const visits = await this.api.fetchVisits({
start_at: this.startDateValue,
end_at: this.endDateValue
})
console.log('[Maps V2] Fetched visits:', visits.length)
// Update FilterManager with all visits (for search functionality)
this.filterManager.setAllVisits(visits)
2025-11-26 15:07:12 -05:00
// Convert to GeoJSON
const visitsGeoJSON = this.dataLoader.visitsToGeoJSON(visits)
console.log('[Maps V2] Converted to GeoJSON:', visitsGeoJSON.features.length, 'features')
2025-11-26 15:07:12 -05:00
// Get the visits layer and update it
const visitsLayer = this.layerManager.getLayer('visits')
if (visitsLayer) {
visitsLayer.update(visitsGeoJSON)
console.log('[Maps V2] Visits layer updated successfully')
} else {
console.warn('[Maps V2] Visits layer not found, cannot update')
}
2025-11-26 15:07:12 -05:00
} catch (error) {
console.error('[Maps V2] Failed to reload visits:', error)
}
}
/**
* Handle place creation event - reload places and update layer
*/
async handlePlaceCreated(event) {
console.log('[Maps V2] Place created, reloading places...', event.detail)
try {
// Get currently selected tag filters
const selectedTags = this.getSelectedPlaceTags()
// Fetch updated places with filters
const places = await this.api.fetchPlaces({
tag_ids: selectedTags
})
console.log('[Maps V2] Fetched places:', places.length)
// Convert to GeoJSON
const placesGeoJSON = this.dataLoader.placesToGeoJSON(places)
console.log('[Maps V2] Converted to GeoJSON:', placesGeoJSON.features.length, 'features')
// Get the places layer and update it
const placesLayer = this.layerManager.getLayer('places')
if (placesLayer) {
placesLayer.update(placesGeoJSON)
console.log('[Maps V2] Places layer updated successfully')
} else {
console.warn('[Maps V2] Places layer not found, cannot update')
}
} catch (error) {
console.error('[Maps V2] Failed to reload places:', error)
}
}
/**
* Start create visit mode
* Allows user to click on map to create a new visit
*/
startCreateVisit() {
console.log('[Maps V2] Starting create visit mode')
// Close settings panel
if (this.hasSettingsPanelTarget && this.settingsPanelTarget.classList.contains('open')) {
this.toggleSettings()
}
// Change cursor to crosshair
this.map.getCanvas().style.cursor = 'crosshair'
// Show info message
Toast.info('Click on the map to place a visit')
// Add map click listener
this.handleCreateVisitClick = (e) => {
const { lng, lat } = e.lngLat
this.openVisitCreationModal(lat, lng)
// Reset cursor
this.map.getCanvas().style.cursor = ''
}
this.map.once('click', this.handleCreateVisitClick)
}
/**
* Open visit creation modal
*/
openVisitCreationModal(lat, lng) {
console.log('[Maps V2] Opening visit creation modal', { lat, lng })
// Find the visit creation controller
const modalElement = document.querySelector('[data-controller="visit-creation-v2"]')
if (!modalElement) {
console.error('[Maps V2] Visit creation modal not found')
Toast.error('Visit creation modal not available')
return
}
// Get the controller instance
const controller = this.application.getControllerForElementAndIdentifier(
modalElement,
'visit-creation-v2'
)
if (controller) {
controller.open(lat, lng, this)
} else {
console.error('[Maps V2] Visit creation controller not found')
Toast.error('Visit creation controller not available')
}
}
/**
* Start create place mode
* Allows user to click on map to create a new place
*/
startCreatePlace() {
console.log('[Maps V2] Starting create place mode')
// Close settings panel
if (this.hasSettingsPanelTarget && this.settingsPanelTarget.classList.contains('open')) {
this.toggleSettings()
}
// Change cursor to crosshair
this.map.getCanvas().style.cursor = 'crosshair'
// Show info message
Toast.info('Click on the map to place a place')
// Add map click listener
this.handleCreatePlaceClick = (e) => {
const { lng, lat } = e.lngLat
// Dispatch event for place creation modal (reuse existing controller)
document.dispatchEvent(new CustomEvent('place:create', {
detail: { latitude: lat, longitude: lng }
}))
// Reset cursor
this.map.getCanvas().style.cursor = ''
}
this.map.once('click', this.handleCreatePlaceClick)
}
2025-11-16 06:45:26 -05:00
/**
* Load map data from API
2025-11-16 06:45:26 -05:00
*/
async loadMapData() {
2025-11-25 14:27:18 -05:00
performanceMonitor.mark('load-map-data')
2025-11-16 06:45:26 -05:00
this.showLoading()
try {
// Fetch all map data
const data = await this.dataLoader.fetchMapData(
this.startDateValue,
this.endDateValue,
this.updateLoadingProgress.bind(this)
)
2025-11-20 17:46:06 -05:00
// Store visits for filtering
this.filterManager.setAllVisits(data.visits)
2025-11-21 13:46:51 -05:00
2025-11-20 16:36:58 -05:00
// Add all layers when style is ready
const addAllLayers = async () => {
await this.layerManager.addAllLayers(
data.pointsGeoJSON,
data.routesGeoJSON,
data.visitsGeoJSON,
data.photosGeoJSON,
data.areasGeoJSON,
data.tracksGeoJSON,
data.placesGeoJSON
)
// Setup event handlers
this.layerManager.setupLayerEventHandlers({
handlePointClick: this.eventHandlers.handlePointClick.bind(this.eventHandlers),
handleVisitClick: this.eventHandlers.handleVisitClick.bind(this.eventHandlers),
handlePhotoClick: this.eventHandlers.handlePhotoClick.bind(this.eventHandlers),
handlePlaceClick: this.eventHandlers.handlePlaceClick.bind(this.eventHandlers)
2025-11-20 16:36:58 -05:00
})
}
2025-11-20 17:01:02 -05:00
// Use 'load' event which fires when map is fully initialized
if (this.map.loaded()) {
2025-11-20 16:36:58 -05:00
await addAllLayers()
2025-11-16 06:45:26 -05:00
} else {
2025-11-20 17:01:02 -05:00
this.map.once('load', async () => {
2025-11-20 16:36:58 -05:00
await addAllLayers()
})
2025-11-16 06:45:26 -05:00
}
// Fit map to data bounds
if (data.points.length > 0) {
this.fitMapToBounds(data.pointsGeoJSON)
2025-11-16 06:45:26 -05:00
}
2025-11-20 18:10:08 -05:00
// Show success toast
Toast.success(`Loaded ${data.points.length} location ${data.points.length === 1 ? 'point' : 'points'}`)
2025-11-20 18:10:08 -05:00
2025-11-16 06:45:26 -05:00
} catch (error) {
console.error('Failed to load map data:', error)
2025-11-20 18:10:08 -05:00
Toast.error('Failed to load location data. Please try again.')
2025-11-16 06:45:26 -05:00
} finally {
this.hideLoading()
2025-11-25 14:27:18 -05:00
const duration = performanceMonitor.measure('load-map-data')
console.log(`[Performance] Map data loaded in ${duration}ms`)
2025-11-16 06:45:26 -05:00
}
}
/**
* Fit map to data bounds
*/
fitMapToBounds(geojson) {
const coordinates = geojson.features.map(f => f.geometry.coordinates)
const bounds = coordinates.reduce((bounds, coord) => {
return bounds.extend(coord)
}, new maplibregl.LngLatBounds(coordinates[0], coordinates[0]))
this.map.fitBounds(bounds, {
padding: 50,
maxZoom: 15
})
}
/**
* Month selector changed
*/
monthChanged(event) {
const { startDate, endDate } = DateManager.parseMonthSelector(event.target.value)
this.startDateValue = startDate
this.endDateValue = endDate
2025-11-21 13:46:51 -05:00
console.log('[Maps V2] Date range changed:', this.startDateValue, 'to', this.endDateValue)
2025-11-16 06:45:26 -05:00
// Reload data
this.loadMapData()
}
/**
* Show loading indicator
*/
showLoading() {
this.loadingTarget.classList.remove('hidden')
}
/**
* Hide loading indicator
*/
hideLoading() {
this.loadingTarget.classList.add('hidden')
}
/**
* Update loading progress
*/
updateLoadingProgress({ loaded, totalPages, progress }) {
2025-11-20 16:36:58 -05:00
if (this.hasLoadingTextTarget) {
const percentage = Math.round(progress * 100)
this.loadingTextTarget.textContent = `Loading... ${percentage}%`
}
}
/**
* Toggle layer visibility
*/
toggleLayer(event) {
2025-11-26 13:40:12 -05:00
const element = event.currentTarget
const layerName = element.dataset.layer || event.params?.layer
2025-11-20 16:36:58 -05:00
const visible = this.layerManager.toggleLayer(layerName)
if (visible === null) return
2025-11-20 16:36:58 -05:00
2025-11-26 13:40:12 -05:00
// Update button style (for button-based toggles)
if (element.tagName === 'BUTTON') {
if (visible) {
element.classList.add('btn-primary')
element.classList.remove('btn-outline')
} else {
element.classList.remove('btn-primary')
element.classList.add('btn-outline')
}
}
// Update checkbox state (for checkbox-based toggles)
if (element.tagName === 'INPUT' && element.type === 'checkbox') {
element.checked = visible
2025-11-20 16:36:58 -05:00
}
}
/**
2025-11-26 13:40:12 -05:00
* Toggle points layer visibility
2025-11-20 16:36:58 -05:00
*/
2025-11-26 13:40:12 -05:00
togglePoints(event) {
const element = event.currentTarget
const visible = element.checked
const pointsLayer = this.layerManager.getLayer('points')
2025-11-26 13:40:12 -05:00
if (pointsLayer) {
pointsLayer.toggle(visible)
}
2025-11-20 16:36:58 -05:00
2025-11-26 13:40:12 -05:00
// Save setting
SettingsManager.updateSetting('pointsVisible', visible)
}
2025-11-20 16:36:58 -05:00
2025-11-26 13:40:12 -05:00
/**
* Toggle routes layer visibility
*/
toggleRoutes(event) {
const element = event.currentTarget
const visible = element.checked
2025-11-20 16:36:58 -05:00
2025-11-26 13:40:12 -05:00
const routesLayer = this.layerManager.getLayer('routes')
if (routesLayer) {
routesLayer.toggle(visible)
2025-11-20 16:36:58 -05:00
}
2025-11-26 15:43:59 -05:00
// Show/hide routes options panel
if (this.hasRoutesOptionsTarget) {
this.routesOptionsTarget.style.display = visible ? 'block' : 'none'
}
2025-11-20 16:36:58 -05:00
// Save setting
2025-11-26 13:40:12 -05:00
SettingsManager.updateSetting('routesVisible', visible)
2025-11-20 16:36:58 -05:00
}
/**
* Toggle settings panel
*/
toggleSettings() {
if (this.hasSettingsPanelTarget) {
this.settingsPanelTarget.classList.toggle('open')
}
}
/**
* Update map style from settings
*/
2025-11-25 14:27:18 -05:00
async updateMapStyle(event) {
const styleName = event.target.value
SettingsManager.updateSetting('mapStyle', styleName)
2025-11-20 16:36:58 -05:00
2025-11-25 14:27:18 -05:00
const style = await getMapStyle(styleName)
2025-11-20 16:36:58 -05:00
// Clear layer references
this.layerManager.clearLayerReferences()
2025-11-20 16:36:58 -05:00
2025-11-25 14:27:18 -05:00
this.map.setStyle(style)
2025-11-20 16:36:58 -05:00
// Reload layers after style change
this.map.once('style.load', () => {
console.log('Style loaded, reloading map data')
this.loadMapData()
})
}
/**
* Toggle heatmap visibility
*/
toggleHeatmap(event) {
const enabled = event.target.checked
SettingsManager.updateSetting('heatmapEnabled', enabled)
const heatmapLayer = this.layerManager.getLayer('heatmap')
if (heatmapLayer) {
2025-11-20 16:36:58 -05:00
if (enabled) {
heatmapLayer.show()
2025-11-20 16:36:58 -05:00
} else {
heatmapLayer.hide()
2025-11-20 16:36:58 -05:00
}
}
}
/**
* Reset settings to defaults
*/
resetSettings() {
if (confirm('Reset all settings to defaults? This will reload the page.')) {
SettingsManager.resetToDefaults()
window.location.reload()
}
}
2025-11-26 13:40:12 -05:00
/**
* Update route opacity in real-time
*/
updateRouteOpacity(event) {
const opacity = parseInt(event.target.value) / 100
const routesLayer = this.layerManager.getLayer('routes')
if (routesLayer && this.map.getLayer('routes')) {
this.map.setPaintProperty('routes', 'line-opacity', opacity)
}
// Save setting
SettingsManager.updateSetting('routeOpacity', opacity)
}
/**
* Update fog radius display value
*/
updateFogRadiusDisplay(event) {
if (this.hasFogRadiusValueTarget) {
this.fogRadiusValueTarget.textContent = `${event.target.value}m`
}
}
/**
* Update fog threshold display value
*/
updateFogThresholdDisplay(event) {
if (this.hasFogThresholdValueTarget) {
this.fogThresholdValueTarget.textContent = event.target.value
}
}
/**
* Update meters between routes display value
*/
updateMetersBetweenDisplay(event) {
if (this.hasMetersBetweenValueTarget) {
this.metersBetweenValueTarget.textContent = `${event.target.value}m`
}
}
/**
* Update minutes between routes display value
*/
updateMinutesBetweenDisplay(event) {
if (this.hasMinutesBetweenValueTarget) {
this.minutesBetweenValueTarget.textContent = `${event.target.value}min`
}
}
/**
* Update advanced settings from form submission
*/
async updateAdvancedSettings(event) {
event.preventDefault()
const formData = new FormData(event.target)
const settings = {
routeOpacity: parseFloat(formData.get('routeOpacity')) / 100,
fogOfWarRadius: parseInt(formData.get('fogOfWarRadius')),
fogOfWarThreshold: parseInt(formData.get('fogOfWarThreshold')),
metersBetweenRoutes: parseInt(formData.get('metersBetweenRoutes')),
minutesBetweenRoutes: parseInt(formData.get('minutesBetweenRoutes')),
pointsRenderingMode: formData.get('pointsRenderingMode'),
speedColoredRoutes: formData.get('speedColoredRoutes') === 'on'
}
// Apply settings to current map
await this.applySettingsToMap(settings)
// Save to backend and localStorage
for (const [key, value] of Object.entries(settings)) {
await SettingsManager.updateSetting(key, value)
}
Toast.success('Settings updated successfully')
}
/**
* Apply settings to map without reload
*/
async applySettingsToMap(settings) {
// Update route opacity
if (settings.routeOpacity !== undefined) {
const routesLayer = this.layerManager.getLayer('routes')
if (routesLayer && this.map.getLayer('routes')) {
this.map.setPaintProperty('routes', 'line-opacity', settings.routeOpacity)
}
}
// Update fog of war settings
if (settings.fogOfWarRadius !== undefined || settings.fogOfWarThreshold !== undefined) {
const fogLayer = this.layerManager.getLayer('fog')
if (fogLayer) {
if (settings.fogOfWarRadius) {
fogLayer.clearRadius = settings.fogOfWarRadius
}
// Redraw fog layer
if (fogLayer.visible) {
await fogLayer.update(fogLayer.data)
}
}
}
// For settings that require data reload (points rendering mode, speed-colored routes, etc)
// we need to reload the map data
if (settings.pointsRenderingMode || settings.speedColoredRoutes !== undefined) {
Toast.info('Reloading map data with new settings...')
await this.loadMapData()
}
}
2025-11-20 16:36:58 -05:00
/**
* Toggle visits layer
*/
toggleVisits(event) {
const enabled = event.target.checked
SettingsManager.updateSetting('visitsEnabled', enabled)
const visitsLayer = this.layerManager.getLayer('visits')
if (visitsLayer) {
2025-11-20 16:36:58 -05:00
if (enabled) {
visitsLayer.show()
2025-11-20 16:36:58 -05:00
// Show visits search
if (this.hasVisitsSearchTarget) {
this.visitsSearchTarget.style.display = 'block'
}
} else {
visitsLayer.hide()
2025-11-20 16:36:58 -05:00
// Hide visits search
if (this.hasVisitsSearchTarget) {
this.visitsSearchTarget.style.display = 'none'
}
}
}
}
/**
* Toggle places layer
*/
togglePlaces(event) {
const enabled = event.target.checked
SettingsManager.updateSetting('placesEnabled', enabled)
const placesLayer = this.layerManager.getLayer('places')
if (placesLayer) {
if (enabled) {
placesLayer.show()
// Show places filters
if (this.hasPlacesFiltersTarget) {
this.placesFiltersTarget.style.display = 'block'
}
// Initialize tag filters: enable all tags if no saved selection exists
this.initializePlaceTagFilters()
} else {
placesLayer.hide()
// Hide places filters
if (this.hasPlacesFiltersTarget) {
this.placesFiltersTarget.style.display = 'none'
}
}
}
}
/**
* Initialize place tag filters (enable all by default or restore saved state)
*/
initializePlaceTagFilters() {
const savedFilters = this.settings.placesTagFilters
if (savedFilters && savedFilters.length > 0) {
// Restore saved tag selection
this.restoreSavedTagFilters(savedFilters)
} else {
// Default: enable all tags
this.enableAllTagsInitial()
}
}
/**
* Restore saved tag filters
*/
restoreSavedTagFilters(savedFilters) {
const tagCheckboxes = document.querySelectorAll('input[name="place_tag_ids[]"]')
tagCheckboxes.forEach(checkbox => {
const value = checkbox.value === 'untagged' ? checkbox.value : parseInt(checkbox.value)
const shouldBeChecked = savedFilters.includes(value)
if (checkbox.checked !== shouldBeChecked) {
checkbox.checked = shouldBeChecked
// Update badge styling
const badge = checkbox.nextElementSibling
const color = badge.style.borderColor
if (shouldBeChecked) {
badge.classList.remove('badge-outline')
badge.style.backgroundColor = color
badge.style.color = 'white'
} else {
badge.classList.add('badge-outline')
badge.style.backgroundColor = 'transparent'
badge.style.color = color
}
}
})
// Sync "Enable All Tags" toggle
this.syncEnableAllTagsToggle()
// Load places with restored filters
this.loadPlacesWithTags(savedFilters)
}
/**
* Enable all tags initially
*/
enableAllTagsInitial() {
if (this.hasEnableAllPlaceTagsToggleTarget) {
this.enableAllPlaceTagsToggleTarget.checked = true
}
const tagCheckboxes = document.querySelectorAll('input[name="place_tag_ids[]"]')
const allTagIds = []
tagCheckboxes.forEach(checkbox => {
checkbox.checked = true
// Update badge styling
const badge = checkbox.nextElementSibling
const color = badge.style.borderColor
badge.classList.remove('badge-outline')
badge.style.backgroundColor = color
badge.style.color = 'white'
// Collect tag IDs
const value = checkbox.value === 'untagged' ? checkbox.value : parseInt(checkbox.value)
allTagIds.push(value)
})
// Save to settings
SettingsManager.updateSetting('placesTagFilters', allTagIds)
// Load places with all tags
this.loadPlacesWithTags(allTagIds)
}
/**
* Get selected place tag IDs
*/
getSelectedPlaceTags() {
return Array.from(
document.querySelectorAll('input[name="place_tag_ids[]"]:checked')
).map(cb => {
const value = cb.value
// Keep "untagged" as string, convert others to integers
return value === 'untagged' ? value : parseInt(value)
})
}
/**
* Filter places by selected tags
*/
filterPlacesByTags(event) {
// Update badge styles
const badge = event.target.nextElementSibling
const color = badge.style.borderColor
if (event.target.checked) {
badge.classList.remove('badge-outline')
badge.style.backgroundColor = color
badge.style.color = 'white'
} else {
badge.classList.add('badge-outline')
badge.style.backgroundColor = 'transparent'
badge.style.color = color
}
// Sync "Enable All Tags" toggle state
this.syncEnableAllTagsToggle()
// Get all checked tag checkboxes
const checkedTags = this.getSelectedPlaceTags()
// Save selection to settings
SettingsManager.updateSetting('placesTagFilters', checkedTags)
// Reload places with selected tags (empty array = show NO places)
this.loadPlacesWithTags(checkedTags)
}
/**
* Sync "Enable All Tags" toggle with individual tag states
*/
syncEnableAllTagsToggle() {
if (!this.hasEnableAllPlaceTagsToggleTarget) return
const tagCheckboxes = document.querySelectorAll('input[name="place_tag_ids[]"]')
const allChecked = Array.from(tagCheckboxes).every(cb => cb.checked)
const noneChecked = Array.from(tagCheckboxes).every(cb => !cb.checked)
// Update toggle state without triggering change event
this.enableAllPlaceTagsToggleTarget.checked = allChecked
}
/**
* Load places filtered by tags
*/
async loadPlacesWithTags(tagIds = []) {
try {
let places = []
if (tagIds.length > 0) {
// Fetch places with selected tags
places = await this.api.fetchPlaces({ tag_ids: tagIds })
}
// If tagIds is empty, places remains empty array = show NO places
const placesGeoJSON = this.dataLoader.placesToGeoJSON(places)
const placesLayer = this.layerManager.getLayer('places')
if (placesLayer) {
placesLayer.update(placesGeoJSON)
}
} catch (error) {
console.error('[Maps V2] Failed to load places:', error)
}
}
/**
* Toggle all place tags on/off
*/
toggleAllPlaceTags(event) {
const enableAll = event.target.checked
const tagCheckboxes = document.querySelectorAll('input[name="place_tag_ids[]"]')
tagCheckboxes.forEach(checkbox => {
if (checkbox.checked !== enableAll) {
checkbox.checked = enableAll
// Update badge styling
const badge = checkbox.nextElementSibling
const color = badge.style.borderColor
if (enableAll) {
badge.classList.remove('badge-outline')
badge.style.backgroundColor = color
badge.style.color = 'white'
} else {
badge.classList.add('badge-outline')
badge.style.backgroundColor = 'transparent'
badge.style.color = color
}
}
})
// Get selected tags
const selectedTags = this.getSelectedPlaceTags()
// Save selection to settings
SettingsManager.updateSetting('placesTagFilters', selectedTags)
// Reload places with selected tags
this.loadPlacesWithTags(selectedTags)
}
2025-11-20 16:36:58 -05:00
/**
* Toggle photos layer
*/
togglePhotos(event) {
const enabled = event.target.checked
SettingsManager.updateSetting('photosEnabled', enabled)
const photosLayer = this.layerManager.getLayer('photos')
if (photosLayer) {
2025-11-20 16:36:58 -05:00
if (enabled) {
photosLayer.show()
2025-11-20 16:36:58 -05:00
} else {
photosLayer.hide()
2025-11-20 16:36:58 -05:00
}
}
}
/**
* Search visits
*/
searchVisits(event) {
const searchTerm = event.target.value.toLowerCase()
const visitsLayer = this.layerManager.getLayer('visits')
this.filterManager.filterAndUpdateVisits(
searchTerm,
this.filterManager.getCurrentVisitFilter(),
visitsLayer
)
2025-11-20 16:36:58 -05:00
}
/**
* Filter visits by status
*/
filterVisits(event) {
const filter = event.target.value
this.filterManager.setCurrentVisitFilter(filter)
2025-11-20 16:36:58 -05:00
const searchTerm = document.getElementById('visits-search')?.value.toLowerCase() || ''
const visitsLayer = this.layerManager.getLayer('visits')
this.filterManager.filterAndUpdateVisits(searchTerm, filter, visitsLayer)
2025-11-16 06:45:26 -05:00
}
2025-11-20 17:46:06 -05:00
/**
* Toggle areas layer
*/
toggleAreas(event) {
const enabled = event.target.checked
SettingsManager.updateSetting('areasEnabled', enabled)
const areasLayer = this.layerManager.getLayer('areas')
if (areasLayer) {
2025-11-20 17:46:06 -05:00
if (enabled) {
areasLayer.show()
2025-11-20 17:46:06 -05:00
} else {
areasLayer.hide()
2025-11-20 17:46:06 -05:00
}
}
}
/**
* Toggle tracks layer
*/
toggleTracks(event) {
const enabled = event.target.checked
SettingsManager.updateSetting('tracksEnabled', enabled)
const tracksLayer = this.layerManager.getLayer('tracks')
if (tracksLayer) {
2025-11-20 17:46:06 -05:00
if (enabled) {
tracksLayer.show()
2025-11-20 17:46:06 -05:00
} else {
tracksLayer.hide()
2025-11-20 17:46:06 -05:00
}
}
}
2025-11-20 18:10:08 -05:00
/**
* Toggle fog of war layer
*/
toggleFog(event) {
const enabled = event.target.checked
SettingsManager.updateSetting('fogEnabled', enabled)
const fogLayer = this.layerManager.getLayer('fog')
if (fogLayer) {
fogLayer.toggle(enabled)
2025-11-25 14:27:18 -05:00
} else {
console.warn('Fog layer not yet initialized')
2025-11-20 18:10:08 -05:00
}
}
/**
* Toggle scratch map layer
*/
2025-11-25 14:27:18 -05:00
async toggleScratch(event) {
2025-11-20 18:10:08 -05:00
const enabled = event.target.checked
SettingsManager.updateSetting('scratchEnabled', enabled)
2025-11-25 14:27:18 -05:00
try {
const scratchLayer = this.layerManager.getLayer('scratch')
if (!scratchLayer && enabled) {
2025-11-25 14:27:18 -05:00
// Lazy load scratch layer
const ScratchLayer = await lazyLoader.loadLayer('scratch')
const newScratchLayer = new ScratchLayer(this.map, {
2025-11-25 14:27:18 -05:00
visible: true,
apiClient: this.api
})
const pointsLayer = this.layerManager.getLayer('points')
const pointsData = pointsLayer?.data || { type: 'FeatureCollection', features: [] }
await newScratchLayer.add(pointsData)
this.layerManager.layers.scratchLayer = newScratchLayer
} else if (scratchLayer) {
2025-11-25 14:27:18 -05:00
if (enabled) {
scratchLayer.show()
2025-11-25 14:27:18 -05:00
} else {
scratchLayer.hide()
2025-11-25 14:27:18 -05:00
}
2025-11-20 18:10:08 -05:00
}
2025-11-25 14:27:18 -05:00
} catch (error) {
console.error('Failed to toggle scratch layer:', error)
Toast.error('Failed to load scratch layer')
2025-11-20 18:10:08 -05:00
}
}
2025-11-26 15:43:59 -05:00
/**
* Toggle speed-colored routes
*/
async toggleSpeedColoredRoutes(event) {
const enabled = event.target.checked
SettingsManager.updateSetting('speedColoredRoutesEnabled', enabled)
// Show/hide color scale container
if (this.hasSpeedColorScaleContainerTarget) {
this.speedColorScaleContainerTarget.classList.toggle('hidden', !enabled)
}
// Reload routes with speed colors
await this.reloadRoutes()
}
/**
* Open speed color editor modal
*/
openSpeedColorEditor() {
const currentScale = this.speedColorScaleInputTarget.value || '0:#00ff00|15:#00ffff|30:#ff00ff|50:#ffff00|100:#ff3300'
// Create modal if it doesn't exist
let modal = document.getElementById('speed-color-editor-modal')
if (!modal) {
modal = this.createSpeedColorEditorModal(currentScale)
document.body.appendChild(modal)
} else {
// Update existing modal with current scale
const controller = this.application.getControllerForElementAndIdentifier(modal, 'speed-color-editor')
if (controller) {
controller.colorStopsValue = currentScale
controller.loadColorStops()
}
}
// Show modal
const checkbox = modal.querySelector('.modal-toggle')
if (checkbox) {
checkbox.checked = true
}
}
/**
* Create speed color editor modal element
*/
createSpeedColorEditorModal(currentScale) {
const modal = document.createElement('div')
modal.id = 'speed-color-editor-modal'
modal.setAttribute('data-controller', 'speed-color-editor')
modal.setAttribute('data-speed-color-editor-color-stops-value', currentScale)
modal.setAttribute('data-action', 'speed-color-editor:save->maps-v2#handleSpeedColorSave')
modal.innerHTML = `
<input type="checkbox" id="speed-color-editor-toggle" class="modal-toggle" />
<div class="modal" role="dialog" data-speed-color-editor-target="modal">
<div class="modal-box max-w-2xl">
<h3 class="text-lg font-bold mb-4">Edit Speed Color Gradient</h3>
<div class="space-y-4">
<!-- Gradient Preview -->
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Preview</span>
</label>
<div class="h-12 rounded-lg border-2 border-base-300"
data-speed-color-editor-target="preview"></div>
<label class="label">
<span class="label-text-alt">This gradient will be applied to routes based on speed</span>
</label>
</div>
<!-- Color Stops List -->
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Color Stops</span>
</label>
<div class="space-y-2" data-speed-color-editor-target="stopsList"></div>
</div>
<!-- Add Stop Button -->
<button type="button"
class="btn btn-sm btn-outline w-full"
data-action="click->speed-color-editor#addStop">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
Add Color Stop
</button>
</div>
<div class="modal-action">
<button type="button"
class="btn btn-ghost"
data-action="click->speed-color-editor#resetToDefault">
Reset to Default
</button>
<button type="button"
class="btn"
data-action="click->speed-color-editor#close">
Cancel
</button>
<button type="button"
class="btn btn-primary"
data-action="click->speed-color-editor#save">
Save
</button>
</div>
</div>
<label class="modal-backdrop" for="speed-color-editor-toggle"></label>
</div>
`
return modal
}
/**
* Handle speed color save event from editor
*/
handleSpeedColorSave(event) {
const newScale = event.detail.colorStops
// Save to settings
this.speedColorScaleInputTarget.value = newScale
SettingsManager.updateSetting('speedColorScale', newScale)
// Reload routes if speed colors are enabled
if (this.speedColoredToggleTarget.checked) {
this.reloadRoutes()
}
}
/**
* Reload routes layer
*/
async reloadRoutes() {
this.showLoading('Reloading routes...')
try {
const pointsLayer = this.layerManager.getLayer('points')
const points = pointsLayer?.data?.features?.map(f => ({
latitude: f.geometry.coordinates[1],
longitude: f.geometry.coordinates[0],
timestamp: f.properties.timestamp
})) || []
// Get route generation settings
const distanceThresholdMeters = this.settings.metersBetweenRoutes || 500
const timeThresholdMinutes = this.settings.minutesBetweenRoutes || 60
// Import speed colors utility
const { calculateSpeed, getSpeedColor } = await import('maps_v2/utils/speed_colors')
// Generate routes with speed coloring if enabled
const routesGeoJSON = await this.generateRoutesWithSpeedColors(
points,
{ distanceThresholdMeters, timeThresholdMinutes },
calculateSpeed,
getSpeedColor
)
// Update routes layer
this.layerManager.updateLayer('routes', routesGeoJSON)
} catch (error) {
console.error('Failed to reload routes:', error)
Toast.error('Failed to reload routes')
} finally {
this.hideLoading()
}
}
/**
* Generate routes with speed coloring
*/
async generateRoutesWithSpeedColors(points, options, calculateSpeed, getSpeedColor) {
const { RoutesLayer } = await import('maps_v2/layers/routes_layer')
const useSpeedColors = this.settings.speedColoredRoutesEnabled || false
const speedColorScale = this.settings.speedColorScale || '0:#00ff00|15:#00ffff|30:#ff00ff|50:#ffff00|100:#ff3300'
// Use RoutesLayer static method to generate basic routes
const routesGeoJSON = RoutesLayer.pointsToRoutes(points, options)
if (!useSpeedColors) {
return routesGeoJSON
}
// Add speed colors to route segments
routesGeoJSON.features = routesGeoJSON.features.map((feature, index) => {
const segment = points.slice(
points.findIndex(p => p.timestamp === feature.properties.startTime),
points.findIndex(p => p.timestamp === feature.properties.endTime) + 1
)
if (segment.length >= 2) {
const speed = calculateSpeed(segment[0], segment[segment.length - 1])
const color = getSpeedColor(speed, useSpeedColors, speedColorScale)
feature.properties.speed = speed
feature.properties.color = color
}
return feature
})
return routesGeoJSON
}
2025-11-16 06:45:26 -05:00
}