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

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

1008 lines
41 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/...).
*/
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.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'),
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'),
history: $('tp-history'),
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;
}
/**
* 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);
}
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.deleted = data.deleted || [];
this.canCreate = !!data.can_create;
this.canHighlight = !!data.can_highlight;
} catch (e) {
if (token !== this.loadToken) return;
this.tactics = [];
this.deleted = [];
this.canCreate = false;
this.canHighlight = 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.canEditCurrent()) 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) {
this.el.list.innerHTML = this.el.message.classList.contains('hidden')
? `<p class="tp-empty">Noch keine Taktiken für diese Karte.${this.canCreate ? ' Mit „+ Neu“ legst du deine erste an – nur für dich oder für alle.' : ''}</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}` : ''),
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);
// 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.canEditCurrent());
this.renderStepBar();
}
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-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;
}
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
// ------------------------------------------------------------------
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();
if (this.canEditCurrent()) this.setTool('pen');
this.toast(values.visibility === 'public'
? 'Öffentliche Taktik angelegt – zeichne jetzt Schritt 1 ein.'
: 'Private Taktik angelegt – nur du siehst sie. Zeichne jetzt Schritt 1 ein.');
}
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 })) {
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 && 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.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;
// 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) {
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);
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 })) {
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. 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.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();
});
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.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);
}
});
}
}