guidebook 0.1.9

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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
mod renderer;
mod template;

use crate::parser::{self, BookConfig, Language, Summary, SummaryItem};
use anyhow::{Context, Result};
use serde::Serialize;
use std::fs;
use std::path::Path;
use std::time::Instant;

pub use renderer::{render_markdown, render_markdown_with_path, extract_headings, TocItem};
pub use template::Templates;

/// Search index entry
#[derive(Serialize)]
struct SearchEntry {
    title: String,
    path: String,
    content: String,
}

/// Build statistics
#[derive(Default)]
struct BuildStats {
    pages: usize,
    assets: usize,
}

// Embed static assets at compile time
const GITBOOK_CSS: &str = include_str!("../../templates/gitbook.css");
const GITBOOK_JS: &str = include_str!("../../templates/gitbook.js");
const COLLAPSIBLE_JS: &str = include_str!("../../templates/collapsible.js");
const SEARCH_JS: &str = include_str!("../../templates/search.js");

/// Build the book from source directory to output directory
pub fn build(source: &Path, output: &Path) -> Result<()> {
    build_with_options(source, output, false)
}

/// Build the book with options (skip_search_index for hot reload)
pub fn build_with_options(source: &Path, output: &Path, skip_search_index: bool) -> Result<()> {
    let start_time = Instant::now();
    let source = source.canonicalize().context("Source directory not found")?;

    println!("Loading book configuration...");
    let config = BookConfig::load(&source)?;
    println!("  Title: {}", if config.title.is_empty() { "(untitled)" } else { &config.title });

    // Check for multi-language book
    let languages = parser::langs::parse_langs(&source)?;

    let stats = if languages.is_empty() {
        // Single language book
        println!("Building single-language book...");
        build_single_book(&source, output, &config, skip_search_index)?
    } else {
        // Multi-language book
        println!("Building multi-language book with {} languages:", languages.len());
        for lang in &languages {
            println!("  - {} ({})", lang.title, lang.code);
        }

        build_multi_lang_book(&source, output, &config, &languages, skip_search_index)?
    };

    let elapsed = start_time.elapsed();
    let elapsed_secs = elapsed.as_secs_f64();

    println!();
    println!(">> generation finished with success in {:.1}s !", elapsed_secs);
    println!("   {} pages built, {} asset files copied", stats.pages, stats.assets);

    Ok(())
}

fn build_single_book(source: &Path, output: &Path, config: &BookConfig, skip_search_index: bool) -> Result<BuildStats> {
    let summary = Summary::parse(source)?;
    let templates = Templates::new(config)?;
    let mut stats = BuildStats::default();

    // Create output directory
    fs::create_dir_all(output)?;

    // Write embedded static assets
    write_static_assets(output, config)?;

    // Copy assets
    stats.assets += copy_assets(source, output)?;

    // Copy custom styles if configured
    if let Some(style_path) = config.get_website_style() {
        let src_style = source.join(style_path);
        if src_style.exists() {
            let dest_style = output.join("gitbook/style.css");
            fs::create_dir_all(dest_style.parent().unwrap())?;
            fs::copy(&src_style, &dest_style)?;
        }
    }

    // Build each chapter
    stats.pages += build_chapters(source, output, &summary.items, config, &templates, &summary)?;

    // Generate index.html from README.md if exists
    let readme_path = source.join("README.md");
    if readme_path.exists() {
        let content = fs::read_to_string(&readme_path)?;
        let html_content = render_markdown(&content);
        let toc_items = extract_headings(&content);
        let page_html = templates.render_page(
            &config.title,
            &html_content,
            "./",
            config,
            &summary,
            Some("index.html"),
            &toc_items,
        )?;
        fs::write(output.join("index.html"), page_html)?;
        stats.pages += 1;
    }

    // Generate search index (skip on hot reload for performance)
    if !skip_search_index {
        generate_search_index(source, output, &summary)?;
    }

    Ok(stats)
}

fn write_static_assets(output: &Path, config: &BookConfig) -> Result<()> {
    let gitbook_dir = output.join("gitbook");
    fs::create_dir_all(&gitbook_dir)?;

    // Write CSS
    fs::write(gitbook_dir.join("gitbook.css"), GITBOOK_CSS)?;

    // Write JS
    fs::write(gitbook_dir.join("gitbook.js"), GITBOOK_JS)?;

    // Write collapsible JS if enabled
    if config.is_plugin_enabled("collapsible-chapters") {
        fs::write(gitbook_dir.join("collapsible.js"), COLLAPSIBLE_JS)?;
    }

    // Write search JS
    fs::write(gitbook_dir.join("search.js"), SEARCH_JS)?;

    Ok(())
}

fn build_multi_lang_book(
    source: &Path,
    output: &Path,
    config: &BookConfig,
    languages: &[Language],
    skip_search_index: bool,
) -> Result<BuildStats> {
    let mut stats = BuildStats::default();

    // Create output directory
    fs::create_dir_all(output)?;

    // Generate language index page
    generate_lang_index(output, languages, config)?;

    // Build each language
    for lang in languages {
        println!("\nBuilding {} ({})...", lang.title, lang.code);
        let lang_source = source.join(&lang.code);
        let lang_output = output.join(&lang.code);

        // Use language-specific config if exists, otherwise use root config
        let lang_config_path = lang_source.join("book.json");
        let lang_config = if lang_config_path.exists() {
            BookConfig::load(&lang_source)?
        } else {
            config.clone()
        };

        let lang_stats = build_single_book(&lang_source, &lang_output, &lang_config, skip_search_index)?;
        stats.pages += lang_stats.pages;
        stats.assets += lang_stats.assets;
    }

    // Copy root assets if they exist
    let assets_dir = source.join("assets");
    if assets_dir.exists() {
        stats.assets += copy_dir_recursive_count(&assets_dir, &output.join("assets"))?;
    }

    Ok(stats)
}

fn build_chapters(
    source: &Path,
    output: &Path,
    items: &[SummaryItem],
    config: &BookConfig,
    templates: &Templates,
    summary: &Summary,
) -> Result<usize> {
    let mut count = 0;

    for item in items {
        if let SummaryItem::Link { title, path, children } = item {
            if let Some(md_path) = path {
                let src_file = source.join(md_path);
                if src_file.exists() {
                    // Read and render markdown
                    let content = fs::read_to_string(&src_file)?;
                    let html_content = render_markdown_with_path(&content, Some(md_path));
                    let toc_items = extract_headings(&content);

                    // Generate output path
                    let html_path = md_path.replace(".md", ".html");
                    let dest_file = output.join(&html_path);

                    // Calculate relative path to root
                    let depth = html_path.matches('/').count();
                    let root_path = if depth > 0 {
                        "../".repeat(depth)
                    } else {
                        "./".to_string()
                    };

                    // Render with template
                    let page_html = templates.render_page(
                        title,
                        &html_content,
                        &root_path,
                        config,
                        summary,
                        Some(&html_path),
                        &toc_items,
                    )?;

                    // Write output
                    if let Some(parent) = dest_file.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::write(&dest_file, page_html)?;
                    count += 1;
                } else {
                    println!("  Warning: {} not found", md_path);
                }
            }

            // Build children recursively
            if !children.is_empty() {
                count += build_chapters(source, output, children, config, templates, summary)?;
            }
        }
    }

    Ok(count)
}

fn copy_assets(source: &Path, output: &Path) -> Result<usize> {
    let mut count = 0;
    // Copy common asset directories
    for dir_name in &["assets", "images", "img"] {
        let src_dir = source.join(dir_name);
        if src_dir.exists() {
            let dest_dir = output.join(dir_name);
            count += copy_dir_recursive_count(&src_dir, &dest_dir)?;
        }
    }
    Ok(count)
}

fn copy_dir_recursive_count(src: &Path, dest: &Path) -> Result<usize> {
    fs::create_dir_all(dest)?;
    let mut count = 0;

    for entry in walkdir::WalkDir::new(src) {
        let entry = entry?;
        let relative = entry.path().strip_prefix(src)?;
        let dest_path = dest.join(relative);

        if entry.file_type().is_dir() {
            fs::create_dir_all(&dest_path)?;
        } else {
            if let Some(parent) = dest_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::copy(entry.path(), &dest_path)?;
            count += 1;
        }
    }

    Ok(count)
}

fn generate_lang_index(output: &Path, languages: &[Language], config: &BookConfig) -> Result<()> {
    let title = if config.title.is_empty() {
        "Select Language"
    } else {
        &config.title
    };

    let mut lang_links = String::new();
    for lang in languages {
        lang_links.push_str(&format!(
            r#"
            <li>
                <a href="{}/">{}</a>
            </li>
        "#,
            lang.code, lang.title
        ));
    }

    let html = format!(
        r#"<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <title>Choose a language ยท {}</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="guidebook">
        <link rel="stylesheet" href="gitbook/style.css">
        <meta name="HandheldFriendly" content="true"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
        <link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">
    </head>
    <body>

<div class="book-langs-index" role="navigation">
    <div class="inner">
        <h3>Choose a language</h3>

        <ul class="languages">
        {}
        </ul>
    </div>
</div>

    </body>
</html>"#,
        title, lang_links
    );

    fs::write(output.join("index.html"), html)?;

    // Copy gitbook static files to root for the language selector page
    copy_gitbook_static_to_root(output)?;

    Ok(())
}

/// Strip HTML tags from content for search indexing
fn strip_html_tags(html: &str) -> String {
    let mut result = String::new();
    let mut in_tag = false;

    for c in html.chars() {
        if c == '<' {
            in_tag = true;
        } else if c == '>' {
            in_tag = false;
        } else if !in_tag {
            result.push(c);
        }
    }

    // Clean up whitespace
    result
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

/// Collect search entries from summary items
fn collect_search_entries(
    source: &Path,
    items: &[SummaryItem],
    entries: &mut Vec<SearchEntry>,
) -> Result<()> {
    for item in items {
        if let SummaryItem::Link { title, path, children } = item {
            if let Some(md_path) = path {
                let src_file = source.join(md_path);
                if src_file.exists() {
                    let content = fs::read_to_string(&src_file)?;
                    let html_content = render_markdown(&content);
                    let text_content = strip_html_tags(&html_content);
                    let html_path = md_path.replace(".md", ".html");

                    entries.push(SearchEntry {
                        title: title.clone(),
                        path: html_path,
                        content: text_content,
                    });
                }
            }
            if !children.is_empty() {
                collect_search_entries(source, children, entries)?;
            }
        }
    }
    Ok(())
}

/// Generate search index JSON file
fn generate_search_index(source: &Path, output: &Path, summary: &Summary) -> Result<()> {
    let mut entries = Vec::new();

    // Collect from README.md
    let readme_path = source.join("README.md");
    if readme_path.exists() {
        let content = fs::read_to_string(&readme_path)?;
        let html_content = render_markdown(&content);
        let text_content = strip_html_tags(&html_content);

        entries.push(SearchEntry {
            title: "Home".to_string(),
            path: "index.html".to_string(),
            content: text_content,
        });
    }

    // Collect from all chapters
    collect_search_entries(source, &summary.items, &mut entries)?;

    // Write search index
    let json = serde_json::to_string(&entries)?;
    fs::write(output.join("search_index.json"), json)?;

    Ok(())
}

fn copy_gitbook_static_to_root(output: &Path) -> Result<()> {
    let gitbook_dir = output.join("gitbook");
    fs::create_dir_all(&gitbook_dir)?;

    // Create a minimal style.css for the language selector page
    let style_css = r#"
.book-langs-index {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.book-langs-index .inner {
    text-align: center;
}

.book-langs-index h3 {
    color: #333;
    font-size: 1.5em;
    margin-bottom: 1em;
}

.book-langs-index .languages {
    list-style: none;
    padding: 0;
    margin: 0;
}

.book-langs-index .languages li {
    margin: 0.5em 0;
}

.book-langs-index .languages a {
    color: #4183c4;
    text-decoration: none;
    font-size: 1.2em;
}

.book-langs-index .languages a:hover {
    text-decoration: underline;
}
"#;

    fs::write(gitbook_dir.join("style.css"), style_css)?;

    // Create images directory with placeholder favicon
    let images_dir = gitbook_dir.join("images");
    fs::create_dir_all(&images_dir)?;

    Ok(())
}