@@ -314,10 +347,239 @@ class TacticController {
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.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);
+ 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':
+ if (this.liveDrafts.delete(key(event.conn, event.id))) {
+ this.renderLive();
+ this.requestRedraw();
+ }
+ break;
+
+ case 'shape_added': {
+ if (event.draft) this.liveDrafts.delete(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;
+ }
+ }
+
+ /** 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 ``
+ + `${esc(u.name)}${index >= 0 && tactic.steps.length > 1 ? `${index + 1} ` : ''} `;
+ }).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;
@@ -403,6 +665,7 @@ class TacticController {
return;
}
if (await this.run('tactic_update', { tactic_id: tactic.id, ...values })) {
+ this.notifyChanged('tactic');
await this.reload();
}
}
@@ -411,6 +674,7 @@ class TacticController {
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();
}
@@ -423,6 +687,7 @@ class TacticController {
+ '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.');
@@ -493,6 +758,8 @@ class TacticController {
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 = {};
@@ -519,6 +786,7 @@ class TacticController {
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);
}
}
@@ -530,12 +798,14 @@ class TacticController {
]);
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);
}
}
@@ -548,6 +818,7 @@ class TacticController {
+ '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();
}
}
@@ -572,10 +843,24 @@ class TacticController {
}
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 || !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);
@@ -599,7 +884,8 @@ class TacticController {
points,
color: this.el.color.value,
width: parseInt(this.el.width.value, 10) || 4,
- label: ''
+ label: '',
+ liveId: TacticController.newLiveId()
};
}
@@ -651,6 +937,7 @@ class TacticController {
break;
}
}
+ this.sendDraft();
this.redraw();
}
@@ -677,6 +964,7 @@ class TacticController {
} else if (this.drawing) {
points[1] = point;
}
+ this.sendDraft();
this.redraw();
}
@@ -737,10 +1025,15 @@ class TacticController {
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.
+ // 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: step.id,
+ step_id: stepId,
type: shape.type,
color: shape.color,
width: shape.width,
@@ -748,11 +1041,19 @@ class TacticController {
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) {
- step.shapes.push(result.shape);
- (this.undoStacks[step.id] = this.undoStacks[step.id] || []).push(result.shape.id);
+ // 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();
}
@@ -760,8 +1061,12 @@ class TacticController {
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 })) {
- step.shapes = step.shapes.filter(s => s.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();
@@ -933,6 +1238,12 @@ class TacticController {
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));
diff --git a/assets/map/js/services/TacticLiveService.js b/assets/map/js/services/TacticLiveService.js
new file mode 100644
index 0000000..4c8cfc6
--- /dev/null
+++ b/assets/map/js/services/TacticLiveService.js
@@ -0,0 +1,285 @@
+/**
+ * TacticLiveService - Live-Ansicht einer Taktik: Striche der anderen erscheinen, waehrend sie
+ * entstehen, gespeicherte und geloeschte Zeichnungen sofort, dazu wer gerade dabei ist.
+ *
+ * Verteiler ist die Bot-API (live_tactics.py im Bot). Die Website stellt ein kurz gueltiges Ticket
+ * aus (tactics_api.php, Aktion live_token); damit empfaengt der Browser per Server-Sent Events und
+ * schickt eigene Ereignisse per POST. Gespeichert wird weiterhin nur ueber tactics_api.php - reisst
+ * die Verbindung ab, holt sich die Karte ein neues Ticket und laedt die Taktik frisch (hello).
+ *
+ * handlers: onEvent(event, tacticId), onStatus(status), onTicketError(error)
+ * status: off | connecting | live | offline | unavailable (Bot-API nicht eingerichtet)
+ */
+
+class TacticLiveService {
+ constructor(tacticService, handlers) {
+ this.service = tacticService;
+ this.handlers = handlers;
+
+ this.tacticId = null;
+ this.ticket = null;
+ this.source = null;
+ this.conn = null; // Kennung dieser Verbindung beim Verteiler (aus "hello")
+ this.status = 'off';
+ this.session = 0; // jede betretene Taktik zaehlt hoch - Rueckmeldungen der alten verfallen
+ this.generation = 0; // ebenso jede neue Verbindung (auch innerhalb einer Taktik)
+ this.retryDelay = 1000;
+ this.retryTimer = null;
+
+ this.outbox = []; // Ereignisse in Reihenfolge, die noch raus muessen
+ this.draft = null; // Strich, der gerade entsteht (wird gebuendelt verschickt)
+ this.sending = false;
+ this.flushTimer = null;
+ this.lastSend = 0;
+ }
+
+ /** Live-Ansicht dieser Taktik betreten (null: verlassen). */
+ join(tacticId) {
+ if (tacticId === this.tacticId) return;
+ this.leave();
+ if (!tacticId) return;
+ this.tacticId = tacticId;
+ this.connect();
+ }
+
+ leave() {
+ this.session++;
+ this.generation++;
+ clearTimeout(this.retryTimer);
+ clearTimeout(this.flushTimer);
+ this.flushTimer = null;
+ this.closeSource();
+ this.tacticId = null;
+ this.ticket = null;
+ this.conn = null;
+ this.outbox = [];
+ this.draft = null;
+ this.sending = false;
+ this.retryDelay = 1000;
+ this.setStatus('off');
+ }
+
+ closeSource() {
+ if (this.source) {
+ this.source.close();
+ this.source = null;
+ }
+ }
+
+ setStatus(status) {
+ if (status === this.status) return;
+ this.status = status;
+ this.handlers.onStatus(status);
+ }
+
+ async connect() {
+ const generation = ++this.generation;
+ this.closeSource();
+ this.conn = null;
+ // Nur beim ersten Mal "wird aufgebaut" - nach einem Abbruch bleibt es bis zum Erfolg bei "unterbrochen",
+ // beim Erneuern des Tickets bei "Live".
+ if (this.status === 'off') this.setStatus('connecting');
+
+ let ticket;
+ try {
+ ticket = await this.service.send('live_token', { tactic_id: this.tacticId });
+ } catch (e) {
+ if (generation !== this.generation) return;
+ if (e.data && e.data.live_unavailable) {
+ this.setStatus('unavailable');
+ return;
+ }
+ // Z.B. inzwischen privat oder geloescht - die Karte laedt neu und verlaesst die Taktik dann
+ this.handlers.onTicketError(e);
+ this.retry(generation);
+ return;
+ }
+ if (generation !== this.generation) return;
+
+ this.ticket = ticket;
+ const source = new EventSource(ticket.stream_url);
+ this.source = source;
+ source.onmessage = message => {
+ if (generation !== this.generation) return;
+ let event;
+ try {
+ event = JSON.parse(message.data);
+ } catch (e) {
+ return;
+ }
+ this.receive(event);
+ };
+ // Nicht den Automatismus des Browsers nehmen (der kaeme mit dem alten Ticket) - selbst neu verbinden.
+ source.onerror = () => {
+ if (generation !== this.generation) return;
+ this.closeSource();
+ this.conn = null;
+ this.retry(generation);
+ };
+ }
+
+ retry(generation) {
+ this.setStatus('offline');
+ clearTimeout(this.retryTimer);
+ const delay = this.retryDelay;
+ this.retryDelay = Math.min(this.retryDelay * 2, 15000);
+ this.retryTimer = setTimeout(() => {
+ if (generation === this.generation) this.connect();
+ }, delay);
+ }
+
+ receive(event) {
+ if (event.type === 'expired') {
+ // Ticket abgelaufen: mit einem neuen weiter (die Rechte werden dabei neu geprueft)
+ this.connect();
+ return;
+ }
+ if (event.type === 'hello') {
+ this.conn = event.conn;
+ this.retryDelay = 1000;
+ this.setStatus('live');
+ // Ein Strich, der gerade entsteht, geht nach einem Abbruch komplett neu raus.
+ if (this.draft) {
+ this.draft.sent = 0;
+ this.draft.dirty = true;
+ }
+ }
+ this.handlers.onEvent(event, this.tacticId);
+ if (event.type === 'hello') this.flush();
+ }
+
+ // ------------------------------------------------------------------
+ // Senden
+ // ------------------------------------------------------------------
+
+ canDraw() {
+ return !!(this.ticket && this.ticket.can_draw);
+ }
+
+ /**
+ * Sofort und unabhaengig von der Warteschlange - fuer Aenderungen, nach denen die Taktik evtl.
+ * gleich verlassen wird (z.B. geloescht): leave() verwirft die Warteschlange, das hier nicht.
+ */
+ sendNow(event) {
+ if (!this.conn || !this.ticket) {
+ this.push(event);
+ return;
+ }
+ fetch(this.ticket.send_url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-Live-Token': this.ticket.token },
+ body: JSON.stringify({ conn: this.conn, events: [event] }),
+ keepalive: true
+ }).catch(() => { /* dann laden die anderen spaetestens beim Neuverbinden frisch */ });
+ }
+
+ /** Ereignis in die Warteschlange (Reihenfolge bleibt erhalten). */
+ push(event) {
+ if (!this.tacticId) return;
+ this.outbox.push(event);
+ // Offline wird nicht endlos gesammelt - nach dem Neuverbinden laden die anderen ohnehin frisch.
+ if (this.outbox.length > 200) this.outbox.splice(0, this.outbox.length - 200);
+ this.schedule();
+ }
+
+ /**
+ * Strich, der gerade entsteht. growing: die Punkte werden nur hinten laenger (Stift) - dann geht
+ * nur der Nachschub raus; sonst (Linie, Pfeil, Kreis, Flaeche) immer der ganze Strich.
+ */
+ updateDraft(id, stepId, shape, points, growing) {
+ if (!this.tacticId) return;
+ if (!this.draft || this.draft.id !== id) {
+ this.materializeDraft();
+ this.draft = { id, sent: 0 };
+ }
+ Object.assign(this.draft, { step: stepId, shape, points, growing, dirty: true });
+ this.schedule();
+ }
+
+ /** Strich abgeschlossen: Rest verschicken. cancelled: er wird nicht gespeichert und verschwindet bei allen. */
+ endDraft(id, cancelled) {
+ if (this.draft && this.draft.id === id) {
+ this.materializeDraft();
+ this.draft = null;
+ }
+ if (cancelled) this.push({ type: 'draft_end', id });
+ else this.schedule();
+ }
+
+ materializeDraft() {
+ const draft = this.draft;
+ if (!draft || !draft.dirty) return;
+ draft.dirty = false;
+ const append = draft.growing && draft.sent > 0 && draft.sent <= draft.points.length;
+ const points = append ? draft.points.slice(draft.sent) : draft.points.slice();
+ if (append && points.length === 0) return;
+ draft.sent = draft.points.length;
+ this.outbox.push({
+ type: 'draft', id: draft.id, step: draft.step, shape: draft.shape, append,
+ points: points.map(p => [Math.round(p[0] * 100) / 100, Math.round(p[1] * 100) / 100])
+ });
+ }
+
+ /** Hoechstens alle 70 ms ein Paket - so bleibt der Strich fluessig, ohne den Server zu fluten. */
+ schedule() {
+ if (this.flushTimer || this.sending) return;
+ const wait = Math.max(0, 70 - (Date.now() - this.lastSend));
+ this.flushTimer = setTimeout(() => {
+ this.flushTimer = null;
+ this.flush();
+ }, wait);
+ }
+
+ async flush() {
+ if (this.sending || !this.conn || !this.ticket) return;
+ this.materializeDraft();
+ if (this.outbox.length === 0) return;
+
+ const session = this.session;
+ const conn = this.conn;
+ const ticket = this.ticket;
+ const events = this.outbox.splice(0, 30);
+ this.sending = true;
+ this.lastSend = Date.now();
+ let status = 0;
+ try {
+ const response = await fetch(ticket.send_url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-Live-Token': ticket.token },
+ body: JSON.stringify({ conn, events })
+ });
+ status = response.status;
+ } catch (e) {
+ status = -1; // Netz weg - der Empfangskanal merkt das auch und verbindet neu
+ }
+ // Inzwischen eine andere Taktik: leave() hat alles zurueckgesetzt, die alten Ereignisse verfallen.
+ if (session !== this.session) return;
+ this.sending = false;
+
+ if (status === 401 || status === 409) {
+ // Ticket abgelaufen bzw. der Verteiler kennt die Verbindung nicht (mehr) - nachreichen. Lief
+ // das Paket noch ueber eine alte Verbindung, genuegt das; sonst neu verbinden.
+ this.requeue(events);
+ if (conn === this.conn && ticket === this.ticket) {
+ this.connect();
+ return;
+ }
+ } else if (status === -1 || status === 429 || status >= 500) {
+ // Netz weg, zu viel auf einmal oder Server-Fehler: kurz warten, dann nachreichen
+ this.requeue(events);
+ this.flushTimer = setTimeout(() => {
+ this.flushTimer = null;
+ this.flush();
+ }, 1000);
+ return;
+ }
+ // Sonst (auch bei abgelehnten Daten) weiter mit dem Rest - live ist nur ein Hinweis, gespeichert
+ // ist schon auf der Website.
+ if (this.outbox.length || (this.draft && this.draft.dirty)) this.schedule();
+ }
+
+ /** Gespeicherte/geloeschte Zeichnungen und Aenderungen nach dem Neuverbinden nachreichen - Entwuerfe nicht. */
+ requeue(events) {
+ this.outbox.unshift(...events.filter(e => e.type !== 'draft'));
+ }
+}
diff --git a/assets/map/js/views/TacticLayer.js b/assets/map/js/views/TacticLayer.js
index 92f192a..c318b45 100644
--- a/assets/map/js/views/TacticLayer.js
+++ b/assets/map/js/views/TacticLayer.js
@@ -18,6 +18,7 @@ class TacticLayer {
// Was gezeichnet wird - setzt der TacticController.
this.shapes = []; // Zeichnungen des aktuellen Schritts
this.ghostShapes = []; // Zeichnungen der vorherigen Schritte (blass)
+ this.liveDrafts = []; // Striche anderer, die gerade entstehen (Live-Ansicht): {shape, name, color}
this.draft = null; // Form, die gerade gezeichnet wird
this.hoverId = null; // Form unter dem Radierer
@@ -48,11 +49,23 @@ class TacticLayer {
ctx.restore();
this.shapes.forEach(shape => this.drawShape(shape, shape.id === this.hoverId));
+ this.liveDrafts.forEach(live => {
+ this.drawShape(live.shape);
+ this.drawDrawerName(live);
+ });
if (this.draft) {
this.drawShape(this.draft);
}
}
+ /** Name dessen, der gerade zeichnet, an der Spitze seines Strichs - bei mehreren sieht man, wer was macht. */
+ drawDrawerName(live) {
+ const points = live.shape.points;
+ if (!points.length || !live.name) return;
+ const tip = this.toScreen(points[points.length - 1]);
+ this.drawLabel(live.name, { x: tip.x + 10, y: tip.y - 12 }, live.color, 12, 'left');
+ }
+
drawShape(shape, highlighted = false) {
const ctx = this.ctx;
const pts = shape.points.map(p => this.toScreen(p));
diff --git a/assets/map/styles.css b/assets/map/styles.css
index 96202ea..17abeeb 100644
--- a/assets/map/styles.css
+++ b/assets/map/styles.css
@@ -862,6 +862,127 @@ button.tp-item.tp-item-recommended {
accent-color: var(--accent-gold);
}
+/* Live-Ansicht: wer gerade in der Taktik ist. Die Farbe je Mitglied kommt als --live-color. */
+.tp-live {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px 6px;
+ margin-top: 8px;
+ font-size: 11px;
+}
+
+.tp-live.hidden {
+ display: none;
+}
+
+.tp-live-state {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-weight: bold;
+ color: #6fcf97;
+}
+
+.tp-live-offline {
+ color: #f2c94c;
+ font-weight: normal;
+}
+
+.tp-live-pulse {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: #6fcf97;
+ animation: tp-live-pulse 1.6s ease-in-out infinite;
+}
+
+@keyframes tp-live-pulse {
+ 0%, 100% { box-shadow: 0 0 0 0 rgba(111, 207, 151, 0.6); }
+ 50% { box-shadow: 0 0 0 5px rgba(111, 207, 151, 0); }
+}
+
+.tp-live-hint {
+ color: var(--text-secondary);
+}
+
+button.tp-live-user {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ max-width: 100%;
+ padding: 1px 7px 1px 5px;
+ border: 1px solid var(--live-color);
+ border-radius: 999px;
+ background: rgba(0, 0, 0, 0.25);
+ color: var(--text-primary);
+ font-size: 11px;
+ line-height: 16px;
+ cursor: pointer;
+}
+
+button.tp-live-user::before {
+ content: "";
+ flex-shrink: 0;
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--live-color);
+}
+
+button.tp-live-user.drawing::before {
+ animation: tp-live-blink 0.8s ease-in-out infinite;
+}
+
+button.tp-live-user small {
+ color: var(--text-secondary);
+ font-size: 10px;
+}
+
+@keyframes tp-live-blink {
+ 50% { opacity: 0.25; }
+}
+
+/* Punkte in der Schrittliste: wer ist hier, wer zeichnet hier gerade (blinkt) */
+.tp-step-live {
+ display: inline-flex;
+ gap: 2px;
+ flex-shrink: 0;
+}
+
+.tp-step-live:empty {
+ display: none;
+}
+
+.tp-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--live-color);
+}
+
+.tp-live-dot.drawing {
+ animation: tp-live-blink 0.8s ease-in-out infinite;
+}
+
+.sb-live {
+ margin-top: 2px;
+ font-size: 11px;
+ color: #6fcf97;
+}
+
+.sb-live.hidden {
+ display: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .tp-live-pulse,
+ button.tp-live-user.drawing::before,
+ .tp-live-dot.drawing {
+ animation: none;
+ }
+}
+
/* Werkzeugleiste im Taktik-Panel - bleibt auch beim Einklappen sichtbar. Raster mit 7 gleich
grossen Feldern: oben die 7 Zeichenwerkzeuge, unten Text, Radierer, Rueckgaengig, Farbe und
Strichstaerke (3 Felder breit). Passt ohne Umbruch-Luecken aufs Panel und aufs Handy. */
diff --git a/datenschutz.php b/datenschutz.php
index b7d336d..4a5448f 100644
--- a/datenschutz.php
+++ b/datenschutz.php
@@ -195,7 +195,7 @@ include __DIR__ . '/includes/header.php';
Raids und Premades: deine Anmeldungen mit Klasse und Gruppe, deine Anwesenheit (anwesend, abwesend, entschuldigt) und die dafür vergebenen Lumipunkte; bei Raids, die du selbst anlegst, dass du ihr Raid-Lead bist (für alle sichtbar).
Lumipunkte und Lumishop: Punktevergaben und -abzüge, deine Shop-Anträge mit Bemerkung (z. B. Charaktername) und deren Bearbeitung.
Lagerhaus: Ein- und Auslagerungen mit dem Namen der Person, von der etwas kam oder die etwas bekommen hat.
- Kalender, Wiki und Karte: Termine, die du einträgst, und deine Teilnahme; Wiki-Seiten und Taktiken samt früheren Versionen mit Autor.
+ Kalender, Wiki und Karte: Termine, die du einträgst, und deine Teilnahme; Wiki-Seiten und Taktiken samt früheren Versionen mit Autor. In der Live-Ansicht einer Taktik sehen die anderen, die sie gerade offen haben, dass du dabei bist und was du gerade zeichnest (Abschnitt = $number['discord-bot'] + 1 ?> ).
Fehlermeldungen: deine Beschreibung, angehängte Bilder oder Links und die Browser-Kennung deines Geräts (hilft beim Nachstellen des Fehlers).
Meldungen und Moderation: wer einen Inhalt gemeldet hat und warum. Neue Bilder, Kommentare und Termine können vor der Veröffentlichung von der Moderation geprüft werden.
@@ -224,6 +224,15 @@ include __DIR__ . '/includes/header.php';
Meldungen über Spieler: gemeldete und meldende Person (Discord-ID und Name), Grund, Zeitpunkt, Beweis-Links und Punkte. Wer gemeldet hat, sieht nur die Legionsleitung. Meldungen löscht der Bot nach 10 Tagen automatisch.
Aktivitätschecks: wer auf einen Check geantwortet hat (Discord-ID, Name, Antwort, Zeitpunkt) und wer nicht.
+
+ Live-Ansicht der Taktik-Karte: Öffnest du auf der Karte eine Taktik, verbindet sich dein
+ Browser direkt mit dem Server des Bots - mit einem Zugangsticket der Website (30 Minuten gültig), das
+ deine Konto-ID, deinen Anzeigenamen und dein Recht zum Bearbeiten enthält. Wer dieselbe Taktik gerade
+ offen hat, sieht deinen Anzeigenamen, welchen Schritt du ansiehst und deine Striche, während du sie
+ zeichnest. Der Bot leitet das nur weiter und speichert nichts davon; eine Zeichnung wird wie bisher erst
+ beim Abschließen gespeichert, und zwar auf der Website. Technisch nötig verarbeitet der Server dabei
+ auch deine IP-Adresse (Abschnitt = $number['hosting'] + 1 ?> ).
+
Automatische Maßnahmen: Erreichen Meldungen gegen einen Spieler eine festgelegte
Punktzahl, schaltet der Bot ihn für 48 Stunden stumm (Timeout) und benachrichtigt ihn per
diff --git a/includes/patchnotes.php b/includes/patchnotes.php
index 6c40ebf..d55334f 100644
--- a/includes/patchnotes.php
+++ b/includes/patchnotes.php
@@ -19,6 +19,17 @@ const PATCHNOTE_TYPES = [
];
const PATCHNOTES = [
+ [
+ 'id' => '2026-09-25-c',
+ 'date' => '2026-09-25',
+ 'title' => 'Taktik-Karte live: alle sehen jeden Strich sofort',
+ 'summary' => 'Wer eine Taktik offen hat, sieht Zeichnungen der anderen schon, während sie entstehen - auch wenn mehrere gleichzeitig zeichnen.',
+ 'changes' => [
+ ['type' => 'neu', 'area' => 'Karte', 'text' => 'Live-Ansicht: Öffnest du eine Taktik, siehst du jeden Strich der anderen, während er gezeichnet wird - mit dem Namen an der Stiftspitze. Gespeicherte und gelöschte Zeichnungen, neue Schritte und Änderungen erscheinen sofort, ohne Neuladen.'],
+ ['type' => 'neu', 'area' => 'Karte', 'text' => 'Mehrere können gleichzeitig in derselben Taktik zeichnen, auch im selben Schritt. Jeder nimmt mit „Rückgängig“ nur seine eigenen Striche zurück.'],
+ ['type' => 'neu', 'area' => 'Karte', 'text' => 'Im Taktik-Fenster steht, wer gerade dabei ist; ein Punkt in der Schrittliste zeigt, wer in welchem Schritt ist, und blinkt, solange dort gezeichnet wird. Ein Klick auf einen Namen springt in dessen Schritt - praktisch im Raid, um dem Raid-Lead zu folgen.'],
+ ],
+ ],
[
'id' => '2026-09-25-b',
'date' => '2026-09-25',
diff --git a/includes/raids_api.php b/includes/raids_api.php
index 35ad9a2..bbd9dac 100644
--- a/includes/raids_api.php
+++ b/includes/raids_api.php
@@ -37,7 +37,9 @@ function raids_api_config(): array
throw new RuntimeException('Raid-API ist nicht konfiguriert (config.php: raids_api.url / raids_api.key fehlt).');
}
- return ['url' => rtrim($apiUrl, '/'), 'key' => $apiKey];
+ // live_url (optional): oeffentliche Adresse der Bot-API fuer die Live-Ansicht der Karte, falls die
+ // Browser sie anders erreichen als die Website (sonst url ohne /api/raids, siehe tactic_live_ticket).
+ return ['url' => rtrim($apiUrl, '/'), 'key' => $apiKey, 'live_url' => rtrim((string) ($config['raids_api']['live_url'] ?? ''), '/')];
}
/**
diff --git a/includes/tactics.php b/includes/tactics.php
index 9d60f66..74029da 100644
--- a/includes/tactics.php
+++ b/includes/tactics.php
@@ -294,6 +294,64 @@ function tactic_clean_points($points, string $type): ?array
return $valid ? $clean : null;
}
+// ---------------------------------------------------------------------------
+// Live-Ansicht: Striche erscheinen bei allen, die die Taktik offen haben, waehrend sie entstehen
+// ---------------------------------------------------------------------------
+
+// Verteiler ist die Bot-API (live_tactics.py im Bot) - sie prueft die Tickets mit demselben
+// Schluessel (raids_api.key = API_SECRET_KEY im Bot). Der Kontext muss dort gleich lauten.
+const TACTIC_LIVE_CONTEXT = 'lumina-tactics-live-v1.';
+// So lange gilt ein Ticket - danach holt sich die Karte ein neues, die Rechte werden neu geprueft.
+const TACTIC_LIVE_TTL = 1800;
+
+function tactic_live_b64(string $bytes): string
+{
+ return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
+}
+
+/**
+ * Ticket fuer die Live-Ansicht einer Taktik, die das Konto sehen darf (vorher pruefen): zuschauen
+ * darf jeder, der sie sieht - live zeichnen, wer sie bearbeiten darf. Der Browser verbindet sich
+ * damit direkt mit dem Bot; gespeichert wird weiterhin nur hier (tactics_api.php).
+ * null, wenn die Bot-API nicht eingerichtet ist.
+ *
+ * @param array{id: mixed, created_by: mixed, visibility: string, highlight?: string} $tactic
+ * @param array $user
+ * @return array{stream_url: string, send_url: string, token: string, expires_in: int, can_draw: bool, user_id: int}|null
+ */
+function tactic_live_ticket(array $tactic, array $user): ?array
+{
+ require_once __DIR__ . '/raids_api.php';
+ try {
+ $api = raids_api_config();
+ } catch (RuntimeException $e) {
+ return null;
+ }
+ $base = $api['live_url'] !== '' ? $api['live_url'] : (string) preg_replace('#/api/raids$#', '', $api['url']);
+
+ $userId = (int) $user['id'];
+ $name = trim((string) ($user['display_name'] ?? ''));
+ $claims = [
+ 'u' => $userId,
+ 'n' => mb_substr($name !== '' ? $name : (string) ($user['username'] ?? ''), 0, 60),
+ 't' => (int) $tactic['id'],
+ 'e' => tactic_can_edit($tactic, $userId) ? 1 : 0,
+ 'x' => time() + TACTIC_LIVE_TTL,
+ ];
+ $payload = tactic_live_b64((string) json_encode($claims, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
+ $token = $payload . '.' . tactic_live_b64(hash_hmac('sha256', TACTIC_LIVE_CONTEXT . $payload, $api['key'], true));
+ $path = $base . '/api/live/tactics/' . (int) $tactic['id'];
+
+ return [
+ 'stream_url' => $path . '/stream?token=' . rawurlencode($token),
+ 'send_url' => $path . '/send',
+ 'token' => $token,
+ 'expires_in' => TACTIC_LIVE_TTL,
+ 'can_draw' => $claims['e'] === 1,
+ 'user_id' => $userId,
+ ];
+}
+
/** Aktualisiert den Zeitstempel einer Taktik, damit die Liste zeigt, wann zuletzt gezeichnet wurde. */
function tactic_touch(int $tacticId): void
{
diff --git a/tactics_api.php b/tactics_api.php
index 3fc5bff..e70b255 100644
--- a/tactics_api.php
+++ b/tactics_api.php
@@ -452,6 +452,17 @@ try {
tactic_touch($tacticId);
json_response(true, '');
+ // ---- Live-Ansicht ----
+ case 'live_token':
+ // Ticket fuer den Live-Verteiler im Bot (tactic_live_ticket): zuschauen darf, wer die Taktik
+ // sieht, live zeichnen, wer sie bearbeiten darf.
+ $tactic = tactic_load((int) ($input['tactic_id'] ?? 0), $userId, false);
+ $ticket = tactic_live_ticket($tactic, current_user());
+ if ($ticket === null) {
+ json_response(false, 'Die Live-Ansicht ist hier nicht eingerichtet.', ['live_unavailable' => true]);
+ }
+ json_response(true, '', $ticket);
+
// ---- Verlauf und Papierkorb ----
case 'revision_list':
// Nur fuer bestehende Taktiken, die das Konto bearbeiten darf (Staende aus privater