LuminaWebsite/assets/map/js/controllers/PetController.js
Maaxxs 50f6171452 Karte: Pets zeigen ihren Namen aus dem Spiel (z. B. Kuru Worker) statt Kuerzel wie Kuru 01
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 18:05:15 +02:00

262 lines
11 KiB
JavaScript
Raw Permalink 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.

/**
* PetController - Pets auf der Karte als erledigt abhaken.
*
* Klick bzw. Antippen eines Pet-Symbols oeffnet ein kleines Fenster mit "Erledigt". Ein Pet erkennt man an seinem
* Symbol (MapData.petKey) - abgehakt gilt es an allen Fundorten auf allen Karten. Gespeichert wird je Konto ueber
* die Website (map_pets_api.php, Recht map.view). Erledigte Pets zeichnet MapView blass mit Haken; in der
* Kategorienliste zeigen die Pet-Kategorien "erledigt/Pets auf dieser Karte", und "Erledigte ausblenden" blendet
* sie ganz aus (Browserspeicher lumina-map-pets-hide).
*/
class PetController {
constructor(mapController) {
this.map = mapController;
this.view = mapController.view;
this.mapData = mapController.mapData;
this.endpoint = '/map_pets_api.php';
this.enabled = false;
this.popup = null;
this.current = null; // Marker im offenen Fenster
this.storageKey = 'lumina-map-pets-hide';
// Gaeste des Consiliums sehen keine Marker
if (this.map.guest) return;
try {
this.mapData.hideDonePets = localStorage.getItem(this.storageKey) === '1';
} catch (e) {
this.mapData.hideDonePets = false;
}
// Antippen (Touch): erst Ort teilen/auswaehlen (LocationController), dann Pets
const previousTap = this.map.onTap;
this.map.onTap = (clientX, clientY) => (previousTap && previousTap(clientX, clientY)) || this.handleTap(clientX, clientY);
// Mausklick (ohne Ziehen)
let down = null;
this.view.canvas.addEventListener('mousedown', e => { down = { x: e.clientX, y: e.clientY }; });
this.view.canvas.addEventListener('mouseup', e => {
const click = down && Math.hypot(e.clientX - down.x, e.clientY - down.y) < 5;
down = null;
if (!click || (this.map.locations && this.map.locations.active)) return;
this.handleTap(e.clientX, e.clientY);
});
window.addEventListener('keydown', e => {
if (e.key === 'Escape' && this.popup && !this.popup.classList.contains('hidden')) this.close();
});
this.map.onCategoriesBuilt = () => this.updateCategories();
const previousChanged = this.map.onMapChanged;
this.map.onMapChanged = (...args) => {
if (previousChanged) previousChanged(...args);
this.close();
};
this.load();
}
/** Anzeigename: Name aus dem Spiel ("Kuru Worker"), sonst Name des Symbols ("Kuru 01"),
* sonst aus dem Dateinamen. Alte Markerdaten haben chinesische Namen - die werden uebergangen. */
static petName(marker) {
if (marker.nt && !/[一-鿿]/.test(marker.nt)) return marker.nt;
if (marker.iconName) return marker.iconName;
return String(marker.petKey || marker.name).replace(/^UT_Vehicle_Portrait_/, '').replace(/_/g, ' ');
}
csrfToken() {
try {
const meta = window.parent.document.querySelector('meta[name="csrf-token"]');
return meta ? meta.content : '';
} catch (e) {
return '';
}
}
async request(options = {}) {
const response = await fetch(this.endpoint, {
credentials: 'same-origin',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
...options
});
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch (e) {
throw new Error(text ? text.replace(/<[^>]*>/g, ' ').trim().slice(0, 200) : 'Speichern fehlgeschlagen.');
}
if (data.status !== 'success') throw new Error(data.message || 'Speichern fehlgeschlagen.');
return data;
}
async load() {
try {
const data = await this.request({ method: 'GET' });
this.mapData.petsDone = new Set(data.pets || []);
this.enabled = true;
} catch (e) {
// Ohne Endpunkt oder ohne Recht (z.B. Ortsauswahl im Kalender): kein Abhaken
this.enabled = false;
this.mapData.petsDone = new Set();
this.mapData.hideDonePets = false;
}
this.updateCategories();
this.map.render();
}
/** Klick/Antippen: Pet-Symbol -> Fenster oeffnen. true = erledigt (kein Tooltip mehr) */
handleTap(clientX, clientY) {
if (!this.enabled) return false;
const rect = this.view.canvas.getBoundingClientRect();
const marker = this.view.findNearestMarker(this.mapData, clientX - rect.left, clientY - rect.top);
if (!marker || !marker.petKey) {
this.close();
return false;
}
this.open(marker, clientX, clientY);
return true;
}
buildPopup() {
const popup = document.createElement('div');
popup.id = 'pet-popup';
popup.className = 'panel hidden';
popup.setAttribute('role', 'dialog');
popup.innerHTML = `
<button type="button" class="pet-close" title="Schließen (Esc)" aria-label="Schließen">×</button>
<div class="pet-head">
<img class="pet-icon" alt="">
<div>
<strong class="pet-name"></strong>
<span class="pet-meta"></span>
</div>
</div>
<label class="pet-done"><input type="checkbox"> Erledigt</label>
<p class="pet-hint">Gilt an allen Fundorten auf allen Karten.</p>`;
document.getElementById('map-container').appendChild(popup);
popup.querySelector('.pet-close').addEventListener('click', () => this.close());
popup.querySelector('input').addEventListener('change', e => this.setDone(this.current, e.target.checked, e.target));
// Klicks im Fenster nicht an die Karte weiterreichen
['mousedown', 'touchstart', 'wheel'].forEach(type => popup.addEventListener(type, e => e.stopPropagation(), { passive: true }));
this.popup = popup;
}
open(marker, clientX, clientY) {
if (!this.popup) this.buildPopup();
this.current = marker;
const popup = this.popup;
const img = popup.querySelector('.pet-icon');
if (marker.iconImage) {
img.src = `${CONFIG.ICONS_DIR}/${marker.iconImage.split('/').pop()}`;
img.hidden = false;
} else {
img.hidden = true;
}
const spots = this.mapData.markers.filter(m => m.petKey === marker.petKey).length;
popup.querySelector('.pet-name').textContent = PetController.petName(marker);
popup.querySelector('.pet-meta').textContent = `${marker.category_name} · ${spots} ${spots === 1 ? 'Fundort' : 'Fundorte'} auf dieser Karte`;
popup.querySelector('input').checked = this.mapData.isPetDone(marker);
this.map.tooltip.classList.add('hidden');
popup.classList.remove('hidden');
// Neben dem Klickpunkt, aber im Fenster halten
const container = document.getElementById('map-container').getBoundingClientRect();
const width = popup.offsetWidth;
const height = popup.offsetHeight;
let x = clientX - container.left + 16;
let y = clientY - container.top - 16;
if (x + width > container.width - 8) x = clientX - container.left - width - 16;
x = Math.max(8, x);
y = Math.max(8, Math.min(y, container.height - height - 8));
popup.style.left = `${x}px`;
popup.style.top = `${y}px`;
}
close() {
if (this.popup) this.popup.classList.add('hidden');
this.current = null;
}
async setDone(marker, done, checkbox) {
if (!marker) return;
const key = marker.petKey;
const apply = on => {
if (on) this.mapData.petsDone.add(key);
else this.mapData.petsDone.delete(key);
this.updateCategories();
this.map.render();
};
apply(done);
checkbox.disabled = true;
try {
await this.request({
method: 'POST',
body: JSON.stringify({ csrf_token: this.csrfToken(), pet: key, done })
});
} catch (e) {
apply(!done);
checkbox.checked = !done;
this.toast(e.message);
} finally {
checkbox.disabled = false;
}
}
/** Pet-Kategorien: "erledigt/Pets auf dieser Karte" und der Schalter "Erledigte ausblenden" */
updateCategories() {
const list = this.map.categoriesList;
const groupToggle = document.getElementById('group-Pets');
if (!list || !groupToggle) return;
const perCategory = {};
this.mapData.markers.forEach(m => {
if (!m.petKey) return;
const key = `${m.group_name}/${m.category_name}`;
(perCategory[key] = perCategory[key] || new Set()).add(m.petKey);
});
Object.entries(perCategory).forEach(([key, pets]) => {
const input = document.getElementById(`cat-${key}`);
const count = input && input.parentElement.querySelector('.category-count');
if (!count) return;
if (!this.enabled) {
count.textContent = this.mapData.categories[key] ? this.mapData.categories[key].count : count.textContent;
count.removeAttribute('title');
return;
}
const done = [...pets].filter(p => this.mapData.petsDone.has(p)).length;
count.textContent = `${done}/${pets.size}`;
count.title = `${done} von ${pets.size} Pets auf dieser Karte erledigt (${this.mapData.categories[key].count} Fundorte)`;
count.classList.toggle('pet-count-full', done === pets.size);
});
let row = list.querySelector('.pet-hide-row');
if (!this.enabled) {
if (row) row.remove();
return;
}
if (!row) {
row = document.createElement('div');
row.className = 'category-item pet-hide-row';
row.innerHTML = '<input type="checkbox" id="pets-hide-done"><label for="pets-hide-done">Erledigte Pets ausblenden</label>';
groupToggle.closest('.category-item').after(row);
row.querySelector('input').addEventListener('change', e => {
this.mapData.hideDonePets = e.target.checked;
try {
if (e.target.checked) localStorage.setItem(this.storageKey, '1');
else localStorage.removeItem(this.storageKey);
} catch (err) { /* ohne Browserspeicher nur bis zum Neuladen */ }
this.map.render();
});
}
row.querySelector('input').checked = this.mapData.hideDonePets;
}
toast(text) {
const toast = document.getElementById('toast');
if (!toast) return;
toast.textContent = text;
toast.classList.remove('hidden');
clearTimeout(this.toastTimer);
this.toastTimer = setTimeout(() => toast.classList.add('hidden'), 3500);
}
}