Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
520 lines (478 loc) · 43.1 KB
/
Copy pathapp.js
File metadata and controls
520 lines (478 loc) · 43.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
const players = [
{ name: 'Declan Rice', role: 'Deep midfielder', initials: 'DR', value: '0.84' },
{ name: 'Martin Ødegaard', role: 'Advanced midfielder', initials: 'MØ', value: '0.79' },
{ name: 'Bukayo Saka', role: 'Right winger', initials: 'BS', value: '0.76' },
{ name: 'Gabriel Martinelli', role: 'Left winger', initials: 'GM', value: '0.71' },
{ name: 'Oleksandr Zinchenko', role: 'Left back', initials: 'OZ', value: '0.68' },
];
const events = [
{ time: '09:42', title: 'Pressure escape', text: 'Rice → Ødegaard → Saka', detail: '3 actions · high pressure' },
{ time: '22:18', title: 'Left overload', text: 'Zinchenko receives between lines', detail: 'Martinelli creates width' },
{ time: '38:06', title: 'Progressive sequence', text: 'Ødegaard → Jesus → Martinelli', detail: '+18.4m territory gained' },
{ time: '64:51', title: 'Recovery', text: 'Rice wins second ball in zone 14', detail: 'Transition begins' },
];
const queries = {
pressure: { title: 'Arsenal under high pressure', passes: '186', edges: '42', cypher: "MATCH (p1:Player)-[r:PASSED_TO]->(p2:Player)\nWHERE r.team = 'Arsenal' AND r.pressure = 'high'\nRETURN p1, p2, r" },
progressive: { title: 'Progressive sequences · Arsenal', passes: '74', edges: '24', cypher: "MATCH path = (start:Player)-[:PASSED_TO*3..5]->(finish:Player)\nWHERE ALL(rel IN relationships(path) WHERE rel.team = 'Arsenal')\nRETURN path" },
hold: { title: 'Hold-up play in the final third', passes: '31', edges: '11', cypher: "MATCH (source:Player)-[r:PASSED_TO]->(target:Player)\nWHERE r.outcome = 'successful'\nRETURN source, target, r" },
recoveries: { title: 'Ball recoveries', passes: '58', edges: '18', cypher: "MATCH (p:Player)-[r:RECOVERED_IN]->(z:PitchZone)\nRETURN p, z, r" },
};
let dashboardState = null;
let currentResult = null;
let eventDisplayCount = 5;
let eventFilter = 'all';
let graphFilter = 'all';
let graphView = { x: 0, y: 0, scale: 1 };
let analysisFilters = { minute_from: null, minute_to: null, period: 'all', player_name: null, zone_id: null, possession_phase: null, score_state: 'all', team: null };
let pendingAnnotation = null;
let authToken = localStorage.getItem('taktik-access-token');
let signedInUser = null;
async function apiFetch(path, options = {}) {
const headers = new Headers(options.headers || {});
if (authToken) headers.set('Authorization', `Bearer ${authToken}`);
const response = await fetch(path, { ...options, headers });
if (response.status === 401 && authToken) {
authToken = null;
signedInUser = null;
localStorage.removeItem('taktik-access-token');
showAuth();
}
return response;
}
function renderPlayers() {
document.querySelector('#playerList').innerHTML = players.map((player) => `<div class="player-row"><span class="player-avatar">${player.initials}</span><div><strong>${player.name}</strong><small>${player.role}</small></div><div class="centrality"><b>${player.value}</b><small>centrality</small></div></div>`).join('');
}
function renderEvents() {
document.querySelector('#eventList').innerHTML = events.map((event) => `<div class="event-row"><span class="event-time">${event.time}</span><span class="event-marker"></span><div><strong>${event.title}</strong><p><b>${event.text}</b> · ${event.detail}</p></div></div>`).join('');
}
function escapeSvg(value) {
return String(value).replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]);
}
function initials(name) {
return name.split(' ').map((part) => part[0]).join('').slice(0, 2).toUpperCase();
}
function renderDashboard(dashboard) {
if (!dashboard.available) return;
dashboardState = dashboard;
const home = dashboard.home;
const away = dashboard.away;
const heading = document.querySelector('.page-heading');
heading.querySelector('h1').textContent = `${home.name} vs ${away.name}`;
heading.querySelector('.subheading').textContent = [dashboard.fixture?.competition, dashboard.fixture?.season, dashboard.fixture?.stadium, dashboard.fixture?.date].filter(Boolean).join(' · ') || 'StatsBomb Open Data · Imported match';
const score = heading.querySelector('.match-score');
const scoreTeams = score.querySelectorAll('span');
const scoreValues = score.querySelectorAll('strong');
scoreTeams[0].textContent = home.name.slice(0, 3).toUpperCase();
scoreTeams[1].textContent = away.name.slice(0, 3).toUpperCase();
scoreValues[0].textContent = home.goals;
scoreValues[1].textContent = away.goals;
score.querySelector('small').textContent = 'IMPORTED MATCH';
const metrics = document.querySelectorAll('.metric');
metrics[0].querySelector('span').textContent = 'Passes';
metrics[0].querySelector('strong').textContent = `${home.passes} — ${away.passes}`;
metrics[0].querySelector('small').textContent = `${home.name} · ${away.name}`;
metrics[1].querySelector('span').textContent = 'Network volume';
metrics[1].querySelector('strong').textContent = home.passes + away.passes;
metrics[1].querySelector('small').textContent = 'completed passing events';
metrics[2].querySelector('span').textContent = 'Progressive passes';
metrics[2].querySelector('strong').textContent = dashboard.progressive;
metrics[2].querySelector('small').textContent = `${home.name} forward passes of 10m+`;
metrics[3].querySelector('span').textContent = 'Ball recoveries';
metrics[3].querySelector('strong').textContent = dashboard.recoveries;
metrics[3].querySelector('small').textContent = `${home.name} recoveries`;
const bestLink = dashboard.links[0];
metrics[4].querySelector('span').textContent = 'Top connection';
metrics[4].querySelector('strong').textContent = bestLink ? `${bestLink.source} → ${bestLink.target}` : 'No passing links';
metrics[4].querySelector('small').textContent = bestLink ? `${bestLink.weight} completed passes · Neo4j graph` : 'Neo4j graph';
document.querySelector('#queryInput').value = `Show ${home.name}'s passing network under high pressure`;
const suggestions = document.querySelectorAll('.suggestions button');
suggestions[0].dataset.query = `Show ${home.name}'s passing network under high pressure`;
suggestions[1].dataset.query = `Which ${home.name} players created the most progressive sequences?`;
suggestions[2].dataset.query = `Show ${home.name}'s hold-up play in the final third`;
suggestions[3].dataset.query = `Where did ${home.name} recover the ball?`;
suggestions[0].textContent = 'High pressure network';
suggestions[1].textContent = 'Progressive sequences';
suggestions[2].textContent = `${home.name} hold-up play`;
suggestions[3].textContent = 'Ball recoveries';
document.querySelector('.pitch-label.left').innerHTML = `${escapeSvg(home.name.toUpperCase())}<br /><b>IN POSSESSION</b>`;
renderAnnotations();
document.querySelector('.system-card .status-line').innerHTML = '<span class="green-dot"></span>Match data online';
document.querySelector('.system-card .mono').textContent = `${dashboard.events.length} key events · ${home.passes + away.passes} passes`;
document.querySelector('.page-footer span:first-child').textContent = `Data source: StatsBomb Open Data · ${home.name} vs ${away.name}`;
const footer = document.querySelector('.network-footer');
footer.querySelector('.mono').textContent = `Neo4j match ${dashboard.match_id}`;
footer.querySelector('span:last-child').innerHTML = `Showing <b id="edgeCount">${currentResult?.metrics.relationships || 0}</b> passing connections <button class="text-button">View full map ↗</button>`;
footer.querySelector('.text-button').addEventListener('click', () => document.querySelector('#networkStage').scrollIntoView({ behavior: 'smooth', block: 'center' }));
if (!footer.querySelector('.timeline-scrubber')) {
const slider = document.createElement('input');
slider.className = 'timeline-scrubber'; slider.type = 'range'; slider.min = '0'; slider.max = '90'; slider.value = '90'; slider.title = 'Show actions up to this minute';
slider.addEventListener('change', () => { analysisFilters.minute_from = null; analysisFilters.minute_to = Number(slider.value); runQuery(); });
footer.prepend(slider);
const play = document.createElement('button'); play.className = 'text-button timeline-play'; play.textContent = '▶ Play';
let timer = null;
play.addEventListener('click', () => { if (timer) { clearInterval(timer); timer = null; play.textContent = '▶ Play'; return; } slider.value = analysisFilters.minute_to ?? 0; play.textContent = '❚❚ Pause'; timer = setInterval(() => { slider.value = Math.min(90, Number(slider.value) + 1); if (Number(slider.value) >= 90) { clearInterval(timer); timer = null; play.textContent = '▶ Play'; } analysisFilters.minute_from = null; analysisFilters.minute_to = Number(slider.value); runQuery(); }, 900); });
footer.prepend(play);
}
document.querySelector('#playerList').innerHTML = dashboard.players.map((player) => `<button class="player-row compare-player" data-player="${escapeSvg(player.name)}"><span class="player-avatar">${initials(player.name)}</span><span><strong>${escapeSvg(player.name)}</strong><small>Passing involvement</small></span><span class="centrality"><b>${player.value}</b><small>actions</small></span></button>`).join('');
document.querySelector('.player-panel .mono.small').textContent = `${home.name.toUpperCase()} · 90 MIN`;
document.querySelectorAll('.compare-player').forEach((button) => button.addEventListener('click', () => showPlayerComparison(button.dataset.player)));
renderEventStream();
const lead = document.querySelector('.insight-lead');
lead.querySelector('strong').textContent = bestLink ? `${bestLink.source} and ${bestLink.target} are the strongest link.` : 'No passing links are available.';
lead.querySelector('p').textContent = bestLink ? `${bestLink.weight} completed passes connect this pair for ${home.name}.` : 'Import a match to populate this panel.';
document.querySelector('.insight-list').innerHTML = dashboard.links.slice(0, 3).map((link, index) => `<div class="insight-row"><span class="rank">${String(index + 1).padStart(2, '0')}</span><div><strong>${escapeSvg(link.source)} ↔ ${escapeSvg(link.target)}</strong><p>${link.weight} completed passes</p></div><b class="orange-text">#${index + 1}</b></div>`).join('');
}
function renderEventStream() {
if (!dashboardState) return;
const events = dashboardState.events.filter((event) => eventFilter === 'all' || (eventFilter === 'defensive' ? ['Ball Recovery', 'Interception'].includes(event.type) : event.type === 'Shot')).slice(0, eventDisplayCount);
document.querySelector('#eventList').innerHTML = events.map((event) => {
const time = `${String(event.minute || 0).padStart(2, '0')}:${String(event.second || 0).padStart(2, '0')}`;
return `<div class="event-row"><span class="event-time">${time}</span><span class="event-marker"></span><div><strong>${escapeSvg(event.type)}</strong><p><b>${escapeSvg(event.player)}</b> · ${escapeSvg(event.outcome || 'recorded')}</p></div></div>`;
}).join('') || '<p class="empty-state">No matching events.</p>';
const more = document.querySelector('.load-more');
more.hidden = events.length >= dashboardState.events.filter((event) => eventFilter === 'all' || (eventFilter === 'defensive' ? ['Ball Recovery', 'Interception'].includes(event.type) : event.type === 'Shot')).length;
}
async function loadDashboard(matchId = null) {
try {
const response = await apiFetch(matchId ? `/api/dashboard?match_id=${encodeURIComponent(matchId)}` : '/api/dashboard');
if (!response.ok) return;
renderDashboard(await response.json());
} catch (_) {
// The browser-only demo remains available when FastAPI is not running.
}
}
function drawNetwork(mode = 'pressure') {
const svg = document.querySelector('.network-svg');
const points = { Rice: [105, 275], Zinchenko: [205, 145], Martinelli: [330, 90], Odegaard: [360, 220], Jesus: [485, 166], Saka: [610, 108], White: [615, 275], Saliba: [290, 320], Gabriel: [170, 335], Partey: [465, 305] };
const links = mode === 'recoveries' ? [['Gabriel', 'Rice'], ['Rice', 'Zinchenko'], ['Saliba', 'Rice'], ['Rice', 'White'], ['Zinchenko', 'Martinelli'], ['Rice', 'Odegaard'], ['Odegaard', 'Jesus'], ['Jesus', 'Saka']] : [['Rice', 'Zinchenko'], ['Rice', 'Odegaard'], ['Rice', 'Saliba'], ['Rice', 'Partey'], ['Zinchenko', 'Martinelli'], ['Zinchenko', 'Odegaard'], ['Martinelli', 'Odegaard'], ['Odegaard', 'Jesus'], ['Odegaard', 'Saka'], ['Jesus', 'Saka'], ['Jesus', 'White'], ['Saka', 'White'], ['Saliba', 'Gabriel'], ['Partey', 'Jesus']];
svg.innerHTML = links.map(([source, target], index) => `<line x1="${points[source][0]}" y1="${points[source][1]}" x2="${points[target][0]}" y2="${points[target][1]}" class="edge ${index % 3 === 0 ? 'bright' : ''}"/>`).join('') + Object.entries(points).map(([name, point], index) => `<g class="node" transform="translate(${point[0]},${point[1]})"><circle r="${name === 'Odegaard' || name === 'Rice' ? 15 : 11}"/><text y="29">${name}</text><text y="3" class="node-number">${index + 1}</text></g>`).join('');
}
function drawNeo4jNetwork(nodes, edges) {
const svg = document.querySelector('.network-svg');
const connected = new Set(edges.flatMap((edge) => [edge.source, edge.target]));
const graphNodes = nodes.filter((node) => connected.has(node.id)).slice(0, 18);
const positions = new Map(graphNodes.map((node, index) => {
const angle = (Math.PI * 2 * index / Math.max(graphNodes.length, 1)) - Math.PI / 2;
const radius = node.type === 'zone' ? 150 : 125;
return [node.id, [380 + radius * Math.cos(angle), 205 + radius * Math.sin(angle)]];
}));
const visibleEdges = edges.filter((edge) => positions.has(edge.source) && positions.has(edge.target));
graphView = { x: 0, y: 0, scale: 1 };
svg.innerHTML = `<g class="graph-content">${visibleEdges.map((edge, index) => {
const source = positions.get(edge.source);
const target = positions.get(edge.target);
const width = Math.min(4, 1 + Math.log2(Math.max(edge.weight || 1, 1)));
return `<line data-edge="${index}" data-source="${edge.source}" data-target="${edge.target}" data-weight="${edge.weight}" x1="${source[0]}" y1="${source[1]}" x2="${target[0]}" y2="${target[1]}" class="edge bright" style="stroke-width:${width}"/>`;
}).join('')}${graphNodes.map((node, index) => {
const [x, y] = positions.get(node.id);
const label = node.label.length > 18 ? `${node.label.slice(0, 17)}…` : node.label;
const radius = node.type === 'zone' ? 15 : 12;
return `<g class="node" data-node="${node.id}" data-label="${escapeSvg(node.label)}" transform="translate(${x},${y})"><title>${escapeSvg(node.label)}</title><circle r="${radius}"/><text y="30">${escapeSvg(label)}</text><text y="3" class="node-number">${index + 1}</text></g>`;
}).join('')}</g>`;
attachGraphInteractions(svg);
}
function attachGraphInteractions(svg) {
const content = svg.querySelector('.graph-content');
const updateView = () => content.setAttribute('transform', `translate(${graphView.x} ${graphView.y}) scale(${graphView.scale})`);
svg.addEventListener('wheel', (event) => {
event.preventDefault();
graphView.scale = Math.max(0.55, Math.min(2.5, graphView.scale * (event.deltaY < 0 ? 1.12 : 0.89)));
updateView();
}, { passive: false });
let dragging = null;
svg.addEventListener('pointerdown', (event) => {
if (event.target.closest('.node, .edge')) return;
dragging = { x: event.clientX, y: event.clientY, viewX: graphView.x, viewY: graphView.y };
svg.setPointerCapture(event.pointerId);
});
svg.addEventListener('pointermove', (event) => {
if (!dragging) return;
graphView.x = dragging.viewX + (event.clientX - dragging.x) / (svg.clientWidth / 760);
graphView.y = dragging.viewY + (event.clientY - dragging.y) / (svg.clientHeight / 400);
updateView();
});
svg.addEventListener('pointerup', () => { dragging = null; });
svg.querySelectorAll('.node').forEach((node) => node.addEventListener('click', () => {
const selected = node.dataset.node;
const connected = new Set([selected]);
svg.querySelectorAll('.edge').forEach((edge) => { if (edge.dataset.source === selected || edge.dataset.target === selected) { connected.add(edge.dataset.source); connected.add(edge.dataset.target); edge.style.opacity = '1'; } else edge.style.opacity = '.08'; });
svg.querySelectorAll('.node').forEach((item) => { const active = connected.has(item.dataset.node); item.style.opacity = active ? '1' : '.2'; item.querySelector('circle').style.stroke = item.dataset.node === selected ? '#f0a24d' : ''; item.querySelector('circle').style.strokeWidth = item.dataset.node === selected ? '3' : ''; });
showToast(`${node.dataset.label}: showing direct connections`);
}));
svg.querySelectorAll('.edge').forEach((edge) => edge.addEventListener('click', () => showToast(`${edge.dataset.weight} actions between connected nodes`)));
}
function selectQuery(input) {
const value = input.toLowerCase();
if (value.includes('hold-up') || value.includes('saka') || value.includes('retention')) return 'hold';
if (value.includes('progressive') || value.includes('sequence')) return 'progressive';
if (value.includes('recover') || value.includes('win the ball')) return 'recoveries';
return 'pressure';
}
function updateResult(result) {
currentResult = result;
document.querySelector('#resultTitle').textContent = result.title;
document.querySelector('#passCount').textContent = result.metrics.passes;
document.querySelector('#edgeCount').textContent = result.metrics.relationships;
document.querySelector('#cypherCode').textContent = result.cypher;
}
function runDemoQuery() {
const mode = selectQuery(document.querySelector('#queryInput').value);
const query = queries[mode];
updateResult({ title: query.title, metrics: { passes: query.passes, relationships: query.edges }, cypher: query.cypher });
drawNetwork(mode);
showToast('Showing bundled demo data');
}
async function runQuery() {
try {
const response = await apiFetch('/api/query', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: document.querySelector('#queryInput').value, match_id: dashboardState?.match_id || null, graph_filter: graphFilter, ...analysisFilters, team: analysisFilters.team || dashboardState?.home?.name || undefined }) });
if (!response.ok) throw new Error('Query request failed');
const result = await response.json();
updateResult(result);
if (result.source === 'neo4j' && result.nodes.length && result.edges.length) {
drawNeo4jNetwork(result.nodes, result.edges);
showToast(`Passing map updated · ${result.metrics.relationships} connections`);
return;
}
drawNetwork(result.intent === 'hold_up' ? 'hold' : result.intent);
showToast('No matching graph records; showing demo layout');
} catch (_) {
runDemoQuery();
}
}
function showToast(message) {
const toast = document.querySelector('#toast');
toast.textContent = message;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 2200);
}
function openModal(title, content) {
document.querySelector('.workspace-modal')?.remove();
const modal = document.createElement('div');
modal.className = 'workspace-modal';
modal.innerHTML = `<div class="workspace-modal__card"><button class="workspace-modal__close" aria-label="Close">×</button><h2>${escapeSvg(title)}</h2><div class="workspace-modal__content">${content}</div></div>`;
modal.addEventListener('click', (event) => { if (event.target === modal || event.target.closest('.workspace-modal__close')) modal.remove(); });
document.body.append(modal);
return modal;
}
function setSignedInUser(user) {
signedInUser = user;
const profile = document.querySelector('.profile');
profile.querySelector('.avatar').textContent = initials(user.name);
profile.querySelector('strong').textContent = user.name;
profile.querySelector('small').textContent = `${user.role} workspace`;
}
function showAuth(mode = 'login') {
const registration = mode === 'register';
const modal = openModal(registration ? 'Create analyst account' : 'Sign in to Taktik', `<form class="auth-form"><label>Email<input required type="email" name="email" autocomplete="email" /></label>${registration ? '<label>Name<input required type="text" name="name" autocomplete="name" minlength="2" /></label>' : ''}<label>Password<input required type="password" name="password" autocomplete="${registration ? 'new-password' : 'current-password'}" minlength="12" /></label><p class="auth-error"></p><button class="run-query" type="submit">${registration ? 'Create account' : 'Sign in'}</button><button class="text-button auth-switch" type="button">${registration ? 'Already have an account? Sign in' : 'New here? Create an account'}</button></form>`);
modal.querySelector('.workspace-modal__close').remove();
modal.addEventListener('click', (event) => event.stopPropagation());
modal.querySelector('.auth-switch').addEventListener('click', () => { modal.remove(); showAuth(registration ? 'login' : 'register'); });
modal.querySelector('.auth-form').addEventListener('submit', async (event) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
const payload = Object.fromEntries(form.entries());
const response = await fetch(`/api/auth/${registration ? 'register' : 'login'}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
const result = await response.json();
if (!response.ok) { modal.querySelector('.auth-error').textContent = result.detail || 'Unable to sign in.'; return; }
authToken = result.access_token;
localStorage.setItem('taktik-access-token', authToken);
setSignedInUser(result.user);
modal.remove();
await loadDashboard();
await runQuery();
showToast(`Welcome, ${result.user.name}`);
});
}
async function initializeAuth() {
if (!authToken) { showAuth(); return; }
try {
const response = await apiFetch('/api/auth/me');
if (!response.ok) return;
setSignedInUser(await response.json());
await loadDashboard();
await runQuery();
} catch (_) {
showAuth();
}
}
function savedQueries() {
return JSON.parse(localStorage.getItem('taktik-saved-queries') || '[]');
}
async function saveCurrentQuery() {
if (!currentResult) return showToast('Run a query before saving it');
const modal = openModal('Save analysis', `<form class="auth-form"><label>Name<input name="title" required value="${escapeSvg(currentResult.title)}" /></label><label>Tags <input name="tags" placeholder="e.g. progression, pressing" /></label><label>Analyst note<textarea name="note" rows="4" placeholder="What should the team investigate?"></textarea></label><button class="run-query" type="submit">Save to workspace</button></form>`);
modal.querySelector('form').addEventListener('submit', async (event) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
const payload = { title: form.get('title'), query: currentResult.query, match_id: dashboardState?.match_id || null, tags: String(form.get('tags')).split(',').map((tag) => tag.trim()).filter(Boolean), note: form.get('note') };
const response = await apiFetch('/api/saved-queries', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
if (response.ok) { modal.remove(); showToast('Analysis saved to your workspace'); }
});
}
async function showSavedQueries() {
const response = await apiFetch('/api/saved-queries');
const saved = response.ok ? (await response.json()).queries : savedQueries();
const modal = openModal('Saved queries', saved.length ? saved.map((item, index) => `<div class="saved-query"><strong>${escapeSvg(item.title)}</strong><small>${escapeSvg(item.query)}</small><p>${escapeSvg((item.tags || []).join(', '))}</p><button class="text-button" data-load="${index}">Open</button><button class="text-button" data-share="${item.id}">Share</button><button class="text-button" data-comments="${item.id}">Comments</button></div>`).join('') : '<p>No saved queries yet. Run a query, then select Save insight.</p>');
modal.querySelectorAll('[data-load]').forEach((button) => button.addEventListener('click', () => { document.querySelector('#queryInput').value = saved[button.dataset.load].query; modal.remove(); runQuery(); }));
modal.querySelectorAll('[data-share]').forEach((button) => button.addEventListener('click', async () => { const result = await apiFetch(`/api/saved-queries/${button.dataset.share}/share`, { method: 'POST' }); if (result.ok) { const token = (await result.json()).token; await navigator.clipboard?.writeText(`${location.origin}/shared/${token}`); showToast('Read-only share link copied'); } }));
modal.querySelectorAll('[data-comments]').forEach((button) => button.addEventListener('click', () => showComments(button.dataset.comments)));
}
async function showComments(queryId) {
const response = await apiFetch(`/api/saved-queries/${queryId}/comments`);
const comments = response.ok ? (await response.json()).comments : [];
const modal = openModal('Analysis comments', `<div>${comments.map((comment) => `<p><strong>${escapeSvg(comment.author)}</strong>: ${escapeSvg(comment.body)}</p>`).join('') || '<p>No comments yet.</p>'}</div><form class="auth-form"><label>Add comment<textarea name="body" required rows="3"></textarea></label><button class="run-query">Post comment</button></form>`);
modal.querySelector('form').addEventListener('submit', async (event) => { event.preventDefault(); const body = new FormData(event.currentTarget).get('body'); const result = await apiFetch(`/api/saved-queries/${queryId}/comments`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ body }) }); if (result.ok) { modal.remove(); showComments(queryId); } });
}
function exportCurrentView() {
if (!currentResult || !dashboardState) return showToast('Run a graph query before exporting');
const modal = openModal('Export tactical report', '<button class="saved-query" data-format="pdf"><strong>Print tactical report</strong><small>Choose Save as PDF in the print dialog</small></button><button class="saved-query" data-format="json"><strong>JSON analysis package</strong><small>Dashboard, query, filters, nodes, and relationships</small></button><button class="saved-query" data-format="csv"><strong>CSV relationship table</strong><small>Ready for spreadsheets and reporting tools</small></button>');
modal.querySelectorAll('[data-format]').forEach((button) => button.addEventListener('click', () => {
const format = button.dataset.format;
const name = dashboardState.match_id || 'match';
let content;
let type;
if (format === 'pdf') {
const report = window.open('', '_blank');
report.document.write(`<title>Taktik report</title><style>body{font-family:Arial;padding:36px;color:#17221d}h1{margin-bottom:4px}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.card{border:1px solid #bdc9bf;padding:14px;border-radius:8px}.note{margin-top:24px;padding:16px;background:#f3f6f2}</style><h1>${escapeSvg(currentResult.title)}</h1><p>${escapeSvg(dashboardState.home.name)} vs ${escapeSvg(dashboardState.away.name)} · Match ${escapeSvg(dashboardState.match_id)}</p><div class="grid"><div class="card"><b>Actions</b><br>${currentResult.metrics.passes}</div><div class="card"><b>Relationships</b><br>${currentResult.metrics.relationships}</div><div class="card"><b>Filter</b><br>${escapeSvg(graphFilter)} · ${analysisFilters.minute_to ?? 90}'</div></div><div class="note"><h2>Analyst readout</h2><p>${escapeSvg(document.querySelector('.insight-lead').innerText)}</p></div><h2>Top connections</h2><ol>${dashboardState.links.map((link) => `<li>${escapeSvg(link.source)} → ${escapeSvg(link.target)}: ${link.weight}</li>`).join('')}</ol>`); report.document.close(); report.focus(); report.print(); modal.remove(); return;
}
if (format === 'csv') {
const labels = Object.fromEntries(currentResult.nodes.map((node) => [node.id, node.label]));
content = ['source,target,relationship,weight', ...currentResult.edges.map((edge) => [labels[edge.source] || edge.source, labels[edge.target] || edge.target, edge.type, edge.weight].map((value) => `"${String(value).replaceAll('"', '""')}"`).join(','))].join('\n');
type = 'text/csv';
} else {
content = JSON.stringify({ exportedAt: new Date().toISOString(), dashboard: dashboardState, filters: { graphFilter, analysisFilters }, query: currentResult }, null, 2);
type = 'application/json';
}
const url = URL.createObjectURL(new Blob([content], { type }));
const link = document.createElement('a'); link.href = url; link.download = `taktik-${name}.${format}`; link.click(); URL.revokeObjectURL(url);
modal.remove(); showToast(`Report exported as ${format.toUpperCase()}`);
}));
}
function chooseImport() {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json,.json';
input.addEventListener('change', async () => {
const file = input.files?.[0];
if (!file) return;
const form = new FormData();
form.append('file', file);
showToast('Importing match into Neo4j…');
try {
const response = await apiFetch('/api/import', { method: 'POST', body: form });
const result = await response.json();
if (!response.ok) throw new Error(result.detail || 'Import failed');
eventDisplayCount = 5;
eventFilter = 'all';
renderDashboard(result);
await runQuery();
showToast('Match imported and dashboard refreshed');
} catch (error) {
showToast(error.message || 'Import failed');
}
});
input.click();
}
function showSchema() {
openModal('Data model (advanced)', '<p>This technical reference explains how imported football actions are connected. You do not need it to analyse a match.</p><pre>(:Player)-[:PERFORMED]->(:Event)-[:OCCURRED_IN]->(:PitchZone)\n(:Player)-[:PASSED_TO {team, pressure, progressive, outcome}]->(:Player)\n(:Player)-[:RECOVERED_IN {team}]->(:PitchZone)</pre>');
}
function showGraphFilter() {
const modal = openModal('Pitch area', '<button class="saved-query" data-filter="all"><strong>All pitch</strong><small>Show all matching actions</small></button><button class="saved-query" data-filter="final_third"><strong>Final third</strong><small>Only actions starting in the final third</small></button>');
modal.querySelectorAll('[data-filter]').forEach((button) => button.addEventListener('click', () => {
graphFilter = button.dataset.filter;
document.querySelector('.network-context').innerHTML = `Pitch area: <b>${graphFilter === 'final_third' ? 'Final 3rd' : 'All pitch'}</b> ×`;
modal.remove();
runQuery();
}));
}
async function showPlayerComparison(name) {
const peer = dashboardState.players.find((player) => player.name !== name)?.name;
const response = await apiFetch(`/api/players/compare?match_id=${encodeURIComponent(dashboardState.match_id)}&players=${encodeURIComponent(name)}&players=${encodeURIComponent(peer)}`);
if (!response.ok) return showToast('Player comparison is unavailable');
const players = (await response.json()).players;
const maximum = Math.max(1, ...players.flatMap((player) => [player.passes, player.progressive, player.pressure, player.recoveries]));
const modal = openModal('Player comparison', `<table class="comparison-table"><thead><tr><th>Player</th><th>Passes</th><th>Progressive</th><th>Under pressure</th><th>Recoveries</th><th></th></tr></thead><tbody>${players.map((player) => `<tr><td>${escapeSvg(player.name)}</td><td>${player.passes}</td><td>${player.progressive}</td><td>${player.pressure}</td><td>${player.recoveries}</td><td><button class="text-button watch-player" data-player="${escapeSvg(player.name)}">Watch</button></td></tr>`).join('')}</tbody></table><div class="comparison-bars">${players.map((player) => `<h3>${escapeSvg(player.name)}</h3>${['passes','progressive','pressure','recoveries'].map((metric) => `<div><small>${metric}</small><i style="width:${Math.max(4, player[metric] / maximum * 100)}%"></i><b>${player[metric]}</b></div>`).join('')}`).join('')}</div>`);
modal.querySelectorAll('.watch-player').forEach((button) => button.addEventListener('click', async () => { const response = await apiFetch(`/api/watchlist/${encodeURIComponent(button.dataset.player)}`, { method: 'POST' }); if (response.ok) showToast(`${button.dataset.player} added to watchlist`); }));
}
function showAnalysisFilters() {
const teams = [dashboardState?.home?.name, dashboardState?.away?.name].filter(Boolean);
const zones = [['defensive_left', 'Defensive left'], ['defensive_centre', 'Defensive centre'], ['defensive_right', 'Defensive right'], ['middle_left', 'Middle left'], ['middle_centre', 'Middle centre'], ['middle_right', 'Middle right'], ['final_left', 'Final third left'], ['final_centre', 'Final third centre'], ['final_right', 'Final third right']];
const phases = ['Regular Play', 'From Counter', 'From Corner', 'From Free Kick', 'From Throw In', 'From Goal Kick', 'From Kick Off'];
const modal = openModal('Analysis filters', `<form class="auth-form"><label>Team focus<select name="team"><option value="">Primary team</option>${teams.map((team) => `<option value="${escapeSvg(team)}">${escapeSvg(team)}</option>`).join('')}</select></label><label>Player <input name="player_name" value="${escapeSvg(analysisFilters.player_name ?? '')}" placeholder="Any player" /></label><label>Origin zone<select name="zone_id"><option value="">All zones</option>${zones.map(([id, label]) => `<option value="${id}">${label}</option>`).join('')}</select></label><label>Possession phase<select name="possession_phase"><option value="">All phases</option>${phases.map((phase) => `<option value="${escapeSvg(phase)}">${escapeSvg(phase)}</option>`).join('')}</select></label><label>Score state<select name="score_state"><option value="all">Any score state</option><option value="winning">Winning</option><option value="drawing">Drawing</option><option value="losing">Losing</option></select></label><label>Period<select name="period"><option value="all">Full match</option><option value="1">First half</option><option value="2">Second half</option></select></label><label>From minute <input name="minute_from" type="number" min="0" max="130" value="${analysisFilters.minute_from ?? ''}" /></label><label>To minute <input name="minute_to" type="number" min="0" max="130" value="${analysisFilters.minute_to ?? ''}" /></label><button class="run-query" type="submit">Apply filters</button><button class="text-button clear-analysis" type="button">Clear filters</button><button class="text-button add-annotation" type="button">Add pitch annotation</button></form>`);
const form = modal.querySelector('form');
form.period.value = analysisFilters.period;
form.team.value = analysisFilters.team ?? '';
form.zone_id.value = analysisFilters.zone_id ?? '';
form.possession_phase.value = analysisFilters.possession_phase ?? '';
form.score_state.value = analysisFilters.score_state;
form.addEventListener('submit', (event) => { event.preventDefault(); const values = new FormData(form); analysisFilters = { team: values.get('team') || null, player_name: values.get('player_name').trim() || null, zone_id: values.get('zone_id') || null, possession_phase: values.get('possession_phase') || null, score_state: values.get('score_state'), period: values.get('period'), minute_from: values.get('minute_from') === '' ? null : Number(values.get('minute_from')), minute_to: values.get('minute_to') === '' ? null : Number(values.get('minute_to')) }; modal.remove(); runQuery(); });
modal.querySelector('.clear-analysis').addEventListener('click', () => { analysisFilters = { minute_from: null, minute_to: null, period: 'all', player_name: null, zone_id: null, possession_phase: null, score_state: 'all', team: null }; modal.remove(); runQuery(); });
modal.querySelector('.add-annotation').addEventListener('click', () => { const text = window.prompt('Annotation text'); if (text?.trim()) { pendingAnnotation = text.trim(); modal.remove(); showToast('Click the pitch to place your annotation'); } });
}
function annotationKey() { return `taktik-annotations-${dashboardState?.match_id || 'demo'}`; }
function renderAnnotations() { const stage = document.querySelector('#networkStage'); stage.querySelectorAll('.pitch-annotation').forEach((item) => item.remove()); const annotations = JSON.parse(localStorage.getItem(annotationKey()) || '[]'); annotations.forEach((annotation) => { const marker = document.createElement('button'); marker.className = 'pitch-annotation'; marker.style.left = `${annotation.x}%`; marker.style.top = `${annotation.y}%`; marker.textContent = annotation.text; marker.title = 'Click to remove'; marker.addEventListener('click', () => { localStorage.setItem(annotationKey(), JSON.stringify(annotations.filter((item) => item.id !== annotation.id))); renderAnnotations(); }); stage.append(marker); }); }
async function chooseMatch() {
try {
const response = await apiFetch('/api/matches');
const data = await response.json();
const matches = data.matches || [];
const modal = openModal('Loaded matches', matches.length ? matches.map((match) => { const fixture = match.home && match.away ? `${match.home} ${match.home_score ?? '–'}–${match.away_score ?? '–'} ${match.away}` : (match.teams || []).join(' vs ') || match.id; const context = [match.competition, match.season, match.date, `${match.events || 0} events`].filter(Boolean).join(' · '); return `<button class="saved-query" data-match-id="${escapeSvg(match.id)}"><strong>${escapeSvg(fixture)}</strong><small>${escapeSvg(context || match.id)}</small></button>`; }).join('') : '<p>No imported matches are available.</p>');
modal.querySelectorAll('[data-match-id]').forEach((button) => button.addEventListener('click', async () => { await loadDashboard(button.dataset.matchId); await runQuery(); modal.remove(); showToast('Match changed'); }));
} catch (_) {
showToast('Unable to load the match catalogue');
}
}
async function showWatchlist() {
const response = await apiFetch('/api/watchlist');
if (!response.ok) return showToast('Your watchlist is unavailable');
const players = (await response.json()).players || [];
const modal = openModal('Scouting watchlist', players.length ? players.map((name) => `<div class="saved-query"><strong>${escapeSvg(name)}</strong><small>Tracked player</small><button class="text-button" data-watch-compare="${escapeSvg(name)}">Compare in this match</button><button class="text-button" data-watch-filter="${escapeSvg(name)}">Filter network</button></div>`).join('') : '<p>No watched players yet. Open a player comparison and select <strong>Watch</strong> to add one.</p>');
modal.querySelectorAll('[data-watch-compare]').forEach((button) => button.addEventListener('click', () => {
const name = button.dataset.watchCompare;
if (!dashboardState?.players.some((player) => player.name === name)) return showToast(`${name} is not in the selected match`);
modal.remove(); showPlayerComparison(name);
}));
modal.querySelectorAll('[data-watch-filter]').forEach((button) => button.addEventListener('click', () => {
analysisFilters.player_name = button.dataset.watchFilter;
modal.remove(); runQuery(); showToast(`Network filtered for ${analysisFilters.player_name}`);
}));
}
document.querySelector('#runQuery').addEventListener('click', runQuery);
document.querySelector('#queryInput').addEventListener('keydown', (event) => { if (event.key === 'Enter') runQuery(); });
document.querySelectorAll('.suggestions button').forEach((button) => button.addEventListener('click', () => { document.querySelector('#queryInput').value = button.dataset.query; runQuery(); }));
document.querySelector('#saveInsight').addEventListener('click', saveCurrentQuery);
document.querySelector('#copyCypher').addEventListener('click', async () => { await navigator.clipboard?.writeText(document.querySelector('#cypherCode').textContent); showToast('Cypher copied to clipboard'); });
document.querySelector('#exportBtn').addEventListener('click', exportCurrentView);
document.querySelector('.filter-button').addEventListener('click', (event) => { const filters = ['all', 'defensive', 'attacking']; eventFilter = filters[(filters.indexOf(eventFilter) + 1) % filters.length]; event.currentTarget.textContent = ({ all: 'All phases⌄', defensive: 'Defensive actions⌄', attacking: 'Shots⌄' })[eventFilter]; eventDisplayCount = 5; renderEventStream(); });
document.querySelector('.load-more').addEventListener('click', () => { eventDisplayCount += 5; renderEventStream(); });
document.querySelector('.text-button').addEventListener('click', () => document.querySelector('#networkStage').scrollIntoView({ behavior: 'smooth', block: 'center' }));
document.querySelector('.panel-tools .icon-button').addEventListener('click', () => document.querySelector('#networkStage').requestFullscreen?.());
document.querySelector('.panel-tools .icon-button:nth-child(2)').addEventListener('click', showAnalysisFilters);
document.querySelector('.network-context').addEventListener('click', showGraphFilter);
document.querySelector('.network-context').style.cursor = 'pointer';
document.querySelector('#networkStage').addEventListener('click', (event) => { if (!pendingAnnotation || event.target.closest('.pitch-annotation')) return; const bounds = event.currentTarget.getBoundingClientRect(); const annotations = JSON.parse(localStorage.getItem(annotationKey()) || '[]'); annotations.push({ id: crypto.randomUUID(), text: pendingAnnotation, x: (event.clientX - bounds.left) / bounds.width * 100, y: (event.clientY - bounds.top) / bounds.height * 100 }); localStorage.setItem(annotationKey(), JSON.stringify(annotations)); pendingAnnotation = null; renderAnnotations(); showToast('Pitch annotation saved'); });
document.querySelectorAll('.nav-item').forEach((button) => button.addEventListener('click', () => {
document.querySelectorAll('.nav-item').forEach((item) => item.classList.remove('active'));
button.classList.add('active');
const label = button.textContent.trim();
if (label.includes('Match room')) window.scrollTo({ top: 0, behavior: 'smooth' });
else if (label.includes('Passing map')) document.querySelector('#networkStage').scrollIntoView({ behavior: 'smooth', block: 'center' });
else if (label.includes('Saved queries')) showSavedQueries();
else if (label.includes('Scouting watchlist')) showWatchlist();
else if (label.includes('Import match')) chooseImport();
else if (label.includes('Data model')) showSchema();
}));
document.querySelector('.workspace-switcher').addEventListener('click', chooseMatch);
document.querySelector('.profile').addEventListener('click', () => { if (signedInUser) { const modal = openModal('Account', `<p>Signed in as <strong>${escapeSvg(signedInUser.email)}</strong></p><button class="saved-query sign-out">Sign out</button>`); modal.querySelector('.sign-out').addEventListener('click', () => { authToken = null; signedInUser = null; localStorage.removeItem('taktik-access-token'); modal.remove(); showAuth(); }); } });
function enterWorkspace(question) {
if (question) document.querySelector('#queryInput').value = question;
document.body.classList.remove('landing-active');
initializeAuth();
}
document.querySelectorAll('[data-enter-workspace]').forEach((button) => button.addEventListener('click', () => enterWorkspace()));
document.querySelectorAll('[data-landing-question]').forEach((button) => button.addEventListener('click', () => enterWorkspace(button.dataset.landingQuestion)));
renderPlayers();
renderEvents();
drawNetwork();
document.querySelector('.network-context').innerHTML = 'Pitch area: <b>All pitch</b> ×';
if (authToken) enterWorkspace();