Compare commits

..
11 Commits
Author SHA1 Message Date
IgorMino b92aedb7d8 odstranene podmienky na document root 2026-11-06 10:25:29 +01:00
IgorMino a9022e1fb2 includovanie CSS a JS do vystupneho HTML aby nebolo potrebne linkovat subory 2026-11-06 10:07:37 +01:00
Agent 81e31a5468 Document Markdown path and raw HTML invariants 2026-11-06 09:34:50 +01:00
Agent 6ffd8b89ef Document MD2HTML FastCGI routing and asset URLs 2026-11-06 09:34:44 +01:00
Agent 9d324e32a4 Resolve Markdown paths safely across Linux and Windows 2026-11-06 09:34:39 +01:00
IgorMino 715a0e354b pridaná generovaná navigácia z H1–H3 s unikátnymi ID,
pridaný responzívny panel a ukladanie stavu podľa URL,
pridané verzovanie CSS a JS pomocou MD5 hashov,
aktualizovaná dokumentácia
2026-10-26 19:08:34 +01:00
IgorMino 7b39f26c99 ukazka NGINX konfiguracie 2026-10-26 18:48:30 +01:00
IgorMino 58e3a7503c presunute zdrojove kody do ./src/ 2026-10-26 18:44:34 +01:00
IgorMino 6c6a6c7dfe inicializacia do existujuceho adresara
Merge branch 'main' of https://gitea.tpsoft.org/TPsoft.org/MD2HTML
2026-10-26 18:37:21 +01:00
IgorMino e7fad18c7e Remove vendor from tracking and update gitignore 2026-10-26 18:34:37 +01:00
IgorMino 80594366b7 Initial commit 2026-10-26 18:33:57 +01:00
9 changed files with 841 additions and 1 deletions
+2
View File
@@ -0,0 +1,2 @@
"/vendor/"
/vendor
+69
View File
@@ -0,0 +1,69 @@
# AGENTS.md
## Purpose
This project is a small Markdown-to-HTML utility used behind NGINX.
When a `.md` file is requested, `src/md2html.php` loads the Markdown, converts it with Parsedown, and renders HTML styled by `src/markdown.css`.
`src/toc.js` builds an interactive table of contents from the rendered headings.
## Key Files
- `src/md2html.php`: entrypoint for conversion and HTML output.
- `src/markdown.css`: visual styling for rendered Markdown (`.markdown-body`).
- `src/toc.js`: vanilla JavaScript for the table of contents and per-document panel state.
- `composer.json`: PHP dependency config (`erusev/parsedown`).
- An optional local `tests/` suite covers PHP rendering and TOC behavior with DOM doubles.
## Environment Assumptions
- NGINX supplies the original request URI and the site document root via FastCGI.
- The project can live outside the document root. PHP embeds local CSS/JS into HTML; no static asset URLs are required.
- External symlinks and junctions work without per-prefix configuration, subject to PHP filesystem access.
## Change Priorities
1. Keep output readable on desktop and mobile.
2. Preserve Markdown semantics generated by Parsedown.
3. Keep JavaScript in `src/toc.js`, use vanilla JavaScript, and avoid unnecessary dependencies.
4. Keep the utility simple and fast.
## Styling Rules (`src/markdown.css`)
- Style only inside `.markdown-body` unless there is a strong reason to change global page behavior.
- Navigation is outside `.markdown-body`; scope its styles to `.md2html-toc*` and `.md2html-document` where possible.
- At widths above 760px, the open panel must leave space for the document; at smaller widths, use a dismissible overlay.
- Keep the toggle fixed and available, the panel independently scrollable, and reduced-motion preferences respected.
- Must cover: headings, links, lists, blockquotes, inline code, code blocks, tables, images, hr.
- Keep strong contrast and accessible font sizes.
- Ensure long code lines and wide tables remain usable on small screens (`overflow-x`).
- Prefer CSS variables for colors and spacing to simplify future theme changes.
## PHP Rules (`src/md2html.php`)
- Keep dependency loading via the project root's `vendor/autoload.php`, resolved relative to the entrypoint directory.
- Keep response minimal: `<!doctype html>`, UTF-8 and viewport meta, inline style, navigation controls, wrapped content, and inline script after the content.
- Load CSS and JS from paths relative to `__DIR__`; safely escape closing script tags when embedding JavaScript.
- Do not assign anonymous functions or closures to PHP variables; use named functions or class methods.
- Output helpers should return rendered content for callers to consume.
- Validate the decoded URL path, including the `.md` extension, before filesystem lookup. Query parameters must never select a file.
- Require a regular Markdown file after canonical resolution; symlink and junction targets may lie outside the document root.
- Keep path handling compatible with Linux and Windows, including symlink and junction resolution.
- Keep Parsedown raw HTML rendering enabled. Serve Markdown from trusted sources.
## Table of Contents Rules (`src/toc.js`)
- Build navigation from rendered H1–H3 in `.markdown-body`, preserving order and indicating levels with indentation. Do not add a Markdown parser.
- Keep existing unique IDs, generate collision-free IDs for other headings, and retain native anchor navigation.
- Use DOM creation and `textContent` for heading labels; do not insert untrusted content through `innerHTML`.
- Default to closed. Store panel state under `md2html:toc:` + pathname + query string, excluding the fragment.
- Handle unavailable localStorage without disabling navigation.
- Maintain ARIA state, keyboard access, Escape dismissal, mobile close controls, and readable output without JavaScript.
## Validation After Edits
- Never use a browser or browser automation. Leave visual browser verification to Igor; use non-browser checks instead.
- Run relevant checks from the project root:
- `php -l src/md2html.php`
- `node --check src/toc.js`
- `./tests/run.ps1` when the local suite is available
- `git diff --check`
- Tests require PHP with DOM, Composer dependencies, and Node.js supporting `node:test` and `--test-isolation=none`.
- Keep regression coverage for heading levels, formatting, code fences, duplicate and existing anchors, Unicode, empty and long contents, URL-specific state, blocked storage, mobile dismissal, inline assets, script escaping, and the `.md` guard.
- DOM doubles do not verify actual layout or scrolling. Igor manually checks desktop/mobile layout, long-panel scrolling, anchor navigation, and readability of Markdown elements.
## Non-Goals
- Building a full CMS.
- Adding heavy frontend frameworks.
- Replacing Parsedown unless explicitly requested.
+101 -1
View File
@@ -1,3 +1,103 @@
# MD2HTML
Koverzia Markdown do HTML, pouzitelne aj pre priame zobrazovanie Markdown suborov pomocou webservera.
Malý nástroj na zobrazovanie Markdown súborov cez NGINX. PHP načíta dokument podľa URL, prevedie ho pomocou Parsedown a vráti samostatné HTML s responzívnym vzhľadom a interaktívnym obsahom z nadpisov H1 až H3.
## Požiadavky a inštalácia
- PHP 8.0 alebo novšie s rozšírením `mbstring`, pre NGINX aj PHP-FPM alebo FastCGI.
- Composer na inštaláciu serverovej knižnice Parsedown.
- NGINX a účet PHP s právom čítať projekt aj publikované dokumenty.
V koreňovom adresári projektu spusti:
```sh
composer install
```
Projekt môže byť mimo webového koreňa. Nasadzuj `src/` aj `vendor/`; autoload sa načítava relatívne k PHP vstupnému bodu.
- `src/md2html.php`: výber dokumentu, konverzia a generovanie HTML.
- `src/markdown.css`: štýly, ktoré PHP vloží priamo do `<style>`.
- `src/toc.js`: vlastný JavaScript, ktorý PHP vloží do `<script>` za dokumentom.
CSS a JavaScript sú súčasťou každej HTML odpovede. Nie sú potrebné samostatné URL ani NGINX pravidlá pre statické súbory nástroja. Zdrojové CSS/JS zostávajú na serveri, ale klient ich samostatne nenačítava. Zmenený obsah sa vloží do ďalšej odpovede.
## Konfigurácia NGINX
Spoločný snippet [`nginx/md2html.conf`](nginx/md2html.conf) includuj do každého `server` bloku, kde chceš zobrazovať Markdown. Cestu k PHP súboru a PHP-FPM socket nastavíš v snippete iba raz:
```nginx
location ~* \.md$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /storage/tpsoft.org/MD2HTML/src/md2html.php;
fastcgi_pass unix:/run/php/php8.4-fpm.sock;
}
```
Konfigurácia jednotlivých webov potom obsahuje iba ich vlastný koreň a spoločný include:
```nginx
server {
listen 80;
server_name example.com;
root /storage/www;
include /storage/tpsoft.org/MD2HTML/nginx/md2html.conf;
}
server {
listen 80;
server_name docs.example.com;
root /storage/docs;
include /storage/tpsoft.org/MD2HTML/nginx/md2html.conf;
}
```
Existujúce nastavenia domény, HTTPS a ostatných ciest ponechaj v príslušnom `server` bloku. Snippet používa jeho `root`, takže každý web číta dokumenty dostupné cez svoj koreň vrátane symlinkov. Includuj ho priamo do `server`, iba raz, pred prípadnými všeobecnejšími regulárnymi `location` pravidlami. Prefixové pravidlá s `^~` môžu spracovanie Markdownu v danom prefixe potlačiť.
Uprav cesty a socket podľa servera. `fastcgi_params` musí odovzdávať `REQUEST_URI $request_uri` a `DOCUMENT_ROOT $document_root` a nesmie pridávať inú hodnotu `SCRIPT_FILENAME`. Vo Windows použi napríklad `include D:/www/md2html/nginx/md2html.conf;`; v snippete nastav `fastcgi_param SCRIPT_FILENAME D:/www/md2html/src/md2html.php;` a `fastcgi_pass 127.0.0.1:9999;` podľa nastavenia PHP. Koreň každého webu zostáva v jeho `server` bloku.
Po úprave konfigurácie ju over cez `nginx -t` a načítaj cez `nginx -s reload`. Správanie `include` a výber `location` opisuje [oficiálna dokumentácia NGINX](https://nginx.org/en/docs/beginners_guide.html).
### Symlinky a junctiony
Ľubovoľný počet existujúcich symlinkov alebo Windows junctionov funguje cez ten istý snippet, aj keď ich ciele ležia mimo `DOCUMENT_ROOT`. Nie sú potrebné pravidlá ani povolenia pre jednotlivé prefixy. Napríklad pri `root /storage/www;`:
- `/storage/www/polyanalyzer` → `/storage/tpsoft.org/polymarket-analyzer/reports`: URL `/polyanalyzer/report.md`.
- `/storage/www/manualy` → `/storage/manualy`: URL `/manualy/navod.md`.
PHP vyhodnotí skutočný cieľ a načíta ho, ak ide o regulárny `.md` súbor a má k nemu prístup. Kontroluje sa prípona v URL aj prípona cieľového súboru. Cieľ nemusí ležať pod webovým koreňom. Prístup naďalej podlieha oprávneniam účtu PHP, prípadnému `open_basedir` a izolácii PHP-FPM.
URL sa stále mapuje cez koreň webu: absolútnu diskovú cestu ani parameter `file` nemožno použiť na výber súboru. Externé dokumenty sprístupni cez symlink alebo junction. Neplatné URL vrátane segmentov `..` zostávajú odmietnuté.
## Používanie a offline zobrazenie
Pre súbor `/storage/www/docs/navod.md` otvor napríklad `https://example.com/docs/navod.md`. URL `https://example.com/docs/navod.md?view=print#instalacia` načíta ten istý súbor; query string ani parameter `file` nevyberajú dokument. Cez existujúci symlink možno používať aj `https://example.com/polyanalyzer/report.md`.
PHP prijíma regulárne `.md` súbory dostupné cez URL cestu pod webovým koreňom vrátane symlinkov a junctionov smerujúcich mimo neho. Neplatné a nenájdené cesty vracajú 404.
HTML odpoveď možno uložiť ako `.html` a otvoriť bez internetu. Vlastný vzhľad ani ovládanie nástroja nepotrebujú sieť, externé fonty, obrázky, ikony ani JS knižnice. Používajú sa systémové fonty a textové symboly. Podporované sú nadpisy, odseky, zoznamy, tabuľky, citácie a bloky kódu; automatické syntax highlighting nie je implementované. Markdown obsah sa nevkladá do JavaScriptového kódu. Uzatváracie tagy skriptu v jeho zdroji sú escapované.
Odkazy, obrázky a surové HTML z Markdown dokumentu zostávajú zachované. Ich prípadné externé zdroje sa nebaľujú do HTML a môžu potrebovať sieť alebo pôvodné relatívne cesty. Offline záruka sa týka vlastných štýlov a ovládania nástroja. Parsedown aj naďalej povoľuje surové HTML, preto publikuj iba dôveryhodný Markdown. Webový koreň, ciele symlinkov aj nadradené adresáre musia spravovať dôveryhodní používatelia. Vo Windows používaj lokálne cesty s písmenom jednotky; vyhni sa UNC cestám a bodom pripojenia zväzkov.
Ak server pridáva Content-Security-Policy, musí povoľovať tieto inline štýly a skripty; nástroj sám CSP hlavičku nenastavuje.
## Obsah dokumentu
Tlačidlo vľavo hore otvorí obsah z nadpisov H1 až H3. Na desktope panel uvoľní miesto vedľa dokumentu, na mobile tvorí prekrytie. Má vlastné scrollovanie; zatvára sa tlačidlom, Escape alebo na mobile kliknutím mimo panelu či na odkaz. Jednoznačné existujúce ID nadpisov zostávajú zachované a ostatné sú generované bez kolízií. Odkazy používajú natívnu navigáciu na fragmenty.
Stav sa ukladá do localStorage pod kľúčom `md2html:toc:` + pathname + query string, bez fragmentu. Pri blokovanom úložisku ovládanie funguje ďalej. Bez JavaScriptu zostáva dokument čitateľný a navigačné ovládanie skryté.
## Testovanie
Sada `tests/` vyžaduje PHP s `mbstring` a DOM, Composer závislosti a Node.js s podporou `node:test` a `--test-isolation=none`. Z koreňa v PowerShelli spusti:
```powershell
php -l src/md2html.php
node --check src/toc.js
./tests/run.ps1
git diff --check
```
Testy overujú skutočný výstup Parsedown, vložené CSS/JS bez externých odkazov, absenciu sieťového načítavania vo vlastných zdrojoch, escapovanie `</script>`, diakritiku, surové HTML, URL guard a obsah dokumentu pomocou DOM modelu. Overujú aj dva externé symlinky (vo Windows junctiony) mimo testovacieho webového koreňa a odmietnutie adresárov, chýbajúcich súborov a súborov bez prípony `.md`. Spúšťajú JavaScript extrahovaný z generovanej HTML odpovede bez sieťových API. Nepoužívajú prehliadač ani ďalšie balíčky.
Skutočné rozloženie, scrollovanie, offline otvorenie uloženého HTML a desktopové/mobilné ovládanie manuálne overuje Igor. Lokálna sada neoveruje bežiaci NGINX ani produkčné HTTP hlavičky.
+19
View File
@@ -0,0 +1,19 @@
{
"name": "igor/md2html",
"type": "project",
"license": "MIT",
"autoload": {
"psr-4": {
"Igor\\Md2html\\": "src/"
}
},
"authors": [
{
"name": "igor",
"email": "mino@tpsoft.org"
}
],
"require": {
"erusev/parsedown": "^1.7"
}
}
Generated
+69
View File
@@ -0,0 +1,69 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "9b8ae6f7614e5b41ba18814b6b6e7bb1",
"packages": [
{
"name": "erusev/parsedown",
"version": "1.7.4",
"source": {
"type": "git",
"url": "https://github.com/erusev/parsedown.git",
"reference": "cb17b6477dfff935958ba01325f2e8a2bfa6dab3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/erusev/parsedown/zipball/cb17b6477dfff935958ba01325f2e8a2bfa6dab3",
"reference": "cb17b6477dfff935958ba01325f2e8a2bfa6dab3",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35"
},
"type": "library",
"autoload": {
"psr-0": {
"Parsedown": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Emanuil Rusev",
"email": "hello@erusev.com",
"homepage": "http://erusev.com"
}
],
"description": "Parser for Markdown.",
"homepage": "http://parsedown.org",
"keywords": [
"markdown",
"parser"
],
"support": {
"issues": "https://github.com/erusev/parsedown/issues",
"source": "https://github.com/erusev/parsedown/tree/1.7.x"
},
"time": "2019-12-30T22:54:17+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {},
"platform-dev": {},
"plugin-api-version": "2.6.0"
}
+7
View File
@@ -0,0 +1,7 @@
# Include inside each server that should render Markdown.
# Configure the shared MD2HTML path and PHP-FPM endpoint for this machine.
location ~* \.md$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /storage/tpsoft.org/MD2HTML/src/md2html.php;
fastcgi_pass unix:/run/php/php8.4-fpm.sock;
}
+388
View File
@@ -0,0 +1,388 @@
:root {
--page-bg: #f4efe8;
--paper-bg: #fffdf9;
--text: #24201c;
--muted: #6a5f52;
--line: #ddd3c5;
--accent: #0f6d8a;
--accent-soft: #d9eef4;
--quote-bg: #f4f8fa;
--code-bg: #1f2328;
--code-text: #f4f6f8;
--toc-width: 19rem;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
font-size: 17px;
line-height: 1.65;
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
color: var(--text);
background:
radial-gradient(circle at 15% 10%, #f8f2e8 0%, transparent 35%),
radial-gradient(circle at 90% 0%, #e4eef2 0%, transparent 30%),
var(--page-bg);
font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif;
}
.markdown-body {
width: min(90%, calc(100% - 2rem));
margin: 2.5rem auto 3rem;
padding: 2.25rem clamp(1.1rem, 2vw, 2.5rem);
background: var(--paper-bg);
border: 1px solid #ece3d6;
border-radius: 18px;
box-shadow:
0 12px 30px rgba(64, 49, 33, 0.08),
0 2px 6px rgba(64, 49, 33, 0.06);
}
.markdown-body > *:first-child {
margin-top: 0;
}
.markdown-body > *:last-child {
margin-bottom: 0;
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
font-family: "Avenir Next", "Segoe UI", "Trebuchet MS", sans-serif;
line-height: 1.22;
letter-spacing: 0.01em;
color: #1f2b33;
margin-top: 2.2rem;
margin-bottom: 0.85rem;
}
.markdown-body h1 {
font-size: clamp(2rem, 3.5vw, 2.8rem);
margin-top: 0.4rem;
padding-bottom: 0.45rem;
border-bottom: 2px solid var(--line);
}
.markdown-body h2 {
font-size: clamp(1.55rem, 2.3vw, 2rem);
padding-bottom: 0.3rem;
border-bottom: 1px solid var(--line);
}
.markdown-body h3 {
font-size: clamp(1.24rem, 1.8vw, 1.5rem);
}
.markdown-body h4 {
font-size: 1.13rem;
}
.markdown-body h5,
.markdown-body h6 {
font-size: 1rem;
color: #384a56;
}
.markdown-body p,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body table,
.markdown-body blockquote {
margin: 1rem 0;
}
.markdown-body ul,
.markdown-body ol {
padding-left: 1.55rem;
}
.markdown-body li + li {
margin-top: 0.35rem;
}
.markdown-body a {
color: var(--accent);
text-decoration-thickness: 0.08em;
text-underline-offset: 0.13em;
}
.markdown-body a:hover {
color: #0a546a;
background: var(--accent-soft);
}
.markdown-body hr {
border: 0;
height: 1px;
margin: 2rem 0;
background: linear-gradient(to right, transparent, var(--line), transparent);
}
.markdown-body blockquote {
padding: 0.8rem 1rem 0.8rem 1.2rem;
border-left: 4px solid #8db9c8;
background: var(--quote-bg);
color: #30414e;
border-radius: 0 10px 10px 0;
}
.markdown-body code {
font-family: "JetBrains Mono", "Consolas", "Courier New", monospace;
font-size: 0.9em;
background: #efe7d9;
border-radius: 6px;
padding: 0.1em 0.35em;
}
.markdown-body pre {
background: var(--code-bg);
color: var(--code-text);
border-radius: 12px;
padding: 1rem 1.1rem;
overflow-x: auto;
margin: 1.25rem 0;
}
.markdown-body pre code {
background: transparent;
color: inherit;
padding: 0;
font-size: 0.9rem;
}
.markdown-body table {
width: 100%;
border-collapse: collapse;
display: block;
overflow-x: auto;
border: 1px solid var(--line);
border-radius: 10px;
}
.markdown-body th,
.markdown-body td {
border: 1px solid var(--line);
padding: 0.55rem 0.7rem;
text-align: left;
}
.markdown-body th {
font-family: "Avenir Next", "Segoe UI", "Trebuchet MS", sans-serif;
background: #f3eee5;
}
.markdown-body img {
max-width: 100%;
height: auto;
display: block;
margin: 1rem auto;
border-radius: 10px;
box-shadow: 0 5px 18px rgba(20, 22, 26, 0.14);
}
.markdown-body strong {
color: #1e1a14;
}
.markdown-body em {
color: #5b4f40;
}
.markdown-body :target {
scroll-margin-top: 4.5rem;
animation: mark-target 1.2s ease;
}
/* Navigation lives outside the rendered Markdown. */
.md2html-document {
transition: margin-left 200ms ease;
}
.markdown-body :is(h1, h2, h3) {
scroll-margin-top: 4.5rem;
}
html:has(.md2html-toc-ready) {
scroll-behavior: smooth;
}
.md2html-toc-toggle,
.md2html-toc-close {
display: inline-grid;
place-items: center;
width: 2.75rem;
height: 2.75rem;
padding: 0;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--accent);
background: var(--paper-bg);
font: 1.25rem/1 sans-serif;
cursor: pointer;
}
.md2html-toc-toggle {
position: fixed;
top: 0.75rem;
left: 0.75rem;
z-index: 30;
box-shadow: 0 2px 6px #40312118;
}
.md2html-toc-toggle[hidden],
.md2html-toc[hidden],
.md2html-toc-backdrop[hidden] {
display: none;
}
.md2html-toc-toggle[aria-expanded="true"] {
color: var(--paper-bg);
background: var(--accent);
}
.md2html-toc :is(a, button):focus-visible,
.md2html-toc-toggle:focus-visible {
outline: 3px solid var(--accent);
outline-offset: 2px;
}
.md2html-toc {
position: fixed;
z-index: 20;
top: 4rem;
bottom: 1rem;
left: 0.75rem;
width: var(--toc-width);
max-width: calc(100% - 4.5rem);
max-height: calc(100vh - 5rem);
max-height: calc(100dvh - 5rem);
overflow-y: auto;
overscroll-behavior: contain;
padding: 1rem;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--paper-bg);
box-shadow: 0 8px 24px #40312120;
font: 0.95rem/1.5 "Segoe UI", sans-serif;
overflow-wrap: anywhere;
visibility: hidden;
transform: translateX(calc(-100% - 1rem));
transition: transform 200ms ease, visibility 200ms;
}
.md2html-toc-open .md2html-toc {
visibility: visible;
transform: translateX(0);
}
.md2html-toc-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
margin-bottom: 0.75rem;
}
.md2html-toc-close {
flex-shrink: 0;
}
.md2html-toc-list {
list-style: none;
margin: 0;
padding: 0;
}
.md2html-toc-list a {
display: block;
padding: 0.4rem 0.25rem;
color: var(--accent);
text-decoration: none;
border-radius: 4px;
}
.md2html-toc-list a:hover {
background: var(--accent-soft);
text-decoration: underline;
}
.md2html-toc-level-2 { padding-left: 1rem; }
.md2html-toc-level-3 { padding-left: 2rem; }
.md2html-toc-backdrop { display: none; }
@media (min-width: 761px) {
.md2html-toc-open .md2html-document {
margin-left: calc(var(--toc-width) + 1.5rem);
}
}
@media (max-width: 760px) {
.md2html-toc-ready .markdown-body {
margin-top: 4.25rem;
}
.md2html-toc-backdrop {
display: block;
position: fixed;
inset: 0;
z-index: 10;
background: #24201c55;
visibility: hidden;
opacity: 0;
transition: opacity 200ms ease, visibility 200ms;
}
.md2html-toc-open .md2html-toc-backdrop {
visibility: visible;
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
html:has(.md2html-toc-ready) { scroll-behavior: auto; }
.md2html-document,
.md2html-toc,
.md2html-toc-backdrop { transition: none; }
.markdown-body :target { animation: none; }
}
@keyframes mark-target {
0% {
background: #fff3c9;
}
100% {
background: transparent;
}
}
@media (max-width: 760px) {
html {
font-size: 16px;
}
.markdown-body {
width: calc(100% - 1rem);
margin: 0.75rem auto 1.2rem;
padding: 1rem;
border-radius: 14px;
}
.markdown-body pre {
border-radius: 10px;
padding: 0.85rem;
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
function canonicalPath(string $path): string|false
{
// Windows can leave another junction in the result of a single realpath().
for ($depth = 0; $depth < 32; ++$depth) {
$resolved = realpath($path);
if ($resolved === false || DIRECTORY_SEPARATOR === '/' || $resolved === $path) {
return $resolved;
}
$path = $resolved;
}
return false;
}
function requestedMarkdown(): string|false
{
$uri = explode('?', $_SERVER['REQUEST_URI'] ?? '', 2)[0];
if (preg_match('/%(?![0-9a-f]{2})/i', $uri)) {
return false;
}
$path = rawurldecode($uri);
if (!str_starts_with($path, '/') || !str_ends_with(strtolower($path), '.md')
|| str_contains($path, '\\') || preg_match('/[\x00-\x1f\x7f:]/', $path)) {
return false;
}
foreach (explode('/', substr($path, 1)) as $segment) {
if ($segment === '' || $segment === '.' || $segment === '..'
|| (DIRECTORY_SEPARATOR === '\\' && rtrim($segment, ' .') !== $segment)) {
return false;
}
}
$documentRoot = $_SERVER['DOCUMENT_ROOT'] ?? '';
if ($documentRoot === '') {
return false;
}
// Recheck symlink targets on every request, including under persistent FastCGI.
clearstatcache(true);
$root = canonicalPath($documentRoot);
if ($root === false || !is_dir($root)) {
return false;
}
// Follow symlinks/junctions even when their target is outside DOCUMENT_ROOT.
$file = canonicalPath(rtrim($root, DIRECTORY_SEPARATOR) . str_replace('/', DIRECTORY_SEPARATOR, $path));
if ($file === false || !str_ends_with(strtolower($file), '.md') || !is_file($file)) {
return false;
}
return @file_get_contents($file);
}
function inlineScript(string $source): string
{
// HTML ends a raw-text script even when the tag occurs inside a JS string/comment.
return '<script>' . preg_replace('~</(script)~i', '<\\\\/$1', $source) . '</script>';
}
$md = requestedMarkdown();
if ($md === false) {
http_response_code(404);
exit('Not found');
}
require dirname(__DIR__) . '/vendor/autoload.php';
$parser = new Parsedown();
echo '<!doctype html>';
echo '<html><head>';
echo '<meta charset="utf-8">';
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '<title>Markdown</title>';
echo '<style>' . file_get_contents(__DIR__ . '/markdown.css') . '</style>';
echo '</head><body>';
echo '<button class="md2html-toc-toggle" type="button" aria-expanded="false" aria-label="Zobraziť obsah dokumentu" hidden><span aria-hidden="true">☰</span></button>';
echo '<div class="md2html-toc-backdrop" aria-hidden="true" hidden></div>';
echo '<nav class="md2html-toc" aria-label="Obsah dokumentu" hidden>';
echo '<div class="md2html-toc-header"><strong>Obsah dokumentu</strong><button class="md2html-toc-close" type="button" aria-label="Zatvoriť obsah dokumentu">×</button></div>';
echo '<ol class="md2html-toc-list"></ol>';
echo '</nav>';
echo '<div class="md2html-document">';
echo '<div class="markdown-body">';
echo $parser->text($md);
echo '</div>';
echo '</div>';
// Inline classic scripts execute immediately; all required DOM nodes now exist.
echo inlineScript(file_get_contents(__DIR__ . '/toc.js'));
echo '</body></html>';
+94
View File
@@ -0,0 +1,94 @@
(() => {
'use strict';
const content = document.querySelector('.markdown-body');
const panel = document.querySelector('.md2html-toc');
const toggle = document.querySelector('.md2html-toc-toggle');
const close = document.querySelector('.md2html-toc-close');
const backdrop = document.querySelector('.md2html-toc-backdrop');
const list = document.querySelector('.md2html-toc-list');
if (!content || !panel || !toggle || !close || !backdrop || !list) return;
// Reserve all existing anchors, including anchors outside headings.
const usedIds = new Set(Array.from(document.querySelectorAll('[id]'), node => node.id));
function uniqueId(base) {
let id = base;
let suffix = 2;
while (usedIds.has(id)) id = `${base}-${suffix++}`;
usedIds.add(id);
return id;
}
panel.id = uniqueId('md2html-toc-panel');
toggle.setAttribute('aria-controls', panel.id);
const headings = content.querySelectorAll('h1, h2, h3');
const seenHeadingIds = new Set();
for (const heading of headings) {
const label = heading.textContent.trim() || 'Bez názvu';
if (!heading.id || seenHeadingIds.has(heading.id) || document.getElementById(heading.id) !== heading) {
const slug = label.normalize('NFC').toLowerCase()
.replace(/[^\p{L}\p{N}_-]+/gu, '-').replace(/^-+|-+$/g, '') || 'nadpis';
heading.id = uniqueId(slug);
}
seenHeadingIds.add(heading.id);
const item = document.createElement('li');
item.className = `md2html-toc-level-${heading.tagName.slice(1)}`;
const link = document.createElement('a');
link.setAttribute('href', `#${encodeURIComponent(heading.id)}`);
link.textContent = label;
link.addEventListener('click', () => {
if (window.matchMedia('(max-width: 760px)').matches) setOpen(false);
if (!heading.hasAttribute('tabindex')) heading.setAttribute('tabindex', '-1');
heading.focus({ preventScroll: true });
// Native anchor navigation updates the fragment and supports Back/Forward.
});
item.append(link);
list.append(item);
}
if (!headings.length) {
const message = document.createElement('p');
message.textContent = 'Obsah dokumentu nie je dostupný.';
list.replaceWith(message);
}
const storageKey = `md2html:toc:${window.location.pathname}${window.location.search}`;
let open = false;
function setOpen(value, persist = true) {
open = value;
document.body.classList.toggle('md2html-toc-open', open);
toggle.setAttribute('aria-expanded', String(open));
toggle.setAttribute('aria-label', open ? 'Zatvoriť obsah dokumentu' : 'Zobraziť obsah dokumentu');
panel.setAttribute('aria-hidden', String(!open));
panel.inert = !open;
if (!open && panel.contains(document.activeElement)) toggle.focus();
if (persist) {
try { window.localStorage.setItem(storageKey, String(open)); } catch { /* Storage is optional. */ }
}
}
let savedOpen = false;
try { savedOpen = window.localStorage.getItem(storageKey) === 'true'; } catch { /* Default to closed. */ }
setOpen(savedOpen, false);
panel.hidden = false;
toggle.hidden = false;
backdrop.hidden = false;
document.body.classList.add('md2html-toc-ready');
toggle.addEventListener('click', () => setOpen(!open));
close.addEventListener('click', () => { setOpen(false); toggle.focus(); });
backdrop.addEventListener('click', () => setOpen(false));
document.addEventListener('keydown', event => {
if (event.key === 'Escape' && open) {
setOpen(false);
toggle.focus();
}
});
// The browser may have tried to resolve the fragment before generated IDs existed.
if (window.location.hash) {
try {
const target = document.getElementById(decodeURIComponent(window.location.hash.slice(1)));
if (target && content.contains(target)) target.scrollIntoView();
} catch { /* Ignore malformed URL fragments. */ }
}
})();