Repository navigation
Expand file tree
/
Copy pathlog-viewer.js
More file actions
641 lines (565 loc) · 18.4 KB
/
Copy pathlog-viewer.js
File metadata and controls
641 lines (565 loc) · 18.4 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
// log-viewer.js — WordPress Log Viewer panel
(async function main() {
const { logViewer } = await chrome.storage.sync.get("logViewer");
if (!logViewer) return;
const {
enabled,
logFilePath = "/wp-content/debug.log",
autoRefresh = false,
refreshIntervalValue = 10,
highlightErrors = true,
showTimestamps = true,
maxLogLines = 200,
panelPosition = "top-right",
domains = [],
} = logViewer;
if (!enabled) return;
// Check if current domain matches allowed domains
function isDomainAllowed() {
if (!domains || domains.length === 0) return true; // Show on all domains if none specified
const currentHost = window.location.hostname;
return domains.some((domain) => {
// Handle wildcard domains like *.example.com
if (domain.startsWith("*.")) {
const baseDomain = domain.substring(2);
return (
currentHost === baseDomain || currentHost.endsWith("." + baseDomain)
);
}
// Handle exact domain matches
return currentHost === domain;
});
}
// Check if current site is WordPress
function isWordPressSite() {
const indicators = [
document.querySelector('meta[name="generator"][content*="WordPress"]'),
document.querySelector('link[href*="wp-content"]'),
document.querySelector('script[src*="wp-content"]'),
window.location.pathname.includes("/wp-"),
window.location.pathname.includes("/wp-admin"),
window.location.pathname.includes("/wp-json"),
document.body && document.body.classList.toString().includes("wp-"),
document.documentElement &&
document.documentElement.classList.toString().includes("wp-"),
document.querySelector("#wpadminbar"),
document.querySelector(".wp-block"),
document.querySelector("[data-wp-theme]"),
typeof window.wp !== "undefined",
typeof window.wpApiSettings !== "undefined",
];
return indicators.some((indicator) => !!indicator);
}
// Get log file URL
function getLogFileUrl() {
return new URL(logFilePath, window.location.origin).toString();
}
// Fetch log content
async function fetchLogContent() {
try {
const url = getLogFileUrl();
const response = await fetch(url, {
method: "GET",
headers: {
"Cache-Control": "no-cache",
},
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const text = await response.text();
return text;
} catch (error) {
console.error("Log Viewer: Error fetching log content:", error);
return `Error fetching log file: ${error.message}`;
}
}
// Parse and format log lines
function parseLogLines(logContent) {
const lines = logContent.split("\n").filter((line) => line.trim());
const parsedLines = [];
lines.forEach((line, index) => {
const logLine = {
index: index + 1,
raw: line,
timestamp: null,
level: "info",
message: line,
isError: false,
isWarning: false,
};
// Extract timestamp if present
const timestampMatch = line.match(
/^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]/
);
if (timestampMatch) {
logLine.timestamp = timestampMatch[1];
logLine.message = line.replace(
/^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]\s*/,
""
);
}
// Detect log levels and errors
const lowerMessage = logLine.message.toLowerCase();
if (
lowerMessage.includes("fatal error") ||
lowerMessage.includes("fatal:") ||
lowerMessage.includes("error:")
) {
logLine.level = "error";
logLine.isError = true;
} else if (
lowerMessage.includes("warning:") ||
lowerMessage.includes("warn:")
) {
logLine.level = "warning";
logLine.isWarning = true;
} else if (
lowerMessage.includes("notice:") ||
lowerMessage.includes("notice")
) {
logLine.level = "notice";
} else if (
lowerMessage.includes("debug:") ||
lowerMessage.includes("debug")
) {
logLine.level = "debug";
}
parsedLines.push(logLine);
});
return parsedLines;
}
// Create log viewer panel
function createLogViewerPanel() {
// Remove existing panel if it exists
const existingPanel = document.getElementById("devstack-log-viewer-panel");
if (existingPanel) {
existingPanel.remove();
}
const panel = document.createElement("div");
panel.id = "devstack-log-viewer-panel";
// Get panel position styles based on panelPosition setting
const getPanelPositionStyles = (position) => {
const baseStyles = `
position: fixed;
background: #1a1a1a;
color: #fff;
padding: 15px;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, monospace;
font-size: 12px;
z-index: 999999;
width: 600px;
max-width: 90vw;
height: 500px;
max-height: 80vh;
border: 1px solid #333;
display: flex;
flex-direction: column;
`;
switch (position) {
case "top-left":
return baseStyles + "top: 20px; left: 20px;";
case "top-right":
return baseStyles + "top: 20px; right: 20px;";
case "bottom-left":
return baseStyles + "bottom: 20px; left: 20px;";
case "bottom-right":
return baseStyles + "bottom: 20px; right: 20px;";
default:
return baseStyles + "top: 20px; right: 20px;";
}
};
panel.style.cssText = getPanelPositionStyles(panelPosition);
// Header
const header = document.createElement("div");
header.style.cssText = `
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid #333;
flex-shrink: 0;
`;
const title = document.createElement("h3");
title.textContent = "📋 Log Viewer";
title.style.cssText = "margin: 0; font-size: 14px; font-weight: 600;";
const controls = document.createElement("div");
controls.style.cssText = "display: flex; gap: 8px; align-items: center;";
// Refresh button
const refreshBtn = document.createElement("button");
refreshBtn.textContent = "🔄";
refreshBtn.title = "Refresh Log";
refreshBtn.style.cssText = `
background: #007bff;
border: none;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
cursor: pointer;
`;
refreshBtn.onclick = () => loadAndDisplayLogs();
// Auto-refresh toggle
const autoRefreshBtn = document.createElement("button");
autoRefreshBtn.textContent = autoRefresh ? "⏸️" : "▶️";
autoRefreshBtn.title = autoRefresh
? "Pause Auto-refresh"
: "Start Auto-refresh";
autoRefreshBtn.style.cssText = `
background: ${autoRefresh ? "#28a745" : "#6c757d"};
border: none;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
cursor: pointer;
`;
autoRefreshBtn.onclick = () => toggleAutoRefresh();
// Clear button
const clearBtn = document.createElement("button");
clearBtn.textContent = "🗑️";
clearBtn.title = "Clear Log Display";
clearBtn.style.cssText = `
background: #dc3545;
border: none;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
cursor: pointer;
`;
clearBtn.onclick = () => clearLogDisplay();
const closeBtn = document.createElement("button");
closeBtn.textContent = "×";
closeBtn.style.cssText = `
background: none;
border: none;
color: #fff;
font-size: 18px;
cursor: pointer;
padding: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
`;
closeBtn.onclick = () => panel.remove();
controls.appendChild(refreshBtn);
controls.appendChild(autoRefreshBtn);
controls.appendChild(clearBtn);
controls.appendChild(closeBtn);
header.appendChild(title);
header.appendChild(controls);
// Log content area
const logContent = document.createElement("div");
logContent.id = "log-content";
logContent.style.cssText = `
flex: 1;
overflow-y: auto;
background: #0d1117;
border: 1px solid #333;
border-radius: 4px;
padding: 8px;
font-family: 'Courier New', monospace;
font-size: 11px;
line-height: 1.4;
`;
// Status bar
const statusBar = document.createElement("div");
statusBar.id = "log-status";
statusBar.className = "log-status info";
statusBar.style.cssText = `
margin-top: 8px;
padding: 4px 8px;
background: #2a2a2a;
border-radius: 4px;
font-size: 10px;
flex-shrink: 0;
`;
statusBar.textContent = "Loading log content...";
// Assemble panel
panel.appendChild(header);
panel.appendChild(logContent);
panel.appendChild(statusBar);
document.body.appendChild(panel);
// Load initial log content
loadAndDisplayLogs();
// Click outside to close functionality
const handleClickOutside = (event) => {
if (
panel &&
panel.parentNode &&
!panel.contains(event.target) &&
!document
.getElementById("devstack-log-viewer-trigger")
.contains(event.target)
) {
panel.remove();
document.removeEventListener("click", handleClickOutside);
}
};
// Add click outside listener after a small delay to prevent immediate closing
setTimeout(() => {
document.addEventListener("click", handleClickOutside);
}, 100);
}
// Load and display logs
async function loadAndDisplayLogs() {
const logContent = document.getElementById("log-content");
const statusBar = document.getElementById("log-status");
if (!logContent || !statusBar) return;
statusBar.textContent = "Loading log content...";
statusBar.className = "log-status info";
try {
const content = await fetchLogContent();
const logLines = parseLogLines(content);
// Limit lines based on maxLogLines setting
const displayLines = logLines.slice(-maxLogLines);
// Clear previous content
logContent.innerHTML = "";
if (displayLines.length === 0) {
logContent.innerHTML =
'<div style="color: #666; font-style: italic;">No log entries found</div>';
statusBar.textContent = "No log entries found";
return;
}
// Display log lines
displayLines.forEach((line) => {
const lineDiv = document.createElement("div");
lineDiv.className = "log-line";
// Add appropriate CSS class based on log level
if (highlightErrors) {
if (line.isError) {
lineDiv.classList.add("error");
} else if (line.isWarning) {
lineDiv.classList.add("warning");
} else if (line.level === "notice") {
lineDiv.classList.add("notice");
} else if (line.level === "debug") {
lineDiv.classList.add("debug");
} else {
lineDiv.classList.add("info");
}
} else {
lineDiv.classList.add("info");
}
let displayText = line.message;
if (showTimestamps && line.timestamp) {
displayText = `[${line.timestamp}] ${displayText}`;
}
lineDiv.textContent = displayText;
logContent.appendChild(lineDiv);
});
// Scroll to bottom
logContent.scrollTop = logContent.scrollHeight;
// Update status
const errorCount = displayLines.filter((l) => l.isError).length;
const warningCount = displayLines.filter((l) => l.isWarning).length;
statusBar.textContent = `Showing ${displayLines.length} lines (${errorCount} errors, ${warningCount} warnings)`;
// Update status bar class
statusBar.className = "log-status";
if (errorCount > 0) {
statusBar.classList.add("error");
} else if (warningCount > 0) {
statusBar.classList.add("warning");
} else {
statusBar.classList.add("success");
}
} catch (error) {
logContent.innerHTML = `<div style="color: #ff6b6b;">Error loading log: ${error.message}</div>`;
statusBar.textContent = `Error: ${error.message}`;
statusBar.className = "log-status error";
}
}
// Clear log display
function clearLogDisplay() {
const logContent = document.getElementById("log-content");
const statusBar = document.getElementById("log-status");
if (logContent) {
logContent.innerHTML =
'<div style="color: #666; font-style: italic;">Log display cleared</div>';
}
if (statusBar) {
statusBar.textContent = "Log display cleared";
statusBar.className = "log-status info";
}
}
// Auto-refresh functionality
let autoRefreshInterval = null;
function startAutoRefresh() {
if (autoRefreshInterval) {
clearInterval(autoRefreshInterval);
}
autoRefreshInterval = setInterval(() => {
loadAndDisplayLogs();
}, refreshIntervalValue * 1000);
}
function stopAutoRefresh() {
if (autoRefreshInterval) {
clearInterval(autoRefreshInterval);
autoRefreshInterval = null;
}
}
function toggleAutoRefresh() {
const autoRefreshBtn = document.querySelector(
"#devstack-log-viewer-panel button[title*='Auto-refresh']"
);
if (!autoRefreshBtn) return;
if (autoRefreshInterval) {
stopAutoRefresh();
autoRefreshBtn.textContent = "▶️";
autoRefreshBtn.title = "Start Auto-refresh";
autoRefreshBtn.style.background = "#6c757d";
} else {
startAutoRefresh();
autoRefreshBtn.textContent = "⏸️";
autoRefreshBtn.title = "Pause Auto-refresh";
autoRefreshBtn.style.background = "#28a745";
}
}
// Create floating trigger button
function createTriggerButton() {
// Remove existing button if it exists
const existingButton = document.getElementById(
"devstack-log-viewer-trigger"
);
if (existingButton) {
existingButton.remove();
}
// Get position styles based on panelPosition setting
const getPositionStyles = (position) => {
const baseStyles = `
position: fixed;
width: 50px;
height: 50px;
border-radius: 50%;
background: #6f42c1;
color: white;
border: none;
font-size: 20px;
cursor: pointer;
z-index: 999998;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
transition: all 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
`;
switch (position) {
case "top-left":
return baseStyles + "top: 20px; left: 20px;";
case "top-right":
return baseStyles + "top: 20px; right: 20px;";
case "bottom-left":
return baseStyles + "bottom: 20px; left: 20px;";
case "bottom-right":
return baseStyles + "bottom: 20px; right: 20px;";
default:
return baseStyles + "top: 20px; right: 20px;";
}
};
const triggerButton = document.createElement("button");
triggerButton.id = "devstack-log-viewer-trigger";
triggerButton.innerHTML = "📋";
triggerButton.title = "DevStack Log Viewer (Ctrl+Shift+L)";
triggerButton.style.cssText = getPositionStyles(panelPosition);
triggerButton.addEventListener("mouseenter", () => {
triggerButton.style.transform = "scale(1.1)";
triggerButton.style.background = "#5a32a3";
});
triggerButton.addEventListener("mouseleave", () => {
triggerButton.style.transform = "scale(1)";
triggerButton.style.background = "#6f42c1";
});
triggerButton.onclick = () => {
const existingPanel = document.getElementById(
"devstack-log-viewer-panel"
);
if (existingPanel) {
existingPanel.remove();
stopAutoRefresh();
} else {
createLogViewerPanel();
if (autoRefresh) {
startAutoRefresh();
}
}
};
document.body.appendChild(triggerButton);
}
// Keyboard shortcut handler
function handleKeyboardShortcut(e) {
// Ctrl+Shift+L to toggle log viewer panel
if (e.ctrlKey && e.shiftKey && e.key.toLowerCase() === "l") {
e.preventDefault();
e.stopPropagation();
const existingPanel = document.getElementById(
"devstack-log-viewer-panel"
);
if (existingPanel) {
existingPanel.remove();
stopAutoRefresh();
} else {
createLogViewerPanel();
if (autoRefresh) {
startAutoRefresh();
}
}
}
}
// Initialize
function init() {
console.log("📋 DevStack Log Viewer initialized");
// Check domain filtering first
if (!isDomainAllowed()) {
console.log("📋 Domain not in allowed list, log viewer disabled");
return;
}
// Only show on WordPress sites
if (!isWordPressSite()) {
console.log("📋 Not a WordPress site, log viewer disabled");
return;
}
// Create floating trigger button
createTriggerButton();
// Add keyboard shortcut
document.addEventListener("keydown", handleKeyboardShortcut);
// Listen for storage changes
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === "sync" && changes.logViewer) {
const newSettings = changes.logViewer.newValue;
if (newSettings) {
// Update settings without reloading
if (newSettings.enabled) {
// Recreate trigger button
createTriggerButton();
} else {
// Remove trigger button and panel if disabled
const existingButton = document.getElementById(
"devstack-log-viewer-trigger"
);
const existingPanel = document.getElementById(
"devstack-log-viewer-panel"
);
if (existingButton) existingButton.remove();
if (existingPanel) existingPanel.remove();
stopAutoRefresh();
}
}
}
});
}
// Only run on page load, not on every navigation
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})().catch((error) => {
console.error("Log Viewer: Error in main function:", error);
});