LuminaWebsite/assets/map/js/controllers/TacticController.js
Maaxxs 03597f14ad Raidplaner: tactics on the maps of all dungeons and raids, with tokens that move from step to step
Asked for in Discord: "raidplan.io bitte einbauen für die harten Dungeons". raidplan.io has no Aion 2
(only WoW, FFXIV, Lost Ark, New World), so the map tactics got what it offers.

- Dungeon maps: the in-game map textures of 11 expeditions, 7 transcendence dungeons, the 3 sanctuaries
  (Ludra, Corroded Decontamination Facility, Chalice of Muspel), the 6 awakening towers and 3
  subjugations, as published by the DPS meter Waffle-ens/waffle_meter (dotnet/Assets/Maps, pinned
  commit). assets/map/dungeons/dungeons.json is kept by hand: groups, slugs (= tactics.map_slug),
  German names from the Global client (aion2.app), KR/TW-only dungeons marked as unavailable, boss
  hints for the awakening towers. scripts/download_dungeon_maps.py fetches the images, writes
  dungeons/<slug>.webp (2048 px, about 3 MB in total, in Git) and the previews, and finds the dungeon
  area (bounds) by comparing each map with the shared background of all maps. Two empty arenas
  (round, square) are drawn in code.
- Viewer: image maps and arenas next to the tile maps (MapView.drawImageMap/drawArena, half zoom
  steps, opens fitted to the dungeon beside the tactic panel), map picker with the tabs "Welt" and
  "Dungeons & Raids", each area remembers its last map, no category panel without markers. The mouse
  wheel zooms to the cursor.
- New page raidplan.php ("Raidplaner" in the menu, map.view) = map.php started in the dungeon area.
  Location links on dungeon maps point to /raidplan.php and are recognized in texts and by the
  calendar picker.
- Tokens (shape type 'token', TokenIcons.js): classes, roles, players 1-8, markers A-D and symbols,
  boss, add, danger, stack, spread, tower, orb, bomb. Colour and size come from the toolbar, numbers
  and letters count up while placing, tokens are drawn above areas. Server whitelist
  TACTIC_TOKEN_ICONS.
- Move tool (✥) with label/delete actions above the selected shape, double click and Del; new action
  shape_update in tactics_api.php (points and label, same permissions, snapshot before). Undo also
  reverts moves and labels. Rectangle and cone tools, saved as areas.
- Step transitions: tactic_shapes.ref is kept by "Kopie dieses Schritts", tactic copies and restores
  (existing shapes get s<id>), so the same shape glides to its new place when stepping or playing;
  play button (and space) runs through all steps. 🔗 copies a link to the tactic and step
  (?taktik=&schritt=), which opens it after loading.
- Live view: the bot relay only knows the old shape types and events, so placing tokens and moving
  send "changed" and the others reload - no bot deploy needed.
- Schema version 60 (tactic_shapes.icon, .ref, enum 'token'; also in sql/schema.sql), tour step on the
  dashboard, patch notes and README.

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

1830 lines
80 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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