-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
478 lines (426 loc) · 13.9 KB
/
index.js
File metadata and controls
478 lines (426 loc) · 13.9 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
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const { marked } = require('marked');
const { gfmHeadingId } = require('marked-gfm-heading-id');
const { markedHighlight } = require('marked-highlight');
const hljs = require('highlight.js');
const open = require('open').default || require('open');
const chokidar = require('chokidar');
marked.use(gfmHeadingId());
marked.use(markedHighlight({
langPrefix: 'hljs language-',
highlight(code, lang) {
const language = hljs.getLanguage(lang) ? lang : 'plaintext';
return hljs.highlight(code, { language }).value;
}
}));
marked.setOptions({
gfm: true,
breaks: true,
tables: true
});
function extractH1Title(markdown) {
const lines = markdown.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('# ')) {
return trimmed.substring(2).trim();
}
if (trimmed && !trimmed.startsWith('#')) {
break;
}
}
return null;
}
async function viewMarkdown(filePaths, options = {}) {
const app = express();
const port = options.port || 0;
const clients = new Set(); // Track SSE clients
let shutdownTimer = null; // Timer for auto-shutdown
try {
// Handle both single file (legacy) and multiple files
const paths = Array.isArray(filePaths) ? filePaths : [filePaths];
// Function to read and process all files
const readAllFiles = async () => {
const fileContents = [];
for (const filePath of paths) {
const absolutePath = path.resolve(filePath);
const markdown = await fs.readFile(absolutePath, 'utf-8');
const html = marked(markdown);
const filename = path.basename(filePath);
const h1Title = extractH1Title(markdown);
const displayTitle = h1Title || filename;
const hasH1 = h1Title !== null;
fileContents.push({ filename, displayTitle, html, filePath, hasH1 });
}
return fileContents;
};
// Initial read
let fileContents = await readAllFiles();
const title = paths.length === 1 ? fileContents[0].displayTitle : `${paths.length} Markdown Files`;
app.get('/', async (req, res) => {
// Always re-read files to get fresh content (no caching)
try {
fileContents = await readAllFiles();
} catch (err) {
console.error('Error re-reading files:', err.message);
}
// Generate table of contents for multiple files
let tableOfContents = '';
if (fileContents.length > 1) {
tableOfContents = `
<div class="table-of-contents">
<h2>Table of Contents</h2>
<ul>
${fileContents.map((file, index) =>
`<li><a href="#file-${index}">${file.displayTitle}</a></li>`
).join('')}
</ul>
</div>
<div class="page-break"></div>
`;
}
// Generate combined content with page breaks
const combinedContent = fileContents.map((file, index) => `
<div id="file-${index}" class="file-section">
${index > 0 ? '<div class="page-break"></div>' : ''}
${!file.hasH1 ? `<div class="file-header">
<h1 class="file-title">${file.displayTitle}</h1>
</div>` : ''}
<div class="file-content">
${file.html}
</div>
</div>
`).join('');
// Auto-reload/connection script
const autoReloadScript = `
// Auto-reload functionality
(function() {
let reconnectDelay = 1000;
let reconnectAttempts = 0;
const maxReconnectDelay = 30000;
function connectEventSource() {
const eventSource = new EventSource('/events');
eventSource.onopen = function() {
console.log('Auto-reload connected');
reconnectDelay = 1000;
reconnectAttempts = 0;
};
eventSource.onmessage = function(event) {
try {
const data = JSON.parse(event.data);
if (data.type === 'reload' && ${options.watch ? 'true' : 'false'}) {
console.log('File change detected, reloading...');
isAutoReloading = true;
// Set flag to show notification after reload
sessionStorage.setItem('viewmd-reloaded', 'true');
location.reload();
}
} catch (err) {
console.error('Error parsing SSE message:', err);
}
};
eventSource.onerror = function(err) {
console.error('Auto-reload connection lost, retrying...');
eventSource.close();
// Exponential backoff for reconnection
reconnectAttempts++;
reconnectDelay = Math.min(reconnectDelay * 1.5, maxReconnectDelay);
setTimeout(connectEventSource, reconnectDelay);
};
}
// Start the connection
connectEventSource();
// Show a flash notification when page reloads (only in watch mode)
if (${options.watch ? 'true' : 'false'}) {
// Check if this is a reload (not initial load)
if (performance.navigation.type === 1 || sessionStorage.getItem('viewmd-reloaded')) {
const notification = document.createElement('div');
notification.style.position = 'fixed';
notification.style.bottom = '10px';
notification.style.right = '10px';
notification.style.padding = '8px 12px';
notification.style.background = '#28a745';
notification.style.color = 'white';
notification.style.borderRadius = '4px';
notification.style.fontSize = '13px';
notification.style.opacity = '0';
notification.style.transition = 'opacity 0.3s ease-in-out';
notification.style.zIndex = '9999';
notification.textContent = '⟳ Reloaded';
document.body.appendChild(notification);
// Fade in
setTimeout(() => notification.style.opacity = '0.9', 10);
// Fade out and remove after 1.5 seconds
setTimeout(() => {
notification.style.opacity = '0';
setTimeout(() => notification.remove(), 300);
}, 1500);
// Clear the flag
sessionStorage.removeItem('viewmd-reloaded');
}
}
})();
`;
res.send(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.5.1/github-markdown-light.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.10.0/styles/github.min.css">
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
mermaid.initialize({
startOnLoad: true,
theme: 'default',
securityLevel: 'loose'
});
</script>
<style>
body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
background-color: #ffffff;
}
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 100%;
}
@media (max-width: 767px) {
body { padding: 15px; }
}
pre.mermaid {
text-align: center;
background: transparent;
border: none;
}
/* Table of Contents Styles */
.table-of-contents {
background-color: #f6f8fa;
border: 1px solid #d0d7de;
border-radius: 6px;
padding: 16px;
margin-bottom: 24px;
}
.table-of-contents h2 {
margin-top: 0;
color: #24292f;
}
.table-of-contents ul {
margin-bottom: 0;
}
.table-of-contents a {
text-decoration: none;
color: #0969da;
}
.table-of-contents a:hover {
text-decoration: underline;
}
/* File Section Styles */
.file-section {
margin-bottom: 2rem;
}
.file-header {
border-bottom: 2px solid #d0d7de;
margin-bottom: 2rem;
padding-bottom: 1rem;
}
.file-title {
color: #24292f;
font-size: 2em;
font-weight: 600;
margin: 0;
}
/* Page Break Styles */
.page-break {
display: none;
}
/* Print Styles */
@media print {
body {
padding: 0;
margin: 0;
max-width: none;
}
.page-break {
display: block;
page-break-before: always;
height: 0;
border: none;
margin: 0;
padding: 0;
}
.table-of-contents {
page-break-after: always;
}
.file-header {
page-break-after: avoid;
}
/* Hide TOC links in print */
@media print {
.table-of-contents {
display: block;
}
}
}
/* Screen-only file separators */
@media screen {
.file-section:not(:last-child) {
border-bottom: 3px solid #d0d7de;
padding-bottom: 2rem;
margin-bottom: 3rem;
}
}
</style>
</head>
<body>
<article class="markdown-body">
${tableOfContents}
${combinedContent}
</article>
<script>
document.querySelectorAll('pre > code.language-mermaid').forEach((element) => {
const pre = element.parentElement;
pre.classList.add('mermaid');
pre.innerHTML = element.textContent;
});
// Track if we're reloading due to file change
let isAutoReloading = false;
${autoReloadScript}
</script>
</body>
</html>
`);
});
// Server-Sent Events endpoint for auto-reload
app.get('/events', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
// Send initial connection message
res.write(`data: {"type":"connected"}\n\n`);
// Clear shutdown timer when client connects
if (shutdownTimer) {
clearTimeout(shutdownTimer);
shutdownTimer = null;
console.log('Client reconnected, cancelling shutdown');
}
// Add client to tracking set
clients.add(res);
console.log(`Client connected. Total clients: ${clients.size}`);
// Remove client on disconnect
req.on('close', () => {
clients.delete(res);
console.log(`Client disconnected. Remaining clients: ${clients.size}`);
// If no clients left and not in keep-alive mode, start shutdown timer
if (clients.size === 0 && !options.keepAlive) {
console.log('All clients disconnected, shutting down in 1 second...');
shutdownTimer = setTimeout(() => {
console.log('Auto-shutdown: No clients connected');
if (watcher) watcher.close();
server.close();
process.exit(0);
}, 1000);
}
});
});
app.post('/shutdown', (req, res) => {
res.send('Shutting down');
setTimeout(() => {
if (watcher) watcher.close();
server.close();
process.exit(0);
}, 100);
});
// Set up file watcher if watch option is enabled
let watcher = null;
if (options.watch) {
const absolutePaths = paths.map(p => path.resolve(p));
watcher = chokidar.watch(absolutePaths, {
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 200,
pollInterval: 100
}
});
let reloadTimeout = null;
const triggerReload = (filepath) => {
// Clear any pending reload
if (reloadTimeout) {
clearTimeout(reloadTimeout);
}
// Debounce: wait 300ms before triggering reload
reloadTimeout = setTimeout(() => {
console.log(`File change detected: ${filepath}`);
console.log(`Connected clients: ${clients.size}`);
// Notify all connected clients
const message = `data: {"type":"reload","timestamp":${Date.now()}}\n\n`;
clients.forEach(client => {
try {
client.write(message);
console.log('Sent reload event to client');
} catch (err) {
console.error('Failed to send to client:', err.message);
// Client might be disconnected
clients.delete(client);
}
});
}, 300);
};
watcher.on('change', (filepath) => {
console.log(`File changed: ${filepath}`);
triggerReload(filepath);
});
watcher.on('add', (filepath) => {
console.log(`File added: ${filepath}`);
triggerReload(filepath);
});
watcher.on('unlink', (filepath) => {
console.log(`File removed: ${filepath}`);
triggerReload(filepath);
});
}
const server = app.listen(port, async () => {
const actualPort = server.address().port;
const url = `http://localhost:${actualPort}`;
if (fileContents.length === 1) {
console.log(`Viewing ${fileContents[0].displayTitle} at ${url}`);
} else {
console.log(`Viewing ${fileContents.length} markdown files at ${url}`);
fileContents.forEach((file, index) => {
console.log(` ${index + 1}. ${file.displayTitle}`);
});
}
if (options.watch) {
console.log('Auto-reload enabled - watching for file changes');
}
if (!options.noOpen) {
await open(url);
}
if (!options.keepAlive) {
console.log('Press Ctrl+C to stop the server');
}
});
process.on('SIGINT', () => {
console.log('\nShutting down server...');
if (watcher) watcher.close();
server.close();
process.exit(0);
});
} catch (error) {
console.error('Error:', error.message);
process.exit(1);
}
}
module.exports = { viewMarkdown };