/**
* 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. Ansehen darf jeder mit map.view, anlegen und
* zeichnen nur, wer map.tactics hat - das entscheidet der Server (can_edit).
*/
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.canEdit = false;
this.selectedId = null;
this.stepIndex = 0;
this.showGhosts = false;
this.tool = 'pan';
this.draft = null;
this.drawing = false;
this.undoStacks = {}; // step_id -> IDs der in dieser Sitzung gezeichneten Formen
this.loadToken = 0;
this.dialogOpen = false;
this.dialogCancel = null;
const $ = id => document.getElementById(id);
this.el = {
panel: $('tactic-panel'),
body: $('tp-body'),
collapse: $('tp-collapse'),
newBtn: $('tp-new'),
list: $('tp-list'),
message: $('tp-message'),
detail: $('tp-detail'),
name: $('tp-name'),
desc: $('tp-desc'),
edit: $('tp-edit'),
del: $('tp-delete'),
steps: $('tp-steps'),
stepAdd: $('tp-step-add'),
stepCopy: $('tp-step-copy'),
ghosts: $('tp-ghosts'),
toolbar: $('tactic-toolbar'),
color: $('tool-color'),
width: $('tool-width'),
undo: $('tool-undo'),
stepBar: $('step-bar'),
prev: $('sb-prev'),
next: $('sb-next'),
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);
window.addEventListener('resize', () => {
this.layer.resize();
this.redraw();
});
this.bindPanel();
this.bindToolbar();
this.bindCanvas();
this.bindKeyboard();
}
// ------------------------------------------------------------------
// Daten
// ------------------------------------------------------------------
currentTactic() {
return this.tactics.find(t => t.id === this.selectedId) || null;
}
currentStep() {
const tactic = this.currentTactic();
return tactic ? tactic.steps[this.stepIndex] || null : null;
}
async loadMap(slug) {
this.slug = slug;
this.selectedId = null;
this.stepIndex = 0;
this.setTool('pan');
await this.reload();
}
/**
* Laedt die Taktiken der aktuellen Region neu. focusStepId: Schritt, der danach
* ausgewaehlt sein soll (z.B. ein gerade angelegter oder verschobener).
*/
async reload(focusStepId = null) {
const token = ++this.loadToken;
let error = null;
try {
const data = await this.service.list(this.slug);
if (token !== this.loadToken) return;
this.tactics = data.tactics || [];
this.canEdit = !!data.can_edit;
} catch (e) {
if (token !== this.loadToken) return;
this.tactics = [];
this.canEdit = false;
error = e;
}
// 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.canEdit || !tactic) 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 => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[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);
}
renderUI() {
const esc = TacticController.esc;
const tactic = this.currentTactic();
this.el.panel.classList.toggle('can-edit', this.canEdit);
this.el.newBtn.classList.toggle('hidden', !this.canEdit);
// Liste der Taktiken
if (this.tactics.length === 0) {
this.el.list.innerHTML = this.el.message.classList.contains('hidden')
? `
Noch keine Taktiken für diese Karte.${this.canEdit ? ' Mit „+ Neu“ legst du die erste an.' : ''}
`
: '';
} else {
this.el.list.innerHTML = this.tactics.map(t => `
`).join('');
}
// Details der gewaehlten Taktik
this.el.detail.classList.toggle('hidden', !tactic);
if (tactic) {
this.el.name.textContent = tactic.name;
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.canEdit && tactic));
this.renderStepBar();
}
renderSteps(tactic) {
const esc = TacticController.esc;
const last = tactic.steps.length - 1;
this.el.steps.innerHTML = tactic.steps.map((step, i) => `
${i + 1}
${esc(TacticController.stepLabel(step, i))}
${step.shapes.length}
${this.canEdit ? `
` : ''}
`).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;
}
redraw() {
const tactic = this.currentTactic();
const step = this.currentStep();
this.layer.shapes = step ? step.shapes : [];
this.layer.ghostShapes = tactic && this.showGhosts
? tactic.steps.slice(0, this.stepIndex).flatMap(s => s.shapes)
: [];
this.layer.draft = this.draft;
this.layer.draw();
}
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) {
this.cancelDraft();
this.selectedId = this.selectedId === id ? null : id;
this.stepIndex = 0;
if (!this.selectedId) this.setTool('pan');
this.renderUI();
this.redraw();
}
goToStep(index) {
const tactic = this.currentTactic();
if (!tactic) return;
const target = Math.max(0, Math.min(index, tactic.steps.length - 1));
if (target === this.stepIndex) return;
this.cancelDraft();
this.stepIndex = target;
this.renderUI();
this.redraw();
}
// ------------------------------------------------------------------
// Taktiken und Schritte bearbeiten
// ------------------------------------------------------------------
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 …' }
], '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();
if (this.canEdit) this.setTool('pen');
this.toast('Taktik angelegt – zeichne jetzt Schritt 1 ein.');
}
async editTactic() {
const tactic = this.currentTactic();
if (!tactic) return;
const values = await this.dialog('Taktik bearbeiten', [
{ name: 'name', label: 'Name', required: true, max: 120, value: tactic.name },
{ name: 'description', label: 'Beschreibung (optional)', type: 'textarea', max: 5000, value: tactic.description }
]);
if (!values) return;
if (await this.run('tactic_update', { tactic_id: tactic.id, ...values })) {
await this.reload();
}
}
async deleteTactic() {
const tactic = this.currentTactic();
if (!tactic || !confirm(`Taktik „${tactic.name}“ mit allen Schritten und Zeichnungen löschen?`)) return;
if (await this.run('tactic_delete', { tactic_id: tactic.id })) {
this.selectedId = null;
await this.reload();
this.toast('Taktik gelöscht.');
}
}
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) {
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 })) {
await this.reload(step.id);
}
}
async moveStep(step, direction) {
if (await this.run('step_move', { step_id: step.id, direction })) {
await this.reload(step.id);
}
}
async deleteStep(step, index) {
const label = TacticController.stepLabel(step, index);
if (!confirm(`Schritt ${index + 1} („${label}“) mit ${step.shapes.length} Zeichnung(en) löschen?`)) return;
if (await this.run('step_delete', { step_id: step.id })) {
await this.reload();
}
}
// ------------------------------------------------------------------
// Zeichnen
// ------------------------------------------------------------------
setTool(tool) {
this.cancelDraft();
this.tool = tool;
this.layer.hoverId = null;
this.layer.canvas.classList.toggle('drawing', tool !== 'pan');
this.layer.canvas.classList.toggle('erasing', tool === 'eraser');
this.el.toolbar.querySelectorAll('.tool[data-tool]').forEach(btn => {
btn.classList.toggle('active', btn.dataset.tool === tool);
});
if (tool === 'area') {
this.toast('Eckpunkte anklicken – Doppelklick oder Enter schließt die Fläche ab.');
}
this.redraw();
}
cancelDraft() {
this.draft = null;
this.drawing = false;
}
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: ''
};
}
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;
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 '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.layer.hitTest(screen.x, screen.y);
if (hit) this.deleteShape(hit);
break;
}
}
this.redraw();
}
onPointerMove(event) {
if (this.tool === 'eraser') {
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.draft) return;
const point = this.worldAt(event);
const points = this.draft.points;
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;
}
this.redraw();
}
onPointerUp() {
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 (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;
// Die Form bleibt als Entwurf sichtbar, bis der Server sie bestaetigt hat.
const result = await this.run('shape_create', {
step_id: step.id,
type: shape.type,
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;
if (result) {
step.shapes.push(result.shape);
(this.undoStacks[step.id] = this.undoStacks[step.id] || []).push(result.shape.id);
this.renderUI();
}
this.redraw();
}
async deleteShape(shape) {
const step = this.currentStep();
if (!step) return;
if (await this.run('shape_delete', { shape_id: shape.id })) {
step.shapes = step.shapes.filter(s => s.id !== shape.id);
this.layer.hoverId = null;
this.renderUI();
this.redraw();
}
}
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 shapeId = stack.pop();
const shape = step.shapes.find(s => s.id === shapeId);
if (shape) {
this.deleteShape(shape);
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.
*/
dialog(title, fields, submitLabel = 'Speichern') {
if (this.dialogCancel) this.dialogCancel();
return new Promise(resolve => {
const el = this.el;
el.dTitle.textContent = title;
el.dSubmit.textContent = submitLabel;
el.dFields.innerHTML = '';
fields.forEach(field => {
const label = document.createElement('label');
label.className = 'td-field';
label.textContent = field.label;
const input = document.createElement(field.type === 'textarea' ? 'textarea' : 'input');
if (field.type === 'textarea') {
input.rows = 4;
} 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');
const first = el.dFields.querySelector('input, textarea');
if (first) first.focus();
});
}
// ------------------------------------------------------------------
// 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.edit.addEventListener('click', () => this.editTactic());
el.del.addEventListener('click', () => this.deleteTactic());
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();
});
el.prev.addEventListener('click', () => this.goToStep(this.stepIndex - 1));
el.next.addEventListener('click', () => this.goToStep(this.stepIndex + 1));
// 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());
}
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();
this.redraw();
});
canvas.addEventListener('dblclick', event => {
event.preventDefault();
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, 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.canEdit) 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);
}
});
}
}