LuminaWebsite/assets/map/js/controllers/MapController.js
Maaxxs c4f94bf84a Member feedback: raid input checks and fixed raid points, premades in the raid form, live raid page, Lumina-style dialogs, leadership calendar entries, class-based weapon picker, map and tactics fixes
- Raids: "Max. Spieler" only whole numbers up to groups x 5 (max. 10 groups / 50), gearscore only a number; fixed +1 Lumipunkt per participation, other values only with the new raids.points permission; pick an existing premade per group when creating a raid; unchanged legacy values no longer block editing
- Raid page updates itself every 15 s while visible (raids_live.php, cards rendered by includes/raid_card.php), open editors and confirm dialogs are kept
- Restore takes the new raid_id from the bot (archived messages are now deleted in Discord) and moves settings, attendance and awards; website signups send the server display name
- Premades: dissolve by leadership needs a reason, lead gets DMs on join/assign/decline/remove (source/actor_id sent to the bot), transfer picker skips players who already lead a group, website accept keeps the one-group rule, no commas in names
- Site-wide Lumina dialog (assets/js/confirm-dialog.js) replaces confirm/prompt/alert via data-confirm; error flashes are a dialog you confirm with OK
- Calendar: audience per entry (all / leadership takes part / internal) with the new calendar.leadership permission; day cells list all entries and scroll
- Gear planner: main-hand picker filtered by the set's class, mismatches marked, "keine Klasse" option, link to an external skill/Daevanion plan per set
- Map: correct kisk icons (Elyos on Verteron/Abyss, Altgard fixed), per-map max zoom and bounded panning, German texts, data source note
- Tactics: toolbar as a uniform grid, whole-tactic copy, automatic versions with restore and a 90-day trash, official tactics protected
- Global thin gold scrollbars, readable hover colours, "Sedes Luminis" spelling, patch notes and README, schema version 34

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 16:12:18 +02:00

660 lines
No EOL
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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.mapPicker = document.getElementById('map-picker');
this.mapPickerList = document.getElementById('map-picker-list');
this.mapPickerBtn = document.getElementById('map-picker-btn');
this.mapCurrentName = document.getElementById('map-current-name');
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();
// Zuletzt gewaehlte Karte, sonst die Standardkarte, sonst die erste
if (this.mapData.maps.length > 0) {
let saved = null;
try {
saved = localStorage.getItem('lumina_map');
} catch (e) {
saved = null;
}
const has = slug => this.mapData.maps.some(m => m.slug === slug);
// Ein geteilter Ort (?karte=...) hat Vorrang vor der zuletzt gewaehlten Karte
const linked = this.locations ? this.locations.requestedMap() : null;
const slug = linked || (has(saved) ? saved : (has(CONFIG.DEFAULT_MAP) ? CONFIG.DEFAULT_MAP : this.mapData.maps[0].slug));
await this.loadMap(slug);
if (this.locations) this.locations.applyLink();
}
} 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: CONFIG.MAP_NAMES[mapEntry.slug] || mapEntry.name,
zone: mapEntry.zone
});
}
} catch (e) {
console.warn('Failed to load maps list:', e);
}
// Populate map selector dropdown
this.populateMapSelector();
}
/**
* Kartenauswahl aufbauen: pro Gebiet eine Reihe Karten mit Vorschaubild.
*/
populateMapSelector() {
const maps = this.mapData.maps;
this.mapPickerList.textContent = '';
if (maps.length === 0) {
this.mapCurrentName.textContent = 'Keine Karten';
return;
}
// Nach den Gebieten aus CONFIG.MAP_ZONES ordnen (maps.json kennt keine Gebiete).
const zones = {};
for (const zone of CONFIG.MAP_ZONES) {
const zoneMaps = zone.maps.map(slug => maps.find(m => m.slug === slug)).filter(Boolean);
if (zoneMaps.length) zones[zone.name] = zoneMaps;
}
const assigned = new Set(CONFIG.MAP_ZONES.flatMap(zone => zone.maps));
const rest = maps.filter(m => !assigned.has(m.slug));
if (rest.length) zones['Weitere'] = rest;
for (const [zoneName, zoneMaps] of Object.entries(zones)) {
const section = document.createElement('section');
section.className = 'map-picker-zone';
const heading = document.createElement('h3');
heading.textContent = zoneName;
const grid = document.createElement('div');
grid.className = 'map-picker-grid';
for (const map of zoneMaps) {
const card = document.createElement('button');
card.type = 'button';
card.className = 'map-card';
card.dataset.slug = map.slug;
const img = document.createElement('img');
img.src = `${CONFIG.PREVIEWS_DIR}/${map.slug}.webp`;
img.alt = '';
// Nicht lazy: die zehn kleinen Vorschauen (~300 KB) laden gleich mit, damit sie
// beim Oeffnen der Auswahl sofort da sind.
img.decoding = 'async';
img.onerror = () => img.remove();
const name = document.createElement('span');
name.className = 'map-card-name';
name.textContent = map.name;
card.append(img, name);
if (CONFIG.MAP_UNAVAILABLE.includes(map.slug)) {
card.classList.add('unavailable');
const note = document.createElement('span');
note.className = 'map-card-note';
note.textContent = 'Auf unserem Patch noch nicht verfügbar';
card.appendChild(note);
}
card.addEventListener('click', () => {
this.closeMapPicker();
if (map.slug !== this.mapData.currentMap?.slug) {
this.loadMap(map.slug);
}
});
grid.appendChild(card);
}
section.append(heading, grid);
this.mapPickerList.appendChild(section);
}
}
openMapPicker() {
this.mapPickerList.querySelectorAll('.map-card').forEach(card => {
card.classList.toggle('active', card.dataset.slug === this.mapData.currentMap?.slug);
});
this.mapPicker.classList.remove('hidden');
const active = this.mapPickerList.querySelector('.map-card.active') || this.mapPickerList.querySelector('.map-card');
if (active) active.focus();
}
closeMapPicker() {
this.mapPicker.classList.add('hidden');
this.mapPickerBtn.focus();
}
/**
* 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`);
this.mapCurrentName.textContent = mapInfo.name;
document.getElementById('map-unavailable').classList.toggle('hidden', !CONFIG.MAP_UNAVAILABLE.includes(slug));
try {
localStorage.setItem('lumina_map', slug);
} catch (e) {
// ohne Speicher eben jedes Mal die Standardkarte
}
// Load tile manifest
await this.tileService.loadManifest(slug);
// Nur so weit zoomen, wie es Kacheln gibt (manche Karten enden bei Stufe 5)
this.view.maxZoom = this.tileService.maxZoom(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();
if (this.onMapChanged) this.onMapChanged(slug);
} 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 class="category-empty">Für diese Karte gibt es noch keine Markierungen.</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 => {
// Icon-Grafik, sonst (oder wenn sie nicht laedt, siehe unten) das Emoji der Kategorie
const symbol = CONFIG.CATEGORY_SYMBOLS[cat.name] || '📍';
let iconHtml = '';
if (cat.iconImage) {
const filename = cat.iconImage.split('/').pop();
iconHtml = `<img src="${CONFIG.ICONS_DIR}/${filename}" class="category-icon" alt="" data-symbol="${symbol}">`;
} else {
iconHtml = `<span class="category-symbol">${symbol}</span>`;
}
html += `
<div class="category-item">
<input type="checkbox" id="cat-${cat.key}" ${this.mapData.visibleCategories.has(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;
// Fehlt eine Icon-Datei, statt des kaputten Bildes das Emoji zeigen (wie auf der Karte)
this.categoriesList.querySelectorAll('img.category-icon').forEach(img => {
img.addEventListener('error', () => {
const span = document.createElement('span');
span.className = 'category-symbol';
span.textContent = img.dataset.symbol || '📍';
img.replaceWith(span);
}, { once: true });
});
// Herkunft der Markerdaten: die Zahlen kommen 1:1 von dort und sind nicht immer vollstaendig
const source = document.createElement('p');
source.className = 'category-source';
const stand = this.formatDate(this.mapData.extractedAt);
source.textContent = 'Markerdaten: interactivemap.app' + (stand ? `, Stand ${stand}` : '')
+ ' – kann unvollständig sein';
this.categoriesList.appendChild(source);
// Attach event listeners to checkboxes
this.attachCategoryListeners();
}
/**
* "2026-09-20T14:57:12Z" -> "20.09.2026" (leer, wenn kein Datum erkennbar ist)
*/
formatDate(iso) {
const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso || ''));
return match ? `${match[3]}.${match[2]}.${match[1]}` : '';
}
/**
* 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;
}
}
/**
* Alle Kategorien ein- oder ausblenden und die Haekchen nachziehen
*/
setAllCategories(visible) {
Object.keys(this.mapData.categories).forEach(key => {
this.mapData.toggleCategory(key, visible);
});
this.categoriesList.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
checkbox.checked = visible;
checkbox.indeterminate = false;
});
this.render();
}
/**
* 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() {
// Kartenauswahl: Knopf oeffnet das Popup, Klick daneben / X / Esc schliesst es
this.mapPickerBtn.addEventListener('click', () => this.openMapPicker());
document.getElementById('map-picker-close').addEventListener('click', () => this.closeMapPicker());
this.mapPicker.addEventListener('click', (e) => {
if (e.target === this.mapPicker) this.closeMapPicker();
});
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !this.mapPicker.classList.contains('hidden')) {
e.stopPropagation();
this.closeMapPicker();
}
}, true);
// Alle Kategorien auf einmal ein- bzw. ausblenden
document.getElementById('btn-show-all').addEventListener('click', () => this.setAllCategories(true));
document.getElementById('btn-hide-all').addEventListener('click', () => this.setAllCategories(false));
// 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;
});
this.setupTouch();
this.setupPanelToggles();
// 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();
}
});
}
/**
* Fenster ausblenden: der Augen-Knopf (oder Taste H) blendet alles ausser der
* Zoom-Leiste aus. Die Kategorien lassen sich ausserdem einzeln einklappen. Auf
* schmalen Bildschirmen starten Kategorien und Taktiken eingeklappt, sonst
* verdecken sie fast die ganze Karte.
*/
setupPanelToggles() {
const overlay = document.getElementById('ui-overlay');
const toggleBtn = document.getElementById('btn-toggle-ui');
const setUiHidden = hidden => {
overlay.classList.toggle('ui-hidden', hidden);
toggleBtn.setAttribute('aria-pressed', String(hidden));
this.tooltip.classList.add('hidden');
};
toggleBtn.addEventListener('click', () => setUiHidden(!overlay.classList.contains('ui-hidden')));
window.addEventListener('keydown', (e) => {
const tag = e.target && e.target.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
if (e.key === 'h' || e.key === 'H') setUiHidden(!overlay.classList.contains('ui-hidden'));
});
const panel = document.getElementById('category-panel');
const collapseBtn = document.getElementById('cp-collapse');
collapseBtn.addEventListener('click', () => {
const collapsed = panel.classList.toggle('collapsed');
collapseBtn.textContent = collapsed ? '▸' : '▾';
collapseBtn.setAttribute('aria-expanded', String(!collapsed));
});
if (window.matchMedia('(max-width: 700px)').matches) {
collapseBtn.click();
const tacticCollapse = document.getElementById('tp-collapse');
if (tacticCollapse && tacticCollapse.getAttribute('aria-expanded') === 'true') tacticCollapse.click();
}
}
/**
* Touch: ein Finger verschiebt die Karte, zwei Finger zoomen (Pinch) und verschieben.
* Die Kacheln gibt es nur in ganzen Zoomstufen - deshalb wird eine Stufe gewechselt,
* sobald die Finger sich um einen festen Faktor auseinander- bzw. zusammenbewegt haben.
* Doppeltippen zoomt eine Stufe hinein.
*/
setupTouch() {
const PINCH_STEP = 1.5;
let lastX = 0;
let lastY = 0;
let pinchBase = 0; // Fingerabstand bei der letzten Zoomstufe
let lastTap = 0;
let moved = false;
let startX = 0; // wo der Finger aufgesetzt hat - Tippen darf etwas wackeln
let startY = 0;
const midpoint = touches => {
const rect = this.canvas.getBoundingClientRect();
let x = 0;
let y = 0;
for (const t of touches) {
x += t.clientX;
y += t.clientY;
}
return { x: x / touches.length - rect.left, y: y / touches.length - rect.top };
};
const distance = touches => Math.hypot(
touches[0].clientX - touches[1].clientX,
touches[0].clientY - touches[1].clientY
);
const resetTracking = touches => {
const mid = midpoint(touches);
lastX = mid.x;
lastY = mid.y;
pinchBase = touches.length >= 2 ? distance(touches) : 0;
};
this.canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
this.tooltip.classList.add('hidden');
if (e.touches.length === 1) {
moved = false;
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
}
resetTracking(e.touches);
}, { passive: false });
this.canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
const mid = midpoint(e.touches);
const dx = mid.x - lastX;
const dy = mid.y - lastY;
// Erst ab 10 px vom Aufsetzpunkt ist es Ziehen - Finger wackeln beim Tippen immer etwas
if (e.touches.length === 1 && Math.hypot(e.touches[0].clientX - startX, e.touches[0].clientY - startY) > 10) moved = true;
this.view.panBy(dx, dy);
lastX = mid.x;
lastY = mid.y;
if (e.touches.length >= 2 && pinchBase > 0) {
moved = true;
const ratio = distance(e.touches) / pinchBase;
if (ratio >= PINCH_STEP || ratio <= 1 / PINCH_STEP) {
this.view.zoomAt(ratio > 1 ? 1 : -1, mid.x, mid.y);
pinchBase = distance(e.touches);
this.render();
return;
}
}
this.view.requestRender(this.tileService, this.mapData);
}, { passive: false });
this.canvas.addEventListener('touchend', (e) => {
e.preventDefault();
if (e.touches.length > 0) {
// Ein Finger bleibt liegen: von dort aus ohne Sprung weiterschieben.
resetTracking(e.touches);
return;
}
if (moved || e.changedTouches.length !== 1) return;
const touch = e.changedTouches[0];
const now = Date.now();
if (now - lastTap < 300) {
const rect = this.canvas.getBoundingClientRect();
if (this.view.zoomAt(1, touch.clientX - rect.left, touch.clientY - rect.top)) this.render();
lastTap = 0;
} else {
lastTap = now;
// Ort teilen/auswaehlen: Antippen setzt den Pin
if (this.onTap && this.onTap(touch.clientX, touch.clientY)) return;
// Antippen zeigt den Namen eines Markers (statt Mauszeiger-Hover).
this.checkHover(touch);
}
}, { passive: false });
}
/**
* 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');
}
}
}