refactor to templates

This commit is contained in:
thek4n 2026-02-20 17:56:19 +03:00
parent cc2a4f91bf
commit b3e04d7581
3 changed files with 173 additions and 224 deletions

View File

@ -22,6 +22,10 @@ use syntect::highlighting::ThemeSet;
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground}; use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::SyntaxSet; use syntect::parsing::SyntaxSet;
// Загрузка шаблонов при компиляции
const TEMPLATE_FILE: &str = include_str!("../templates/file.html");
const TEMPLATE_DIR: &str = include_str!("../templates/dir.html");
#[derive(Clone)] #[derive(Clone)]
struct AppState { struct AppState {
syntax_set: Arc<SyntaxSet>, syntax_set: Arc<SyntaxSet>,
@ -37,7 +41,6 @@ async fn main() {
let ss = SyntaxSet::load_defaults_newlines(); let ss = SyntaxSet::load_defaults_newlines();
let ts = ThemeSet::load_defaults(); let ts = ThemeSet::load_defaults();
// Создаем канал broadcast для SSE
let (tx, _rx) = broadcast::channel::<String>(100); let (tx, _rx) = broadcast::channel::<String>(100);
let state = AppState { let state = AppState {
@ -46,7 +49,6 @@ async fn main() {
tx: Arc::new(tx), tx: Arc::new(tx),
}; };
// Запускаем глобальный вотчер в отдельной задаче
let watcher_state = state.clone(); let watcher_state = state.clone();
tokio::spawn(async move { tokio::spawn(async move {
run_file_watcher(watcher_state).await; run_file_watcher(watcher_state).await;
@ -66,8 +68,8 @@ async fn main() {
axum::serve(listener, app).await.unwrap(); axum::serve(listener, app).await.unwrap();
} }
async fn root() -> Html<&'static str> { async fn root() -> Result<Html<String>, StatusCode> {
Html("<h1 style='color:white; text-align:center;'>Markdown Server</h1><p style='color:#aaa; text-align:center;'>Перейдите на <a href='/files/example.md'>/files/example.md</a></p>") render_directory_index(&PathBuf::from("./notes"), "").await
} }
async fn sse_handler( async fn sse_handler(
@ -124,6 +126,7 @@ async fn serve_file(
let mut requested_path = PathBuf::from("./notes"); let mut requested_path = PathBuf::from("./notes");
requested_path.push(&full_path); requested_path.push(&full_path);
// Безопасность путей
let safe_path = match fs::canonicalize(&requested_path).await { let safe_path = match fs::canonicalize(&requested_path).await {
Ok(p) => p, Ok(p) => p,
Err(_) => return Err(StatusCode::NOT_FOUND), Err(_) => return Err(StatusCode::NOT_FOUND),
@ -148,7 +151,7 @@ async fn serve_file(
}; };
if metadata.is_dir() { if metadata.is_dir() {
return render_directory_index(&safe_path, &full_path).await; return render_directory_index(&safe_path, &full_path).await;
} }
let content = match fs::read_to_string(&safe_path).await { let content = match fs::read_to_string(&safe_path).await {
@ -159,9 +162,33 @@ async fn serve_file(
} }
}; };
// Логика кнопки "Назад"
let back_link = if let Some(pos) = full_path.rfind('/') {
let parent = &full_path[..pos];
if parent.is_empty() { "/".to_string() } else { format!("/{}", parent) }
} else {
"/".to_string()
};
let back_button_html = format!(
r#"<div style="margin-bottom: 20px;">
<a href="{}" style="display: inline-flex; align-items: center; color: #90a4ae; text-decoration: none; font-size: 0.95em; transition: color 0.2s;"
onmouseover="this.style.color='#ffffff'" onmouseout="this.style.color='#90a4ae'">
<span style="margin-right: 8px; font-size: 1.2em;"></span> Назад
</a>
</div>"#,
back_link
);
let html_content = markdown_to_html(&content, &state.syntax_set, &state.theme_set, &full_path); let html_content = markdown_to_html(&content, &state.syntax_set, &state.theme_set, &full_path);
Ok(Html(html_content)) // Заполнение шаблона
let final_html = TEMPLATE_FILE
.replace("{{CONTENT}}", &html_content)
.replace("{{SSE_URL}}", &format!("/events/{}", full_path))
.replace("{{BACK_BUTTON}}", &back_button_html);
Ok(Html(final_html))
} }
async fn render_directory_index( async fn render_directory_index(
@ -176,19 +203,17 @@ async fn render_directory_index(
} }
}; };
let mut files: Vec<(String, String, bool)> = Vec::new(); // (name, link, is_dir) let mut files: Vec<(String, String, bool)> = Vec::new();
while let Some(entry) = entries.next_entry().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? { while let Some(entry) = entries.next_entry().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? {
let file_name = entry.file_name().to_string_lossy().to_string(); let file_name = entry.file_name().to_string_lossy().to_string();
// Пропускаем скрытые файлы (начинающиеся с точки)
if file_name.starts_with('.') { if file_name.starts_with('.') {
continue; continue;
} }
let is_dir = entry.metadata().await.map(|m| m.is_dir()).unwrap_or(false); let is_dir = entry.metadata().await.map(|m| m.is_dir()).unwrap_or(false);
// Формируем ссылку
let mut link_path = request_path.to_string(); let mut link_path = request_path.to_string();
if !link_path.ends_with('/') { if !link_path.ends_with('/') {
link_path.push('/'); link_path.push('/');
@ -198,25 +223,23 @@ async fn render_directory_index(
files.push((file_name, link_path, is_dir)); files.push((file_name, link_path, is_dir));
} }
// Сортировка: сначала директории, потом файлы, по алфавиту
files.sort_by(|a, b| { files.sort_by(|a, b| {
match (a.2, b.2) { match (a.2, b.2) {
(true, false) => std::cmp::Ordering::Less, // Директории первыми (true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater, (false, true) => std::cmp::Ordering::Greater,
_ => a.0.cmp(&b.0), // Затем по имени _ => a.0.cmp(&b.0),
} }
}); });
let mut list_html = String::from("<ul style=\"list-style-type: none; padding: 0; margin: 0;\">"); let mut list_html = String::from("<ul>");
// Добавляем ссылку на родительскую директорию, если мы не в корне if !request_path.is_empty() && request_path != "files" {
if request_path != "files" && !request_path.is_empty() {
let parent_path = request_path.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); let parent_path = request_path.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
let parent_link = if parent_path.is_empty() { "/".to_string() } else { format!("/{}", parent_path) }; let parent_link = if parent_path.is_empty() { "/".to_string() } else { format!("/{}", parent_path) };
list_html.push_str(&format!( list_html.push_str(&format!(
r#"<li style="padding: 10px 0; border-bottom: 1px solid #333;"> r#"<li>
<a href="{}" style="color: #90a4ae; font-weight: bold; text-decoration: none !important; display: block;">📁 ..</a> <a href="{}" class="back-link">📁 ..</a>
</li>"#, </li>"#,
parent_link parent_link
)); ));
@ -224,63 +247,29 @@ async fn render_directory_index(
for (name, link, is_dir) in files { for (name, link, is_dir) in files {
let icon = if is_dir { "📁" } else { "📄" }; let icon = if is_dir { "📁" } else { "📄" };
// Новый цвет: светло-голубой для файлов и папок
let color = "#64b5f6";
let hover_color = "#90caf9"; // Чуть светлее при наведении
list_html.push_str(&format!( list_html.push_str(&format!(
r#"<li style="padding: 10px 0; border-bottom: 1px solid #333; transition: background-color 0.2s;"> r#"<li>
<a href="/{}" style="color: {}; text-decoration: none !important; font-size: 1.1em; display: flex; align-items: center;" <a href="/{}" class="file-link">
onmouseover="this.style.color='{}'" onmouseout="this.style.color='{}'"> <span class="icon">{}</span>
<span style="margin-right: 10px; min-width: 24px;">{}</span>
<span>{}</span> <span>{}</span>
</a> </a>
</li>"#, </li>"#,
link.trim_start_matches('/'), link.trim_start_matches('/'),
color,
hover_color,
color,
icon, icon,
name name
)); ));
} }
list_html.push_str("</ul>"); list_html.push_str("</ul>");
let html_content = format!( let title_path = if request_path.is_empty() { "" } else { request_path.trim_start_matches('/') };
r#"<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Обзор директории</title>
<style>
body {{ background-color: #121212; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 40px 20px; display: flex; justify-content: center; }}
.content {{ max-width: 800px; width: 100%; background-color: #1e1e1e; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.5); }}
h1 {{ color: #ffffff; border-bottom: 1px solid #333; padding-bottom: 10px; margin-top: 0; }}
/* Глобальный сброс подчеркивания для всех ссылок в этом шаблоне */
a {{ text-decoration: none !important; transition: opacity 0.2s; }}
a:hover {{ opacity: 0.8; }}
</style>
</head>
<body>
<div class="content">
<h1>📂 Обзор директории: /{}</h1>
{}
<p style="margin-top: 30px; color: #666; font-size: 0.9em; border-top: 1px solid #333; padding-top: 15px;">
<a href="/" style="color: #757575;"> На главную</a>
</p>
</div>
</body>
</html>"#,
request_path.trim_start_matches('/'),
list_html
);
Ok(Html(html_content)) let final_html = TEMPLATE_DIR
.replace("{{TITLE_PATH}}", title_path)
.replace("{{FILE_LIST}}", &list_html);
Ok(Html(final_html))
} }
// <--- КОНЕЦ ИЗМЕНЕНИЯ
/// Запуск наблюдателя за файловой системой
async fn run_file_watcher(state: AppState) { async fn run_file_watcher(state: AppState) {
let (tx_fs, mut rx_fs) = tokio::sync::mpsc::channel::<PathBuf>(100); let (tx_fs, mut rx_fs) = tokio::sync::mpsc::channel::<PathBuf>(100);
@ -313,7 +302,7 @@ async fn run_file_watcher(state: AppState) {
} }
} }
fn markdown_to_html(markdown: &str, ss: &SyntaxSet, ts: &ThemeSet, file_path: &str) -> String { fn markdown_to_html(markdown: &str, ss: &SyntaxSet, ts: &ThemeSet, _file_path: &str) -> String {
let theme = &ts.themes["base16-ocean.dark"]; let theme = &ts.themes["base16-ocean.dark"];
let mut options = Options::empty(); let mut options = Options::empty();
@ -343,13 +332,9 @@ fn markdown_to_html(markdown: &str, ss: &SyntaxSet, ts: &ThemeSet, file_path: &s
}, },
Event::End(Tag::CodeBlock(_)) => { Event::End(Tag::CodeBlock(_)) => {
in_code_block = false; in_code_block = false;
// Проверка на Mermaid
let is_mermaid = current_lang.as_deref() == Some("mermaid"); let is_mermaid = current_lang.as_deref() == Some("mermaid");
if is_mermaid { if is_mermaid {
// Для Mermaid просто экранируем контент и оборачиваем в div
// Кнопка копирования тоже нужна
let escaped_code = escape_html(&current_code); let escaped_code = escape_html(&current_code);
let mermaid_html = format!( let mermaid_html = format!(
r#"<div class="code-block-wrapper mermaid-wrapper"> r#"<div class="code-block-wrapper mermaid-wrapper">
@ -363,7 +348,6 @@ fn markdown_to_html(markdown: &str, ss: &SyntaxSet, ts: &ThemeSet, file_path: &s
); );
processed_events.push(Event::Html(mermaid_html.into())); processed_events.push(Event::Html(mermaid_html.into()));
} else { } else {
// Обычная обработка кода с подсветкой
let lang_display = current_lang.as_deref().unwrap_or("text"); let lang_display = current_lang.as_deref().unwrap_or("text");
let lang_escaped = escape_html(lang_display); let lang_escaped = escape_html(lang_display);
@ -371,7 +355,6 @@ fn markdown_to_html(markdown: &str, ss: &SyntaxSet, ts: &ThemeSet, file_path: &s
if let Some(syntax) = ss.find_syntax_by_token(lang) { if let Some(syntax) = ss.find_syntax_by_token(lang) {
let mut h = HighlightLines::new(syntax, theme); let mut h = HighlightLines::new(syntax, theme);
let mut result_html = String::new(); let mut result_html = String::new();
for line in current_code.lines() { for line in current_code.lines() {
let line_with_newline = format!("{}\n", line); let line_with_newline = format!("{}\n", line);
match h.highlight_line(&line_with_newline, ss) { match h.highlight_line(&line_with_newline, ss) {
@ -402,7 +385,6 @@ fn markdown_to_html(markdown: &str, ss: &SyntaxSet, ts: &ThemeSet, file_path: &s
lang_escaped, lang_escaped,
highlighted_html highlighted_html
); );
processed_events.push(Event::Html(code_container.into())); processed_events.push(Event::Html(code_container.into()));
} }
}, },
@ -419,162 +401,7 @@ fn markdown_to_html(markdown: &str, ss: &SyntaxSet, ts: &ThemeSet, file_path: &s
let mut body_html = String::new(); let mut body_html = String::new();
html::push_html(&mut body_html, processed_events.into_iter()); html::push_html(&mut body_html, processed_events.into_iter());
body_html
let sse_url = format!("/events/{}", file_path);
format!(
r#"<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Preview</title>
<!-- Подключаем Mermaid JS -->
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
<style>
body {{ background-color: #121212; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 40px 20px; display: flex; justify-content: center; line-height: 1.6; }}
.content {{ max-width: 800px; width: 100%; background-color: #1e1e1e; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.5); }}
a {{ color: #bb86fc; text-decoration: none !important; }}
h1, h2, h3, h4 {{ color: #ffffff; margin-top: 1.5em; margin-bottom: 0.5em; }}
h1 {{ border-bottom: 1px solid #333; padding-bottom: 10px; }}
table {{ border-collapse: collapse; width: 100%; margin: 1em 0; }}
th, td {{ border: 1px solid #444; padding: 8px; text-align: left; }}
th {{ background-color: #2c2c2c; }}
blockquote {{ border-left: 4px solid #bb86fc; margin: 1em 0; padding-left: 1em; color: #aaa; background: #252525; padding: 10px; }}
code {{ font-family: 'Consolas', 'Monaco', monospace; }}
/* Стили для обычных инлайн кодов */
p > code, li > code {{ background-color: #2c2c2c; padding: 2px 6px; border-radius: 4px; color: #ff79c6; }}
/* Стили для блоков кода с подсветкой */
.code-block-wrapper {{
margin: 1em 0;
border: 1px solid #444;
border-radius: 6px;
overflow: hidden;
background-color: #2b303b;
}}
.code-header {{
display: flex;
justify-content: space-between;
align-items: center;
background-color: #232730;
padding: 6px 12px;
border-bottom: 1px solid #444;
font-size: 0.85em;
color: #a0a0a0;
}}
.code-lang {{
font-weight: bold;
text-transform: uppercase;
letter-spacing: 0.5px;
}}
.copy-btn {{
background: transparent;
border: 1px solid #555;
color: #ccc;
padding: 2px 8px;
border-radius: 4px;
cursor: pointer;
font-size: 0.8em;
transition: all 0.2s;
}}
.copy-btn:hover {{
background-color: #444;
color: #fff;
border-color: #777;
}}
.copy-btn:active {{
transform: scale(0.95);
}}
pre {{
padding: 15px;
overflow-x: auto;
margin: 0;
}}
pre code {{
background: transparent;
padding: 0;
color: inherit;
}}
/* Специфичные стили для Mermaid */
.mermaid-wrapper .mermaid {{
background-color: #f9f9f9; /* Светлый фон для контраста диаграммы */
border-radius: 0 0 6px 6px;
display: flex;
justify-content: center;
}}
#status {{ position: fixed; top: 10px; right: 10px; padding: 5px 10px; border-radius: 4px; font-size: 12px; font-weight: bold; }}
.connected {{ background-color: #2ecc71; color: #000; }}
.disconnected {{ background-color: #e74c3c; color: #fff; }}
.reconnecting {{ background-color: #f1c40f; color: #000; }}
</style>
</head>
<body>
<div class="content">
{}
</div>
<script>
const sseUrl = "{}";
function connect() {{
const evtSource = new EventSource(sseUrl);
evtSource.onerror = (err) => {{
evtSource.close();
setTimeout(connect, 3000);
}};
evtSource.addEventListener("reload", (event) => {{
console.log("Получено событие обновления");
location.reload();
}});
}}
connect();
function copyCode(button) {{
const wrapper = button.closest('.code-block-wrapper');
if (!wrapper) return;
// Для mermaid берем текст из div.mermaid, для кода из pre
const target = wrapper.querySelector('pre') || wrapper.querySelector('.mermaid');
if (!target) return;
const codeText = target.innerText;
navigator.clipboard.writeText(codeText).then(() => {{
const originalText = button.innerText;
button.innerText = 'Copied!';
button.style.borderColor = '#2ecc71';
button.style.color = '#2ecc71';
setTimeout(() => {{
button.innerText = originalText;
button.style.borderColor = '';
button.style.color = '';
}}, 2000);
}}).catch(err => {{
console.error('Ошибка копирования:', err);
button.innerText = 'Error';
}});
}}
// Инициализация Mermaid с темной темой
mermaid.initialize({{
startOnLoad: true,
theme: 'dark',
securityLevel: 'loose',
}});
</script>
</body>
</html>"#,
body_html,
sse_url
)
} }
fn escape_html(text: &str) -> String { fn escape_html(text: &str) -> String {

32
templates/dir.html Normal file
View File

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Обзор директории</title>
<style>
body { background-color: #121212; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 40px 20px; display: flex; justify-content: center; }
.content { max-width: 800px; width: 100%; background-color: #1e1e1e; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.5); }
h1 { color: #ffffff; border-bottom: 1px solid #333; padding-bottom: 10px; margin-top: 0; }
a { text-decoration: none !important; transition: opacity 0.2s; }
a:hover { opacity: 0.8; }
ul { list-style-type: none; padding: 0; margin: 0; }
li { padding: 10px 0; border-bottom: 1px solid #333; transition: background-color 0.2s; }
.file-link { color: #64b5f6; text-decoration: none !important; font-size: 1.1em; display: flex; align-items: center; }
.file-link:hover { color: #90caf9; }
.back-link { color: #90a4ae; font-weight: bold; text-decoration: none !important; display: block; }
.icon { margin-right: 10px; min-width: 24px; }
.footer { margin-top: 30px; color: #666; font-size: 0.9em; border-top: 1px solid #333; padding-top: 15px; }
.footer a { color: #757575; }
</style>
</head>
<body>
<div class="content">
<h1>📂 Обзор директории: /{{TITLE_PATH}}</h1>
{{FILE_LIST}}
<div class="footer">
<a href="/">На главную</a>
</div>
</div>
</body>
</html>

90
templates/file.html Normal file
View File

@ -0,0 +1,90 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Preview</title>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
<style>
body { background-color: #121212; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 40px 20px; display: flex; justify-content: center; line-height: 1.6; }
.content { max-width: 800px; width: 100%; background-color: #1e1e1e; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.5); }
a { color: #bb86fc; text-decoration: none !important; }
h1, h2, h3, h4 { color: #ffffff; margin-top: 1.5em; margin-bottom: 0.5em; }
h1 { border-bottom: 1px solid #333; padding-bottom: 10px; }
table { border-collapse: collapse; width: 100%; margin: 1em 0; }
th, td { border: 1px solid #444; padding: 8px; text-align: left; }
th { background-color: #2c2c2c; }
blockquote { border-left: 4px solid #bb86fc; margin: 1em 0; padding-left: 1em; color: #aaa; background: #252525; padding: 10px; }
code { font-family: 'Consolas', 'Monaco', monospace; }
p > code, li > code { background-color: #2c2c2c; padding: 2px 6px; border-radius: 4px; color: #ff79c6; }
.code-block-wrapper { margin: 1em 0; border: 1px solid #444; border-radius: 6px; overflow: hidden; background-color: #2b303b; }
.code-header { display: flex; justify-content: space-between; align-items: center; background-color: #232730; padding: 6px 12px; border-bottom: 1px solid #444; font-size: 0.85em; color: #a0a0a0; }
.code-lang { font-weight: bold; text-transform: uppercase; letter-spacing: 0.5px; }
.copy-btn { background: transparent; border: 1px solid #555; color: #ccc; padding: 2px 8px; border-radius: 4px; cursor: pointer; font-size: 0.8em; transition: all 0.2s; }
.copy-btn:hover { background-color: #444; color: #fff; border-color: #777; }
.copy-btn:active { transform: scale(0.95); }
pre { padding: 15px; overflow-x: auto; margin: 0; }
pre code { background: transparent; padding: 0; color: inherit; }
.mermaid-wrapper .mermaid { background-color: #f9f9f9; border-radius: 0 0 6px 6px; display: flex; justify-content: center; }
#status { position: fixed; top: 10px; right: 10px; padding: 5px 10px; border-radius: 4px; font-size: 12px; font-weight: bold; }
.connected { background-color: #2ecc71; color: #000; }
.disconnected { background-color: #e74c3c; color: #fff; }
.reconnecting { background-color: #f1c40f; color: #000; }
</style>
</head>
<body>
<div class="content">
{{BACK_BUTTON}}
{{CONTENT}}
</div>
<script>
const sseUrl = "{{SSE_URL}}";
function connect() {
const evtSource = new EventSource(sseUrl);
evtSource.onerror = (err) => {
evtSource.close();
setTimeout(connect, 3000);
};
evtSource.addEventListener("reload", (event) => {
console.log("Получено событие обновления");
location.reload();
});
}
connect();
function copyCode(button) {
const wrapper = button.closest('.code-block-wrapper');
if (!wrapper) return;
const target = wrapper.querySelector('pre') || wrapper.querySelector('.mermaid');
if (!target) return;
const codeText = target.innerText;
navigator.clipboard.writeText(codeText).then(() => {
const originalText = button.innerText;
button.innerText = 'Copied!';
button.style.borderColor = '#2ecc71';
button.style.color = '#2ecc71';
setTimeout(() => {
button.innerText = originalText;
button.style.borderColor = '';
button.style.color = '';
}, 2000);
}).catch(err => {
console.error('Ошибка копирования:', err);
button.innerText = 'Error';
});
}
mermaid.initialize({
startOnLoad: true,
theme: 'dark',
securityLevel: 'loose',
});
</script>
</body>
</html>