LuminaWebsite/assets/map/js/controllers/MapController.js
Maaxxs c5213b5736 Karte: replace the tactical map with the interactive map viewer
The Karte page now embeds a standalone viewer (assets/map/) covering all ten
regions - Verteron, Altgard, Elthen, Morheim, Poeta, Ishalgen and the
Reshanta maps - with markers and category filters from interactivemap.app.
map.php loads it in an iframe because its stylesheet restyles body, button
and * globally and would otherwise break the site layout.

The tile, marker and icon data (~230 MB, ~39,000 files) is kept out of Git
and uploaded by FTP; the README explains where it comes from.

Removed with it: own markers and categories, tactic layers, the in-browser
map builder, the tile/stitch/viewer tools, the bundled Leaflet, the four map
tables in schema.sql and the map.manage / map.tactics permissions. Existing
databases keep their old map tables untouched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 06:54:17 +02:00

402 lines
No EOL
13 KiB
JavaScript

/**
* MapController - Main controller for the map viewer application
*/
class MapController {
constructor() {
this.mapData = new MapData();
this.tileService = new TileService();
this.markerService = new MarkerService();
// DOM elements
this.canvas = document.getElementById('map-canvas');
this.mapSelect = document.getElementById('map-select');
this.categoriesList = document.getElementById('categories-list');
this.zoomLevelEl = document.getElementById('zoom-level');
this.loadingOverlay = document.getElementById('loading-overlay');
this.tooltip = document.getElementById('tooltip');
// Initialize view
this.view = new MapView(this.canvas);
this.view.resize();
window.addEventListener('resize', () => {
this.view.resize();
this.render();
});
}
/**
* Initialize the application
*/
async init() {
this.showLoading(true);
try {
// Discover available maps
await this.discoverMaps();
// Load first map by default
if (this.mapData.maps.length > 0) {
const firstMap = this.mapData.maps[0];
this.mapSelect.value = firstMap.slug;
await this.loadMap(firstMap.slug);
}
} catch (e) {
console.error('Failed to initialize:', e);
} finally {
this.showLoading(false);
}
// Setup event listeners
this.setupEventListeners();
}
/**
* Discover available maps from local maps.json file
*/
async discoverMaps() {
try {
const response = await fetch(CONFIG.MAPS_LIST);
if (!response.ok) throw new Error('maps.json not found');
const data = await response.json();
const maps = data.maps || [];
for (const mapEntry of maps) {
this.mapData.addMap({
id: mapEntry.id,
slug: mapEntry.slug,
name: mapEntry.name,
zone: mapEntry.zone
});
}
} catch (e) {
console.warn('Failed to load maps list:', e);
}
// Populate map selector dropdown
this.populateMapSelector();
}
/**
* Populate the map selection dropdown
*/
populateMapSelector() {
const maps = this.mapData.maps;
if (maps.length === 0) {
this.mapSelect.innerHTML = '<option value="">No maps available</option>';
return;
}
// Group by zone
let html = '';
const zones = {};
for (const map of maps) {
if (!zones[map.zone]) {
zones[map.zone] = [];
}
zones[map.zone].push(map);
}
for (const [zoneName, zoneMaps] of Object.entries(zones)) {
html += `<optgroup label="${zoneName}">`;
for (const map of zoneMaps) {
html += `<option value="${map.slug}">${map.name}</option>`;
}
html += '</optgroup>';
}
this.mapSelect.innerHTML = html;
}
/**
* Load a specific map by slug
*/
async loadMap(slug) {
this.showLoading(true);
try {
// Set current map in model
const mapInfo = this.mapData.setCurrentMap(slug);
if (!mapInfo) throw new Error(`Map ${slug} not found`);
// Load tile manifest
await this.tileService.loadManifest(slug);
// Load markers
try {
const markerData = await this.markerService.loadMarkers(slug);
this.mapData.loadMarkers(markerData);
} catch (e) {
console.warn(`No markers found for ${slug}`);
}
// Reset view and render
this.view.resetView();
this.buildCategoryUI();
this.render();
} catch (e) {
console.error('Failed to load map:', e);
} finally {
this.showLoading(false);
}
}
/**
* Build the category filter UI
*/
buildCategoryUI() {
const categories = this.mapData.categories;
if (Object.keys(categories).length === 0) {
this.categoriesList.innerHTML = '<p>No categories available</p>';
return;
}
// Group by group_name
const groups = {};
Object.entries(categories).forEach(([key, cat]) => {
if (!groups[cat.group]) {
groups[cat.group] = [];
}
groups[cat.group].push({ key, ...cat });
});
let html = '';
for (const [groupName, cats] of Object.entries(groups)) {
html += `<div class="category-group">`;
// Group-level toggle checkbox
const allVisible = this.mapData.isGroupFullyVisible(groupName);
const someVisible = this.mapData.isGroupPartiallyVisible(groupName) && !allVisible;
html += `
<div class="category-item group-toggle">
<input type="checkbox" id="group-${groupName}"
${allVisible ? 'checked' : ''} ${someVisible ? 'indeterminate' : ''}>
<label for="group-${groupName}" style="font-weight:bold;">${groupName}</label>
</div>
`;
cats.forEach(cat => {
// Use icon image if available, otherwise fallback to emoji
let iconHtml = '';
if (cat.iconImage) {
const filename = cat.iconImage.split('/').pop();
iconHtml = `<img src="${CONFIG.ICONS_DIR}/${filename}" class="category-icon" alt="">`;
} else {
const symbol = CONFIG.CATEGORY_SYMBOLS[cat.name] || '📍';
iconHtml = `<span>${symbol}</span>`;
}
html += `
<div class="category-item">
<input type="checkbox" id="cat-${cat.key}" checked>
${iconHtml}
<label for="cat-${cat.key}">${cat.name}</label>
<span class="category-count">${cat.count}</span>
</div>
`;
});
html += `</div>`;
}
this.categoriesList.innerHTML = html;
// Attach event listeners to checkboxes
this.attachCategoryListeners();
}
/**
* Attach event listeners to category checkboxes
*/
attachCategoryListeners() {
// Group toggles
document.querySelectorAll('.group-toggle input[type="checkbox"]').forEach(checkbox => {
checkbox.addEventListener('change', (e) => {
const groupName = e.target.id.replace('group-', '');
this.mapData.toggleGroup(groupName, e.target.checked);
// Update individual checkboxes
document.querySelectorAll(`.category-item:not(.group-toggle)`).forEach(item => {
const catCheckbox = item.querySelector('input[type="checkbox"]');
if (catCheckbox) {
const key = catCheckbox.id.replace('cat-', '');
const cat = this.mapData.categories[key];
if (cat && cat.group === groupName) {
catCheckbox.checked = e.target.checked;
}
}
});
this.render();
});
});
// Individual category toggles
document.querySelectorAll('.category-item:not(.group-toggle) input[type="checkbox"]').forEach(checkbox => {
checkbox.addEventListener('change', (e) => {
const key = e.target.id.replace('cat-', '');
this.mapData.toggleCategory(key, e.target.checked);
// Update parent group checkbox state
const cat = this.mapData.categories[key];
if (cat) {
this.updateGroupCheckboxState(cat.group);
}
this.render();
});
});
}
/**
* Update group checkbox state based on child categories
*/
updateGroupCheckboxState(groupName) {
const allVisible = this.mapData.isGroupFullyVisible(groupName);
const someVisible = this.mapData.isGroupPartiallyVisible(groupName) && !allVisible;
const groupCheckbox = document.getElementById(`group-${groupName}`);
if (groupCheckbox) {
groupCheckbox.checked = allVisible;
groupCheckbox.indeterminate = someVisible;
}
}
/**
* Render the map
*/
render() {
this.view.render(this.tileService, this.mapData).then(() => {
// Update zoom indicator
this.zoomLevelEl.textContent = this.view.zoom;
});
}
/**
* Setup all event listeners
*/
setupEventListeners() {
// Map selection change
this.mapSelect.addEventListener('change', (e) => {
const slug = e.target.value;
if (slug) {
this.loadMap(slug);
}
});
// Zoom controls
document.getElementById('btn-zoom-in').addEventListener('click', () => {
if (this.view.zoomIn()) this.render();
});
document.getElementById('btn-zoom-out').addEventListener('click', () => {
if (this.view.zoomOut()) this.render();
});
document.getElementById('btn-reset-view').addEventListener('click', () => {
this.view.resetView();
this.render();
});
// Mouse wheel zoom
this.canvas.addEventListener('wheel', (e) => {
e.preventDefault();
if (e.deltaY < 0) {
if (this.view.zoomIn()) this.render();
} else {
if (this.view.zoomOut()) this.render();
}
});
// Pan with mouse drag
this.canvas.addEventListener('mousedown', (e) => {
this.view.isDragging = true;
this.view.lastMouseX = e.clientX;
this.view.lastMouseY = e.clientY;
});
window.addEventListener('mousemove', (e) => {
if (this.view.isDragging) {
const dx = e.clientX - this.view.lastMouseX;
const dy = e.clientY - this.view.lastMouseY;
this.view.panBy(dx, dy);
this.view.lastMouseX = e.clientX;
this.view.lastMouseY = e.clientY;
this.view.requestRender(this.tileService, this.mapData);
} else {
// Hover detection for tooltips
this.checkHover(e);
}
});
window.addEventListener('mouseup', () => {
this.view.isDragging = false;
});
// Keyboard shortcuts
window.addEventListener('keydown', (e) => {
if (e.key === '+' || e.key === '=') {
if (this.view.zoomIn()) this.render();
} else if (e.key === '-') {
if (this.view.zoomOut()) this.render();
} else if (e.key === '0') {
this.view.resetView();
this.render();
}
});
}
/**
* Check for marker hover and show tooltip
*/
checkHover(e) {
const rect = this.canvas.getBoundingClientRect();
const screenX = e.clientX - rect.left;
const screenY = e.clientY - rect.top;
const nearest = this.view.findNearestMarker(this.mapData, screenX, screenY);
if (nearest) {
this.tooltip.classList.remove('hidden');
this.tooltip.querySelector('.name').textContent =
nearest.iconText || nearest.nt || nearest.name;
this.tooltip.querySelector('.category').textContent =
`${nearest.group_name} / ${nearest.category_name}`;
// Position tooltip near cursor but not off-screen
let tx = e.clientX + 15;
let ty = e.clientY - 10;
if (tx + 300 > window.innerWidth) tx = e.clientX - 315;
if (ty < 0) ty = 10;
this.tooltip.style.left = tx + 'px';
this.tooltip.style.top = ty + 'px';
} else {
this.tooltip.classList.add('hidden');
}
}
/**
* Show/hide loading overlay
*/
showLoading(show) {
if (show) {
this.loadingOverlay.classList.remove('hidden');
} else {
this.loadingOverlay.classList.add('hidden');
}
}
}