guidebook 0.1.35

HonKit/GitBook compatible static book generator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use crate::parser::{BookConfig, FrontMatter, Summary, SummaryItem};
use crate::builder::TocItem;
use anyhow::Result;
use tera::{Context, Tera};

pub struct Templates {
    tera: Tera,
}

impl Templates {
    pub fn new(_config: &BookConfig) -> Result<Self> {
        let mut tera = Tera::default();

        // Register the main page template
        tera.add_raw_template("page.html", PAGE_TEMPLATE)?;

        Ok(Self { tera })
    }

    pub fn render_page(
        &self,
        title: &str,
        content: &str,
        root_path: &str,
        config: &BookConfig,
        summary: &Summary,
        current_path: Option<&str>,
        toc_items: &[TocItem],
    ) -> Result<String> {
        let mut context = Context::new();

        context.insert("title", title);
        context.insert("book_title", &config.title);
        context.insert("content", content);
        context.insert("root_path", root_path);

        // Check plugin features
        let collapsible = config.is_plugin_enabled("collapsible-chapters");
        context.insert("collapsible", &collapsible);

        // Generate sidebar HTML - links need root_path prefix
        let sidebar = generate_sidebar(&summary.items, current_path, root_path, collapsible);
        context.insert("sidebar", &sidebar);

        // Generate prev/next navigation
        let (prev_page, next_page) = get_prev_next_pages(&summary.items, current_path);
        context.insert("prev_url", &prev_page.as_ref().map(|(url, _)| url.clone()));
        context.insert("prev_title", &prev_page.map(|(_, title)| title));
        context.insert("next_url", &next_page.as_ref().map(|(url, _)| url.clone()));
        context.insert("next_title", &next_page.map(|(_, title)| title));

        // Check plugin features
        context.insert("back_to_top", &config.is_plugin_enabled("back-to-top-button"));
        context.insert("mermaid", &config.is_plugin_enabled("mermaid-md-adoc"));
        context.insert("fontsettings", &config.is_plugin_enabled("fontsettings"));

        // Generate TOC HTML
        let toc_html = generate_toc_html(toc_items);
        context.insert("toc", &toc_html);
        context.insert("has_toc", &!toc_items.is_empty());

        // Custom styles
        let has_custom_style = config.get_website_style().is_some();
        context.insert("has_custom_style", &has_custom_style);

        // Add book variables to context (accessible as {{ book.xxx }} in templates)
        if !config.variables.is_empty() {
            context.insert("book", &config.variables);
        }

        // No description by default
        context.insert("description", &"");
        context.insert("has_description", &false);

        let html = self.tera.render("page.html", &context)?;
        Ok(html)
    }

    /// Render a page with front matter metadata support
    pub fn render_page_with_meta(
        &self,
        title: &str,
        content: &str,
        root_path: &str,
        config: &BookConfig,
        summary: &Summary,
        current_path: Option<&str>,
        toc_items: &[TocItem],
        front_matter: Option<&FrontMatter>,
    ) -> Result<String> {
        let mut context = Context::new();

        context.insert("title", title);
        context.insert("book_title", &config.title);
        context.insert("content", content);
        context.insert("root_path", root_path);

        // Check plugin features
        let collapsible = config.is_plugin_enabled("collapsible-chapters");
        context.insert("collapsible", &collapsible);

        // Generate sidebar HTML - links need root_path prefix
        let sidebar = generate_sidebar(&summary.items, current_path, root_path, collapsible);
        context.insert("sidebar", &sidebar);

        // Generate prev/next navigation
        let (prev_page, next_page) = get_prev_next_pages(&summary.items, current_path);
        context.insert("prev_url", &prev_page.as_ref().map(|(url, _)| url.clone()));
        context.insert("prev_title", &prev_page.map(|(_, title)| title));
        context.insert("next_url", &next_page.as_ref().map(|(url, _)| url.clone()));
        context.insert("next_title", &next_page.map(|(_, title)| title));

        // Check plugin features
        context.insert("back_to_top", &config.is_plugin_enabled("back-to-top-button"));
        context.insert("mermaid", &config.is_plugin_enabled("mermaid-md-adoc"));
        context.insert("fontsettings", &config.is_plugin_enabled("fontsettings"));

        // Generate TOC HTML
        let toc_html = generate_toc_html(toc_items);
        context.insert("toc", &toc_html);
        context.insert("has_toc", &!toc_items.is_empty());

        // Custom styles
        let has_custom_style = config.get_website_style().is_some();
        context.insert("has_custom_style", &has_custom_style);

        // Add book variables to context (accessible as {{ book.xxx }} in templates)
        if !config.variables.is_empty() {
            context.insert("book", &config.variables);
        }

        // Add front matter metadata
        if let Some(fm) = front_matter {
            if let Some(ref desc) = fm.description {
                context.insert("description", desc);
                context.insert("has_description", &true);
            } else {
                context.insert("description", &"");
                context.insert("has_description", &false);
            }
        } else {
            context.insert("description", &"");
            context.insert("has_description", &false);
        }

        let html = self.tera.render("page.html", &context)?;
        Ok(html)
    }
}

/// Get the previous and next pages based on the summary order
fn get_prev_next_pages(
    items: &[SummaryItem],
    current_path: Option<&str>,
) -> (Option<(String, String)>, Option<(String, String)>) {
    // Flatten all pages into a list
    let pages = flatten_pages(items);

    if let Some(current) = current_path {
        // Find current page index
        let current_idx = pages.iter().position(|(path, _)| path == current);

        if let Some(idx) = current_idx {
            let prev = if idx > 0 {
                pages.get(idx - 1).cloned()
            } else {
                None
            };
            let next = pages.get(idx + 1).cloned();
            return (prev, next);
        }
    }

    (None, None)
}

/// Flatten summary items into a list of (html_path, title)
fn flatten_pages(items: &[SummaryItem]) -> Vec<(String, String)> {
    let mut pages = Vec::new();

    for item in items {
        if let SummaryItem::Link { title, path, children } = item {
            if let Some(md_path) = path {
                let html_path = md_path.replace(".md", ".html");
                pages.push((html_path, title.clone()));
            }
            // Recursively add children
            pages.extend(flatten_pages(children));
        }
    }

    pages
}

/// Check if any descendant of items contains the current path
fn contains_current_path(items: &[SummaryItem], current_path: Option<&str>) -> bool {
    let current = match current_path {
        Some(p) => p,
        None => return false,
    };

    for item in items {
        if let SummaryItem::Link { path, children, .. } = item {
            if let Some(md_path) = path {
                let html_path = md_path.replace(".md", ".html");
                if html_path == current {
                    return true;
                }
            }
            if contains_current_path(children, current_path) {
                return true;
            }
        }
    }
    false
}

fn generate_sidebar(items: &[SummaryItem], current_path: Option<&str>, prefix: &str, collapsible: bool) -> String {
    let mut html = String::new();

    for item in items {
        match item {
            SummaryItem::Link { title, path, children } => {
                let html_path = path.as_ref().map(|p| p.replace(".md", ".html"));
                let is_active = current_path.map(|cp| {
                    html_path.as_ref().map(|hp| cp == hp).unwrap_or(false)
                }).unwrap_or(false);

                let has_children = !children.is_empty();
                // Always expand by default. User can collapse via JS, state saved in localStorage
                let should_expand = has_children;

                let active_class = if is_active { " active" } else { "" };
                // Only add expandable class if collapsible plugin is enabled
                let expandable_class = if has_children && collapsible { " expandable" } else { "" };
                let expanded_class = if has_children && should_expand { " expanded" } else { "" };

                html.push_str(&format!(
                    r#"<li class="chapter{}{}{}">"#,
                    active_class, expandable_class, expanded_class
                ));

                if let Some(ref hp) = html_path {
                    html.push_str(&format!(
                        r#"<a href="{}{}">{}</a>"#,
                        prefix, hp, html_escape(title)
                    ));
                } else {
                    html.push_str(&format!(
                        r#"<span class="chapter-title">{}</span>"#,
                        html_escape(title)
                    ));
                }

                if has_children {
                    html.push_str("<ul class=\"articles\">");
                    html.push_str(&generate_sidebar(children, current_path, prefix, collapsible));
                    html.push_str("</ul>");
                }

                html.push_str("</li>");
            }
            SummaryItem::Separator => {
                html.push_str(r#"<li class="divider"></li>"#);
            }
            SummaryItem::PartTitle(part_title) => {
                html.push_str(&format!(
                    r#"<li class="part-title"><span>{}</span></li>"#,
                    html_escape(part_title)
                ));
            }
        }
    }

    html
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// Generate TOC HTML from heading items
fn generate_toc_html(items: &[TocItem]) -> String {
    if items.is_empty() {
        return String::new();
    }

    let mut html = String::from("<ul class=\"toc-list\">");

    for item in items {
        let indent_class = match item.level {
            2 => "toc-h2",
            3 => "toc-h3",
            4 => "toc-h4",
            _ => "toc-h2",
        };
        html.push_str(&format!(
            "<li class=\"{}\"><a href=\"#{}\">{}</a></li>",
            indent_class,
            html_escape(&item.id),
            html_escape(&item.text)
        ));
    }

    html.push_str("</ul>");
    html
}

const PAGE_TEMPLATE: &str = r##"<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }} | {{ book_title }}</title>
    {% if has_description %}
    <meta name="description" content="{{ description }}">
    {% endif %}
    <link rel="stylesheet" href="{{ root_path }}gitbook/gitbook.css">
    {% if has_custom_style %}
    <link rel="stylesheet" href="{{ root_path }}gitbook/style.css">
    {% endif %}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    {% if mermaid %}
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script>mermaid.initialize({startOnLoad:true});</script>
    {% endif %}
</head>
<body class="book font-family-1" data-root-path="{{ root_path }}">
    <div class="book-summary">
        <div class="search-wrapper">
            <input type="text" class="search-input" placeholder="Search..." aria-label="Search">
            <div class="search-results"></div>
        </div>
        <nav role="navigation">
            <ul class="summary">
                {{ sidebar | safe }}
            </ul>
        </nav>
    </div>

    <div class="book-body">
        <div class="sidebar-toggle" title="Toggle Sidebar">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="3" y1="6" x2="21" y2="6"></line>
                <line x1="3" y1="12" x2="21" y2="12"></line>
                <line x1="3" y1="18" x2="21" y2="18"></line>
            </svg>
        </div>
        {% if fontsettings %}
        <div class="fontsettings-toolbar" title="Font Settings">
            <button class="fontsettings-decrease" title="Decrease font size">A-</button>
            <button class="fontsettings-increase" title="Increase font size">A+</button>
            <span class="fontsettings-separator"></span>
            <button class="fontsettings-theme" data-theme="white" title="White theme"></button>
            <button class="fontsettings-theme" data-theme="sepia" title="Sepia theme"></button>
            <button class="fontsettings-theme" data-theme="night" title="Night theme"></button>
        </div>
        {% endif %}
        {% if has_toc %}
        <div class="toc-toggle" title="Toggle Table of Contents">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="3" y1="6" x2="15" y2="6"></line>
                <line x1="3" y1="12" x2="21" y2="12"></line>
                <line x1="3" y1="18" x2="18" y2="18"></line>
                <polyline points="17 4 21 6 17 8"></polyline>
            </svg>
        </div>
        <nav class="page-toc">
            <div class="toc-header">On This Page</div>
            {{ toc | safe }}
        </nav>
        {% endif %}
        <div class="body-inner">
            {% if prev_url %}
            <a class="page-nav prev" href="{{ root_path }}{{ prev_url | safe }}" title="{{ prev_title }}">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="15 18 9 12 15 6"></polyline>
                </svg>
            </a>
            {% endif %}
            {% if next_url %}
            <a class="page-nav next" href="{{ root_path }}{{ next_url | safe }}" title="{{ next_title }}">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="9 18 15 12 9 6"></polyline>
                </svg>
            </a>
            {% endif %}
            <div class="page-wrapper">
                <div class="page-inner">
                    <section class="markdown-section">
                        {{ content | safe }}
                    </section>
                </div>
            </div>
        </div>
    </div>

    {% if back_to_top %}
    <a href="#" class="back-to-top" title="Back to top">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M18 15l-6-6-6 6"/>
        </svg>
    </a>
    {% endif %}

    <script src="{{ root_path }}gitbook/gitbook.js"></script>
    {% if collapsible %}
    <script src="{{ root_path }}gitbook/collapsible.js"></script>
    {% endif %}
    {% if fontsettings %}
    <script src="{{ root_path }}gitbook/fontsettings.js"></script>
    {% endif %}
    <script src="{{ root_path }}gitbook/search.js"></script>
</body>
</html>
"##;