LuminaWebsite/assets/map/js/controllers/TacticController.js
2026-09-29 06:41:44 +02:00

1995 lines
90 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.

/**
* TacticController - Taktiken auf der Karte: anlegen, in Schritte gliedern, zeichnen.
*
* Eine Taktik gehoert zu einer Region und besteht aus Schritten (Schritt 1, Schritt 2 ...),
* jeder Schritt ist eine eigene Zeichenebene. Jeder mit map.view legt eigene Taktiken an -
* privat oder oeffentlich - und kann jede sichtbare Taktik als eigene Kopie anlegen. Fremde
* oeffentliche bearbeiten Strategen (map.tactics); mit map.tactics.highlight lassen sie sich
* als "Empfohlen"/"Offiziell" markieren, und nur damit bearbeitet man fremde offizielle bzw.
* loescht hervorgehobene. Vor Aenderungen sichert der Server den bisherigen Stand (Verlauf),
* geloeschte Taktiken liegen eine Weile im Papierkorb ("Gelöschte"). Was erlaubt ist,
* entscheidet der Server (can_create, can_highlight, pro Taktik can_edit/can_delete/...).
* Die gewaehlte Taktik ist live (TacticLiveService): Striche anderer erscheinen, waehrend sie
* entstehen, gespeicherte Aenderungen sofort, dazu wer gerade dabei ist.
*
* Consilium Elyseum: Wer die Taktik bearbeiten darf, gibt ihre laufende Live-Sitzung fuer die verbuendeten
* Legionen frei (🤝 im Live-Bereich). Deren Mitglieder sind hier Gaeste (this.guest): Sie sehen nur solche
* Sitzungen, schauen zu und zeichnen mit Berechtigung mit - nur zeichnen (GUEST_TOOLS), nichts loeschen,
* verschieben oder anlegen. Das pruefen tactics_api.php und der Verteiler, nicht nur diese Oberflaeche.
*
* Raidplaner: Figuren (Form 'token', TokenIcons), Verschieben/Beschriften mit ✥, Rechteck und
* Kegel (gespeichert als Flaeche). Zeichnungen mit derselben Kennung (ref) laufen beim Blaettern
* und Abspielen von ihrer Stelle im vorigen Schritt an die neue.
*/
class TacticController {
constructor(mapController) {
this.map = mapController;
this.view = mapController.view;
this.service = new TacticService();
this.layer = new TacticLayer(this.view);
this.slug = null;
this.tactics = [];
this.deleted = []; // Papierkorb der Region: was dieses Konto wiederherstellen darf
this.canCreate = false;
this.canHighlight = false;
this.guest = null; // Gast des Consiliums: {can_draw} - sonst null
this.consiliumEnabled = false; // gibt es ein Consilium, fuer das sich eine Sitzung freigeben laesst?
// Gast des Consiliums: die Sitzung, fuer die map_frame.php die Karte geoeffnet hat ({karte, taktik}). Endet
// sie, geht es zurueck zur Liste der Live-Sitzungen (endGuestSession).
this.guestSession = mapController.guest || null;
this.guestEnded = false;
this.selectedId = null;
this.stepIndex = 0;
this.showGhosts = false;
this.tool = 'pan';
this.draft = null;
this.drawing = false;
// step_id -> eigene Aenderungen dieser Sitzung zum Zuruecknehmen: {kind: 'create', id} oder
// {kind: 'update', id, points, label} (Stand vor dem Verschieben/Beschriften)
this.undoStacks = {};
this.loadToken = 0;
this.dialogOpen = false;
this.dialogCancel = null;
// Raidplaner: Figuren, Verschieben, animierte Schritte, Abspielen
this.tokenIcon = 'num-1'; // Figur, die das Werkzeug ♟ als naechstes setzt
this.drag = null; // Zeichnung, die gerade mit ✥ verschoben wird
this.selectedShapeId = null;
this.anim = null; // laufender Uebergang zwischen zwei Schritten
this.animFrame = null;
this.playTimer = null; // Abspielen laeuft
this.reducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// Link auf eine Taktik (?taktik=12&schritt=3, "🔗"): nach dem ersten Laden der Karte oeffnen
const params = new URLSearchParams(window.location.search);
const linkedTactic = parseInt(params.get('taktik'), 10);
this.pendingLink = linkedTactic > 0
? { slug: params.get('karte'), tactic: linkedTactic, step: Math.max(1, parseInt(params.get('schritt'), 10) || 1) }
: null;
// Live-Ansicht der gewaehlten Taktik: wer dabei ist und welche Striche bei anderen gerade entstehen
this.live = new TacticLiveService(this.service, {
onEvent: (event, tacticId) => this.onLiveEvent(event, tacticId),
onStatus: () => this.renderLive(),
onTicketError: error => this.onLiveTicketError(error)
});
this.liveClients = []; // offene Verbindungen (je Tab) laut Verteiler
this.liveDrafts = new Map(); // "conn|id" -> Strich eines anderen, der gerade entsteht
this.liveFinished = new Map(); // "conn|id" -> fertige Striche anderer (Nachzuegler zaehlen nicht mehr)
this.liveFocus = null; // zuletzt gemeldeter eigener Schritt
this.liveConsilium = null; // Freigabe der Sitzung fuers Consilium laut Verteiler: {by, since} oder null
this.lastLoadAt = 0;
this.reloadTimer = null;
this.redrawFrame = null;
const $ = id => document.getElementById(id);
this.el = {
panel: $('tactic-panel'),
body: $('tp-body'),
collapse: $('tp-collapse'),
newBtn: $('tp-new'),
trash: $('tp-trash'),
list: $('tp-list'),
message: $('tp-message'),
detail: $('tp-detail'),
name: $('tp-name'),
desc: $('tp-desc'),
meta: $('tp-meta'),
highlight: $('tp-highlight'),
highlightSelect: $('tp-highlight-select'),
copy: $('tp-copy'),
share: $('tp-share'),
history: $('tp-history'),
edit: $('tp-edit'),
del: $('tp-delete'),
steps: $('tp-steps'),
stepAdd: $('tp-step-add'),
stepCopy: $('tp-step-copy'),
ghosts: $('tp-ghosts'),
live: $('tp-live'),
sbLive: $('sb-live'),
toolbar: $('tactic-toolbar'),
color: $('tool-color'),
width: $('tool-width'),
angle: $('tool-angle'),
undo: $('tool-undo'),
palette: $('token-palette'),
shapeActions: $('shape-actions'),
stepBar: $('step-bar'),
prev: $('sb-prev'),
next: $('sb-next'),
play: $('sb-play'),
sbTitle: $('sb-title'),
sbDesc: $('sb-desc'),
dialog: $('tactic-dialog'),
form: $('td-form'),
dTitle: $('td-title'),
dFields: $('td-fields'),
dSubmit: $('td-submit'),
dCancel: $('td-cancel'),
toast: $('toast')
};
this.view.onViewChange = () => this.redraw();
this.map.onMapChanged = slug => this.loadMap(slug);
if (this.guestSession) this.el.panel.querySelector('.tp-head h3').textContent = 'Live-Sitzung';
window.addEventListener('resize', () => {
this.layer.resize();
this.redraw();
});
// Klassen-Wappen in der Figurenauswahl nachzeichnen, sobald sie geladen sind
TokenIcons.onImageLoad(() => this.renderPaletteIcons());
this.bindPanel();
this.bindToolbar();
this.bindCanvas();
this.bindKeyboard();
}
// ------------------------------------------------------------------
// Daten
// ------------------------------------------------------------------
currentTactic() {
return this.tactics.find(t => t.id === this.selectedId) || null;
}
/**
* Darf das Konto die gewaehlte Taktik bearbeiten (eigene; fremde oeffentliche als Stratege,
* fremde offizielle nur mit dem Recht zum Hervorheben)?
*/
canEditCurrent() {
const tactic = this.currentTactic();
return !!(tactic && tactic.can_edit);
}
/** Zeichnen: wer die Taktik bearbeiten darf - und Gaeste des Consiliums mit Zeichenrecht (nur GUEST_TOOLS). */
canDrawCurrent() {
return this.canEditCurrent() || !!(this.guest && this.guest.can_draw && this.currentTactic());
}
/** Darf das Konto die laufende Sitzung fuers Consilium freigeben (bearbeiten duerfen, oeffentliche Taktik)? */
canShareCurrent() {
const tactic = this.currentTactic();
return !this.guest && this.consiliumEnabled && this.canEditCurrent() && tactic.visibility === 'public';
}
currentStep() {
const tactic = this.currentTactic();
return tactic ? tactic.steps[this.stepIndex] || null : null;
}
/** Schritt der gewaehlten Taktik nach ID - nach einem Neuladen sind es neue Objekte. */
stepById(stepId) {
const tactic = this.currentTactic();
return tactic ? tactic.steps.find(s => s.id === stepId) || null : null;
}
async loadMap(slug) {
this.slug = slug;
this.selectedId = null;
this.stepIndex = 0;
this.stopPlay();
this.anim = null;
this.setTool('pan');
await this.reload();
this.openPendingLink();
}
/** Link auf eine Taktik (?taktik=...&schritt=...): einmal nach dem Laden ihrer Karte oeffnen. */
openPendingLink() {
const link = this.pendingLink;
if (!link || (link.slug && link.slug !== this.slug)) return;
this.pendingLink = null;
const tactic = this.tactics.find(t => t.id === link.tactic);
if (!tactic) {
if (this.guestSession) {
this.endGuestSession('ended');
return;
}
this.toast('Diese Taktik gibt es nicht mehr – oder sie ist privat und nur für ihren Ersteller sichtbar.', true);
return;
}
this.selectedId = tactic.id;
this.stepIndex = Math.min(link.step, tactic.steps.length) - 1;
this.renderUI();
this.redraw();
}
/**
* Laedt die Taktiken der aktuellen Region neu. focusStepId: Schritt, der danach
* ausgewaehlt sein soll (z.B. ein gerade angelegter oder verschobener). keepOnError: bei einem
* Fehler den bisherigen Stand behalten und es gleich noch mal versuchen (Abgleich der Live-Ansicht -
* ein kurzer Netzaussetzer soll die offene Taktik mitten im Raid nicht schliessen).
*/
async reload(focusStepId = null, keepOnError = false) {
const token = ++this.loadToken;
let error = null;
try {
const data = await this.service.list(this.slug, this.guestSession ? this.guestSession.taktik : null);
if (token !== this.loadToken) return;
this.lastLoadAt = Date.now();
this.tactics = data.tactics || [];
this.deleted = data.deleted || [];
this.canCreate = !!data.can_create;
this.canHighlight = !!data.can_highlight;
this.guest = data.guest || null;
this.consiliumEnabled = !!data.consilium;
} catch (e) {
if (token !== this.loadToken) return;
if (keepOnError && this.tactics.length) {
this.scheduleReload(5000);
return;
}
this.tactics = [];
this.deleted = [];
this.canCreate = false;
this.canHighlight = false;
this.consiliumEnabled = false;
error = e;
}
// Gast: Fehlt die Taktik seiner Sitzung (Freigabe vorbei, privat gestellt, geloescht), zurueck zur Liste
if (this.guestSession && !error && !this.tactics.some(t => t.id === this.guestSession.taktik)) {
this.endGuestSession('ended');
return;
}
// Ausserhalb der Website (kein tactics_api.php) gibt es keine Taktiken.
this.el.panel.classList.toggle('hidden', !!(error && error.unavailable));
this.showMessage(error && !error.unavailable ? error.message : '');
const tactic = this.currentTactic();
if (!tactic) {
this.selectedId = null;
this.stepIndex = 0;
} else {
const focused = focusStepId ? tactic.steps.findIndex(s => s.id === focusStepId) : -1;
if (focused >= 0) this.stepIndex = focused;
this.stepIndex = Math.max(0, Math.min(this.stepIndex, tactic.steps.length - 1));
}
if (!this.canDrawCurrent()) this.setTool('pan');
this.renderUI();
this.redraw();
}
async run(action, payload) {
try {
return await this.service.send(action, payload);
} catch (e) {
this.toast(e.message, true);
return null;
}
}
// ------------------------------------------------------------------
// Oberflaeche
// ------------------------------------------------------------------
static esc(text) {
return String(text).replace(/[&<>"']/g, c => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
}[c]));
}
static stepLabel(step, index) {
return step.title ? step.title : `Schritt ${index + 1}`;
}
showMessage(text) {
this.el.message.textContent = text;
this.el.message.classList.toggle('hidden', !text);
}
/** Kleine Kennzeichen hinter dem Namen: Offiziell/Empfohlen, privat. */
static badges(tactic) {
const badges = [];
if (tactic.highlight === 'official') badges.push('<span class="tp-badge tp-badge-official" title="Offizielle Taktik">★ Offiziell</span>');
if (tactic.highlight === 'recommended') badges.push('<span class="tp-badge tp-badge-recommended" title="Empfohlene Taktik">👍 Empfohlen</span>');
if (tactic.visibility === 'private') badges.push('<span class="tp-badge tp-badge-private" title="Nur du siehst diese Taktik">🔒 Privat</span>');
return badges.join('');
}
renderUI() {
const esc = TacticController.esc;
const tactic = this.currentTactic();
this.el.panel.classList.toggle('can-edit', this.canEditCurrent());
this.el.newBtn.classList.toggle('hidden', !this.canCreate);
// Papierkorb nur, wenn es hier etwas gibt, das man wiederherstellen darf
this.el.trash.classList.toggle('hidden', this.deleted.length === 0);
this.el.trash.title = this.deleted.length === 1
? '1 gelöschte Taktik wiederherstellen'
: `${this.deleted.length} gelöschte Taktiken wiederherstellen`;
// Liste der Taktiken - hervorgehobene zuerst, dann die eigenen, dann die der anderen
if (this.tactics.length === 0) {
const empty = this.guest
? 'Auf dieser Karte läuft gerade keine Live-Sitzung, die für Elyos Allianz freigegeben ist. '
+ '<a href="/map.php" target="_top">Alle Live-Sitzungen</a>'
: `Noch keine Taktiken für diese Karte.${this.canCreate ? ' Mit „+ Neu“ legst du deine erste an – nur für dich oder für alle.' : ''}`;
this.el.list.innerHTML = this.el.message.classList.contains('hidden') ? `<p class="tp-empty">${empty}</p>` : '';
} else {
const groups = [
{ title: 'Offiziell & empfohlen', items: this.tactics.filter(t => t.highlight !== 'none') },
{ title: 'Meine Taktiken', items: this.tactics.filter(t => t.highlight === 'none' && t.is_mine) },
{ title: 'Von anderen', items: this.tactics.filter(t => t.highlight === 'none' && !t.is_mine) }
].filter(g => g.items.length > 0);
const showTitles = groups.length > 1;
this.el.list.innerHTML = groups.map(group => `
${showTitles ? `<div class="tp-group-title">${group.title}</div>` : ''}
${group.items.map(t => `
<button type="button" class="tp-item${t.id === this.selectedId ? ' active' : ''}${t.highlight !== 'none' ? ' tp-item-' + t.highlight : ''}" data-id="${t.id}">
<span class="tp-item-main">
<span class="tp-item-name">${esc(t.name)}</span>
<span class="tp-item-badges">${TacticController.badges(t)}</span>
</span>
<span class="tp-item-meta">${t.is_mine ? 'von dir' : (t.author ? 'von ' + esc(t.author) : '')} · ${t.steps.length} ${t.steps.length === 1 ? 'Schritt' : 'Schritte'}</span>
</button>`).join('')}`).join('');
}
// Details der gewaehlten Taktik
this.el.detail.classList.toggle('hidden', !tactic);
if (tactic) {
this.el.name.textContent = tactic.name;
const meta = [
tactic.is_mine ? 'Deine Taktik' : (tactic.author ? `Von ${tactic.author}` : ''),
this.guest
? 'für Elyos Allianz freigegeben'
: (tactic.visibility === 'private' ? 'nur für dich sichtbar' : 'für alle sichtbar'),
tactic.highlight !== 'none' && tactic.highlighted_by
? `${tactic.highlight === 'official' ? 'offiziell' : 'empfohlen'} von ${tactic.highlighted_by}` : ''
].filter(Boolean);
this.el.meta.innerHTML = TacticController.badges(tactic) + `<span>${esc(meta.join(' · '))}</span>`;
this.el.copy.classList.toggle('hidden', !this.canCreate);
// Link teilen nur in der Legion - Gaeste kommen ueber die Liste der Live-Sitzungen
this.el.share.classList.toggle('hidden', !!this.guest);
// Hervorgehobene Taktiken loescht nur, wer Taktiken hervorheben darf - auch nicht der Ersteller.
this.el.del.disabled = !tactic.can_delete;
this.el.del.title = tactic.can_delete
? 'Taktik löschen'
: 'Hervorgehobene Taktiken kann nur löschen, wer Taktiken hervorheben darf';
// Hervorheben: nur mit Berechtigung und nur bei oeffentlichen Taktiken
const canHighlight = this.canHighlight && tactic.visibility === 'public';
this.el.highlight.classList.toggle('hidden', !canHighlight);
if (canHighlight) this.el.highlightSelect.value = tactic.highlight;
this.el.desc.textContent = tactic.description;
this.el.desc.classList.toggle('hidden', !tactic.description);
this.el.ghosts.checked = this.showGhosts;
this.renderSteps(tactic);
}
this.el.toolbar.classList.toggle('hidden', !this.canDrawCurrent());
// Gaeste zeichnen nur: ohne Verschieben, Figuren, Radierer und Rueckgaengig (das loescht)
this.el.toolbar.querySelectorAll('.tool[data-tool]').forEach(button => {
button.classList.toggle('hidden', !!this.guest && !TacticController.GUEST_TOOLS.includes(button.dataset.tool));
});
this.el.undo.classList.toggle('hidden', !!this.guest);
this.el.palette.classList.toggle('hidden', !this.canEditCurrent() || this.tool !== 'token');
this.renderStepBar();
this.syncLive();
this.renderLive();
}
renderSteps(tactic) {
const esc = TacticController.esc;
const last = tactic.steps.length - 1;
this.el.steps.innerHTML = tactic.steps.map((step, i) => `
<li class="tp-step${i === this.stepIndex ? ' active' : ''}" data-index="${i}">
<span class="tp-step-no">${i + 1}</span>
<span class="tp-step-name">${esc(TacticController.stepLabel(step, i))}</span>
<span class="tp-step-live"></span>
<span class="tp-step-count" title="Zeichnungen">${step.shapes.length}</span>
${tactic.can_edit ? `
<span class="tp-step-tools">
<button type="button" class="tp-icon" data-step-action="up" title="Nach oben"${i === 0 ? ' disabled' : ''}>↑</button>
<button type="button" class="tp-icon" data-step-action="down" title="Nach unten"${i === last ? ' disabled' : ''}>↓</button>
<button type="button" class="tp-icon" data-step-action="edit" title="Umbenennen/beschreiben">✎</button>
<button type="button" class="tp-icon tp-danger" data-step-action="delete" title="Schritt löschen"${last === 0 ? ' disabled' : ''}>🗑</button>
</span>` : ''}
</li>`).join('');
}
renderStepBar() {
const tactic = this.currentTactic();
const step = this.currentStep();
this.el.stepBar.classList.toggle('hidden', !step);
if (!step) return;
const total = tactic.steps.length;
// Der Name der Taktik steht schon im Panel - hier nur, wo man gerade ist.
this.el.sbTitle.textContent = `Schritt ${this.stepIndex + 1}/${total}`
+ (step.title ? ` – ${step.title}` : '');
this.el.stepBar.title = tactic.name;
this.el.sbDesc.textContent = step.description;
this.el.sbDesc.classList.toggle('hidden', !step.description);
this.el.prev.disabled = this.stepIndex === 0;
this.el.next.disabled = this.stepIndex >= total - 1;
this.el.play.disabled = total < 2;
// Kreis mit Dreieck bzw. zwei Balken - sonst verwechselt man ihn mit ▶ (naechster Schritt)
this.el.play.innerHTML = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" '
+ 'stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/>'
+ (this.playTimer
? '<line x1="10" y1="8.5" x2="10" y2="15.5"/><line x1="14" y1="8.5" x2="14" y2="15.5"/>'
: '<polygon points="10 8 16 12 10 16" fill="currentColor"/>')
+ '</svg>';
this.el.play.setAttribute('aria-label', this.playTimer ? 'Anhalten' : 'Abspielen');
this.el.play.setAttribute('aria-pressed', String(!!this.playTimer));
this.el.play.title = this.playTimer
? 'Anhalten (Leertaste)'
: 'Abspielen: alle Schritte nacheinander zeigen (Leertaste)';
}
redraw() {
const tactic = this.currentTactic();
const step = this.currentStep();
this.layer.shapes = step ? this.animatedShapes(step) : [];
this.layer.selectedId = this.tool === 'move' ? this.selectedShapeId : null;
this.layer.ghostShapes = tactic && this.showGhosts
? tactic.steps.slice(0, this.stepIndex).flatMap(s => s.shapes)
: [];
this.layer.liveDrafts = step
? [...this.liveDrafts.values()].filter(d => d.step === step.id).map(d => ({
shape: { ...d.shape, points: d.points },
name: d.name,
color: TacticController.userColor(d.user)
}))
: [];
this.layer.draft = this.draft;
this.layer.draw();
this.placeShapeActions();
}
// ------------------------------------------------------------------
// Uebergang zwischen Schritten: dieselbe Figur (gleiche ref) laeuft an ihre neue Stelle
// ------------------------------------------------------------------
static ease(t) {
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}
/**
* Uebergang vom Schritt mit den Zeichnungen fromShapes zum jetzigen Schritt starten: Zeichnungen
* mit derselben Kennung (ref, gleiche Art und Punktzahl) wandern, neue blenden ein, wegfallende aus.
*/
startTransition(fromShapes) {
const step = this.currentStep();
this.anim = null;
if (!step || !fromShapes || this.reducedMotion) return;
const byRef = new Map(fromShapes.filter(s => s.ref).map(s => [s.ref, s]));
const kept = new Set();
const moves = new Map();
step.shapes.forEach(shape => {
const from = shape.ref ? byRef.get(shape.ref) : null;
if (!from) return;
kept.add(shape.ref);
if (from.type === shape.type && from.points.length === shape.points.length) moves.set(shape.id, from.points);
});
const leaving = fromShapes.filter(s => !s.ref || !kept.has(s.ref));
const entering = new Set(step.shapes.filter(s => !s.ref || !byRef.has(s.ref)).map(s => s.id));
if (moves.size === 0 && leaving.length === 0 && entering.size === 0) return;
this.anim = { stepId: step.id, start: performance.now(), duration: 700, moves, leaving, entering };
const tick = () => {
this.animFrame = null;
if (!this.anim) return;
if (performance.now() - this.anim.start >= this.anim.duration) this.anim = null;
this.redraw();
if (this.anim) this.animFrame = requestAnimationFrame(tick);
};
if (this.animFrame) cancelAnimationFrame(this.animFrame);
this.animFrame = requestAnimationFrame(tick);
}
/** Die Zeichnungen des Schritts, waehrend eines Uebergangs mit Zwischenpositionen und Blende. */
animatedShapes(step) {
const anim = this.anim;
if (!anim || anim.stepId !== step.id) return step.shapes;
const t = TacticController.ease(Math.min(1, (performance.now() - anim.start) / anim.duration));
const shapes = step.shapes.map(shape => {
const from = anim.moves.get(shape.id);
if (from) {
return {
...shape,
points: shape.points.map((p, i) => [from[i][0] + (p[0] - from[i][0]) * t, from[i][1] + (p[1] - from[i][1]) * t])
};
}
return anim.entering.has(shape.id) ? { ...shape, _alpha: t } : shape;
});
// Wegfallende blenden unter den anderen aus (anklicken lassen sie sich nicht mehr)
return anim.leaving.map(shape => ({ ...shape, id: `leaving-${shape.id}`, _alpha: 1 - t, _leaving: true })).concat(shapes);
}
// ------------------------------------------------------------------
// Abspielen
// ------------------------------------------------------------------
togglePlay() {
if (this.playTimer) {
this.stopPlay();
return;
}
const tactic = this.currentTactic();
if (!tactic || tactic.steps.length < 2) return;
// Am Ende angekommen: von vorn
if (this.stepIndex >= tactic.steps.length - 1) this.goToStep(0, true);
this.playTimer = setInterval(() => {
const current = this.currentTactic();
if (current && this.stepIndex < current.steps.length - 1) this.goToStep(this.stepIndex + 1, true);
// Beim letzten Schritt angekommen (oder Taktik weg): fertig
if (!current || this.stepIndex >= current.steps.length - 1) this.stopPlay();
}, 2600);
this.renderStepBar();
}
stopPlay() {
if (!this.playTimer) return;
clearInterval(this.playTimer);
this.playTimer = null;
this.renderStepBar();
}
/** Neu zeichnen, hoechstens einmal pro Bild - Live-Striche kommen in schneller Folge. */
requestRedraw() {
if (this.redrawFrame) return;
this.redrawFrame = requestAnimationFrame(() => {
this.redrawFrame = null;
this.redraw();
});
}
// ------------------------------------------------------------------
// Live-Ansicht
// ------------------------------------------------------------------
/** Feste Farbe je Mitglied (Punkte in der Schrittliste, Name am Strich). */
static userColor(userId) {
return `hsl(${Math.round((userId * 137.508) % 360)}, 75%, 62%)`;
}
static newLiveId() {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
}
/** Taktik neu laden - gebuendelt, wenn mehrere Aenderungen kurz hintereinander kommen. Der Schritt bleibt. */
scheduleReload(delay = 250) {
clearTimeout(this.reloadTimer);
this.reloadTimer = setTimeout(() => {
const step = this.currentStep();
this.reload(step ? step.id : null, true);
}, delay);
}
/** Live-Ansicht der gewaehlten Taktik betreten bzw. verlassen und den eigenen Schritt melden. */
syncLive() {
const tactic = this.currentTactic();
const tacticId = tactic ? tactic.id : null;
if (tacticId !== this.live.tacticId) {
this.liveClients = [];
this.liveDrafts.clear();
this.liveFinished.clear();
this.liveFocus = null;
this.liveConsilium = null;
this.live.join(tacticId);
}
const step = this.currentStep();
const stepId = step ? step.id : null;
if (tacticId && this.live.conn && stepId !== this.liveFocus) {
this.liveFocus = stepId;
this.live.push({ type: 'focus', step: stepId });
}
}
/** Aenderung an Schritten oder der Taktik selbst - die anderen laden neu. */
notifyChanged(what) {
if (this.live.canDraw()) this.live.sendNow({ type: 'changed', what });
}
onLiveEvent(event, tacticId) {
const tactic = this.tactics.find(t => t.id === tacticId) || null;
const stepOf = id => (tactic ? tactic.steps.find(s => s.id === id) : null) || null;
const key = (conn, id) => `${conn}|${id}`;
const current = this.currentStep();
switch (event.type) {
case 'hello':
this.liveClients = event.clients || [];
this.liveDrafts.clear();
(event.drafts || []).forEach(d => this.liveDrafts.set(key(d.conn, d.id), d));
this.liveFocus = undefined;
this.liveConsilium = event.consilium || null;
// Nach einem Abbruch kann etwas fehlen - frisch laden (direkt nach dem Laden nicht noetig).
if (Date.now() - this.lastLoadAt > 3000) {
this.scheduleReload(0);
} else {
this.syncLive();
this.renderLive();
this.requestRedraw();
}
break;
case 'presence':
this.liveClients = event.clients || [];
this.renderLive();
break;
case 'draft': {
const draftKey = key(event.conn, event.id);
// Nachzuegler eines schon gespeicherten oder abgebrochenen Strichs: nicht wieder anzeigen
if (this.liveFinished.has(draftKey)) return;
const known = this.liveDrafts.get(draftKey);
if (event.append) {
// Nachschub zu einem unbekannten Strich: der naechste volle Stand kommt noch
if (!known) return;
known.points.push(...event.points);
} else {
this.liveDrafts.set(draftKey, event);
if (!known) this.renderLive();
}
if (current && current.id === event.step) this.requestRedraw();
break;
}
case 'draft_end':
this.finishLiveDraft(key(event.conn, event.id));
// Mitten im Strich gegangen (Tab zu, andere Taktik): was er bis dahin gespeichert hat,
// kam evtl. nicht mehr live an - frisch laden
if (event.reason === 'left') this.scheduleReload(1000);
break;
case 'shape_added': {
if (event.draft) this.finishLiveDraft(key(event.conn, event.draft));
const step = stepOf(event.step);
if (!step) {
this.scheduleReload(); // ein Schritt, den wir noch nicht kennen
break;
}
if (!step.shapes.some(s => s.id === event.shape.id)) step.shapes.push(event.shape);
this.renderUI();
this.requestRedraw();
break;
}
case 'shape_removed': {
const step = stepOf(event.step);
if (!step) {
this.scheduleReload();
break;
}
step.shapes = step.shapes.filter(s => s.id !== event.shape_id);
if (this.layer.hoverId === event.shape_id) this.layer.hoverId = null;
this.renderUI();
this.requestRedraw();
break;
}
case 'changed':
case 'resync':
this.scheduleReload();
break;
case 'consilium':
// Freigabe fuers Consilium an/aus. Gaeste trennt der Verteiler danach - sie gehen zurueck zur Liste.
this.liveConsilium = event.on ? { by: event.by || '', since: event.since || 0 } : null;
if ((this.guestSession || this.guest) && !event.on) {
this.endGuestSession(event.reason === 'stopped' ? 'stopped' : 'ended');
return;
}
if (!this.guest && this.consiliumEnabled && event.by && event.by !== this.liveMyName()) {
this.toast(event.on
? `${event.by} hat diese Sitzung für Elyos Allianz freigegeben.`
: `${event.by} hat die Freigabe für Elyos Allianz beendet.`);
}
this.renderLive();
break;
}
}
/**
* Gast des Consiliums: Die Sitzung ist vorbei - die ganze Seite geht zurueck zur Liste der Live-Sitzungen
* (map.php sagt dort, warum). reason: stopped (Freigabe beendet) oder ended (Sitzung vorbei).
*/
endGuestSession(reason) {
if (this.guestEnded) return;
this.guestEnded = true;
this.live.leave();
const target = '/map.php?beendet=' + encodeURIComponent(reason);
try {
window.top.location.replace(target);
} catch (e) {
window.location.replace(target);
}
}
/** Kein Ticket fuer die Live-Ansicht: Gaeste, deren Sitzung vorbei ist, gehen zurueck - sonst neu laden. */
onLiveTicketError(error) {
if (this.guestSession && error && error.data && error.data.consilium_ended) {
this.endGuestSession('ended');
return;
}
this.scheduleReload();
}
/** Eigener Name, wie ihn der Verteiler kennt (fuer Hinweise, die man selbst ausgeloest hat). */
liveMyName() {
const me = this.live.ticket ? this.live.ticket.user_id : null;
const client = this.liveClients.find(c => c.user === me);
return client ? client.name : null;
}
/** Laufende Sitzung fuers Consilium freigeben bzw. die Freigabe beenden (tactics_api.php, consilium_share). */
async toggleConsilium() {
const tactic = this.currentTactic();
if (!tactic || !this.canShareCurrent()) return;
const on = !this.liveConsilium;
if (on && !(await this.confirmDialog('Für Elyos Allianz freigeben',
`„${tactic.name}“ mit allen Schritten und Zeichnungen für die verbündeten Legionen freigeben?\n`
+ 'Sie sehen die Sitzung dann unter „Karte“ und schauen zu – wer die Berechtigung hat, zeichnet mit '
+ '(nur zeichnen: nichts löschen, verschieben oder anlegen).\n'
+ 'Die Freigabe gilt nur für diese Sitzung: Sie endet, wenn du sie beendest oder niemand aus der Legion mehr dabei ist.',
'Freigeben'))) {
return;
}
const result = await this.run('consilium_share', { tactic_id: tactic.id, on });
if (!result) return;
if (this.live.tacticId === tactic.id) this.liveConsilium = result.consilium || null;
this.toast(result.message);
this.renderLive();
}
/** Strich eines anderen ist fertig (gespeichert oder abgebrochen): weg damit und merken, dass er fertig ist. */
finishLiveDraft(draftKey) {
this.liveFinished.set(draftKey, true);
if (this.liveFinished.size > 200) this.liveFinished.delete(this.liveFinished.keys().next().value);
if (this.liveDrafts.delete(draftKey)) {
this.renderLive();
this.requestRedraw();
}
}
/** Wer gerade live dabei ist - je Mitglied einmal (auch mit mehreren Tabs), man selbst zuerst. */
liveUsers() {
const me = this.live.ticket ? this.live.ticket.user_id : null;
const users = new Map();
this.liveClients.forEach(client => {
const user = users.get(client.user)
|| { id: client.user, name: client.name, me: client.user === me, guest: !!client.guest, legion: client.legion || '',
steps: new Set(), drawing: new Set() };
if (client.step) user.steps.add(client.step);
users.set(client.user, user);
});
this.liveDrafts.forEach(draft => {
const user = users.get(draft.user);
if (user) user.drawing.add(draft.step);
});
return [...users.values()].sort((a, b) => (b.me - a.me) || a.name.localeCompare(b.name, 'de'));
}
/** Wo jemand gerade ist: der Schritt, in dem er zeichnet, sonst der, den er ansieht (Index oder -1). */
liveUserStepIndex(user) {
const tactic = this.currentTactic();
if (!tactic) return -1;
const stepId = user.drawing.size ? [...user.drawing][0] : [...user.steps][0];
return tactic.steps.findIndex(s => s.id === stepId);
}
renderLive() {
const esc = TacticController.esc;
const tactic = this.currentTactic();
const status = this.live.status;
const show = !!tactic && status !== 'off' && status !== 'unavailable';
const users = show && status === 'live' ? this.liveUsers() : [];
const others = users.filter(u => !u.me);
// Wer das Consilium nicht sieht (normale Mitglieder), sieht Gaeste wie alle anderen - ohne 🤝 und Legion
const markGuests = !!this.guest || this.consiliumEnabled;
// Punkte in der Schrittliste: wer ist in welchem Schritt, wer zeichnet dort gerade
this.el.steps.querySelectorAll('.tp-step').forEach(li => {
const step = tactic ? tactic.steps[parseInt(li.dataset.index, 10)] : null;
const marker = li.querySelector('.tp-step-live');
if (!step || !marker) return;
marker.innerHTML = others
.filter(u => u.steps.has(step.id) || u.drawing.has(step.id))
.map(u => {
const drawing = u.drawing.has(step.id);
return `<span class="tp-live-dot${drawing ? ' drawing' : ''}" style="--live-color:${TacticController.userColor(u.id)}"`
+ ` title="${esc(u.name)} ${drawing ? 'zeichnet hier gerade' : 'ist hier'}"></span>`;
}).join('');
});
this.el.live.classList.toggle('hidden', !show);
this.el.sbLive.classList.toggle('hidden', !show || status !== 'live' || others.length === 0);
if (!show) return;
if (status !== 'live') {
this.el.live.innerHTML = status === 'connecting'
? '<span class="tp-live-state">◌ Live-Verbindung wird aufgebaut …</span>'
: '<span class="tp-live-state tp-live-offline">⚠ Live-Verbindung unterbrochen – neuer Versuch läuft …</span>';
return;
}
this.el.live.innerHTML = '<span class="tp-live-state" title="Striche erscheinen bei allen, während sie entstehen">'
+ '<span class="tp-live-pulse"></span>Live</span>'
+ (others.length === 0
? '<span class="tp-live-hint">Gerade ist sonst niemand in dieser Taktik.</span>'
: others.map(u => {
const index = this.liveUserStepIndex(u);
const where = index >= 0 ? `Schritt ${index + 1}` : '';
// Gaeste des Consiliums: mit 🤝 und ihrer Legion
const isGuest = u.guest && markGuests;
const guest = isGuest ? ` – Gast aus ${u.legion ? 'der Legion ' + u.legion : 'Elyos Allianz'}` : '';
const title = `${u.name}${guest}${where ? ' – ' + where : ''}${u.drawing.size ? ' – zeichnet gerade' : ''}`
+ (index >= 0 && index !== this.stepIndex ? ' (klicken: dorthin springen)' : '');
return `<button type="button" class="tp-live-user${u.drawing.size ? ' drawing' : ''}${isGuest ? ' guest' : ''}" data-user="${u.id}"`
+ ` style="--live-color:${TacticController.userColor(u.id)}" title="${esc(title)}">`
+ `${isGuest ? '🤝 ' : ''}${esc(u.name)}${index >= 0 && tactic.steps.length > 1 ? `<small>${index + 1}</small>` : ''}</button>`;
}).join(''))
+ this.consiliumLiveHtml();
const drawingHere = others.filter(u => this.currentStep() && u.drawing.has(this.currentStep().id));
this.el.sbLive.textContent = drawingHere.length
? `✏️ ${drawingHere.map(u => u.name).join(', ')}`
: `● ${others.length + 1} live`;
this.el.sbLive.title = 'Gerade in dieser Taktik: ' + users.map(u => (u.me ? 'du' : u.name)).join(', ');
}
/**
* Zeile im Live-Bereich zum Consilium Elyseum: Gaeste sehen, was sie duerfen; wer die Taktik bearbeiten darf,
* gibt die Sitzung frei bzw. beendet die Freigabe; die anderen sehen, dass sie freigegeben ist.
*/
consiliumLiveHtml() {
const esc = TacticController.esc;
const share = this.liveConsilium;
if (this.guest) {
return '<span class="tp-live-consilium">🤝 Du bist Gast von Elyos Allianz – '
+ (this.guest.can_draw ? 'du darfst mitzeichnen, aber nichts löschen oder verschieben.' : 'du schaust zu.')
+ '</span>';
}
// Normale Mitglieder sehen vom Consilium nichts (tactics_api.php: consilium nur mit consilium.view)
if (!this.consiliumEnabled) return '';
const since = share && share.since
? ' seit ' + new Date(share.since * 1000).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }) + ' Uhr'
: '';
if (this.canShareCurrent()) {
return share
? `<span class="tp-live-consilium is-shared" title="${esc(`Freigegeben von ${share.by || 'unbekannt'}${since}`)}">`
+ '🤝 Für Elyos Allianz freigegeben'
+ '<button type="button" class="tp-btn tp-consilium-toggle">Freigabe beenden</button></span>'
: '<span class="tp-live-consilium"><button type="button" class="tp-btn tp-consilium-toggle" '
+ 'title="Die verbündeten Legionen sehen diese Sitzung dann unter „Karte“ und schauen zu – nur solange sie läuft">'
+ '🤝 Für Elyos Allianz freigeben</button></span>';
}
return share
? `<span class="tp-live-consilium is-shared" title="${esc(`Freigegeben von ${share.by || 'unbekannt'}${since}`)}">`
+ '🤝 Für Elyos Allianz freigegeben – die verbündeten Legionen können zuschauen</span>'
: '';
}
/** Zum Schritt springen, in dem jemand gerade zeichnet bzw. den er ansieht. */
followUser(userId) {
const user = this.liveUsers().find(u => u.id === userId);
const index = user ? this.liveUserStepIndex(user) : -1;
if (index >= 0) this.goToStep(index);
}
toast(text, isError = false) {
const el = this.el.toast;
el.textContent = text;
el.classList.toggle('error', isError);
el.classList.remove('hidden');
clearTimeout(this.toastTimer);
this.toastTimer = setTimeout(() => el.classList.add('hidden'), isError ? 6000 : 3500);
}
select(id) {
// Gaeste bleiben in der Taktik ihrer Sitzung
if (this.guestSession) return;
this.cancelDraft();
this.stopPlay();
this.anim = null;
this.selectedShapeId = null;
this.selectedId = this.selectedId === id ? null : id;
this.stepIndex = 0;
if (!this.selectedId) this.setTool('pan');
this.renderUI();
this.redraw();
}
/** Zu einem Schritt blaettern - mit Uebergang vom bisherigen. byPlayer: vom Abspielen (laeuft weiter). */
goToStep(index, byPlayer = false) {
const tactic = this.currentTactic();
if (!tactic) return;
if (!byPlayer) this.stopPlay();
const target = Math.max(0, Math.min(index, tactic.steps.length - 1));
if (target === this.stepIndex) return;
const from = this.currentStep();
this.cancelDraft();
this.selectedShapeId = null;
this.stepIndex = target;
this.startTransition(from ? from.shapes : null);
this.renderUI();
this.redraw();
}
// ------------------------------------------------------------------
// Taktiken und Schritte bearbeiten
// ------------------------------------------------------------------
static visibilityField(value) {
return {
name: 'visibility', label: 'Sichtbarkeit', type: 'select', value: value || 'private',
options: [
{ value: 'private', label: '🔒 Privat – nur ich sehe sie' },
{ value: 'public', label: '🌐 Öffentlich – alle Mitglieder können sie ansehen' }
]
};
}
async newTactic() {
const values = await this.dialog('Neue Taktik', [
{ name: 'name', label: 'Name', required: true, max: 120, placeholder: 'z. B. Festung Süd – Angriff' },
{ name: 'description', label: 'Beschreibung (optional)', type: 'textarea', max: 5000,
placeholder: 'Ziel, Aufstellung, Rollen …' },
TacticController.visibilityField('private')
], 'Anlegen');
if (!values) return;
const result = await this.run('tactic_create', { map: this.slug, ...values });
if (!result) return;
this.selectedId = result.tactic_id;
this.stepIndex = 0;
await this.reload();
// Im Raidplaner beginnt man mit der Aufstellung, auf den Weltkarten mit dem Stift
const dungeon = this.map.mapData.currentMap && this.map.mapData.currentMap.area === 'dungeons';
if (this.canEditCurrent()) this.setTool(dungeon ? 'token' : 'pen');
const next = dungeon
? 'Stell jetzt die Figuren für Schritt 1 auf – für den nächsten Schritt „+ Kopie dieses Schritts“ und verschieben.'
: 'Zeichne jetzt Schritt 1 ein.';
this.toast(values.visibility === 'public'
? `Öffentliche Taktik angelegt. ${next}`
: `Private Taktik angelegt – nur du siehst sie. ${next}`);
}
async editTactic() {
const tactic = this.currentTactic();
if (!tactic) return;
const fields = [
{ name: 'name', label: 'Name', required: true, max: 120, value: tactic.name },
{ name: 'description', label: 'Beschreibung (optional)', type: 'textarea', max: 5000, value: tactic.description }
];
// Die Sichtbarkeit legt nur der Ersteller fest - bei hervorgehobenen Taktiken nur mit dem
// Recht zum Hervorheben (sonst waere eine offizielle Taktik mit einem Klick fuer alle weg).
if (tactic.can_change_visibility) fields.push(TacticController.visibilityField(tactic.visibility));
const message = tactic.is_mine && !tactic.can_change_visibility
? 'Die Taktik ist hervorgehoben und bleibt deshalb öffentlich – privat stellen kann sie nur, wer Taktiken hervorheben darf.'
: '';
const values = await this.dialog('Taktik bearbeiten', fields, 'Speichern', { message });
if (!values) return;
if (values.visibility === 'private' && tactic.visibility === 'public' && tactic.highlight !== 'none'
&& !(await this.confirmDialog('Hervorhebung geht verloren',
'Die Taktik ist hervorgehoben. Wird sie privat, geht die Hervorhebung verloren und nur du siehst sie noch. Trotzdem privat stellen?',
'Privat stellen'))) {
return;
}
if (await this.run('tactic_update', { tactic_id: tactic.id, ...values })) {
this.notifyChanged('tactic');
await this.reload();
}
}
async setHighlight(value) {
const tactic = this.currentTactic();
if (!tactic || value === tactic.highlight) return;
const result = await this.run('tactic_highlight', { tactic_id: tactic.id, highlight: value });
if (result) this.notifyChanged('highlight');
if (result && result.message) this.toast(result.message);
await this.reload();
}
async deleteTactic() {
const tactic = this.currentTactic();
if (!tactic || !tactic.can_delete) return;
const confirmed = await this.confirmDialog('Taktik löschen',
`Taktik „${tactic.name}“ mit allen Schritten und Zeichnungen löschen?\n`
+ 'Unter „Gelöschte“ lässt sie sich 90 Tage lang wiederherstellen.', 'Löschen', true);
if (!confirmed) return;
if (await this.run('tactic_delete', { tactic_id: tactic.id })) {
this.notifyChanged('deleted');
this.selectedId = null;
await this.reload();
this.toast('Taktik gelöscht – unter „Gelöschte“ lässt sie sich wiederherstellen.');
}
}
/** Ganze Taktik als eigene Kopie anlegen - geht bei jeder Taktik, die man sehen kann. */
async copyTactic() {
const tactic = this.currentTactic();
if (!tactic) return;
const values = await this.dialog('Taktik kopieren', [
{ name: 'name', label: 'Name der Kopie', required: true, max: 120,
value: Array.from(`Kopie von ${tactic.name}`).slice(0, 120).join('') },
TacticController.visibilityField('private')
], 'Kopieren', {
message: 'Legt eine eigene Taktik mit allen Schritten und Zeichnungen an. Die Vorlage bleibt unverändert.'
});
if (!values) return;
const result = await this.run('tactic_copy', { tactic_id: tactic.id, ...values });
if (!result) return;
this.cancelDraft();
this.selectedId = result.tactic_id;
this.stepIndex = 0;
await this.reload();
this.toast(values.visibility === 'public'
? 'Kopie angelegt – für alle sichtbar.'
: 'Kopie angelegt – nur du siehst sie.');
}
/** Verlauf: gesicherte Staende der gewaehlten Taktik ansehen und einen wiederherstellen. */
async showHistory() {
const tactic = this.currentTactic();
if (!tactic || !tactic.can_edit) return;
const result = await this.run('revision_list', { tactic_id: tactic.id });
if (!result) return;
const revisions = result.revisions || [];
if (revisions.length === 0) {
this.toast('Noch keine gesicherten Stände – sie entstehen automatisch, sobald jemand etwas ändert.');
return;
}
const values = await this.dialog(`Verlauf: ${tactic.name}`, [
{ name: 'revision_id', label: 'Stand', type: 'select', value: String(revisions[0].id),
options: revisions.map(r => ({ value: String(r.id), label: r.label })) }
], 'Wiederherstellen', {
message: 'Vor Änderungen wird der bisherige Stand automatisch gesichert (höchstens alle 30 Minuten je Person). '
+ 'Beim Wiederherstellen kommt auch der jetzige Stand in den Verlauf – es geht also nichts verloren.'
});
if (!values) return;
await this.restoreRevision(parseInt(values.revision_id, 10));
}
/** Papierkorb: eine geloeschte Taktik dieser Region zurueckholen. */
async showTrash() {
if (this.deleted.length === 0) return;
const values = await this.dialog('Gelöschte Taktiken', [
{ name: 'revision_id', label: 'Taktik', type: 'select', value: String(this.deleted[0].revision_id),
options: this.deleted.map(d => ({ value: String(d.revision_id), label: d.label })) }
], 'Wiederherstellen', {
message: 'Gelöschte Taktiken lassen sich 90 Tage lang wiederherstellen – mit allen Schritten und Zeichnungen, '
+ 'Ersteller und Sichtbarkeit wie vor dem Löschen.'
});
if (!values) return;
await this.restoreRevision(parseInt(values.revision_id, 10));
}
async restoreRevision(revisionId) {
const result = await this.run('revision_restore', { revision_id: revisionId });
if (!result) return;
// Frueherer Stand der offenen Taktik: die anderen laden ihn auch (aus dem Papierkorb ist niemand drin)
if (result.tactic_id === this.live.tacticId) this.notifyChanged('restore');
// Schritte und Zeichnungen haben danach neue IDs - die Rueckgaengig-Liste passt nicht mehr.
this.cancelDraft();
this.undoStacks = {};
this.selectedId = result.tactic_id;
this.stepIndex = 0;
await this.reload();
this.toast(result.message || 'Wiederhergestellt.');
}
async addStep(copyCurrent) {
const tactic = this.currentTactic();
const current = this.currentStep();
if (!tactic) return;
const number = tactic.steps.length + 1;
const values = await this.dialog(copyCurrent ? `Schritt ${number} als Kopie` : `Schritt ${number} anlegen`, [
{ name: 'title', label: 'Titel (optional)', max: 120, placeholder: `z. B. Vorrücken zum Tor` },
{ name: 'description', label: 'Beschreibung (optional)', type: 'textarea', max: 5000,
placeholder: 'Was passiert in diesem Schritt?' }
], 'Anlegen');
if (!values) return;
const payload = { tactic_id: tactic.id, ...values };
if (copyCurrent && current) payload.copy_from = current.id;
const result = await this.run('step_create', payload);
if (result) {
this.notifyChanged('steps');
await this.reload(result.step_id);
}
}
async editStep(step, index) {
const values = await this.dialog(`Schritt ${index + 1} bearbeiten`, [
{ name: 'title', label: 'Titel (optional)', max: 120, value: step.title },
{ name: 'description', label: 'Beschreibung (optional)', type: 'textarea', max: 5000, value: step.description }
]);
if (!values) return;
if (await this.run('step_update', { step_id: step.id, ...values })) {
this.notifyChanged('steps');
await this.reload(step.id);
}
}
async moveStep(step, direction) {
if (await this.run('step_move', { step_id: step.id, direction })) {
this.notifyChanged('steps');
await this.reload(step.id);
}
}
async deleteStep(step, index) {
const label = TacticController.stepLabel(step, index);
const count = step.shapes.length;
const confirmed = await this.confirmDialog('Schritt löschen',
`Schritt ${index + 1} („${label}“) mit ${count} ${count === 1 ? 'Zeichnung' : 'Zeichnungen'} löschen?\n`
+ 'Ein früherer Stand lässt sich über 🕘 Verlauf wiederherstellen.', 'Löschen', true);
if (!confirmed) return;
if (await this.run('step_delete', { step_id: step.id })) {
this.notifyChanged('steps');
await this.reload();
}
}
// ------------------------------------------------------------------
// Zeichnen
// ------------------------------------------------------------------
setTool(tool) {
this.cancelDraft();
this.drag = null;
if (tool !== 'move') this.selectedShapeId = null;
this.tool = tool;
this.layer.hoverId = null;
this.layer.canvas.classList.toggle('drawing', tool !== 'pan');
this.layer.canvas.classList.toggle('erasing', tool === 'eraser');
this.layer.canvas.classList.toggle('moving', tool === 'move');
this.el.toolbar.querySelectorAll('.tool[data-tool]').forEach(btn => {
btn.classList.toggle('active', btn.dataset.tool === tool);
});
this.el.palette.classList.toggle('hidden', tool !== 'token' || !this.canEditCurrent());
this.el.angle.classList.toggle('hidden', tool !== 'cone');
if (tool === 'area') {
this.toast('Eckpunkte anklicken – Doppelklick oder Enter schließt die Fläche ab.');
} else if (tool === 'token') {
this.renderPaletteIcons();
this.toast('Figur auswählen und auf die Karte klicken – Spielernummern und Markierungen zählen von selbst weiter.');
} else if (tool === 'move') {
this.toast('Figur oder Zeichnung ziehen zum Verschieben – antippen zum Beschriften oder Löschen.');
}
this.redraw();
}
// ------------------------------------------------------------------
// Figuren (Werkzeug ♟)
// ------------------------------------------------------------------
/** Auswahl der Figuren aufbauen - einmal; die Bilder zeichnet renderPaletteIcons. */
buildPalette() {
const esc = TacticController.esc;
this.el.palette.innerHTML = TOKEN_ICONS.map(group => `
<div class="tk-group">
<div class="tk-group-title">${esc(group.group)}</div>
<div class="tk-grid">
${group.items.map(item => `
<button type="button" class="tk-item" data-icon="${item.id}" title="${esc(item.label)}" aria-label="${esc(item.label)}">
<canvas width="32" height="32"></canvas>
</button>`).join('')}
</div>
</div>`).join('');
this.el.palette.addEventListener('click', event => {
const button = event.target.closest('.tk-item');
if (!button) return;
this.tokenIcon = button.dataset.icon;
this.markPaletteSelection();
});
this.renderPaletteIcons();
}
/** Figuren der Auswahl in der gewaehlten Farbe zeichnen (auch fuer hochaufloesende Bildschirme). */
renderPaletteIcons() {
if (!this.el.palette || this.el.palette.classList.contains('hidden') && this.paletteDrawn) return;
const ratio = window.devicePixelRatio || 1;
this.el.palette.querySelectorAll('.tk-item').forEach(button => {
const canvas = button.querySelector('canvas');
const size = 32;
if (canvas.width !== size * ratio) {
canvas.width = size * ratio;
canvas.height = size * ratio;
}
const ctx = canvas.getContext('2d');
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
ctx.clearRect(0, 0, size, size);
const r = 11 * (TokenIcons.scale(button.dataset.icon) > 1 ? 1.15 : 1);
TokenIcons.draw(ctx, button.dataset.icon, size / 2, size / 2, r, this.el.color.value);
});
this.paletteDrawn = true;
this.markPaletteSelection();
}
markPaletteSelection() {
this.el.palette.querySelectorAll('.tk-item').forEach(button => {
button.classList.toggle('active', button.dataset.icon === this.tokenIcon);
});
}
/** Figur an einer Stelle setzen; Spielernummern und Markierungen A-D zaehlen danach weiter. */
placeToken(point) {
const shape = this.newDraft('token', [point]);
shape.icon = this.tokenIcon;
this.saveShape(shape);
const item = TokenIcons.find(this.tokenIcon);
if (item && item.next) {
this.tokenIcon = item.next;
this.markPaletteSelection();
}
}
// ------------------------------------------------------------------
// Rechteck und Kegel - gespeichert als Flaeche (Form 'area')
// ------------------------------------------------------------------
static rectPoints(a, b) {
return [[a[0], a[1]], [b[0], a[1]], [b[0], b[1]], [a[0], b[1]]];
}
/** Kegel von der Spitze apex in Richtung tip, Oeffnungswinkel in Grad - als Vieleck mit Bogen. */
static conePoints(apex, tip, degrees) {
const radius = Math.hypot(tip[0] - apex[0], tip[1] - apex[1]);
const direction = Math.atan2(tip[1] - apex[1], tip[0] - apex[0]);
const half = (degrees * Math.PI / 180) / 2;
const segments = Math.max(4, Math.round(degrees / 7.5));
const points = degrees >= 360 ? [] : [[apex[0], apex[1]]];
for (let i = 0; i <= segments; i++) {
const angle = direction - half + (2 * half * i) / segments;
points.push([apex[0] + Math.cos(angle) * radius, apex[1] + Math.sin(angle) * radius]);
}
return points;
}
// ------------------------------------------------------------------
// Verschieben und Beschriften (Werkzeug ✥)
// ------------------------------------------------------------------
/** Die echte Zeichnung des aktuellen Schritts zu einem Treffer (beim Blaettern sind es Kopien). */
realShape(hit) {
const step = this.currentStep();
return hit && step ? step.shapes.find(s => s.id === hit.id) || null : null;
}
/** Kleine Leiste mit ✎ und 🗑 ueber der ausgewaehlten Zeichnung. */
placeShapeActions() {
const el = this.el.shapeActions;
const step = this.currentStep();
const shape = this.tool === 'move' && this.selectedShapeId && !this.drag && step
? step.shapes.find(s => s.id === this.selectedShapeId) : null;
if (!shape || !this.canEditCurrent()) {
el.classList.add('hidden');
return;
}
const pts = shape.points.map(p => this.layer.toScreen(p));
const top = Math.min(...pts.map(p => p.y));
const left = pts.reduce((sum, p) => sum + p.x, 0) / pts.length;
const lift = shape.type === 'token' ? this.layer.tokenRadius(shape) + 8 : 12;
el.style.left = `${Math.round(left)}px`;
el.style.top = `${Math.round(top - lift)}px`;
el.classList.remove('hidden');
// Beschriften geht bei allem, was eine Beschriftung zeigt
el.querySelector('[data-shape-action="label"]').classList.toggle('hidden', ['pen', 'line', 'arrow'].includes(shape.type));
}
async editShapeLabel(shape) {
const isText = shape.type === 'text';
const values = await this.dialog(isText ? 'Text ändern' : 'Beschriftung', [
{ name: 'label', label: isText ? 'Text' : 'Beschriftung (optional)', required: isText, max: 200, value: shape.label,
placeholder: shape.type === 'token' ? 'z. B. Name des Spielers' : '' }
], 'Speichern');
if (!values || values.label === shape.label) return;
this.updateShape(shape, { label: values.label });
}
/**
* Zeichnung aendern (Stuetzpunkte und/oder Beschriftung) und speichern. Die Karte zeigt die Aenderung
* sofort; lehnt der Server ab, springt sie zurueck. remember: fuers Zuruecknehmen merken.
*/
async updateShape(shape, changes, before = null, remember = true) {
const step = this.currentStep();
if (!step) return false;
const stepId = step.id;
const previous = before || { points: shape.points, label: shape.label };
if (changes.points) shape.points = changes.points;
if (changes.label !== undefined) shape.label = changes.label;
this.redraw();
const payload = { shape_id: shape.id };
if (changes.points) payload.points = changes.points.map(p => [Math.round(p[0] * 100) / 100, Math.round(p[1] * 100) / 100]);
if (changes.label !== undefined) payload.label = changes.label;
const result = await this.run('shape_update', payload);
const target = (this.stepById(stepId) || step).shapes.find(s => s.id === shape.id);
if (!result) {
if (target) Object.assign(target, previous);
this.redraw();
return false;
}
if (target) Object.assign(target, result.shape);
if (remember) {
(this.undoStacks[stepId] = this.undoStacks[stepId] || [])
.push({ kind: 'update', id: shape.id, points: previous.points, label: previous.label });
}
// Der Live-Verteiler kennt Verschieben nicht - die anderen laden die Taktik neu.
this.notifyChanged('shapes');
this.redraw();
return true;
}
cancelDraft() {
// Live verschickt und nicht gerade beim Speichern: bei den anderen wieder wegnehmen
const draft = this.draft;
if (draft && draft.liveSent && !draft.saving) this.live.endDraft(draft.liveId, true);
this.draft = null;
this.drawing = false;
}
/** Den Strich, der gerade entsteht, live an die anderen (gebuendelt, siehe TacticLiveService). */
sendDraft() {
const draft = this.draft;
const step = this.currentStep();
if (!draft || draft.saving || !step || !this.live.canDraw()) return;
draft.liveSent = true;
this.live.updateDraft(draft.liveId, step.id,
{ type: draft.type, color: draft.color, width: draft.width, label: draft.label },
draft.points, draft.type === 'pen');
}
worldAt(event) {
const rect = this.layer.canvas.getBoundingClientRect();
const world = this.view.screenToWorld(event.clientX - rect.left, event.clientY - rect.top);
return [world.x, world.y];
}
screenAt(event) {
const rect = this.layer.canvas.getBoundingClientRect();
return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}
screenDistance(a, b) {
const pa = this.layer.toScreen(a);
const pb = this.layer.toScreen(b);
return Math.hypot(pa.x - pb.x, pa.y - pb.y);
}
newDraft(type, points) {
return {
type,
points,
color: this.el.color.value,
width: parseInt(this.el.width.value, 10) || 4,
label: '',
liveId: TacticController.newLiveId()
};
}
onPointerDown(event) {
// Rechte/mittlere Maustaste verschiebt die Karte auch mitten im Zeichnen.
if (event.button !== 0) {
this.view.canvas.dispatchEvent(new MouseEvent('mousedown', {
clientX: event.clientX, clientY: event.clientY, bubbles: true
}));
return;
}
if (!this.currentStep()) return;
// Gaeste des Consiliums: nur die Zeichenwerkzeuge (der Server nimmt auch nichts anderes an)
if (this.guest && !TacticController.GUEST_TOOLS.includes(this.tool)) return;
const point = this.worldAt(event);
switch (this.tool) {
case 'pen':
this.draft = this.newDraft('pen', [point]);
this.drawing = true;
this.layer.canvas.setPointerCapture(event.pointerId);
break;
case 'line':
case 'arrow':
case 'circle':
this.draft = this.newDraft(this.tool, [point, point]);
this.drawing = true;
this.layer.canvas.setPointerCapture(event.pointerId);
break;
case 'rect':
case 'cone':
// Gespeichert wird eine Flaeche; from/to merken sich, wie sie aufgezogen wurde.
this.draft = this.newDraft('area', [point, point, point]);
this.draft.tool = this.tool;
this.draft.from = point;
this.draft.to = point;
this.drawing = true;
this.layer.canvas.setPointerCapture(event.pointerId);
break;
case 'token':
this.placeToken(point);
break;
case 'move': {
const screen = this.screenAt(event);
const shape = this.realShape(this.layer.hitTest(screen.x, screen.y));
if (!shape) {
// Daneben: Auswahl aufheben und die Karte verschieben lassen
this.selectedShapeId = null;
this.redraw();
this.view.canvas.dispatchEvent(new MouseEvent('mousedown', {
clientX: event.clientX, clientY: event.clientY, bubbles: true
}));
return;
}
this.anim = null;
this.selectedShapeId = shape.id;
this.drag = { shape, start: point, orig: shape.points.map(p => [p[0], p[1]]), label: shape.label, moved: false };
this.layer.canvas.setPointerCapture(event.pointerId);
break;
}
case 'area':
// Der letzte Punkt folgt immer der Maus, ein Klick setzt ihn fest.
if (!this.draft) {
this.draft = this.newDraft('area', [point, point]);
} else {
this.draft.points[this.draft.points.length - 1] = point;
this.draft.points.push(point);
}
break;
case 'point':
case 'text':
this.placeLabeled(this.tool, point);
break;
case 'eraser': {
const screen = this.screenAt(event);
const hit = this.realShape(this.layer.hitTest(screen.x, screen.y));
if (hit) this.deleteShape(hit);
break;
}
}
this.sendDraft();
this.redraw();
}
onPointerMove(event) {
if (this.tool === 'eraser' || (this.tool === 'move' && !this.drag)) {
const screen = this.screenAt(event);
const hit = this.layer.hitTest(screen.x, screen.y);
const hoverId = hit ? hit.id : null;
if (hoverId !== this.layer.hoverId) {
this.layer.hoverId = hoverId;
this.redraw();
}
return;
}
if (this.drag) {
this.dragTo(this.worldAt(event));
return;
}
// Ein abgeschlossener Strich wird gerade gespeichert - er folgt der Maus nicht mehr (und geht
// live nicht noch einmal raus, sonst taucht er bei den anderen nach dem Speichern wieder auf).
if (!this.draft || this.draft.saving) return;
const point = this.worldAt(event);
const points = this.draft.points;
if (this.draft.tool === 'rect' || this.draft.tool === 'cone') {
if (!this.drawing) return;
this.draft.to = point;
this.draft.points = this.draft.tool === 'rect'
? TacticController.rectPoints(this.draft.from, point)
: TacticController.conePoints(this.draft.from, point, parseInt(this.el.angle.value, 10) || 90);
} else if (this.draft.type === 'pen') {
if (!this.drawing || this.screenDistance(points[points.length - 1], point) < 3) return;
points.push(point);
} else if (this.draft.type === 'area') {
points[points.length - 1] = point;
} else if (this.drawing) {
points[1] = point;
} else {
return;
}
this.sendDraft();
this.redraw();
}
/** Gezogene Zeichnung mitfuehren - ganz, und nicht ueber den Rand hinaus, den der Server annimmt. */
dragTo(point) {
const drag = this.drag;
let dx = point[0] - drag.start[0];
let dy = point[1] - drag.start[1];
if (!drag.moved && this.screenDistance(drag.start, point) < 4) return;
drag.moved = true;
const xs = drag.orig.map(p => p[0]);
const ys = drag.orig.map(p => p[1]);
const min = CONFIG.WORLD_MIN_X - 512;
const max = CONFIG.WORLD_MAX_X + 512;
dx = Math.max(min - Math.min(...xs), Math.min(max - Math.max(...xs), dx));
dy = Math.max(min - Math.min(...ys), Math.min(max - Math.max(...ys), dy));
drag.shape.points = drag.orig.map(p => [p[0] + dx, p[1] + dy]);
this.redraw();
}
onPointerUp() {
if (this.drag) {
const drag = this.drag;
this.drag = null;
if (drag.moved) {
this.updateShape(drag.shape, { points: drag.shape.points }, { points: drag.orig, label: drag.label });
} else {
this.redraw(); // nur angetippt: ausgewaehlt, die Leiste mit ✎ und 🗑 erscheint
}
return;
}
if (!this.drawing || !this.draft) return;
this.drawing = false;
const draft = this.draft;
if (draft.type === 'pen') {
if (draft.points.length < 2) {
this.cancelDraft();
} else {
// Toleranz: gut ein Bildschirmpixel bei der aktuellen Zoomstufe.
draft.points = TacticLayer.simplify(draft.points, 1.2 / this.layer.scale());
this.saveShape(draft);
}
} else if (draft.from) {
// Rechteck/Kegel: nur geklickt, nicht gezogen - nichts anlegen
if (this.screenDistance(draft.from, draft.to) < 6) this.cancelDraft();
else this.saveShape(draft);
} else if (this.screenDistance(draft.points[0], draft.points[1]) < 6) {
// Nur geklickt, nicht gezogen - nichts anlegen.
this.cancelDraft();
} else {
this.saveShape(draft);
}
this.redraw();
}
finishArea() {
if (!this.draft || this.draft.type !== 'area') return;
// Der mitlaufende Punkt faellt weg, ebenso doppelte Punkte vom Doppelklick.
const points = [];
this.draft.points.slice(0, -1).forEach(point => {
if (points.length === 0 || this.screenDistance(points[points.length - 1], point) >= 4) {
points.push(point);
}
});
if (points.length < 3) {
this.toast('Eine Fläche braucht mindestens drei Eckpunkte.', true);
return;
}
this.draft.points = points;
this.saveShape(this.draft);
this.redraw();
}
async placeLabeled(type, point) {
const isText = type === 'text';
const values = await this.dialog(isText ? 'Text setzen' : 'Punkt setzen', [
{ name: 'label', label: isText ? 'Text' : 'Beschriftung (optional)', required: isText, max: 200,
placeholder: isText ? 'z. B. Heiler hier' : 'z. B. Sammelpunkt' }
], 'Setzen');
if (!values) return;
const shape = this.newDraft(type, [point]);
shape.label = values.label;
this.saveShape(shape);
}
async saveShape(shape) {
const step = this.currentStep();
if (!step) return;
const stepId = step.id;
const tacticId = this.selectedId;
// Die Form bleibt als Entwurf sichtbar, bis der Server sie bestaetigt hat - bei den anderen
// ebenso: der Rest des Strichs geht noch raus, ersetzt wird er erst durch die gespeicherte Form.
shape.saving = true;
if (shape.liveSent) this.live.endDraft(shape.liveId, false);
const result = await this.run('shape_create', {
step_id: stepId,
type: shape.type,
icon: shape.icon || '',
color: shape.color,
width: shape.width,
label: shape.label,
points: shape.points.map(p => [Math.round(p[0] * 100) / 100, Math.round(p[1] * 100) / 100])
});
if (this.draft === shape) this.draft = null;
const liveHere = this.live.tacticId === tacticId;
if (result) {
// Inzwischen neu geladen (Aenderung eines anderen)? Dann ist es ein neues Schritt-Objekt.
const target = this.stepById(stepId) || step;
if (!target.shapes.some(s => s.id === result.shape.id)) target.shapes.push(result.shape);
(this.undoStacks[stepId] = this.undoStacks[stepId] || []).push({ kind: 'create', id: result.shape.id });
if (liveHere && TacticController.LIVE_SHAPE_TYPES.includes(result.shape.type)) {
this.live.push({ type: 'shape_added', step: stepId, shape: result.shape, draft: shape.liveSent ? shape.liveId : null });
} else if (liveHere) {
// Figuren kennt der Live-Verteiler nicht - die anderen laden die Taktik neu
this.notifyChanged('shapes');
}
this.renderUI();
} else if (shape.liveSent && liveHere) {
this.live.push({ type: 'draft_end', id: shape.liveId });
}
this.redraw();
}
async deleteShape(shape) {
const step = this.currentStep();
if (!step) return;
const stepId = step.id;
const tacticId = this.selectedId;
if (await this.run('shape_delete', { shape_id: shape.id })) {
const target = this.stepById(stepId) || step;
target.shapes = target.shapes.filter(s => s.id !== shape.id);
if (this.live.tacticId === tacticId) this.live.push({ type: 'shape_removed', step: stepId, shape_id: shape.id });
this.layer.hoverId = null;
if (this.selectedShapeId === shape.id) this.selectedShapeId = null;
this.renderUI();
this.redraw();
}
}
/** Letzte eigene Aenderung im Schritt zuruecknehmen: Neues loeschen, Verschobenes zurueckschieben. */
undoLast() {
const step = this.currentStep();
if (!step) return;
if (this.draft) {
this.cancelDraft();
this.redraw();
return;
}
const stack = this.undoStacks[step.id] || [];
while (stack.length) {
const entry = stack.pop();
const shape = step.shapes.find(s => s.id === entry.id);
if (!shape) continue;
if (entry.kind === 'create') {
this.deleteShape(shape);
} else {
this.updateShape(shape, { points: entry.points, label: entry.label }, null, false);
}
return;
}
this.toast('In diesem Schritt gibt es nichts rückgängig zu machen.');
}
// ------------------------------------------------------------------
// Eingabedialog
// ------------------------------------------------------------------
/**
* Zeigt einen kleinen Dialog mit Eingabefeldern. Liefert die (getrimmten) Werte oder
* null bei Abbruch. options.message: Text ueber den Feldern, options.danger: roter
* Bestaetigungsknopf. Ohne Felder ist es eine reine Rueckfrage (siehe confirmDialog).
*/
dialog(title, fields, submitLabel = 'Speichern', options = {}) {
if (this.dialogCancel) this.dialogCancel();
return new Promise(resolve => {
const el = this.el;
el.dTitle.textContent = title;
el.dSubmit.textContent = submitLabel;
el.dSubmit.classList.toggle('td-danger', !!options.danger);
el.dFields.innerHTML = '';
if (options.message) {
const message = document.createElement('p');
message.className = 'td-message';
message.textContent = options.message;
el.dFields.appendChild(message);
}
fields.forEach(field => {
const label = document.createElement('label');
label.className = 'td-field';
label.textContent = field.label;
const tag = field.type === 'textarea' ? 'textarea' : (field.type === 'select' ? 'select' : 'input');
const input = document.createElement(tag);
if (field.type === 'textarea') {
input.rows = 4;
} else if (field.type === 'select') {
(field.options || []).forEach(option => {
const el = document.createElement('option');
el.value = option.value;
el.textContent = option.label;
input.appendChild(el);
});
} else {
input.type = 'text';
}
input.name = field.name;
input.value = field.value || '';
if (field.placeholder) input.placeholder = field.placeholder;
if (field.max) input.maxLength = field.max;
if (field.required) input.required = true;
label.appendChild(input);
el.dFields.appendChild(label);
});
const finish = value => {
el.dialog.classList.add('hidden');
el.form.onsubmit = null;
el.dCancel.onclick = null;
this.dialogOpen = false;
this.dialogCancel = null;
resolve(value);
};
el.form.onsubmit = event => {
event.preventDefault();
const values = {};
fields.forEach(field => {
values[field.name] = el.form.elements[field.name].value.trim();
});
if (fields.some(field => field.required && !values[field.name])) return;
finish(values);
};
el.dCancel.onclick = () => finish(null);
this.dialogCancel = () => finish(null);
this.dialogOpen = true;
el.dialog.classList.remove('hidden');
// Erstes Feld - ohne Felder der Knopf, bei Loeschfragen "Abbrechen" (Enter loescht dann nichts).
const first = el.dFields.querySelector('input, textarea, select')
|| (options.danger ? el.dCancel : el.dSubmit);
first.focus();
});
}
/**
* Rueckfrage im Stil der Karte statt des Browser-confirm(): true bei Bestaetigung.
* danger: roter Knopf, z.B. mit okLabel "Löschen".
*/
async confirmDialog(title, message, okLabel = 'OK', danger = false) {
return (await this.dialog(title, [], okLabel, { message, danger })) !== null;
}
// ------------------------------------------------------------------
// Ereignisse
// ------------------------------------------------------------------
bindPanel() {
const el = this.el;
el.collapse.addEventListener('click', () => {
const collapsed = el.panel.classList.toggle('collapsed');
el.collapse.textContent = collapsed ? '▸' : '▾';
el.collapse.setAttribute('aria-expanded', String(!collapsed));
});
el.newBtn.addEventListener('click', () => this.newTactic());
el.trash.addEventListener('click', () => this.showTrash());
el.copy.addEventListener('click', () => this.copyTactic());
el.share.addEventListener('click', () => this.shareTactic());
el.history.addEventListener('click', () => this.showHistory());
el.edit.addEventListener('click', () => this.editTactic());
el.del.addEventListener('click', () => this.deleteTactic());
el.highlightSelect.addEventListener('change', () => this.setHighlight(el.highlightSelect.value));
el.stepAdd.addEventListener('click', () => this.addStep(false));
el.stepCopy.addEventListener('click', () => this.addStep(true));
el.list.addEventListener('click', event => {
const item = event.target.closest('.tp-item');
if (item) this.select(parseInt(item.dataset.id, 10));
});
el.steps.addEventListener('click', event => {
const li = event.target.closest('.tp-step');
if (!li) return;
const index = parseInt(li.dataset.index, 10);
const step = this.currentTactic().steps[index];
const button = event.target.closest('[data-step-action]');
if (!button) {
this.goToStep(index);
return;
}
switch (button.dataset.stepAction) {
case 'up': this.moveStep(step, -1); break;
case 'down': this.moveStep(step, 1); break;
case 'edit': this.editStep(step, index); break;
case 'delete': this.deleteStep(step, index); break;
}
});
el.ghosts.addEventListener('change', () => {
this.showGhosts = el.ghosts.checked;
this.redraw();
});
// Live: Klick auf ein Mitglied springt in den Schritt, in dem es gerade zeichnet bzw. ist
el.live.addEventListener('click', event => {
const button = event.target.closest('.tp-live-user');
if (button) this.followUser(parseInt(button.dataset.user, 10));
if (event.target.closest('.tp-consilium-toggle')) this.toggleConsilium();
});
el.prev.addEventListener('click', () => this.goToStep(this.stepIndex - 1));
el.next.addEventListener('click', () => this.goToStep(this.stepIndex + 1));
el.play.addEventListener('click', () => this.togglePlay());
// ✎ / 🗑 an der ausgewaehlten Zeichnung
el.shapeActions.addEventListener('click', event => {
const button = event.target.closest('[data-shape-action]');
const step = this.currentStep();
const shape = step ? step.shapes.find(s => s.id === this.selectedShapeId) : null;
if (!button || !shape) return;
if (button.dataset.shapeAction === 'label') this.editShapeLabel(shape);
else this.deleteShape(shape);
});
// Tasten im Dialog nicht an die Tastenkuerzel der Karte (+, -, 0 ...) weiterreichen.
el.dialog.addEventListener('keydown', event => {
event.stopPropagation();
if (event.key === 'Escape' && this.dialogCancel) this.dialogCancel();
// Enter in einem einzeiligen Feld schickt ab (in der Beschreibung: neue Zeile).
if (event.key === 'Enter' && event.target.tagName === 'INPUT') {
event.preventDefault();
el.form.requestSubmit();
}
});
}
bindToolbar() {
this.el.toolbar.addEventListener('click', event => {
const button = event.target.closest('.tool[data-tool]');
if (button) this.setTool(button.dataset.tool);
});
this.el.undo.addEventListener('click', () => this.undoLast());
// Die Figuren der Auswahl tragen die gewaehlte Farbe
this.el.color.addEventListener('input', () => this.renderPaletteIcons());
this.buildPalette();
}
bindCanvas() {
const canvas = this.layer.canvas;
canvas.addEventListener('pointerdown', event => this.onPointerDown(event));
canvas.addEventListener('pointermove', event => this.onPointerMove(event));
canvas.addEventListener('pointerup', () => this.onPointerUp());
canvas.addEventListener('pointercancel', () => {
this.cancelDraft();
if (this.drag) {
// Abgebrochenes Ziehen: zurueck an die alte Stelle
this.drag.shape.points = this.drag.orig;
this.drag = null;
}
this.redraw();
});
canvas.addEventListener('dblclick', event => {
event.preventDefault();
if (this.tool === 'move') {
// Doppelklick auf eine Zeichnung: Beschriftung aendern
const screen = this.screenAt(event);
const shape = this.realShape(this.layer.hitTest(screen.x, screen.y));
if (shape && !['pen', 'line', 'arrow'].includes(shape.type)) this.editShapeLabel(shape);
return;
}
this.finishArea();
});
canvas.addEventListener('contextmenu', event => event.preventDefault());
// Zoomen per Mausrad soll auch im Zeichenmodus gehen - weiter an die Karte.
canvas.addEventListener('wheel', event => {
event.preventDefault();
this.view.canvas.dispatchEvent(new WheelEvent('wheel', {
deltaY: event.deltaY, deltaX: event.deltaX, clientX: event.clientX, clientY: event.clientY, cancelable: true
}));
}, { passive: false });
}
bindKeyboard() {
window.addEventListener('keydown', event => {
if (this.dialogOpen) return;
const tag = event.target && event.target.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
if (event.key === 'Escape') {
if (this.draft) {
this.cancelDraft();
this.redraw();
} else if (this.tool !== 'pan') {
this.setTool('pan');
}
} else if (event.key === 'Enter') {
this.finishArea();
} else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z') {
event.preventDefault();
if (this.canEditCurrent()) this.undoLast();
} else if (event.key === 'ArrowLeft' && this.currentTactic()) {
this.goToStep(this.stepIndex - 1);
} else if (event.key === 'ArrowRight' && this.currentTactic()) {
this.goToStep(this.stepIndex + 1);
} else if (event.key === ' ' && this.currentTactic() && !(tag === 'BUTTON')) {
event.preventDefault();
this.togglePlay();
} else if ((event.key === 'Delete' || event.key === 'Backspace') && this.tool === 'move' && this.selectedShapeId) {
const step = this.currentStep();
const shape = step ? step.shapes.find(s => s.id === this.selectedShapeId) : null;
if (shape && this.canEditCurrent()) this.deleteShape(shape);
}
});
}
// ------------------------------------------------------------------
// Link auf die Taktik
// ------------------------------------------------------------------
/** Link zur gewaehlten Taktik beim aktuellen Schritt kopieren (Raidplaner bzw. Karte, je nach Karte). */
shareTactic() {
const tactic = this.currentTactic();
const map = this.map.mapData.currentMap;
if (!tactic || !map) return;
const area = this.map.areaInfo(map.area);
const params = new URLSearchParams({ karte: map.slug, taktik: String(tactic.id) });
if (this.stepIndex > 0) params.set('schritt', String(this.stepIndex + 1));
const url = window.location.origin + area.page + '?' + params.toString();
const done = () => this.toast(tactic.visibility === 'private'
? 'Link kopiert – die Taktik ist privat, öffnen kannst ihn nur du.'
: 'Link kopiert – einfach in Discord, Termin oder Kommentar einfügen.');
const fallback = () => {
const input = document.createElement('input');
input.value = url;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
input.remove();
done();
};
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(url).then(done, fallback);
} else {
fallback();
}
}
}
// Formen, die der Live-Verteiler im Bot kennt (live_tactics.py) - bei allen anderen (Figuren) laden die
// anderen die Taktik neu, statt die Zeichnung live zu bekommen.
TacticController.LIVE_SHAPE_TYPES = ['pen', 'line', 'arrow', 'area', 'circle', 'point', 'text'];
// Werkzeuge fuer Gaeste des Consiliums mit Zeichenrecht - wie TACTIC_GUEST_SHAPE_TYPES in includes/tactics.php
// (Rechteck und Kegel werden als Flaeche gespeichert). Ohne Verschieben, Figuren, Radierer und Rueckgaengig.
TacticController.GUEST_TOOLS = ['pan', 'pen', 'arrow', 'line', 'circle', 'rect', 'cone', 'area', 'point', 'text'];