-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
417 lines (344 loc) Β· 15 KB
/
script.js
File metadata and controls
417 lines (344 loc) Β· 15 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
document.addEventListener('DOMContentLoaded', () => {
const navContainer = document.getElementById('nav-container');
const markdownBody = document.getElementById('markdown-body');
const activePathSpan = document.getElementById('active-path');
const toggleSidebarBtn = document.getElementById('toggle-sidebar-btn');
const sidebar = document.getElementById('sidebar');
const resizer = document.getElementById('resizer');
// Register NASM as x86asm for highlight.js to support specific code blocks
if (typeof hljs !== 'undefined') {
hljs.registerAliases('nasm', { languageName: 'x86asm' });
}
// --- Setup Client-Side Marked Renderer ---
const renderer = new marked.Renderer();
// Custom image renderer to resolve relative paths from the github repository/content directory
renderer.image = function(hrefOrObj, titleInfo, textInfo) {
let href = typeof hrefOrObj === 'object' ? hrefOrObj.href : hrefOrObj;
let title = typeof hrefOrObj === 'object' ? hrefOrObj.title : titleInfo;
let text = typeof hrefOrObj === 'object' ? hrefOrObj.text : textInfo;
let finalHref = href;
if (finalHref && !finalHref.startsWith('http') && !finalHref.startsWith('/') && !finalHref.startsWith('data:')) {
// Resolve path relative to the current markdown file path
const hash = window.location.hash;
if (hash.startsWith('#/')) {
const activePath = decodeURIComponent(hash.substring(2));
const folderPath = activePath.includes('/')
? activePath.substring(0, activePath.lastIndexOf('/'))
: '';
finalHref = 'content/' + (folderPath ? folderPath + '/' : '') + finalHref;
}
}
let out = `<img src="${finalHref}" alt="${text || ''}"`;
if (title) {
out += ` title="${title}"`;
}
out += '>';
return out;
};
// Custom code highlighting with highlight.js inside marked
renderer.code = function(codeOrObj, langInfo) {
let code = typeof codeOrObj === 'object' ? codeOrObj.text : codeOrObj;
let lang = typeof codeOrObj === 'object' ? codeOrObj.lang : langInfo;
lang = lang || 'plaintext';
const language = hljs.getLanguage(lang) ? lang : 'plaintext';
const highlighted = hljs.highlight(code, { language }).value;
return `<pre><code class="hljs language-${language}">${highlighted}</code></pre>`;
};
// Configure marked options
marked.setOptions({
renderer: renderer,
gfm: true,
breaks: true
});
// --- Sidebar Resizing Logic ---
let isDragging = false;
resizer.addEventListener('mousedown', (e) => {
isDragging = true;
resizer.classList.add('dragging');
sidebar.classList.add('no-transition'); // Disable snapping lag temporarily
document.body.style.cursor = 'col-resize';
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
if (sidebar.classList.contains('collapsed')) return;
let newWidth = e.clientX;
if (newWidth < 150) newWidth = 150;
if (newWidth > 800) newWidth = 800;
sidebar.style.width = `${newWidth}px`;
});
document.addEventListener('mouseup', () => {
if (isDragging) {
isDragging = false;
resizer.classList.remove('dragging');
sidebar.classList.remove('no-transition');
document.body.style.cursor = 'default';
}
});
// --- Sidebar Toggle Logic ---
toggleSidebarBtn.addEventListener('click', () => {
if (window.innerWidth <= 768) {
sidebar.classList.toggle('mobile-open');
} else {
sidebar.classList.toggle('collapsed');
if (sidebar.classList.contains('collapsed')) {
resizer.style.display = 'none';
} else {
resizer.style.display = 'block';
}
}
});
// --- Hash Routing Logic ---
function handleRoute() {
const hash = window.location.hash;
if (hash.startsWith('#/')) {
const path = decodeURIComponent(hash.substring(2));
if (path) {
loadContent(path);
return;
}
}
showWelcomeScreen();
}
window.addEventListener('hashchange', handleRoute);
function showWelcomeScreen() {
document.querySelectorAll('.nav-title.active').forEach(el => el.classList.remove('active'));
activePathSpan.textContent = '/';
document.title = 'CTF-Writeups Web';
markdownBody.innerHTML = `
<div class="welcome-screen">
<h1>Welcome to CTF-Writeups</h1>
<p>A personal collection of unofficial writeups. Select a file from the sidebar to start reading.</p>
</div>
`;
}
// --- Reconstruct Directory Tree Dynamically from GitHub API paths ---
function buildTreeFromPaths(flatPaths) {
const root = [];
flatPaths.forEach(filePath => {
// Look for files in content/ directory that end with .md
if (!filePath.startsWith('content/') || !filePath.endsWith('.md')) return;
// Strip "content/" prefix to get relative path
const relativePath = filePath.substring('content/'.length);
const parts = relativePath.split('/');
let currentLevel = root;
let accumulatedPath = '';
parts.forEach((part, index) => {
accumulatedPath = accumulatedPath ? `${accumulatedPath}/${part}` : part;
const isFile = index === parts.length - 1;
let existing = currentLevel.find(item => item.name === part);
if (!existing) {
existing = {
name: part,
path: accumulatedPath,
type: isFile ? 'file' : 'directory'
};
if (!isFile) {
existing.children = [];
}
currentLevel.push(existing);
}
if (!isFile) {
currentLevel = existing.children;
}
});
});
// Sort directories before files, and alphabetically
function sortTree(nodes) {
nodes.sort((a, b) => {
if (a.type === b.type) return a.name.localeCompare(b.name);
return a.type === 'directory' ? -1 : 1;
});
nodes.forEach(node => {
if (node.children) sortTree(node.children);
});
}
sortTree(root);
return root;
}
// Fetch Tree Dynamically
async function fetchTree() {
try {
let tree = [];
const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
if (isLocal) {
// Fetch dynamically from local Express backend
const res = await fetch('/api/tree');
tree = await res.json();
} else {
// Fetch dynamically in real-time from GitHub REST API with caching
const cacheKey = 'github_ctf_tree';
const cachedData = sessionStorage.getItem(cacheKey);
if (cachedData) {
tree = JSON.parse(cachedData);
} else {
const repoOwner = 'ghostware0x00';
const repoName = 'CTF-Writeups';
const res = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/git/trees/main?recursive=1`);
if (!res.ok) {
throw new Error(`GitHub API error! status: ${res.status}`);
}
const data = await res.json();
// Reconstruct the tree from flat paths dynamically in the browser
tree = buildTreeFromPaths(data.tree.map(item => item.path));
// Cache in sessionStorage to prevent hitting API rate limits during quick reloads
sessionStorage.setItem(cacheKey, JSON.stringify(tree));
}
}
navContainer.innerHTML = '';
const ul = buildTreeUI(tree);
navContainer.appendChild(ul);
// Handle initial dynamic routing
handleRoute();
} catch (e) {
console.error('Failed to load tree:', e);
navContainer.innerHTML = '<div style="color:var(--red);">Error loading files</div>';
}
}
function buildTreeUI(nodes) {
const ul = document.createElement('ul');
ul.className = 'nav-tree';
nodes.forEach(node => {
const li = document.createElement('li');
li.className = 'nav-item';
const titleDiv = document.createElement('div');
titleDiv.className = 'nav-title';
titleDiv.dataset.path = node.path;
const icon = document.createElement('span');
icon.className = 'icon';
const text = document.createElement('span');
text.textContent = node.name.replace('.md', '');
if (node.type === 'directory') {
icon.textContent = 'π';
titleDiv.appendChild(icon);
titleDiv.appendChild(text);
li.appendChild(titleDiv);
const childrenUl = buildTreeUI(node.children);
childrenUl.style.display = 'none'; // Collapse by default
li.appendChild(childrenUl);
titleDiv.addEventListener('click', (e) => {
e.stopPropagation();
const isCollapsed = childrenUl.style.display === 'none';
childrenUl.style.display = isCollapsed ? 'block' : 'none';
icon.textContent = isCollapsed ? 'π' : 'π';
});
} else {
icon.textContent = 'π';
titleDiv.appendChild(icon);
titleDiv.appendChild(text);
li.appendChild(titleDiv);
titleDiv.addEventListener('click', (e) => {
e.stopPropagation();
window.location.hash = '#/' + encodeURIComponent(node.path);
if (window.innerWidth <= 768) sidebar.classList.remove('mobile-open');
});
}
ul.appendChild(li);
});
return ul;
}
async function loadContent(path) {
activePathSpan.textContent = '/' + path;
// Set document title dynamically
const fileName = path.includes('/') ? path.substring(path.lastIndexOf('/') + 1) : path;
const cleanName = fileName.replace('.md', '');
document.title = `${cleanName} | CTF-Writeups Web`;
markdownBody.innerHTML = '<div style="text-align:center;color:var(--text-muted);margin-top:50px;">Loading... β‘</div>';
try {
// Fetch the markdown file dynamically
const res = await fetch('content/' + encodeURI(path));
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
let content = await res.text();
// Obsidian image parsing ![[image.png]]
content = content.replace(/!\[\[(.*?)\]\]/g, '');
const htmlContent = marked.parse(content);
markdownBody.innerHTML = `<div class="fade-in">${htmlContent}</div>`;
// Decorate code blocks
decorateCodeBlocks();
// Highlight and expand sidebar parents dynamically
expandSidebarToPath(path);
} catch (e) {
console.error(e);
markdownBody.innerHTML = `<div style="color:var(--red);text-align:center;"><h2>Connection Error</h2><p>Could not fetch file: "${path}".</p></div>`;
}
}
function expandSidebarToPath(path) {
document.querySelectorAll('.nav-title.active').forEach(el => el.classList.remove('active'));
const targetEl = document.querySelector(`.nav-title[data-path="${CSS.escape(path)}"]`);
if (!targetEl) return;
targetEl.classList.add('active');
// Traverse up and expand parent folders
let parent = targetEl.parentElement; // the <li>
while (parent && parent.id !== 'nav-container') {
if (parent.tagName === 'LI') {
const childUl = parent.querySelector('ul');
if (childUl) {
childUl.style.display = 'block';
const folderTitle = parent.querySelector('.nav-title');
if (folderTitle) {
const icon = folderTitle.querySelector('.icon');
if (icon) icon.textContent = 'π';
}
}
} else if (parent.tagName === 'UL') {
parent.style.display = 'block';
const folderLi = parent.parentElement;
if (folderLi && folderLi.tagName === 'LI') {
const folderTitle = folderLi.querySelector('.nav-title');
if (folderTitle) {
const icon = folderTitle.querySelector('.icon');
if (icon) icon.textContent = 'π';
}
}
}
parent = parent.parentElement;
}
targetEl.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
function decorateCodeBlocks() {
document.querySelectorAll('.markdown-body pre').forEach(pre => {
if (pre.parentElement.classList.contains('code-content')) return;
const codeEl = pre.querySelector('code');
let lang = 'bash';
if (codeEl && codeEl.className) {
const match = codeEl.className.match(/language-(\w+)/);
if (match) lang = match[1];
}
const wrapper = document.createElement('div');
wrapper.className = 'custom-code-block';
const header = document.createElement('div');
header.className = 'code-header';
const leftGroup = document.createElement('div');
leftGroup.className = 'left-group';
const windowControls = document.createElement('div');
windowControls.className = 'window-controls';
windowControls.innerHTML = '<div class="ctrl red"></div><div class="ctrl yellow"></div><div class="ctrl green"></div>';
const langLabel = document.createElement('div');
langLabel.className = 'lang-label';
langLabel.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 17 10 11 4 5"></polyline><line x1="12" y1="19" x2="20" y2="19"></line></svg>` + lang;
leftGroup.appendChild(windowControls);
leftGroup.appendChild(langLabel);
const copyBtn = document.createElement('button');
copyBtn.className = 'copy-btn';
copyBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg> <span>COPY</span>`;
copyBtn.onclick = () => {
const textToCopy = codeEl ? codeEl.innerText : pre.innerText;
navigator.clipboard.writeText(textToCopy);
copyBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg> <span class="copied" style="color:var(--green)">COPIED</span>`;
setTimeout(() => {
copyBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg> <span>COPY</span>`;
}, 2000);
};
header.appendChild(leftGroup);
header.appendChild(copyBtn);
wrapper.appendChild(header);
pre.parentNode.insertBefore(wrapper, pre);
const codeContent = document.createElement('div');
codeContent.className = 'code-content';
codeContent.appendChild(pre);
wrapper.appendChild(codeContent);
});
}
fetchTree();
});