dev: add live-reload development server

This commit is contained in:
Théophile Gervreau-Mercier
2026-02-06 14:31:23 +01:00
parent 52f8e267e5
commit 87f0838b5d
3 changed files with 66 additions and 7 deletions

View File

@@ -11,9 +11,16 @@
<link rel="stylesheet" href="assets/modern-normalize.css">
<link rel="stylesheet" href="assets/common.css">
<link rel="stylesheet" href="assets/main.css">
<?php if (getenv('PHP_ENV') === 'development' || php_sapi_name() === 'cli-server'): ?>
<?php if (php_sapi_name() === 'cli-server'): ?>
<!-- Live reload for development -->
<script src="/vendor/php-live-reload/php-live-reload/live-reload.js"></script>
<script>
(function poll() {
fetch('/live-reload.php')
.then(r => r.json())
.then(d => { if (d.changed) location.reload(); else setTimeout(poll, 1000); })
.catch(() => setTimeout(poll, 2000));
})();
</script>
<?php endif; ?>
</head>

View File

@@ -27,11 +27,7 @@ serve:
@echo "📍 Admin panel: http://localhost:8000/admin/"
@echo "🔒 Serving from public/ directory (matches production)"
@echo ""
@if [ -d "vendor/php-live-reload" ]; then \
echo "✨ Live reload enabled - browser auto-refreshes on file save!"; \
else \
echo "💡 Tip: Run 'just setup' to enable live reload"; \
fi
@echo "✨ Live reload enabled - browser auto-refreshes on file save!"
@echo ""
@echo "Press Ctrl+C to stop"
@echo ""

56
public/live-reload.php Normal file
View File

@@ -0,0 +1,56 @@
<?php
/**
* Simple live-reload endpoint for development.
* Polls file mtimes across all source directories and returns
* whether anything changed since last check.
*
* Only active when served by PHP's built-in CLI server.
*/
if (php_sapi_name() !== 'cli-server') {
http_response_code(403);
exit;
}
header('Content-Type: application/json');
$root = dirname(__DIR__);
$watchDirs = [
$root . '/public',
$root . '/includes',
$root . '/lib',
$root . '/config',
];
$watchExts = ['php', 'css', 'js', 'html'];
$hash = '';
foreach ($watchDirs as $dir) {
if (!is_dir($dir)) continue;
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
);
foreach ($it as $file) {
if (in_array($file->getExtension(), $watchExts)) {
$hash .= $file->getMTime() . '|' . $file->getPathname() . "\n";
}
}
}
$fingerprint = md5($hash);
$stateFile = sys_get_temp_dir() . '/posterg-live-reload.txt';
$prev = file_exists($stateFile) ? file_get_contents($stateFile) : null;
// First visit: write baseline, don't fire a reload
if ($prev === null) {
file_put_contents($stateFile, $fingerprint);
$changed = false;
} else {
$changed = $fingerprint !== $prev;
if ($changed) {
file_put_contents($stateFile, $fingerprint);
}
}
echo json_encode(['changed' => $changed]);