-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
478 lines (427 loc) · 15.8 KB
/
app.js
File metadata and controls
478 lines (427 loc) · 15.8 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
import DataLoader from './loader.js';
import { fetchDomainKey } from './loader.js';
import { DataChunks, facets } from '@adobe/rum-distiller';
/* eslint-disable no-unused-vars -- custom elements imported for registration */
import URLAutocomplete from './components/url-autocomplete.js';
import DateRangePicker from './components/date-range-picker.js';
import ErrorDashboard from './dashboards/error-dashboard.js';
import LoadDashboard from './dashboards/performance-dashboard.js';
import EngagementDashboard from './dashboards/engagement-dashboard.js';
import ResourceDashboard from './dashboards/resource-dashboard.js';
/* eslint-enable no-unused-vars */
import { errorDataChunks, performanceDataChunks, engagementDataChunks, resourceDataChunks } from './datachunks.js';
import { formatLocalYMD, localRangeToUTCISOs } from './utils/date-utils.js';
const dataLoader = new DataLoader();
const BUNDLER_ENDPOINT = 'https://bundles.aem.page';
dataLoader.apiEndpoint = BUNDLER_ENDPOINT;
// URL Parameter Management
function getURLParams() {
const params = new URLSearchParams(window.location.search);
return {
tab: params.get('tab') || undefined,
url: params.get('url') || undefined,
startDate: params.get('startDate') || undefined,
endDate: params.get('endDate') || undefined,
domain: params.get('domain') || undefined,
// Optional testing/debug params for Performance dashboard filters
deviceType: params.getAll('deviceType').filter(Boolean),
source: params.getAll('source').filter(Boolean),
};
}
function updateURLParams(params) {
const currentParams = new URLSearchParams(window.location.search);
// Update or set each parameter
Object.keys(params).forEach(key => {
if (params[key]) {
currentParams.set(key, params[key]);
} else {
currentParams.delete(key);
}
});
const newURL = `${window.location.pathname}?${currentParams.toString()}`;
window.history.pushState({ ...params }, '', newURL);
}
function showLoading() {
const urlResults = document.getElementById('url-results');
if (urlResults) {
// If the dashboard is currently mounted, we still show a loader for initial/tab renders
// to avoid a visible "blank" gap.
urlResults.innerHTML = `
<div class="loading-container">
<div class="loading-spinner"></div>
<p>Loading data...</p>
</div>
`;
}
}
function hideLoading() {
const urlResults = document.getElementById('url-results');
const loadingContainer = urlResults?.querySelector?.('.loading-container');
if (loadingContainer) {
loadingContainer.remove();
}
}
function renderInvalidDomainDomainKeyError(message = 'Invalid domain/domainkey combination. Please verify and try again.') {
const urlResults = document.getElementById('url-results');
if (urlResults) {
urlResults.innerHTML = `<p class="error">${message}</p>`;
}
}
const dataChunksConfig = {
error: errorDataChunks,
performance: performanceDataChunks,
engagement: engagementDataChunks,
resource: resourceDataChunks,
};
// Single function to read URL params, set state, and render
async function renderFromURLParams() {
const params = getURLParams();
const dateRangePicker = document.getElementById('date-range-picker');
const urlAutocomplete = document.getElementById('url-autocomplete');
const {
startDate = dateRangePicker.getStartDate(),
endDate = dateRangePicker.getEndDate(),
// url-autocomplete may not have initialized its internal value yet on first paint;
// fall back to the attribute value to avoid an initial "blank" render.
url = urlAutocomplete.getValue() || urlAutocomplete.getAttribute('value') || '',
tab = 'error',
deviceType = [],
source = [],
} = params;
// Set active tab based on URL params
const urlResults = document.getElementById('url-results');
if (domainResolutionState.invalid) {
renderInvalidDomainDomainKeyError(domainResolutionState.message);
hideLoading();
return;
}
document.querySelectorAll('.dashboard-tabs .tab').forEach(tabElement => {
tabElement.classList.remove('active');
});
const activeTab = document.getElementById(`tab-${tab}`);
activeTab?.classList.add('active');
// Only update dates if they're different to avoid circular event triggering
const currentStartDate = dateRangePicker.getStartDate();
const currentEndDate = dateRangePicker.getEndDate();
if (currentStartDate !== startDate || currentEndDate !== endDate) {
dateRangePicker.setDates(startDate, endDate);
}
// Only update URL if it's different
const currentUrl = urlAutocomplete.getValue();
if (currentUrl !== url) {
urlAutocomplete.setValue(url);
}
// If URL is specified, filter data and render dashboard
if (url) {
showLoading();
try {
// Ensure data is loaded before rendering
if (!currentData || !Array.isArray(currentData)) {
await loadData(startDate, endDate);
}
const normalizeUrl = (u) => u.replace(/\.html$/, '').replace(/\?$/, '').replace(/\/$/, '');
const normalizedUrl = normalizeUrl(url);
// Filter by URL
const filteredData = currentData.map((chunk) => ({
date: chunk.date,
hour: chunk.hour,
rumBundles: chunk.rumBundles.filter((bundle) => normalizeUrl(bundle.url) === normalizedUrl),
})).filter((chunk) => chunk.rumBundles.length > 0);
if (filteredData.length > 0 && !filteredData.every(chunk => chunk.rumBundles.length === 0)) {
// Render the dashboard based on the tab (swap in one operation to avoid blank flashes)
let dataChunksForDashboard;
let dashboardElement;
dataChunksForDashboard = dataChunksConfig[tab](filteredData);
dashboardElement = document.createElement(`${tab}-dashboard`);
urlResults.replaceChildren(dashboardElement);
// Pass filteredData as third arg so performance dashboard can aggregate sources fully
if (tab === 'performance') {
dashboardElement.setData(dataChunksForDashboard, url, filteredData, sourceAliasMap, {
deviceTypes: deviceType,
sources: source,
});
} else {
dashboardElement.setData(dataChunksForDashboard, url, filteredData, sourceAliasMap);
}
} else {
urlResults.innerHTML = '<p>No data found for this URL</p>';
}
} catch (error) {
// eslint-disable-next-line no-console -- user-facing error feedback
console.error('Error rendering dashboard:', error);
urlResults.innerHTML = '<p class="error">Error processing data. Please try again.</p>';
} finally {
hideLoading();
}
} else {
urlResults.innerHTML = '<p>Please select a URL to view dashboard</p>';
hideLoading();
}
}
// Generic handler for updating URL params and re-rendering
function handleParamUpdate(paramUpdates) {
updateURLParams(paramUpdates);
renderFromURLParams();
}
let currentData;
let sourceAliasMap = null; // alias -> canonical
let activeDomainDisplay = '';
const domainResolutionState = {
invalid: false,
message: '',
};
function clearDomainResolutionError() {
domainResolutionState.invalid = false;
domainResolutionState.message = '';
}
function setDomainResolutionError(message) {
domainResolutionState.invalid = true;
domainResolutionState.message = message;
}
function setDomainInputValue(domain) {
const domainInput = document.getElementById('domain-input');
if (domainInput) {
domainInput.value = domain;
}
}
async function resolveAndConfigureDomain(domain) {
const normalizedDomain = domain.trim();
const encodedDomain = encodeURIComponent(normalizedDomain);
const resolution = await fetchDomainKey(normalizedDomain);
activeDomainDisplay = normalizedDomain;
dataLoader.domain = encodedDomain;
if (!resolution?.ok) {
dataLoader.domainKey = undefined;
currentData = [];
setDomainResolutionError(
resolution?.error?.userMessage || 'Invalid domain/domainkey combination. Please verify and try again.',
);
renderInvalidDomainDomainKeyError(domainResolutionState.message);
return false;
}
clearDomainResolutionError();
dataLoader.domainKey = resolution.domainKey;
return true;
}
async function syncDomainFromURL() {
const { domain } = getURLParams();
if (!domain) {
return false;
}
setDomainInputValue(domain);
return resolveAndConfigureDomain(domain);
}
async function loadSourceAliasesOnce() {
if (sourceAliasMap) {
return sourceAliasMap;
}
try {
const resp = await fetch('/forms/source-aliases.json');
const json = await resp.json();
const alias = {};
Object.entries(json || {}).forEach(([canonical, list]) => {
const arr = Array.isArray(list) ? list : [];
arr.concat([canonical]).forEach((s) => alias[normalizeSourceValue(s)] = canonical);
});
sourceAliasMap = alias;
} catch (e) {
sourceAliasMap = {};
}
return sourceAliasMap;
}
function normalizeSourceValue(src) {
try {
if (src.startsWith('http://') || src.startsWith('https://')) {
const u = new URL(src);
let path = (u.pathname || '/').replace(/\/+$/, '');
if (path === '') {
path = '';
}
return `${u.origin}${path}`;
}
return src.replace(/\/?#$/, '');
} catch (e) {
return src;
}
}
async function loadData(startDate, endDate) {
await loadSourceAliasesOnce();
const utc = localRangeToUTCISOs(startDate, endDate);
if (!utc) {
currentData = [];
return;
}
currentData = await dataLoader.fetchDateRange(utc.startUTC, utc.endUTC);
// Update the URLs autocomplete with new data
const newDataChunks = new DataChunks();
newDataChunks.load(currentData);
newDataChunks.addFacet('url', facets.url);
const newUrls = newDataChunks.facets.url.map(url => url.value);
const urlAutocomplete = document.getElementById('url-autocomplete');
urlAutocomplete.setUrls(newUrls);
// Update placeholder to reflect the active domain.
if (activeDomainDisplay) {
urlAutocomplete.setAttribute('placeholder', `https://${activeDomainDisplay}/`);
}
}
function setupEventListeners() {
const _urlForm = document.getElementById('url-form');
const urlAutocomplete = document.getElementById('url-autocomplete');
const dateRangePicker = document.getElementById('date-range-picker');
const dashboardTabs = document.querySelector('.dashboard-tabs');
const applyDomainButton = document.getElementById('apply-domain');
const domainInput = document.getElementById('domain-input');
// Handle tab clicks with event delegation on parent
dashboardTabs.addEventListener('click', (e) => {
const tab = e.target.closest('.tab');
if (tab && tab.id) {
const tabName = tab.id.replace('tab-', '');
handleParamUpdate({ tab: tabName });
}
});
urlAutocomplete.addEventListener('url-selected', (event) => {
const url = event.detail.url;
handleParamUpdate({ url });
});
// Date range change handler
dateRangePicker.addEventListener('date-range-changed', async (event) => {
const { startDate, endDate } = event.detail;
// Show loading state
showLoading();
try {
// Fetch new data for the date range
await loadData(startDate, endDate);
// Update URL parameters and re-render
handleParamUpdate({ startDate, endDate });
} catch (error) {
const urlResults = document.getElementById('url-results');
urlResults.innerHTML = '<p class="error">Error loading data. Please try again.</p>';
// eslint-disable-next-line no-console -- user-facing error feedback
console.error('Error fetching data:', error);
hideLoading();
}
});
const applyDomainFromInput = async () => {
const nextDomain = domainInput?.value?.trim() || '';
if (!nextDomain) {
setDomainResolutionError('Please enter a domain before applying changes.');
renderInvalidDomainDomainKeyError(domainResolutionState.message);
return;
}
showLoading();
updateURLParams({ domain: nextDomain });
const resolved = await resolveAndConfigureDomain(nextDomain);
if (!resolved) {
hideLoading();
return;
}
const currentParams = getURLParams();
const startDate = currentParams.startDate || dateRangePicker.getStartDate();
const endDate = currentParams.endDate || dateRangePicker.getEndDate();
try {
await loadData(startDate, endDate);
await renderFromURLParams();
} catch (error) {
renderInvalidDomainDomainKeyError('Error loading data. Please try again.');
// eslint-disable-next-line no-console -- user-facing error feedback
console.error('Error loading data after domain update:', error);
} finally {
hideLoading();
}
};
applyDomainButton?.addEventListener('click', applyDomainFromInput);
domainInput?.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
applyDomainFromInput();
}
});
}
// Handle browser back/forward buttons
window.addEventListener('popstate', async () => {
const params = getURLParams();
if (!params.domain) {
const urlResults = document.getElementById('url-results');
if (urlResults) {
urlResults.innerHTML = '<p>Please provide a <code>?domain=</code> parameter in the URL to load data.</p>';
}
return;
}
const resolved = await syncDomainFromURL();
if (!resolved) {
hideLoading();
return;
}
const dateRangePicker = document.getElementById('date-range-picker');
const startDate = params.startDate || dateRangePicker.getStartDate();
const endDate = params.endDate || dateRangePicker.getEndDate();
try {
await loadData(startDate, endDate);
await renderFromURLParams();
} catch (error) {
renderInvalidDomainDomainKeyError('Error loading data. Please try again.');
// eslint-disable-next-line no-console -- user-facing error feedback
console.error('Error handling browser navigation:', error);
} finally {
hideLoading();
}
});
// Initialize event listeners FIRST
setupEventListeners();
const params = getURLParams();
const dateRangePicker = document.getElementById('date-range-picker');
const today = formatLocalYMD(new Date());
const oneWeekAgo = (() => {
const d = new Date();
d.setDate(d.getDate() - 7);
return formatLocalYMD(d);
})();
dateRangePicker.setDates(oneWeekAgo, today);
const urlAutocomplete = document.getElementById('url-autocomplete');
const defaults = {
tab: 'error',
url: urlAutocomplete.getValue(),
startDate: dateRangePicker.getStartDate(),
endDate: dateRangePicker.getEndDate(),
};
const merged = {
...defaults,
...JSON.parse(JSON.stringify(params)),
};
const changedParams = Object.fromEntries(
Object.entries(defaults).filter(
([key, _value]) => merged[key] !== _value,
).map(([key]) => [key, merged[key]]),
);
// Resolve domain from URL params; guard all data loading on domain presence
if (!merged.domain) {
const urlResults = document.getElementById('url-results');
if (urlResults) {
urlResults.innerHTML = '<p>Please provide a <code>?domain=</code> parameter in the URL to load data.</p>';
}
} else {
setDomainInputValue(merged.domain);
const resolved = await resolveAndConfigureDomain(merged.domain);
// Load initial data
if (resolved && merged.startDate && merged.endDate) {
try {
if (merged.url) {
showLoading();
}
await loadData(merged.startDate, merged.endDate);
} catch (error) {
// eslint-disable-next-line no-console -- user-facing error feedback
console.error('Error loading initial data:', error);
const urlResults = document.getElementById('url-results');
if (urlResults) {
urlResults.innerHTML = '<p class="error">Error loading initial data. Please try again.</p>';
}
}
}
}
// Only update URL params and re-render when domain is present;
// if no domain, the message is already set above and renderFromURLParams
// would overwrite it with "Please select a URL to view dashboard".
if (merged.domain && !domainResolutionState.invalid) {
handleParamUpdate(changedParams);
}