/** * 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. */ 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; // 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: () => this.scheduleReload() }); 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.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'), 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'), 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; } /** 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.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). 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); 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; } 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; 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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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('★ Offiziell'); if (tactic.highlight === 'recommended') badges.push('👍 Empfohlen'); if (tactic.visibility === 'private') badges.push('🔒 Privat'); 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') ? `

Noch keine Taktiken für diese Karte.${this.canCreate ? ' Mit „+ Neu“ legst du deine erste an – nur für dich oder für alle.' : ''}

` : ''; } 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 ? `
${group.title}
` : ''} ${group.items.map(t => ` `).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) + `${esc(meta.join(' · '))}`; 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(); 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) => `
  • ${i + 1} ${esc(TacticController.stepLabel(step, i))} ${step.shapes.length} ${tactic.can_edit ? ` ` : ''}
  • `).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.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(); } /** 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.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; // 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; } } /** 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, 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); // 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 ``; }).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' ? '◌ Live-Verbindung wird aufgebaut …' : '⚠ Live-Verbindung unterbrochen – neuer Versuch läuft …'; return; } this.el.live.innerHTML = '' + 'Live' + (others.length === 0 ? 'Gerade ist sonst niemand in dieser Taktik.' : others.map(u => { const index = this.liveUserStepIndex(u); const where = index >= 0 ? `Schritt ${index + 1}` : ''; const title = `${u.name}${where ? ' – ' + where : ''}${u.drawing.size ? ' – zeichnet gerade' : ''}` + (index >= 0 && index !== this.stepIndex ? ' (klicken: dorthin springen)' : ''); return ``; }).join('')); 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(', '); } /** 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) { 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 })) { 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.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() { // 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; 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.sendDraft(); 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; } // 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.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(); } 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; 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, 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(result.shape.id); if (liveHere) { this.live.push({ type: 'shape_added', step: stepId, shape: result.shape, draft: shape.liveSent ? shape.liveId : null }); } 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; 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(); }); // 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)); }); 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); } }); } }