feat(docs): introduce dynamic markdown documentation viewer

Added a lightweight, self-hosted documentation viewer that dinamically
serves Markdown files as a reactive HTML site with zero build steps.

Features included in this initial release:
- Custom Python HTTPServer (`main.py`) for dynamic Markdown-to-HTML
  rendering
- Responsive UI with dark/light mode togles, breadcrumbs, and search
  filtering
- Built-in support for Mermaid.js diagrams, Prism.js syntax
  highlighting, and GitHub-style alert callouts
- Auto-generated sidebar navigation and directory index pages
- Updated `appctl` to support the new `docs` service, and mappings to
  env-vars for easy host-directory mounting
- Traefik-ready `docker-compose.tml` for seamless integration into the
  proxy network
This commit is contained in:
kiskaadee committed 2026-07-09 17:39:18 -05:00
1 parent 19a63811e2
commit 22b41d142d
6 files changed
+1457 -2

No files matched your search

+8 -2
View File
@@ -65,7 +65,6 @@ load_app_env() {
export SERVICE_DOMAIN="$LEARNING_DOMAIN" export SERVICE_DOMAIN="$LEARNING_DOMAIN"
export APP_PORT="$LEARNING_APP_PORT" export APP_PORT="$LEARNING_APP_PORT"
export PROXY_NETWORK="$PROXY_NETWORK" export PROXY_NETWORK="$PROXY_NETWORK"
export SOCKET_PROXY_NETWORK="$LEARNING_SOCKET_PROXY_NETWORK"
export TURSO_DATABASE_URL="$TURSO_DATABASE_URL" export TURSO_DATABASE_URL="$TURSO_DATABASE_URL"
export TURSO_AUTH_TOKEN="$TURSO_AUTH_TOKEN" export TURSO_AUTH_TOKEN="$TURSO_AUTH_TOKEN"
;; ;;
@@ -74,6 +73,12 @@ load_app_env() {
export PROXY_NETWORK="$PROXY_NETWORK" export PROXY_NETWORK="$PROXY_NETWORK"
export SERVICE_NAME="$MERMAID_SERVICE_NAME" export SERVICE_NAME="$MERMAID_SERVICE_NAME"
;; ;;
docs)
export SERVICE_NAME="docs"
export SERVICE_DOMAIN="$DOCS_DOMAIN"
export PROJECT_PATH="$DOCS_PROJECT_PATH"
export PROXY_NETWORK="$PROXY_NETWORK"
;;
mongo-docker) mongo-docker)
export MONGO_ROOT_USERNAME="$MONGO_ROOT_USERNAME" export MONGO_ROOT_USERNAME="$MONGO_ROOT_USERNAME"
export MONGO_ROOT_PASSWORD="$MONGO_ROOT_PASSWORD" export MONGO_ROOT_PASSWORD="$MONGO_ROOT_PASSWORD"
@@ -144,6 +149,7 @@ cmd_list() {
excalidraw) domain_info="$EXCALIDRAW_DOMAIN" ;; excalidraw) domain_info="$EXCALIDRAW_DOMAIN" ;;
gitea) domain_info="$GITEA_DOMAIN" ;; gitea) domain_info="$GITEA_DOMAIN" ;;
jellyfin) domain_info="$JELLYFIN_DOMAIN" ;; jellyfin) domain_info="$JELLYFIN_DOMAIN" ;;
docs) domain_info="$DOCS_DOMAIN" ;;
learning) domain_info="$LEARNING_DOMAIN" ;; learning) domain_info="$LEARNING_DOMAIN" ;;
mermaid) domain_info="$MERMAID_DOMAIN" ;; mermaid) domain_info="$MERMAID_DOMAIN" ;;
mongo-docker) domain_info="$MONGO_DOMAIN" ;; mongo-docker) domain_info="$MONGO_DOMAIN" ;;
@@ -195,7 +201,7 @@ case "$COMMAND" in
if [ -z "$APP" ]; then echo "Error: Service name required"; exit 1; fi if [ -z "$APP" ]; then echo "Error: Service name required"; exit 1; fi
load_app_env "$APP" load_app_env "$APP"
echo "=== Active Environment Variables for $APP ===" echo "=== Active Environment Variables for $APP ==="
env | grep -E "^(PROXY_NETWORK|CERT_RESOLVER|DOMAIN|SERVICE_DOMAIN|SERVICE_NAME|CONTAINER_NAME|IMAGE_TAG|TZ|PUID|PGID|MEDIA_PATH|HTTP_ENTRYPOINT|HTTPS_ENTRYPOINT|RATE_LIMIT_AVG|RATE_LIMIT_BURST|APP_PORT|SOCKET_PROXY_NETWORK|TURSO_DATABASE_URL|TURSO_AUTH_TOKEN|DOCKER_HOST|MONGO_ROOT_USERNAME|MONGO_ROOT_PASSWORD|MONGO_DOMAIN|POSTGRES_USER|POSTGRES_PASSWORD|POSTGRES_DB|POSTGRES_DOMAIN|OLLAMA_API_KEY|REPLICAS|OLLAMA_DATA_VOLUME|GITEA_VERSION|GITEA_DOMAIN|GITEA_SSH_DOMAIN|GITEA_AUTH_MIDDLEWARE|SSH_DOMAIN|DATA_PATH|AUTH_MIDDLEWARE|HTTPS_REDIRECT_MIDDLEWARE)" | sort env | grep -E "^(PROXY_NETWORK|CERT_RESOLVER|DOMAIN|SERVICE_DOMAIN|SERVICE_NAME|CONTAINER_NAME|IMAGE_TAG|TZ|PUID|PGID|MEDIA_PATH|HTTP_ENTRYPOINT|HTTPS_ENTRYPOINT|RATE_LIMIT_AVG|RATE_LIMIT_BURST|APP_PORT|SOCKET_PROXY_NETWORK|TURSO_DATABASE_URL|TURSO_AUTH_TOKEN|DOCKER_HOST|MONGO_ROOT_USERNAME|MONGO_ROOT_PASSWORD|MONGO_DOMAIN|POSTGRES_USER|POSTGRES_PASSWORD|POSTGRES_DB|POSTGRES_DOMAIN|OLLAMA_API_KEY|REPLICAS|OLLAMA_DATA_VOLUME|GITEA_VERSION|GITEA_DOMAIN|GITEA_SSH_DOMAIN|GITEA_AUTH_MIDDLEWARE|SSH_DOMAIN|DATA_PATH|AUTH_MIDDLEWARE|HTTPS_REDIRECT_MIDDLEWARE|PROJECT_PATH|DOCS_PROJECT_PATH|DOCS_DOMAIN)" | sort
;; ;;
*) *)
show_help show_help
+17
View File
@@ -0,0 +1,17 @@
FROM python:3.11-alpine
WORKDIR /app
# Install dependencies
RUN pip install --no-cache-dir markdown
# Copy application files
COPY app/ /app/
# Default Environment Variables
ENV PORT=8000
ENV DOCS_ROOT=/docs
EXPOSE 8000
CMD ["python", "main.py"]
+943
View File
@@ -0,0 +1,943 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }} - Documentation</title>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Outfit:wght@400;500;600;700&family=Fira+Code:wght@400;500&display=swap" rel="stylesheet">
<!-- Prism Syntax Highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" id="prism-theme">
<style>
:root {
/* Dark Theme Variables (Default) */
--bg-main: #090d16;
--bg-sidebar: rgba(15, 23, 42, 0.75);
--bg-card: #131b2e;
--text-main: #f1f5f9;
--text-muted: #94a3b8;
--border-color: rgba(255, 255, 255, 0.08);
--accent-indigo: #6366f1;
--accent-violet: #8b5cf6;
--accent-gradient: linear-gradient(135deg, #6366f1, #8b5cf6);
--active-bg: rgba(99, 102, 241, 0.12);
--code-bg: #1e293b;
--pre-bg: #0b0f19;
--scrollbar-thumb: #334155;
--sidebar-width: 300px;
--toc-width: 260px;
--header-height: 60px;
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--font-title: 'Outfit', var(--font-sans);
--font-mono: 'Fira Code', monospace;
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
--shadow-glass: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
}
body.light-theme {
/* Light Theme Variables */
--bg-main: #f8fafc;
--bg-sidebar: rgba(241, 245, 249, 0.8);
--bg-card: #ffffff;
--text-main: #0f172a;
--text-muted: #64748b;
--border-color: rgba(0, 0, 0, 0.08);
--accent-indigo: #4f46e5;
--accent-violet: #7c3aed;
--accent-gradient: linear-gradient(135deg, #4f46e5, #7c3aed);
--active-bg: rgba(79, 70, 229, 0.08);
--code-bg: #f1f5f9;
--pre-bg: #f8fafc;
--scrollbar-thumb: #cbd5e1;
--shadow-glass: 0 8px 32px 0 rgba(148, 163, 184, 0.15);
}
/* Basic Setup */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: var(--font-sans);
background-color: var(--bg-main);
color: var(--text-main);
min-height: 100vh;
display: flex;
overflow-x: hidden;
transition: background-color 0.3s, color 0.3s;
}
a {
color: var(--accent-indigo);
text-decoration: none;
transition: color 0.2s;
}
a:hover {
color: var(--accent-violet);
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--scrollbar-thumb);
border-radius: 4px;
}
/* Sidebar Container */
.sidebar {
width: var(--sidebar-width);
background-color: var(--bg-sidebar);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border-right: 1px solid var(--border-color);
height: 100vh;
position: fixed;
left: 0;
top: 0;
display: flex;
flex-direction: column;
z-index: 100;
transition: transform 0.3s ease, background-color 0.3s;
}
.sidebar-header {
padding: 1.5rem 1.25rem;
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
}
.sidebar-brand {
font-family: var(--font-title);
font-size: 1.25rem;
font-weight: 700;
color: var(--text-main);
display: flex;
align-items: center;
gap: 0.5rem;
}
.sidebar-search-container {
padding: 1rem 1.25rem;
border-bottom: 1px solid var(--border-color);
}
.search-input {
width: 100%;
padding: 0.6rem 0.8rem;
background-color: rgba(0, 0, 0, 0.15);
border: 1px solid var(--border-color);
border-radius: 6px;
color: var(--text-main);
font-family: var(--font-sans);
font-size: 0.9rem;
outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
}
.search-input:focus {
border-color: var(--accent-indigo);
box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
}
.sidebar-nav {
flex: 1;
overflow-y: auto;
padding: 1rem 0.75rem;
}
.sidebar-footer {
padding: 1rem;
border-top: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
}
/* Navigation List */
.nav-list {
list-style: none;
padding-left: 0.75rem;
}
.sidebar-nav > .nav-list {
padding-left: 0;
}
.nav-file, .nav-dir {
margin: 0.25rem 0;
}
.nav-file a, .nav-dir summary {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
color: var(--text-muted);
border-radius: 6px;
cursor: pointer;
font-size: 0.925rem;
transition: all 0.2s;
user-select: none;
}
.nav-file a:hover, .nav-dir summary:hover {
color: var(--text-main);
background-color: rgba(255, 255, 255, 0.04);
transform: translateX(2px);
}
body.light-theme .nav-file a:hover, body.light-theme .nav-dir summary:hover {
background-color: rgba(0, 0, 0, 0.03);
}
.nav-file.active a {
color: var(--text-main);
font-weight: 600;
background-color: var(--active-bg);
border-left: 3px solid var(--accent-indigo);
border-radius: 0 6px 6px 0;
padding-left: calc(0.75rem - 3px);
}
.nav-dir details summary {
list-style: none;
}
.nav-dir details summary::-webkit-details-marker {
display: none;
}
.nav-dir details summary::after {
content: '▸';
margin-left: auto;
transition: transform 0.2s;
font-size: 0.8rem;
}
.nav-dir details[open] > summary::after {
transform: rotate(90deg);
}
.icon {
font-size: 1.05rem;
display: inline-block;
width: 1.25rem;
text-align: center;
}
/* Home Button Static */
.home-btn {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.6rem 0.75rem;
margin-bottom: 0.5rem;
color: var(--text-muted);
font-weight: 500;
border-radius: 6px;
font-size: 0.95rem;
}
.home-btn:hover {
color: var(--text-main);
background-color: rgba(255, 255, 255, 0.04);
}
body.light-theme .home-btn:hover {
background-color: rgba(0, 0, 0, 0.03);
}
.home-btn.active {
color: var(--text-main);
font-weight: 600;
background-color: var(--active-bg);
border-left: 3px solid var(--accent-indigo);
border-radius: 0 6px 6px 0;
padding-left: calc(0.75rem - 3px);
}
/* Main Workspace Container */
.main-wrapper {
margin-left: var(--sidebar-width);
flex: 1;
display: flex;
flex-direction: column;
min-height: 100vh;
width: calc(100% - var(--sidebar-width));
transition: margin-left 0.3s ease, width 0.3s ease;
}
/* Top Navbar */
.top-navbar {
height: var(--header-height);
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 2rem;
background-color: rgba(9, 13, 22, 0.4);
backdrop-filter: blur(8px);
position: sticky;
top: 0;
z-index: 90;
}
body.light-theme .top-navbar {
background-color: rgba(248, 250, 252, 0.4);
}
.hamburger {
display: none;
background: none;
border: none;
color: var(--text-main);
font-size: 1.5rem;
cursor: pointer;
outline: none;
}
.breadcrumbs {
font-family: var(--font-title);
font-size: 0.95rem;
color: var(--text-muted);
display: flex;
align-items: center;
gap: 0.5rem;
}
.breadcrumbs span.separator {
color: var(--border-color);
font-size: 0.8rem;
}
.breadcrumbs span.current {
color: var(--text-main);
font-weight: 600;
}
.navbar-actions {
display: flex;
align-items: center;
gap: 1rem;
}
/* Theme Toggle Button */
.theme-toggle {
background: none;
border: 1px solid var(--border-color);
border-radius: 6px;
color: var(--text-main);
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: border-color 0.2s, background-color 0.2s;
font-size: 1rem;
}
.theme-toggle:hover {
border-color: var(--accent-indigo);
background-color: rgba(255, 255, 255, 0.04);
}
body.light-theme .theme-toggle:hover {
background-color: rgba(0, 0, 0, 0.03);
}
/* Layout Grid */
.content-grid {
display: grid;
grid-template-columns: 1fr;
padding: 2.5rem 2rem;
flex: 1;
}
.content-grid.has-toc {
grid-template-columns: minmax(0, 1fr) var(--toc-width);
gap: 3rem;
}
/* Markdown Article Area */
.markdown-body {
max-width: 850px;
width: 100%;
line-height: 1.7;
font-size: 1.05rem;
}
/* Markdown Styles */
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4 {
font-family: var(--font-title);
color: var(--text-main);
font-weight: 700;
margin-top: 2rem;
margin-bottom: 1rem;
line-height: 1.25;
}
.markdown-body h1 {
font-size: 2.2rem;
border-bottom: 1px solid var(--border-color);
padding-bottom: 0.6rem;
margin-top: 0;
background: var(--accent-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: inline-block;
}
.markdown-body h2 {
font-size: 1.6rem;
border-bottom: 1px solid var(--border-color);
padding-bottom: 0.4rem;
}
.markdown-body h3 {
font-size: 1.3rem;
}
.markdown-body p {
margin-bottom: 1.25rem;
color: var(--text-main);
opacity: 0.95;
}
.markdown-body a {
font-weight: 500;
text-decoration: underline;
text-underline-offset: 3px;
}
.markdown-body a:hover {
text-decoration: underline;
}
.markdown-body ul,
.markdown-body ol {
padding-left: 1.75rem;
margin-bottom: 1.25rem;
}
.markdown-body li {
margin-bottom: 0.5rem;
}
.markdown-body blockquote {
padding: 0.75rem 1.25rem;
border-left: 4px solid var(--accent-indigo);
background-color: var(--code-bg);
border-radius: 0 6px 6px 0;
margin: 1.5rem 0;
color: var(--text-muted);
font-style: italic;
}
.markdown-body blockquote p {
margin-bottom: 0;
}
/* Tables */
.markdown-body table {
width: 100%;
border-collapse: collapse;
margin: 1.5rem 0;
font-size: 0.95rem;
overflow-x: auto;
display: block;
}
.markdown-body th,
.markdown-body td {
border: 1px solid var(--border-color);
padding: 0.75rem 1rem;
text-align: left;
}
.markdown-body th {
background-color: var(--code-bg);
font-weight: 600;
}
.markdown-body tr:nth-child(even) {
background-color: rgba(255, 255, 255, 0.02);
}
body.light-theme .markdown-body tr:nth-child(even) {
background-color: rgba(0, 0, 0, 0.01);
}
/* Inline Code */
.markdown-body code {
font-family: var(--font-mono);
font-size: 0.875rem;
background-color: var(--code-bg);
padding: 0.2rem 0.4rem;
border-radius: 4px;
color: var(--accent-indigo);
}
/* Fenced Code Blocks */
.code-wrapper {
position: relative;
margin: 1.5rem 0;
border-radius: 8px;
overflow: hidden;
border: 1px solid var(--border-color);
box-shadow: var(--shadow-lg);
}
.markdown-body pre {
margin: 0 !important;
padding: 1.25rem !important;
font-family: var(--font-mono) !important;
font-size: 0.9rem !important;
background-color: var(--pre-bg) !important;
overflow-x: auto;
}
.markdown-body pre code {
background-color: transparent !important;
padding: 0 !important;
border-radius: 0 !important;
color: inherit !important;
}
/* Copy Button */
.copy-btn {
position: absolute;
top: 0.75rem;
right: 0.75rem;
background-color: rgba(15, 23, 42, 0.6);
backdrop-filter: blur(4px);
border: 1px solid var(--border-color);
color: var(--text-muted);
padding: 0.35rem 0.7rem;
border-radius: 4px;
font-family: var(--font-sans);
font-size: 0.75rem;
font-weight: 500;
cursor: pointer;
opacity: 0;
transition: opacity 0.2s, background-color 0.2s, color 0.2s;
user-select: none;
}
.code-wrapper:hover .copy-btn {
opacity: 1;
}
.copy-btn:hover {
background-color: rgba(99, 102, 241, 0.2);
color: var(--text-main);
}
.copy-btn.copied {
background-color: rgba(16, 185, 129, 0.2);
color: #10b981;
border-color: rgba(16, 185, 129, 0.3);
}
/* Mermaid Diagrams */
.mermaid {
background-color: var(--code-bg);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 1.5rem;
margin: 1.5rem 0;
display: flex;
justify-content: center;
box-shadow: var(--shadow-sm);
}
/* Table of Contents Column */
.toc-column {
display: block;
}
.toc-sticky {
position: sticky;
top: calc(var(--header-height) + 2.5rem);
max-height: calc(100vh - var(--header-height) - 5rem);
overflow-y: auto;
padding-left: 1rem;
border-left: 1px solid var(--border-color);
}
.toc-title {
font-family: var(--font-title);
font-size: 0.85rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-muted);
margin-bottom: 1rem;
}
.toc-sticky .toc {
font-size: 0.9rem;
}
.toc-sticky .toc ul {
list-style: none;
padding-left: 0;
}
.toc-sticky .toc li {
margin: 0.5rem 0;
}
.toc-sticky .toc a {
color: var(--text-muted);
text-decoration: none;
display: block;
transition: color 0.2s;
line-height: 1.4;
}
.toc-sticky .toc a:hover {
color: var(--accent-indigo);
}
/* Folders generated index list */
.folder-index-list {
list-style: none !important;
padding-left: 0 !important;
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-top: 1.5rem;
}
.folder-index-list li {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1rem;
background-color: var(--code-bg);
border: 1px solid var(--border-color);
border-radius: 6px;
font-weight: 500;
}
.folder-index-list li a {
text-decoration: none !important;
color: var(--text-main);
}
.folder-index-list li:hover {
border-color: var(--accent-indigo);
background-color: var(--active-bg);
}
/* Footer styling on pages */
.markdown-footer {
margin-top: 4rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border-color);
font-size: 0.85rem;
color: var(--text-muted);
display: flex;
justify-content: space-between;
}
/* Responsive Breakpoints */
@media (max-width: 1024px) {
.content-grid.has-toc {
grid-template-columns: 1fr;
gap: 2rem;
}
.toc-column {
display: none; /* Hide TOC on medium screens */
}
}
@media (max-width: 768px) {
.sidebar {
transform: translateX(-100%);
}
.sidebar.open {
transform: translateX(0);
box-shadow: var(--shadow-glass);
}
.main-wrapper {
margin-left: 0;
width: 100%;
}
.hamburger {
display: block;
}
.top-navbar {
padding: 0 1rem;
}
.content-grid {
padding: 2rem 1rem;
}
.markdown-body h1 {
font-size: 1.8rem;
}
}
</style>
</head>
<body>
<!-- Sidebar -->
<aside class="sidebar" id="sidebar">
<div class="sidebar-header">
<div class="sidebar-brand">
<span style="background: var(--accent-gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">📝 Docs Viewer</span>
</div>
</div>
<div class="sidebar-search-container">
<input type="text" id="sidebar-search" placeholder="Search files..." class="search-input" autocomplete="off">
</div>
<nav class="sidebar-nav">
<a href="/" class="home-btn{{ home_active }}"><span class="icon">🏠</span> Home</a>
{{ sidebar_tree }}
</nav>
<div class="sidebar-footer">
<button class="theme-toggle" id="theme-toggle" title="Toggle Theme">🌙</button>
<span style="font-size: 0.75rem; color: var(--text-muted);">v1.0.0</span>
</div>
</aside>
<!-- Main Wrapper -->
<div class="main-wrapper" id="main-wrapper">
<!-- Top Navbar -->
<header class="top-navbar">
<button class="hamburger" id="hamburger" title="Toggle Menu">☰</button>
<div class="breadcrumbs">
{{ breadcrumbs }}
</div>
<div class="navbar-actions">
<!-- Theme switch or other buttons could also go here -->
</div>
</header>
<!-- Main Content Area -->
<div class="content-grid{{ grid_class }}">
<main class="markdown-body">
{{ content }}
<footer class="markdown-footer">
<span>Generated dynamically on request</span>
<a href="#">Back to top ↑</a>
</footer>
</main>
{% if has_toc %}
<aside class="toc-column">
<div class="toc-sticky">
<div class="toc-title">On This Page</div>
<div class="toc">
{{ toc }}
</div>
</div>
</aside>
{% endif %}
</div>
</div>
<!-- Scripts -->
<!-- Prism.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<!-- Mermaid.js -->
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script>
// Hamburger Menu Toggle
const hamburger = document.getElementById('hamburger');
const sidebar = document.getElementById('sidebar');
hamburger.addEventListener('click', (e) => {
e.stopPropagation();
sidebar.classList.toggle('open');
});
document.addEventListener('click', (e) => {
if (sidebar.classList.contains('open') && !sidebar.contains(e.target) && e.target !== hamburger) {
sidebar.classList.remove('open');
}
});
// Theme Toggle Logic
const themeToggle = document.getElementById('theme-toggle');
const prismLink = document.getElementById('prism-theme');
// Load theme from localStorage or default to system preference
const savedTheme = localStorage.getItem('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (savedTheme === 'light' || (!savedTheme && !prefersDark)) {
enableLightTheme();
} else {
enableDarkTheme();
}
themeToggle.addEventListener('click', () => {
if (document.body.classList.contains('light-theme')) {
enableDarkTheme();
} else {
enableLightTheme();
}
});
function enableLightTheme() {
document.body.classList.add('light-theme');
themeToggle.textContent = '☀️';
localStorage.setItem('theme', 'light');
prismLink.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css');
updateMermaidTheme('default');
}
function enableDarkTheme() {
document.body.classList.remove('light-theme');
themeToggle.textContent = '🌙';
localStorage.setItem('theme', 'dark');
prismLink.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css');
updateMermaidTheme('dark');
}
function updateMermaidTheme(themeName) {
// If mermaid has already run, re-initialize needs reload.
// But we initialize it on page load with correct theme.
}
// Initialize Mermaid
document.addEventListener('DOMContentLoaded', () => {
// Convert language-mermaid blocks to div.mermaid
const mermaidBlocks = document.querySelectorAll('pre code.language-mermaid');
mermaidBlocks.forEach(codeBlock => {
const pre = codeBlock.parentNode;
const div = document.createElement('div');
div.className = 'mermaid';
div.textContent = codeBlock.textContent;
pre.parentNode.replaceChild(div, pre);
});
if (window.mermaid && mermaidBlocks.length > 0) {
const isLight = document.body.classList.contains('light-theme');
mermaid.initialize({
startOnLoad: false,
theme: isLight ? 'default' : 'dark',
securityLevel: 'loose'
});
mermaid.run();
}
});
// Search Input Filter
const searchInput = document.getElementById('sidebar-search');
// Cache details elements open state
document.querySelectorAll('.nav-dir details').forEach(details => {
details.dataset.initiallyOpen = details.open;
});
searchInput.addEventListener('input', function(e) {
const query = e.target.value.toLowerCase().trim();
const fileItems = document.querySelectorAll('.nav-file');
const dirItems = document.querySelectorAll('.nav-dir');
if (!query) {
// Show everything, restore original details state
fileItems.forEach(item => item.style.display = '');
dirItems.forEach(item => {
item.style.display = '';
const details = item.querySelector('details');
if (details) {
details.open = details.dataset.initiallyOpen === 'true';
}
});
return;
}
// First, hide all directories and files
fileItems.forEach(item => item.style.display = 'none');
dirItems.forEach(item => item.style.display = 'none');
// Show matching files and their parent directories
fileItems.forEach(item => {
const text = item.textContent.toLowerCase();
const link = item.querySelector('a');
const url = link ? link.getAttribute('href').toLowerCase() : '';
if (text.includes(query) || url.includes(query)) {
item.style.display = '';
// Traverse up and show parent directories, and open them
let parent = item.parentElement;
while (parent) {
if (parent.classList.contains('nav-dir')) {
parent.style.display = '';
const details = parent.querySelector('details');
if (details) details.open = true;
}
parent = parent.parentElement;
}
}
});
});
// Copy Code Button Logic
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.markdown-body pre').forEach(pre => {
// Skip if it is within a mermaid block
if (pre.parentNode.classList.contains('mermaid')) return;
// Wrap pre in a div.code-wrapper
const wrapper = document.createElement('div');
wrapper.className = 'code-wrapper';
pre.parentNode.insertBefore(wrapper, pre);
wrapper.appendChild(pre);
// Create copy button
const btn = document.createElement('button');
btn.className = 'copy-btn';
btn.innerHTML = 'Copy';
wrapper.appendChild(btn);
btn.addEventListener('click', () => {
const code = pre.querySelector('code') ? pre.querySelector('code').innerText : pre.innerText;
navigator.clipboard.writeText(code).then(() => {
btn.innerHTML = 'Copied!';
btn.classList.add('copied');
setTimeout(() => {
btn.innerHTML = 'Copy';
btn.classList.remove('copied');
}, 2000);
});
});
});
});
</script>
</body>
</html>
+387
View File
@@ -0,0 +1,387 @@
import os
import sys
import re
import mimetypes
import urllib.parse
import posixpath
from http.server import HTTPServer, BaseHTTPRequestHandler
import markdown
# Configurable paths
DOCS_ROOT = os.path.realpath(os.environ.get("DOCS_ROOT", "/docs"))
PORT = int(os.environ.get("PORT", "8000"))
# Read layout template
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'layout.html')
try:
with open(TEMPLATE_PATH, 'r', encoding='utf-8') as f:
TEMPLATE = f.read()
except OSError:
print(f"Error: Could not read template from {TEMPLATE_PATH}", file=sys.stderr)
TEMPLATE = "<html><body>{{ content }}</body></html>"
def is_safe_path(path):
"""Ensure the path is within the DOCS_ROOT directory to prevent traversal."""
real_path = os.path.realpath(path)
return real_path == DOCS_ROOT or real_path.startswith(DOCS_ROOT + os.sep)
def get_breadcrumbs(url_path):
"""Generate beautiful navigation breadcrumbs."""
parts = [p for p in url_path.split('/') if p]
breadcrumbs_html = '<a href="/">Home</a>'
current_acc = ""
for i, part in enumerate(parts):
current_acc += f"/{part}"
breadcrumbs_html += ' <span class="separator">/</span> '
if i == len(parts) - 1:
breadcrumbs_html += f'<span class="current">{part}</span>'
else:
breadcrumbs_html += f'<a href="{current_acc}">{part}</a>'
return breadcrumbs_html
def build_tree(path):
"""Recursively build a tree of folders and markdown files."""
items = []
try:
names = os.listdir(path)
except OSError:
return []
for name in names:
if name.startswith('.'):
continue
if name in ('node_modules', 'venv', '.git', '__pycache__', 'data'):
continue
full_path = os.path.join(path, name)
rel_path = os.path.relpath(full_path, DOCS_ROOT)
if os.path.isdir(full_path):
children = build_tree(full_path)
# Only list directory if it contains markdown files or subdirs with markdown files
if children:
items.append({
'name': name,
'type': 'dir',
'rel_path': rel_path.replace(os.sep, '/'),
'children': children
})
elif name.endswith('.md'):
url_name = name[:-3]
# Handle root readme differently or filter it
if url_name.lower() in ('readme', 'index') and rel_path == name:
# We skip showing root readme directly in sidebar tree to prevent clutter,
# as it is already mapped to the Home button.
continue
# Form clean url
url_path = os.path.splitext(rel_path)[0]
url = '/' + url_path.replace(os.sep, '/')
# If it's a subdirectory README, we want to link it to the folder URL
if url_name.lower() in ('readme', 'index'):
parent_dir = os.path.dirname(rel_path)
url = '/' + parent_dir.replace(os.sep, '/') if parent_dir else '/'
display_name = os.path.basename(parent_dir) if parent_dir else 'Home'
else:
display_name = url_name
items.append({
'name': display_name,
'type': 'file',
'url': url,
'rel_path': rel_path.replace(os.sep, '/')
})
# Sort folders first, then files
items.sort(key=lambda x: (0 if x['type'] == 'dir' else 1, x['name'].lower()))
return items
def render_tree(tree, active_url):
"""Render the built tree into HTML nested ul/details list."""
if not tree:
return ""
html = '<ul class="nav-list">'
for item in tree:
if item['type'] == 'dir':
# Check if active URL is nested inside this directory
active_clean = active_url.lstrip('/')
is_open = active_clean.startswith(item['rel_path'] + '/') or active_clean == item['rel_path']
open_attr = ' open' if is_open else ''
html += f'<li class="nav-dir"><details{open_attr}><summary><span class="icon">📁</span> {item["name"]}</summary>'
html += render_tree(item['children'], active_url)
html += '</details></li>'
else:
is_active = ' active' if active_url == item['url'] else ''
html += f'<li class="nav-file{is_active}"><a href="{item["url"]}"><span class="icon">📄</span> {item["name"]}</a></li>'
html += '</ul>'
return html
def process_alerts(html):
"""Convert GitHub-style alerts > [!NOTE] into beautiful callouts."""
pattern = re.compile(
r'<blockquote>\s*<p>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](.*?)</p>(.*?)</blockquote>',
re.DOTALL | re.IGNORECASE
)
def replace_alert(match):
alert_type = match.group(1).upper()
content = match.group(2).strip()
rest = match.group(3).strip()
# Colors, icons and styling
alerts = {
'NOTE': ('#3b82f6', 'ℹ️', 'Note', 'rgba(59, 130, 246, 0.08)'),
'TIP': ('#10b981', '💡', 'Tip', 'rgba(16, 185, 129, 0.08)'),
'IMPORTANT': ('#8b5cf6', '📢', 'Important', 'rgba(139, 92, 246, 0.08)'),
'WARNING': ('#f59e0b', '⚠️', 'Warning', 'rgba(245, 158, 11, 0.08)'),
'CAUTION': ('#ef4444', '🚨', 'Caution', 'rgba(239, 68, 68, 0.08)')
}
color, icon, title, bg = alerts.get(alert_type, ('#64748b', 'ℹ️', 'Note', 'rgba(100, 116, 139, 0.08)'))
full_content = content
if rest:
full_content += f"<p>{rest}</p>"
return f'''<div class="alert-box alert-{alert_type.lower()}" style="border-left: 4px solid {color}; background-color: {bg}; margin: 1.5rem 0; padding: 1rem 1.25rem; border-radius: 6px;">
<div class="alert-header" style="display: flex; align-items: center; gap: 0.5rem; font-weight: 600; color: {color}; margin-bottom: 0.5rem; font-size: 0.95rem; text-transform: uppercase; letter-spacing: 0.05em;">
<span>{icon}</span>
<span>{title}</span>
</div>
<div class="alert-body" style="font-size: 0.975rem; line-height: 1.6; color: var(--text-main); opacity: 0.9;">{full_content}</div>
</div>'''
return pattern.sub(replace_alert, html)
def generate_folder_index(folder_path, rel_url_path):
"""Renders a directory list when no index README is present."""
try:
names = os.listdir(folder_path)
except OSError:
return "<h1>Error loading directory</h1>"
names.sort()
html = f"<h1>Index of {rel_url_path}</h1>"
html += "<ul class='folder-index-list'>"
if rel_url_path != '/':
parent = posixpath.dirname(rel_url_path)
html += f"<li><span class='icon'>📁</span> <a href='{parent}'>.. (Parent Directory)</a></li>"
for name in names:
if name.startswith('.') or name in ('node_modules', 'venv', '.git', '__pycache__', 'data'):
continue
full_p = os.path.join(folder_path, name)
is_dir = os.path.isdir(full_p)
if is_dir:
url = posixpath.join(rel_url_path, name)
html += f"<li><span class='icon'>📁</span> <a href='{url}'>{name}/</a></li>"
elif name.endswith('.md'):
url_name = name[:-3]
url = posixpath.join(rel_url_path, url_name)
html += f"<li><span class='icon'>📄</span> <a href='{url}'>{url_name}</a></li>"
else:
url = posixpath.join(rel_url_path, name)
html += f"<li><span class='icon'>📎</span> <a href='{url}'>{name}</a></li>"
html += "</ul>"
return html
class DocsHTTPHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
# Override to log cleanly to stdout/stderr
sys.stdout.write("%s - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_string(),
format%args))
def resolve_url_to_file(self, path_str):
"""Maps HTTP path to filesystem path inside DOCS_ROOT."""
path_str = urllib.parse.unquote(path_str)
parsed = urllib.parse.urlparse(path_str)
clean_path = posixpath.normpath(parsed.path)
if clean_path.startswith('../') or '/../' in clean_path:
return None, None, False
rel_path = clean_path.lstrip('/')
# If accessing root directory
if not rel_path:
for name in ('README.md', 'index.md', 'readme.md', 'README.markdown', 'readme.markdown'):
full_p = os.path.join(DOCS_ROOT, name)
if os.path.isfile(full_p):
return full_p, '/', True
# No root readme, return DOCS_ROOT directory for auto-index
return DOCS_ROOT, '/', False
full_p = os.path.join(DOCS_ROOT, rel_path)
# 1. Direct file check
if os.path.isfile(full_p):
is_md = full_p.endswith('.md') or full_p.endswith('.markdown')
return full_p, '/' + rel_path, is_md
# 2. Check path + .md
if not rel_path.endswith('.md'):
md_path = full_p + '.md'
if os.path.isfile(md_path):
return md_path, '/' + rel_path, True
# 3. Check directory
if os.path.isdir(full_p):
for name in ('README.md', 'index.md', 'readme.md'):
sub_p = os.path.join(full_p, name)
if os.path.isfile(sub_p):
return sub_p, '/' + rel_path, True
# Folder without index README, serve directory index page
return full_p, '/' + rel_path, False
return None, '/' + rel_path, False
def do_GET(self):
filepath, active_url, is_md = self.resolve_url_to_file(self.path)
if not filepath or not is_safe_path(filepath):
self.render_error(404, "Page Not Found", active_url)
return
# Serve static asset
if not is_md and os.path.isfile(filepath):
self.serve_static_file(filepath)
return
# Serve Markdown or Directory Index
if is_md:
try:
with open(filepath, 'r', encoding='utf-8') as f:
md_content = f.read()
except OSError:
self.render_error(500, "Internal Server Error - Could not read file", active_url)
return
# Render Markdown
md = markdown.Markdown(extensions=['extra', 'toc', 'nl2br'])
html_content = md.convert(md_content)
html_content = process_alerts(html_content)
toc_html = md.toc
has_toc = 'href=' in toc_html
title = os.path.basename(filepath)
if title.endswith('.md'):
title = title[:-3]
if title.lower() in ('readme', 'index'):
parent_dir = os.path.basename(os.path.dirname(filepath))
title = parent_dir if parent_dir else "Home"
else:
# Renders folder directory index
html_content = generate_folder_index(filepath, active_url)
toc_html = ""
has_toc = False
title = os.path.basename(filepath) or "Index"
# Generate Sidebar tree
sidebar_tree_data = build_tree(DOCS_ROOT)
sidebar_html = render_tree(sidebar_tree_data, active_url)
# Build breadcrumbs
breadcrumbs = get_breadcrumbs(active_url)
# Render page using layout
page_html = TEMPLATE
page_html = page_html.replace('{{ title }}', title)
page_html = page_html.replace('{{ home_active }}', ' active' if active_url == '/' else '')
page_html = page_html.replace('{{ sidebar_tree }}', sidebar_html)
page_html = page_html.replace('{{ breadcrumbs }}', breadcrumbs)
page_html = page_html.replace('{{ content }}', html_content)
page_html = page_html.replace('{{ toc }}', toc_html)
page_html = page_html.replace('{{ grid_class }}', ' has-toc' if has_toc else '')
# Conditional template logic for TOC
if has_toc:
page_html = page_html.replace('{% if has_toc %}', '').replace('{% endif %}', '')
else:
page_html = re.sub(r'{% if has_toc %}.*?{% endif %}', '', page_html, flags=re.DOTALL)
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
self.end_headers()
self.wfile.write(page_html.encode('utf-8'))
def serve_static_file(self, filepath):
try:
with open(filepath, 'rb') as f:
content = f.read()
except OSError:
self.send_error(404, "File not found")
return
self.send_response(200)
ctype, _ = mimetypes.guess_type(filepath)
if not ctype:
ctype = 'application/octet-stream'
self.send_header('Content-Type', ctype)
self.send_header('Content-Length', str(len(content)))
self.send_header('Cache-Control', 'public, max-age=600')
self.end_headers()
self.wfile.write(content)
def render_error(self, code, message, active_url):
# Render a nice formatted error inside the layout
error_html = f'''
<div style="text-align: center; padding: 4rem 2rem;">
<h1 style="font-size: 5rem; background: var(--accent-gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 1rem;">{code}</h1>
<p style="font-size: 1.25rem; color: var(--text-muted); margin-bottom: 2rem;">{message}</p>
<a href="/" style="display: inline-block; background: var(--accent-gradient); color: white; padding: 0.75rem 1.5rem; border-radius: 6px; font-weight: 600; text-decoration: none;">Go Home</a>
</div>
'''
sidebar_tree_data = build_tree(DOCS_ROOT)
sidebar_html = render_tree(sidebar_tree_data, active_url)
breadcrumbs = get_breadcrumbs(active_url)
page_html = TEMPLATE
page_html = page_html.replace('{{ title }}', f"Error {code}")
page_html = page_html.replace('{{ home_active }}', '')
page_html = page_html.replace('{{ sidebar_tree }}', sidebar_html)
page_html = page_html.replace('{{ breadcrumbs }}', breadcrumbs)
page_html = page_html.replace('{{ content }}', error_html)
page_html = page_html.replace('{{ toc }}', '')
page_html = page_html.replace('{{ grid_class }}', '')
page_html = re.sub(r'{% if has_toc %}.*?{% endif %}', '', page_html, flags=re.DOTALL)
self.send_response(code)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write(page_html.encode('utf-8'))
def run_server():
server_address = ('', PORT)
httpd = HTTPServer(server_address, DocsHTTPHandler)
print(f"Starting markdown docs server on port {PORT}...")
print(f"Serving files from {DOCS_ROOT}")
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
print("\nStopping server.")
if __name__ == '__main__':
run_server()
+71
View File
@@ -0,0 +1,71 @@
# 📝 Documentation Viewer
Self-hosted local documentation viewer. This service serves markdown files from a designated directory as a lightweight, reactive HTML site with instant reloads.
> [!NOTE]
> Any changes you made to the markdown files in the documentation directory will show up here immediately upon refreshing the page. No rebuild steps, no compilation delay.
---
## 🚀 Getting Started
To mount your project documentation, configure the following environment variables in your deployment setup:
1. **`DOCS_DOMAIN`**: The domain you want Traefik to route to this viewer (e.g. `docs.homelab.local`).
2. **`DOCS_PROJECT_PATH`**: The absolute path on your host machine pointing to your markdown files (e.g. `/home/kiskaadee/Projects/my-app/docs`).
For example, when using the repository's `appctl` CLI wrapper:
```bash
# Sourcing environment, appctl maps:
# DOCS_PROJECT_PATH -> PROJECT_PATH
./appctl up docs
```
---
## 🛠️ Features
Here is a breakdown of what this documentation server provides out-of-the-box:
### 1. Dynamic Routing
- `GET /` resolves to `README.md` or `index.md` at your documentation root.
- `GET /docs/infra` matches `docs/infra.md` or `docs/infra/README.md`.
- Clicking directories with no `README.md` serves an automatic, styled list of that folder's contents.
### 2. Search & Sidebar Navigation
- The sidebar dynamically scans the directories of your project workspace for `.md` files.
- You can filter documentation files instantly using the **Search** input at the top of the sidebar. It searches across names and URLs.
### 3. Sleek Themes (Light & Dark)
- Persisted theme settings using `localStorage`.
- Click the toggle button in the bottom-left corner of the sidebar to switch between a gorgeous dark slate mode and a clean light mode.
### 4. Code Highlight & Copy
- Code blocks are automatically highlighted with Prism.js.
- Hovering over a code block shows a **Copy** button to copy code instantly.
```python
# Test Python block
def hello_world():
print("Welcome to your local docs!")
return True
```
### 5. Mermaid.js Support
You can render flowcharts, sequence diagrams, and class diagrams directly inside your markdown pages using standard fenced code blocks labeled `mermaid`.
```mermaid
graph TD
A[Browse Docs] -->|GET /path| B(Safe Path Resolver)
B -->|Found .md| C{Render Markdown}
B -->|Found Folder| D[Generate Directory Listing]
C -->|Parse HTML| E[Inject layout.html Template]
D -->|Inject list| E
E -->|Serve Browser| F((Wow User!))
```
### 6. Alert Callouts
Use standard GitHub alert formatting to highlight notices:
> [!TIP]
> Use callout boxes to highlight important tips, warnings, or caution sections. They render with custom icons and borders.
+31
View File
@@ -0,0 +1,31 @@
services:
docs:
build: .
container_name: ${SERVICE_NAME}
restart: unless-stopped
volumes:
- ${PROJECT_PATH:-./data}:/docs:ro
environment:
- DOCS_ROOT=/docs
- PORT=8000
networks:
- proxy
labels:
- "traefik.enable=true"
- "traefik.http.routers.${SERVICE_NAME}.rule=Host(`${SERVICE_DOMAIN}`)"
- "traefik.http.routers.${SERVICE_NAME}.entrypoints=websecure"
- "traefik.http.routers.${SERVICE_NAME}.tls=true"
- "traefik.http.routers.${SERVICE_NAME}.service=${SERVICE_NAME}-svc"
# HTTP to HTTPS redirect
- "traefik.http.routers.${SERVICE_NAME}-red.rule=Host(`${SERVICE_DOMAIN}`)"
- "traefik.http.routers.${SERVICE_NAME}-red.entrypoints=web"
- "traefik.http.routers.${SERVICE_NAME}-red.middlewares=https-redirect@docker"
# Target Port
- "traefik.http.services.${SERVICE_NAME}-svc.loadbalancer.server.port=8000"
networks:
proxy:
name: ${PROXY_NETWORK}
external: true