feat: change css + watcher

Signed-off-by: Cédric OLIVIER <olivier.cedric@gmail.com>
This commit is contained in:
Cédric OLIVIER
2026-06-19 12:08:45 +02:00
parent 1265beefb8
commit 85f62bf842
5 changed files with 437 additions and 207 deletions
+26 -7
View File
@@ -18,7 +18,13 @@ md-render README.md
# Conversion vers un fichier spécifique # Conversion vers un fichier spécifique
md-render README.md -o documentation.html md-render README.md -o documentation.html
# Mode watch — ouvre http://localhost:3000 dans votre navigateur # Mode preview — ouvre dans le navigateur sans créer de fichier
md-render README.md --preview
# Mode preview sur un port personnalisé
md-render README.md --preview --port 8080
# Mode watch — ouvre http://localhost:3000 avec rechargement automatique
md-render README.md --watch md-render README.md --watch
# Mode watch sur un port personnalisé # Mode watch sur un port personnalisé
@@ -27,12 +33,24 @@ md-render README.md --watch --port 8080
## Options ## Options
| Option | Alias | Description | Défaut | | Option | Alias | Description | Défaut |
|---------------------|-------|---------------------------------------------|--------| |---------------------|-------|----------------------------------------------------|----------------|
| `--watch` | `-w` | Lance le serveur avec rechargement auto | — | | `--watch` | `-w` | Lance le serveur avec rechargement auto | — |
| `--port <port>` | `-p` | Port du serveur en mode watch | `3000` | | `--preview` | `-v` | Ouvre dans le navigateur sans créer de fichier | — |
| `--output <fichier>`| `-o` | Fichier HTML de sortie | `<input>.html` | | `--port <port>` | `-p` | Port du serveur en mode watch ou preview | `3000` |
| `--help` | `-h` | Affiche l'aide | | | `--output <fichier>`| `-o` | Fichier HTML de sortie | `<input>.html` |
| `--help` | `-h` | Affiche l'aide | — |
## Mode preview
En mode `--preview`, le Markdown est converti en mémoire et affiché directement dans votre
navigateur — **aucun fichier HTML n'est créé sur le disque**. Le navigateur s'ouvre automatiquement.
Appuyez sur `Ctrl+C` pour arrêter le serveur.
```bash
md-render README.md --preview # fichier unique
md-render mon-wiki/ --preview # dossier entier (avec sidebar)
```
## Mode watch ## Mode watch
@@ -46,6 +64,7 @@ Les assets relatifs (images, etc.) placés dans le même répertoire que le `.md
- 🎨 Coloration syntaxique du code (highlight.js) - 🎨 Coloration syntaxique du code (highlight.js)
- 📄 Style GitHub-like - 📄 Style GitHub-like
- 👁 Prévisualisation instantanée sans fichier (`--preview`)
- 🔄 Rechargement automatique en mode watch - 🔄 Rechargement automatique en mode watch
- 🖼 Serveur de fichiers statiques pour les images locales - 🖼 Serveur de fichiers statiques pour les images locales
- ⚡ Debounce intelligent pour éviter les rechargements en rafale - ⚡ Debounce intelligent pour éviter les rechargements en rafale
+35 -8
View File
@@ -9,9 +9,9 @@ const { startServer } = require('./lib/server');
const { startWatcher } = require('./lib/watcher'); const { startWatcher } = require('./lib/watcher');
const argv = minimist(process.argv.slice(2), { const argv = minimist(process.argv.slice(2), {
alias: { o: 'output', p: 'port', w: 'watch', h: 'help' }, alias: { o: 'output', p: 'port', w: 'watch', v: 'preview', h: 'help' },
default: { port: 3000 }, default: { port: 3000 },
boolean: ['watch', 'help'], boolean: ['watch', 'preview', 'open', 'help'],
}); });
if (argv.help) { if (argv.help) {
@@ -20,13 +20,17 @@ Usage: md-render <fichier.md|dossier> [options]
Options: Options:
-w, --watch Surveille les modifications et recharge automatiquement -w, --watch Surveille les modifications et recharge automatiquement
-p, --port <port> Port du serveur en mode watch (défaut: 3000) -v, --preview Comme --watch, mais ouvre aussi le navigateur
--open Ouvre le navigateur (combinable avec --watch)
-p, --port <port> Port du serveur (défaut: 3000)
-o, --output <dir> Dossier de sortie HTML (mode dossier, sans --watch) -o, --output <dir> Dossier de sortie HTML (mode dossier, sans --watch)
-h, --help Affiche cette aide -h, --help Affiche cette aide
Exemples: Exemples:
md-render README.md Convertit README.md → README.html md-render README.md Convertit README.md → README.html
md-render README.md --watch Prévisualisation live sur localhost:3000 md-render README.md --watch Live reload sur localhost:3000
md-render README.md --watch --open Live reload + ouvre le navigateur
md-render README.md --preview Alias de --watch --open
md-render ../my-portal.wiki/ Convertit tous les .md du dossier md-render ../my-portal.wiki/ Convertit tous les .md du dossier
md-render ../my-portal.wiki/ --watch Wiki live sur localhost:3000 md-render ../my-portal.wiki/ --watch Wiki live sur localhost:3000
`); `);
@@ -51,24 +55,47 @@ if (!fs.existsSync(absInput)) {
const stat = fs.statSync(absInput); const stat = fs.statSync(absInput);
const isDir = stat.isDirectory(); const isDir = stat.isDirectory();
// ── WATCH MODE ────────────────────────────────────────────────────────────── // ── SERVER MODE (--watch ou --preview) ──────────────────────────────────────
if (argv.watch) { if (argv.watch || argv.preview) {
const port = parseInt(argv.port, 10); const port = parseInt(argv.port, 10);
if (isNaN(port) || port < 1 || port > 65535) { if (isNaN(port) || port < 1 || port > 65535) {
console.error(`\n✗ Erreur : port invalide "${argv.port}".\n`); console.error(`\n✗ Erreur : port invalide "${argv.port}".\n`);
process.exit(1); process.exit(1);
} }
const server = startServer({ const shouldOpen = argv.preview || argv.open;
function openBrowser(url) {
const { exec } = require('child_process');
const cmd =
process.platform === 'darwin' ? `open "${url}"` :
process.platform === 'win32' ? `start "" "${url}"` :
`xdg-open "${url}"`;
exec(cmd, (err) => {
if (err) console.warn(` ⚠ Impossible d'ouvrir le navigateur : ${err.message}`);
});
}
const serverObj = startServer({
inputFile: isDir ? null : absInput, inputFile: isDir ? null : absInput,
inputDir: isDir ? absInput : null, inputDir: isDir ? absInput : null,
port, port,
onReady: shouldOpen ? (p) => {
console.log(' Appuyez sur Ctrl+C pour arrêter.\n');
openBrowser(`http://localhost:${p}`);
} : null,
}); });
startWatcher({ startWatcher({
inputFile: isDir ? null : absInput, inputFile: isDir ? null : absInput,
inputDir: isDir ? absInput : null, inputDir: isDir ? absInput : null,
server, server: serverObj,
});
process.on('SIGINT', () => {
serverObj.server.close();
console.log('\n👋 Au revoir !');
process.exit(0);
}); });
return; return;
} }
+307 -181
View File
@@ -19,13 +19,13 @@ marked.use(markedHighlight({
const STYLES = ` const STYLES = `
/* ── Reset ── */ /* ── Reset ── */
*, *::before, *::after { box-sizing: border-box; } *, *::before, *::after { box-sizing: border-box; }
::selection { background: #ffc3c3; } ::selection { background: #c7d2fe; }
html, body { height: 100%; margin: 0; } html, body { height: 100%; margin: 0; }
body { body {
font-family: 'Poppins', sans-serif; font-family: 'Poppins', sans-serif;
background: #fff; background: #f1f5f9;
color: #222; color: #1e293b;
text-rendering: optimizeLegibility; line-height: 1.7;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
overflow-x: hidden; overflow-x: hidden;
} }
@@ -33,192 +33,287 @@ const STYLES = `
/* ── Sidebar ── */ /* ── Sidebar ── */
.sidebar { .sidebar {
position: fixed; position: fixed;
top: 0; top: 0; left: 0;
left: 0;
width: 264px; width: 264px;
height: 100vh; height: 100vh;
background: #1a1b2e; background: #0f172a;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
z-index: 99; z-index: 99;
overflow: hidden; overflow: hidden;
border-right: 1px solid #1e293b;
} }
.sidebar__title-block { .sidebar__title-block {
margin: 48px 24px 8px; margin: 32px 24px 0;
padding-bottom: 16px;
border-bottom: 1px solid rgba(255,255,255,0.07);
flex-shrink: 0; flex-shrink: 0;
} }
.sidebar__title-block a { .sidebar__title-block a { text-decoration: none; }
text-decoration: none;
}
.sidebar__title-block__title { .sidebar__title-block__title {
color: #fff; color: #fff;
font-size: 26px; font-size: 20px;
font-weight: 700; font-weight: 700;
margin: 0 0 4px; margin: 0;
line-height: 1.25; line-height: 1.3;
pointer-events: none;
} }
.sidebar__title-block__version { .sidebar__title-bolt {
color: rgba(255,255,255,0.3); font-size: 1.1em;
font-size: 14px; filter: drop-shadow(0 0 4px #fbbf24);
font-weight: 700; margin-right: 4px;
display: block;
margin-bottom: 24px;
} }
/* ── Sidebar menu ── */ /* ── Sidebar menu ── */
.sidebar__menu { .sidebar__menu {
list-style: none; list-style: none;
margin: 0; margin: 0;
padding: 8px 0 48px 0; padding: 12px 0 48px;
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
} }
.sidebar__menu::-webkit-scrollbar { width: 0; } .sidebar__menu::-webkit-scrollbar { width: 4px; }
.sidebar__menu::-webkit-scrollbar-track { background: transparent; }
.sidebar__menu::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 4px; }
/* First-level = section group label (non-clickable) */ /* ── Tree nav ── */
.sidebar__menu__group-label { .nav-tree { list-style: none; margin: 0; padding: 0; }
display: block; .nav-tree li { margin: 0; }
padding: 16px 24px 6px;
color: rgba(255,255,255,0.35);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
}
/* First-level links (root files or group header links) */ /* Root-level file links */
.sidebar__menu__first-level-title { margin: 0; } .nav-root-link {
.sidebar__menu__first-level-title__link {
display: block; display: block;
padding: 7px 24px; padding: 6px 24px;
color: rgba(255,255,255,0.85); color: rgba(255,255,255,0.6);
text-decoration: none;
font-size: 16px;
font-weight: 400;
line-height: 1.4;
transition: color 0.2s;
}
.sidebar__menu__first-level-title__link:hover { color: #ff5577; }
.sidebar__menu__first-level-title__link.active {
color: #ff5577;
font-weight: 500;
}
/* Second-level links (files inside a group) */
.sidebar__menu__second-level { list-style: none; padding: 0; margin: 0; }
.sidebar__menu__second-level-title { margin: 0; }
.sidebar__menu__second-level-title__link {
display: block;
padding: 5px 24px 5px 36px;
color: rgba(255,255,255,0.55);
text-decoration: none; text-decoration: none;
font-size: 14px; font-size: 14px;
font-weight: 400; font-weight: 400;
line-height: 1.4; line-height: 1.4;
transition: color 0.2s; transition: color 0.15s, background 0.15s;
} }
.sidebar__menu__second-level-title__link:hover { color: #ff5577; } .nav-root-link:hover { color: #fff; background: rgba(255,255,255,0.06); }
.sidebar__menu__second-level-title__link.active { .nav-root-link.active { color: #818cf8; font-weight: 600; }
color: #ff5577;
opacity: 1; /* Folder <details> block */
.nav-folder { margin: 0; }
.nav-folder > summary {
display: flex;
align-items: center;
list-style: none;
cursor: default;
user-select: none;
padding: 0;
color: rgba(255,255,255,0.35);
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
} }
.nav-folder > summary::-webkit-details-marker { display: none; }
/* Arrow */
.nav-arrow {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 28px;
height: 28px;
font-size: 9px;
opacity: 0.4;
cursor: pointer;
transition: transform 0.18s, opacity 0.2s;
border-radius: 4px;
color: rgba(255,255,255,0.7);
}
.nav-arrow:hover { opacity: 1; background: rgba(255,255,255,0.08); }
.nav-folder[open] > summary .nav-arrow { transform: rotate(90deg); opacity: 0.8; }
/* Folder label */
.nav-folder-link, .nav-folder-name {
flex: 1;
display: block;
padding: 6px 24px 6px 0;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: rgba(255,255,255,0.38);
text-decoration: none;
transition: color 0.15s;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.nav-folder-link:hover { color: rgba(255,255,255,0.85); }
.nav-folder-link.active { color: #818cf8; }
/* Nested folder (depth ≥ 2) */
.nav-folder .nav-folder > summary {
font-size: 13px;
font-weight: 500;
text-transform: none;
letter-spacing: 0;
}
.nav-folder .nav-folder > summary .nav-folder-link,
.nav-folder .nav-folder > summary .nav-folder-name {
font-size: 13px;
font-weight: 500;
text-transform: none;
letter-spacing: 0;
color: rgba(255,255,255,0.45);
}
.nav-folder .nav-folder > summary .nav-folder-link:hover { color: rgba(255,255,255,0.9); }
/* File links inside folders */
.nav-file-link {
display: block;
text-decoration: none;
font-size: 13.5px;
font-weight: 400;
line-height: 1.4;
color: rgba(255,255,255,0.5);
transition: color 0.15s, background 0.15s;
}
.nav-file-link:hover { color: #fff; background: rgba(255,255,255,0.06); }
.nav-file-link.active { color: #818cf8; font-weight: 600; }
/* Indentation per depth level */
.nav-depth-1 > .nav-file-link { padding: 5px 24px 5px 52px; }
.nav-depth-1 > .nav-folder > summary { padding-left: 24px; }
.nav-depth-2 > .nav-file-link { padding: 4px 24px 4px 68px; }
.nav-depth-2 > .nav-folder > summary { padding-left: 40px; }
.nav-depth-3 > .nav-file-link { padding: 4px 24px 4px 84px; }
.nav-depth-3 > .nav-folder > summary { padding-left: 56px; }
/* ── Content ── */ /* ── Content ── */
.content { .content {
margin-left: 264px; margin-left: 264px;
padding: 48px 72px 96px; padding: 32px 40px 96px;
max-width: 1080px;
min-height: 100vh; min-height: 100vh;
}
.content-card {
max-width: 860px;
background: #fff; background: #fff;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 2.5rem 2.75rem;
font-size: 0.94rem;
line-height: 1.75;
color: #1e293b;
} }
/* ── Typography ── */ /* ── Typography ── */
.content a { color: #0000ee; text-decoration: none; transition: color 0.16s; } .content-card a { color: #4f46e5; text-decoration: none; border-bottom: 1px solid #c7d2fe; transition: color 0.15s, border-color 0.15s; }
.content a:hover { color: #ff5577; } .content-card a:hover { color: #3730a3; border-color: #4f46e5; }
.content a:visited { color: #551a8b; } .content-card a:visited { color: #6d28d9; }
.content a:visited:hover { color: #ff5577; } .content-card a:visited:hover { color: #3730a3; }
.content h1, .content h2, .content h3, .content-card h1 { font-size: 1.6rem; font-weight: 800; color: #0f172a; margin: 0 0 1.5rem; padding-bottom: 0.75rem; border-bottom: 2px solid #e2e8f0; line-height: 1.3; }
.content h4, .content h5, .content h6 { .content-card h2 { font-size: 1.1rem; font-weight: 700; color: #0f172a; margin: 2.5rem 0 0.9rem; padding-bottom: 0.35rem; border-bottom: 1px solid #f1f5f9; line-height: 1.3; }
color: #222; .content-card h3 { font-size: 0.97rem; font-weight: 700; color: #1e293b; margin: 1.75rem 0 0.55rem; line-height: 1.3; }
margin-top: 48px; .content-card h4, .content-card h5, .content-card h6 { font-size: 0.87rem; font-weight: 700; color: #334155; margin: 1.2rem 0 0.4rem; text-transform: uppercase; letter-spacing: 0.04em; line-height: 1.3; }
margin-bottom: 12px;
line-height: 1.3;
}
.content h1 { font-size: 2em; margin-top: 0; }
.content h2 { font-size: 1.5em; }
.content h3 { font-size: 1.25em; }
.content hr { margin: 72px 0; border: none; border-top: 1px solid rgba(34,34,34,0.15); } .content-card hr { border: none; border-top: 1px solid #e2e8f0; margin: 2rem 0; }
.content-card p { margin: 0 0 1rem; }
.content p { color: #222; font-size: 1em; line-height: 1.64em; margin: 0 0 1em; } .content-card :not(pre) > code {
.content code {
font-family: 'Roboto Mono', 'SFMono-Regular', Consolas, monospace; font-family: 'Roboto Mono', 'SFMono-Regular', Consolas, monospace;
font-size: 85%; font-size: 0.84em;
font-weight: 700; background: #f1f5f9;
background: #f4f4f7; color: #4f46e5;
padding: 0.15em 0.4em; border: 1px solid #e2e8f0;
border-radius: 4px; border-radius: 4px;
line-height: 1.4; padding: 0.1em 0.4em;
} }
.content pre { background: #f4f4f7; padding: 20px 24px; border-radius: 6px; overflow-x: auto; margin: 16px 0; } .content-card pre {
.content pre code { background: none; padding: 0; font-weight: 400; font-size: 13px; } background: #0f172a;
border-radius: 10px;
.content blockquote { margin: 1.2rem 0;
border-left: 3px solid rgba(34,34,34,0.25); overflow-x: auto;
margin: 24px 0; border: 1px solid #1e293b;
padding: 4px 24px; }
color: rgba(34,34,34,0.65); .content-card pre code {
display: block;
padding: 1.1rem 1.25rem;
background: none;
color: #e2e8f0;
border: none;
font-family: 'Roboto Mono', 'SFMono-Regular', Consolas, monospace;
font-size: 0.82rem;
line-height: 1.6;
font-weight: 400;
} }
.content img { max-width: 100%; margin: 8px 0; } .content-card blockquote {
margin: 1.2rem 0;
padding: 0.8rem 1.1rem;
border-radius: 0 8px 8px 0;
border-left: 4px solid #818cf8;
background: #f5f3ff;
color: #4338ca;
font-size: 0.9rem;
}
.content table { .content-card img { max-width: 100%; margin: 8px 0; border-radius: 8px; }
.content-card table {
width: 100%; width: 100%;
border-spacing: 0;
border-collapse: collapse; border-collapse: collapse;
margin: 24px 0 48px; font-size: 0.875rem;
font-size: 14px; margin: 1.2rem 0;
color: #222; border-radius: 8px;
overflow: hidden;
border: 1px solid #cbd5e1;
} }
.content table th { .content-card thead { background: #e2e8f0; }
border-bottom: 1px solid #ff5577; .content-card th {
padding: 10px; padding: 0.6rem 1rem;
font-weight: 700;
font-size: 0.77rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: #334155;
border-bottom: 2px solid #94a3b8;
border-right: 1px solid #cbd5e1;
text-align: left; text-align: left;
font-weight: 600;
} }
.content table td { .content-card th:last-child { border-right: none; }
border-bottom: 1px solid rgba(255,85,119,0.25); .content-card td {
padding: 10px; padding: 0.6rem 1rem;
border-bottom: 1px solid #e2e8f0;
border-right: 1px solid #e2e8f0;
color: #374151;
vertical-align: top;
} }
.content-card td:last-child { border-right: none; }
.content-card tbody tr:last-child td { border-bottom: none; }
.content-card tbody tr:nth-child(even) { background: #f8fafc; }
.content-card tbody tr:hover { background: #eff6ff; }
.content ul li, .content ol li { .content-card ul, .content-card ol { padding-left: 1.5rem; margin: 0 0 1rem; }
color: #222; .content-card li { margin-bottom: 0.3rem; }
font-size: 1em; .content-card li code { font-weight: 700; }
line-height: 1.64em; .content-card strong { font-weight: 700; color: #0f172a; }
margin-bottom: 8px;
}
.content ul li code, .content ol li code { font-weight: 700; }
/* ── Responsive ── */ /* ── Responsive ── */
@media screen and (max-width: 1020px) { @media screen and (max-width: 1020px) {
.sidebar { .sidebar { left: -300px; transition: left 0.2s cubic-bezier(0.09, 0.46, 0.45, 0.94); }
left: -300px; .content { margin-left: 0; padding: 24px 16px 64px; }
transition: left 0.2s cubic-bezier(0.09, 0.46, 0.45, 0.94);
}
.content { margin-left: 0; padding: 32px 24px 64px; }
} }
@media screen and (max-width: 540px) { @media screen and (max-width: 540px) {
.content { padding: 24px 16px 48px; } .content-card { padding: 1.25rem; border-radius: 8px; }
}`; }`;
const SSE_SCRIPT = ` const SSE_SCRIPT = `
<script> <script>
const es = new EventSource('/events'); (function () {
es.onmessage = () => location.reload(); function connect() {
es.onerror = () => { es.close(); console.warn('Live reload disconnected'); }; const es = new EventSource('/events');
es.onmessage = () => location.reload();
es.onerror = () => { es.close(); setTimeout(connect, 3000); };
}
connect();
})();
</script>`; </script>`;
// ───────────────────────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────────────────────
@@ -233,68 +328,95 @@ function escapeHtml(str) {
.replace(/"/g, '&quot;'); .replace(/"/g, '&quot;');
} }
/** Build the sidebar HTML from the list of all pages (Shell theme structure). */ /** Build a nested tree object from a flat list of relative paths. */
function buildTree(relPaths) {
const tree = { _files: [], _dirs: {} };
relPaths.forEach((rel) => {
const parts = rel.split(path.sep);
let node = tree;
for (let i = 0; i < parts.length - 1; i++) {
const dir = parts[i];
if (!node._dirs[dir]) node._dirs[dir] = { _files: [], _dirs: {} };
node = node._dirs[dir];
}
node._files.push(rel);
});
return tree;
}
/** Render a tree node as HTML list items (recursive). */
function renderTree(node, baseDir, currentRel, depth) {
let html = '';
const depthClass = depth > 0 ? ` class="nav-depth-${Math.min(depth, 3)}"` : '';
// Files first (sorted)
node._files.slice().sort().forEach((rel) => {
const pagePath = rel.replace(/\.md$/i, '');
const label = path.basename(pagePath).replace(/-/g, ' ');
const href = '/' + pagePath.split('/').map(encodeURIComponent).join('/');
const isActive = rel === currentRel;
const cls = isActive ? ' active' : '';
if (depth === 0) {
html += `\n<li><a href="${href}" class="nav-root-link${cls}">${escapeHtml(label)}</a></li>`;
} else {
html += `\n<li${depthClass}><a href="${href}" class="nav-file-link${cls}">${escapeHtml(label)}</a></li>`;
}
});
// Sub-directories (sorted)
Object.keys(node._dirs).sort().forEach((dirName) => {
const child = node._dirs[dirName];
const isOpen = currentRel && currentRel.split(path.sep).includes(dirName);
const openAttr = isOpen ? ' open' : '';
// Look for a home.md in this sub-directory to link the folder name to
const homeFile = child._files.find((f) => /^home\.md$/i.test(path.basename(f)));
let folderLabel;
if (homeFile) {
const pagePath = homeFile.replace(/\.md$/i, '');
const href = '/' + pagePath.split('/').map(encodeURIComponent).join('/');
const isActive = homeFile === currentRel;
const cls = isActive ? ' active' : '';
folderLabel = `<a href="${href}" class="nav-folder-link${cls}" onclick="event.stopPropagation()">${escapeHtml(dirName)}</a>`;
} else {
folderLabel = `<span class="nav-folder-name">${escapeHtml(dirName)}</span>`;
}
// Arrow is the only toggle; preventDefault cancels the browser's native <details> activation,
// stopPropagation prevents it from bubbling further, then we toggle manually.
const arrow = `<span class="nav-arrow" onclick="event.preventDefault();event.stopPropagation();var d=this.closest('details');d.open=!d.open">▶</span>`;
// Render child files, excluding home.md (already used as folder link)
const childNode = {
_files: homeFile ? child._files.filter((f) => f !== homeFile) : child._files,
_dirs: child._dirs,
};
html += `\n<li${depthClass}><details class="nav-folder"${openAttr}>`;
html += `\n <summary>${arrow}${folderLabel}</summary>`;
html += `\n <ul class="nav-tree">`;
html += renderTree(childNode, baseDir, currentRel, depth + 1);
html += `\n </ul>\n</details></li>`;
});
return html;
}
/** Build the sidebar HTML from the list of all pages. */
function buildSidebar(baseDir, files, currentFile) { function buildSidebar(baseDir, files, currentFile) {
const currentRel = currentFile ? path.relative(baseDir, currentFile) : null; const currentRel = currentFile ? path.relative(baseDir, currentFile) : null;
const relPaths = files.map((f) => path.relative(baseDir, f));
// Group by first-level subdirectory const tree = buildTree(relPaths);
const groups = new Map(); // groupName → [rel, ...]
files.forEach((f) => {
const rel = path.relative(baseDir, f);
const parts = rel.split(path.sep);
const group = parts.length > 1 ? parts[0] : '';
if (!groups.has(group)) groups.set(group, []);
groups.get(group).push(rel);
});
const dirName = path.basename(baseDir); const dirName = path.basename(baseDir);
let html = ` let html = `
<aside class="sidebar"> <aside class="sidebar">
<div class="sidebar__title-block"> <div class="sidebar__title-block">
<a href="/"><h1 class="sidebar__title-block__title">${escapeHtml(dirName)}</h1></a> <a href="/"><h1 class="sidebar__title-block__title"><span class="sidebar__title-bolt">⚡</span>${escapeHtml(dirName)}</h1></a>
</div> </div>
<ul class="sidebar__menu">`; <ul class="sidebar__menu nav-tree">`;
const sortedGroups = [...groups.keys()].sort((a, b) => { html += renderTree(tree, baseDir, currentRel, 0);
if (a === '') return -1;
if (b === '') return 1;
return a.localeCompare(b);
});
sortedGroups.forEach((group) => {
const pages = groups.get(group).sort();
if (group !== '') {
// Group label + second-level links
html += `\n <li class="sidebar__menu__first-level-title">
<span class="sidebar__menu__group-label">${escapeHtml(group)}</span>
<ul class="sidebar__menu__second-level">`;
pages.forEach((rel) => {
const pagePath = rel.replace(/\.md$/i, '');
const label = path.basename(pagePath).replace(/-/g, ' ');
const href = '/' + pagePath.split('/').map(encodeURIComponent).join('/');
const isActive = rel === currentRel;
const cls = isActive ? 'active' : '';
html += `\n <li class="sidebar__menu__second-level-title">
<a href="${href}" class="sidebar__menu__second-level-title__link ${cls}">${escapeHtml(label)}</a>
</li>`;
});
html += `\n </ul>
</li>`;
} else {
// Root-level links as first-level items
pages.forEach((rel) => {
const pagePath = rel.replace(/\.md$/i, '');
const label = path.basename(pagePath).replace(/-/g, ' ');
const href = '/' + pagePath.split('/').map(encodeURIComponent).join('/');
const isActive = rel === currentRel;
const cls = isActive ? 'active' : '';
html += `\n <li class="sidebar__menu__first-level-title">
<a href="${href}" class="sidebar__menu__first-level-title__link ${cls}">${escapeHtml(label)}</a>
</li>`;
});
}
});
html += `\n </ul> html += `\n </ul>
</aside>`; </aside>`;
@@ -309,8 +431,9 @@ function htmlShell({ title, sidebar, body, watchMode }) {
const hasSidebar = !!sidebar; const hasSidebar = !!sidebar;
const noSidebarStyle = hasSidebar ? '' : ` const noSidebarStyle = hasSidebar ? '' : `
<style> <style>
body { max-width: 860px; margin: 48px auto; padding: 0 32px; } body { background: #fff; }
.content { margin-left: 0; padding: 0; } .content { max-width: 860px; margin: 0 auto; padding: 48px 40px 96px; }
.content-card { border: none; border-radius: 0; padding: 0; }
</style>`; </style>`;
return `<!DOCTYPE html> return `<!DOCTYPE html>
<html lang="fr"> <html lang="fr">
@@ -318,15 +441,18 @@ function htmlShell({ title, sidebar, body, watchMode }) {
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${escapeHtml(title)}</title> <title>${escapeHtml(title)}</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>">
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Roboto+Mono&display=swap"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&family=Roboto+Mono&display=swap">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<style>${STYLES}</style>${noSidebarStyle} <style>${STYLES}</style>${noSidebarStyle}
</head> </head>
<body> <body>
${hasSidebar ? sidebar : ''} ${hasSidebar ? sidebar : ''}
<div class="content"> <div class="content">
<div class="content-card">
${body} ${body}
</div>
</div>${watchMode ? SSE_SCRIPT : ''} </div>${watchMode ? SSE_SCRIPT : ''}
</body> </body>
</html>`; </html>`;
+65 -8
View File
@@ -42,16 +42,33 @@ function notifyClients(clients) {
return clients.filter((c) => !dead.includes(c) && !c.writableEnded); return clients.filter((c) => !dead.includes(c) && !c.writableEnded);
} }
function startServer({ inputFile, inputDir, port }) { function startServer({ inputFile, inputDir, port, onReady }) {
let clients = []; let clients = [];
const isDir = !!inputDir; const isDir = !!inputDir;
const baseDir = isDir ? path.resolve(inputDir) : path.dirname(path.resolve(inputFile)); const baseDir = isDir ? path.resolve(inputDir) : path.dirname(path.resolve(inputFile));
// --- cache ---
// pageCache: filePath → rendered HTML string
// fileListCache: cached list of all .md files (null = stale)
const pageCache = new Map();
let fileListCache = null;
function getCachedFiles() {
if (!fileListCache) fileListCache = findMarkdownFiles(baseDir);
return fileListCache;
}
// --- rebuild --- // --- rebuild ---
function rebuild(changedFile) { function rebuild(changedFile) {
if (changedFile) { if (changedFile) {
const rel = path.relative(baseDir, changedFile); const rel = path.relative(baseDir, changedFile);
console.log(`${rel} — rechargement...`); console.log(`${rel} — rechargement...`);
// Only this page's HTML is stale; other pages' sidebars are still valid
pageCache.delete(changedFile);
} else {
// File added or removed: file list changed → all caches stale
pageCache.clear();
fileListCache = null;
} }
clients = notifyClients(clients); clients = notifyClients(clients);
} }
@@ -67,7 +84,9 @@ function startServer({ inputFile, inputDir, port }) {
'Content-Type': 'text/event-stream', 'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache', 'Cache-Control': 'no-cache',
Connection: 'keep-alive', Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
}); });
if (req.socket) req.socket.setNoDelay(true);
res.write(': keep-alive\n\n'); res.write(': keep-alive\n\n');
clients.push(res); clients.push(res);
@@ -86,8 +105,11 @@ function startServer({ inputFile, inputDir, port }) {
// ── SINGLE FILE MODE ────────────────────────────────────────────────────── // ── SINGLE FILE MODE ──────────────────────────────────────────────────────
if (!isDir) { if (!isDir) {
if (pathname === '/' || pathname === '/index.html') { if (pathname === '/' || pathname === '/index.html') {
if (!pageCache.has(inputFile)) {
pageCache.set(inputFile, convert(inputFile, true));
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(convert(inputFile, true)); res.end(pageCache.get(inputFile));
return; return;
} }
return serveStatic(req, res, pathname, baseDir, port); return serveStatic(req, res, pathname, baseDir, port);
@@ -97,7 +119,7 @@ function startServer({ inputFile, inputDir, port }) {
// Index page // Index page
if (pathname === '/') { if (pathname === '/') {
const files = findMarkdownFiles(baseDir); const files = getCachedFiles();
// Redirect to Home.md if it exists // Redirect to Home.md if it exists
const homePage = files.find((f) => const homePage = files.find((f) =>
/^home\.md$/i.test(path.basename(f)) && path.dirname(f) === baseDir /^home\.md$/i.test(path.basename(f)) && path.dirname(f) === baseDir
@@ -108,8 +130,12 @@ function startServer({ inputFile, inputDir, port }) {
res.end(); res.end();
return; return;
} }
const indexKey = '__index__';
if (!pageCache.has(indexKey)) {
pageCache.set(indexKey, buildIndex(baseDir, files, true));
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(buildIndex(baseDir, files, true)); res.end(pageCache.get(indexKey));
return; return;
} }
@@ -127,10 +153,12 @@ function startServer({ inputFile, inputDir, port }) {
if (!candidate.startsWith(baseDir + path.sep) && candidate !== baseDir) continue; if (!candidate.startsWith(baseDir + path.sep) && candidate !== baseDir) continue;
if (fs.existsSync(candidate) && /\.md$/i.test(candidate)) { if (fs.existsSync(candidate) && /\.md$/i.test(candidate)) {
try { try {
const files = findMarkdownFiles(baseDir); if (!pageCache.has(candidate)) {
const html = convert(candidate, true, { baseDir, files }); const files = getCachedFiles();
pageCache.set(candidate, convert(candidate, true, { baseDir, files }));
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html); res.end(pageCache.get(candidate));
} catch (err) { } catch (err) {
res.writeHead(500); res.writeHead(500);
res.end(`Erreur de conversion : ${err.message}`); res.end(`Erreur de conversion : ${err.message}`);
@@ -143,12 +171,41 @@ function startServer({ inputFile, inputDir, port }) {
serveStatic(req, res, pathname, baseDir, port); serveStatic(req, res, pathname, baseDir, port);
}); });
function warmCache() {
const files = getCachedFiles();
let count = 0;
if (isDir) {
for (const file of files) {
if (!pageCache.has(file)) {
try {
pageCache.set(file, convert(file, true, { baseDir, files }));
count++;
} catch { /* ignore errors on warm-up */ }
}
}
} else {
if (!pageCache.has(inputFile)) {
try {
pageCache.set(inputFile, convert(inputFile, true));
count++;
} catch { /* ignore */ }
}
}
if (count > 0) console.log(`🔥 Cache préchauffé : ${count} page(s) prête(s)\n`);
}
server.listen(port, () => { server.listen(port, () => {
console.log(`\n🚀 Serveur démarré : http://localhost:${port}`); console.log(`\n🚀 Serveur démarré : http://localhost:${port}`);
if (isDir) { if (isDir) {
console.log(`📂 Dossier : ${baseDir}`); console.log(`📂 Dossier : ${baseDir}`);
} }
console.log('👁 Surveillance des modifications... (Ctrl+C pour arrêter)\n'); if (onReady) {
onReady(port);
} else {
console.log('👁 Surveillance des modifications... (Ctrl+C pour arrêter)');
}
// Pre-render all pages so first visits are instant
setImmediate(warmCache);
}); });
server.on('error', (err) => { server.on('error', (err) => {
+4 -3
View File
@@ -9,9 +9,10 @@ function startWatcher({ inputFile, inputDir, server }) {
const watcher = chokidar.watch(watchTarget, { const watcher = chokidar.watch(watchTarget, {
persistent: true, persistent: true,
ignoreInitial: true, ignoreInitial: true,
ignored: /(^|[/\\])\../, // ignore hidden files ignored: /(^|[/\\])\.\./, // ignore hidden files
usePolling: true, usePolling: true,
interval: 500, interval: 300,
awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 },
}); });
let debounceTimer = null; let debounceTimer = null;
@@ -33,7 +34,7 @@ function startWatcher({ inputFile, inputDir, server }) {
watcher.on('add', (filePath) => { watcher.on('add', (filePath) => {
if (!isDir || isMd(filePath)) { if (!isDir || isMd(filePath)) {
console.log(` + Nouveau fichier : ${path.basename(filePath)}`); console.log(` + Nouveau fichier : ${path.basename(filePath)}`);
schedule(filePath); schedule(null); // file list changed → full cache invalidation
} }
}); });
watcher.on('unlink', (filePath) => { watcher.on('unlink', (filePath) => {