Unnamed repository; edit this file 'description' to name the repository.
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
use anyhow::{anyhow, Context, Result};
use libloading::{Library, Symbol};
use serde::{Deserialize, Serialize};
use std::fs;
use std::time::SystemTime;
use std::{
    collections::HashSet,
    path::{Path, PathBuf},
    process::Command,
    sync::mpsc::channel,
};
use tree_sitter::Language;

#[cfg(unix)]
const DYLIB_EXTENSION: &str = "so";

#[cfg(windows)]
const DYLIB_EXTENSION: &str = "dll";

#[derive(Debug, Serialize, Deserialize)]
struct Configuration {
    #[serde(rename = "use-grammars")]
    pub grammar_selection: Option<GrammarSelection>,
    pub grammar: Vec<GrammarConfiguration>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", untagged)]
pub enum GrammarSelection {
    Only { only: HashSet<String> },
    Except { except: HashSet<String> },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GrammarConfiguration {
    #[serde(rename = "name")]
    pub grammar_id: String,
    pub source: GrammarSource,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", untagged)]
pub enum GrammarSource {
    Local {
        path: String,
    },
    Git {
        #[serde(rename = "git")]
        remote: String,
        #[serde(rename = "rev")]
        revision: String,
        subpath: Option<String>,
    },
}

const BUILD_TARGET: &str = env!("BUILD_TARGET");
const REMOTE_NAME: &str = "origin";

pub fn get_language(name: &str) -> Result<Language> {
    let name = name.to_ascii_lowercase();
    let mut library_path = crate::runtime_dir().join("grammars").join(&name);
    library_path.set_extension(DYLIB_EXTENSION);

    let library = unsafe { Library::new(&library_path) }
        .with_context(|| format!("Error opening dynamic library {:?}", library_path))?;
    let language_fn_name = format!("tree_sitter_{}", name.replace('-', "_"));
    let language = unsafe {
        let language_fn: Symbol<unsafe extern "C" fn() -> Language> = library
            .get(language_fn_name.as_bytes())
            .with_context(|| format!("Failed to load symbol {}", language_fn_name))?;
        language_fn()
    };
    std::mem::forget(library);
    Ok(language)
}

pub fn fetch_grammars() -> Result<()> {
    // We do not need to fetch local grammars.
    let mut grammars = get_grammar_configs()?;
    grammars.retain(|grammar| !matches!(grammar.source, GrammarSource::Local { .. }));

    run_parallel(grammars, fetch_grammar, "fetch")
}

pub fn build_grammars() -> Result<()> {
    run_parallel(get_grammar_configs()?, build_grammar, "build")
}

// Returns the set of grammar configurations the user requests.
// Grammars are configured in the default and user `languages.toml` and are
// merged. The `grammar_selection` key of the config is then used to filter
// down all grammars into a subset of the user's choosing.
fn get_grammar_configs() -> Result<Vec<GrammarConfiguration>> {
    let config: Configuration = crate::config::user_lang_config()
        .context("Could not parse languages.toml")?
        .try_into()?;

    let grammars = match config.grammar_selection {
        Some(GrammarSelection::Only { only: selections }) => config
            .grammar
            .into_iter()
            .filter(|grammar| selections.contains(&grammar.grammar_id))
            .collect(),
        Some(GrammarSelection::Except { except: rejections }) => config
            .grammar
            .into_iter()
            .filter(|grammar| !rejections.contains(&grammar.grammar_id))
            .collect(),
        None => config.grammar,
    };

    Ok(grammars)
}

fn run_parallel<F>(grammars: Vec<GrammarConfiguration>, job: F, action: &'static str) -> Result<()>
where
    F: Fn(GrammarConfiguration) -> Result<()> + std::marker::Send + 'static + Copy,
{
    let pool = threadpool::Builder::new().build();
    let (tx, rx) = channel();

    for grammar in grammars {
        let tx = tx.clone();

        pool.execute(move || {
            tx.send(job(grammar)).unwrap();
        });
    }

    drop(tx);

    // TODO: print all failures instead of the first one found.
    rx.iter()
        .find(|result| result.is_err())
        .map(|err| err.with_context(|| format!("Failed to {} some grammar(s)", action)))
        .unwrap_or(Ok(()))
}

fn fetch_grammar(grammar: GrammarConfiguration) -> Result<()> {
    if let GrammarSource::Git {
        remote, revision, ..
    } = grammar.source
    {
        let grammar_dir = crate::runtime_dir()
            .join("grammars")
            .join("sources")
            .join(&grammar.grammar_id);

        fs::create_dir_all(&grammar_dir).context(format!(
            "Could not create grammar directory {:?}",
            grammar_dir
        ))?;

        // create the grammar dir contains a git directory
        if !grammar_dir.join(".git").is_dir() {
            git(&grammar_dir, ["init"])?;
        }

        // ensure the remote matches the configured remote
        if get_remote_url(&grammar_dir).map_or(true, |s| s != remote) {
            set_remote(&grammar_dir, &remote)?;
        }

        // ensure the revision matches the configured revision
        if get_revision(&grammar_dir).map_or(true, |s| s != revision) {
            // Fetch the exact revision from the remote.
            // Supported by server-side git since v2.5.0 (July 2015),
            // enabled by default on major git hosts.
            git(
                &grammar_dir,
                ["fetch", "--depth", "1", REMOTE_NAME, &revision],
            )?;
            git(&grammar_dir, ["checkout", &revision])?;

            println!(
                "Grammar '{}' checked out at '{}'.",
                grammar.grammar_id, revision
            );
        } else {
            println!("Grammar '{}' is already up to date.", grammar.grammar_id);
        }
    }

    Ok(())
}

// Sets the remote for a repository to the given URL, creating the remote if
// it does not yet exist.
fn set_remote(repository_dir: &Path, remote_url: &str) -> Result<String> {
    git(
        repository_dir,
        ["remote", "set-url", REMOTE_NAME, remote_url],
    )
    .or_else(|_| git(repository_dir, ["remote", "add", REMOTE_NAME, remote_url]))
}

fn get_remote_url(repository_dir: &Path) -> Option<String> {
    git(repository_dir, ["remote", "get-url", REMOTE_NAME]).ok()
}

fn get_revision(repository_dir: &Path) -> Option<String> {
    git(repository_dir, ["rev-parse", "HEAD"]).ok()
}

// A wrapper around 'git' commands which returns stdout in success and a
// helpful error message showing the command, stdout, and stderr in error.
fn git<I, S>(repository_dir: &Path, args: I) -> Result<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<std::ffi::OsStr>,
{
    let output = Command::new("git")
        .args(args)
        .current_dir(repository_dir)
        .output()?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout)
            .trim_end()
            .to_owned())
    } else {
        // TODO: figure out how to display the git command using `args`
        Err(anyhow!(
            "Git command failed.\nStdout: {}\nStderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        ))
    }
}

fn build_grammar(grammar: GrammarConfiguration) -> Result<()> {
    let grammar_dir = if let GrammarSource::Local { path } = &grammar.source {
        PathBuf::from(&path)
    } else {
        crate::runtime_dir()
            .join("grammars")
            .join("sources")
            .join(&grammar.grammar_id)
    };

    let grammar_dir_entries = grammar_dir.read_dir().with_context(|| {
        format!(
            "Failed to read directory {:?}. Did you use 'hx --grammar fetch'?",
            grammar_dir
        )
    })?;

    if grammar_dir_entries.count() == 0 {
        return Err(anyhow!(
            "Directory {:?} is empty. Did you use 'hx --grammar fetch'?",
            grammar_dir
        ));
    };

    let path = match &grammar.source {
        GrammarSource::Git {
            subpath: Some(subpath),
            ..
        } => grammar_dir.join(subpath),
        _ => grammar_dir,
    }
    .join("src");

    build_tree_sitter_library(&path, grammar)
}

fn build_tree_sitter_library(src_path: &Path, grammar: GrammarConfiguration) -> Result<()> {
    let header_path = src_path;
    let parser_path = src_path.join("parser.c");
    let mut scanner_path = src_path.join("scanner.c");

    let scanner_path = if scanner_path.exists() {
        Some(scanner_path)
    } else {
        scanner_path.set_extension("cc");
        if scanner_path.exists() {
            Some(scanner_path)
        } else {
            None
        }
    };
    let parser_lib_path = crate::runtime_dir().join("grammars");
    let mut library_path = parser_lib_path.join(&grammar.grammar_id);
    library_path.set_extension(DYLIB_EXTENSION);

    let recompile = needs_recompile(&library_path, &parser_path, &scanner_path)
        .context("Failed to compare source and binary timestamps")?;

    if !recompile {
        println!("Grammar '{}' is already built.", grammar.grammar_id);
        return Ok(());
    }

    println!("Building grammar '{}'", grammar.grammar_id);

    let mut config = cc::Build::new();
    config
        .cpp(true)
        .opt_level(3)
        .cargo_metadata(false)
        .host(BUILD_TARGET)
        .target(BUILD_TARGET);
    let compiler = config.get_compiler();
    let mut command = Command::new(compiler.path());
    command.current_dir(src_path);
    for (key, value) in compiler.env() {
        command.env(key, value);
    }

    if cfg!(windows) {
        command
            .args(&["/nologo", "/LD", "/I"])
            .arg(header_path)
            .arg("/Od")
            .arg("/utf-8");
        if let Some(scanner_path) = scanner_path.as_ref() {
            command.arg(scanner_path);
        }

        command
            .arg(parser_path)
            .arg("/link")
            .arg(format!("/out:{}", library_path.to_str().unwrap()));
    } else {
        command
            .arg("-shared")
            .arg("-fPIC")
            .arg("-fno-exceptions")
            .arg("-g")
            .arg("-I")
            .arg(header_path)
            .arg("-o")
            .arg(&library_path)
            .arg("-O3");
        if let Some(scanner_path) = scanner_path.as_ref() {
            if scanner_path.extension() == Some("c".as_ref()) {
                command.arg("-xc").arg("-std=c99").arg(scanner_path);
            } else {
                command.arg(scanner_path);
            }
        }
        command.arg("-xc").arg(parser_path);
        if cfg!(all(unix, not(target_os = "macos"))) {
            command.arg("-Wl,-z,relro,-z,now");
        }
    }

    let output = command.output().context("Failed to execute C compiler")?;
    if !output.status.success() {
        return Err(anyhow!(
            "Parser compilation failed.\nStdout: {}\nStderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ));
    }

    Ok(())
}

fn needs_recompile(
    lib_path: &Path,
    parser_c_path: &Path,
    scanner_path: &Option<PathBuf>,
) -> Result<bool> {
    if !lib_path.exists() {
        return Ok(true);
    }
    let lib_mtime = mtime(lib_path)?;
    if mtime(parser_c_path)? > lib_mtime {
        return Ok(true);
    }
    if let Some(scanner_path) = scanner_path {
        if mtime(scanner_path)? > lib_mtime {
            return Ok(true);
        }
    }
    Ok(false)
}

fn mtime(path: &Path) -> Result<SystemTime> {
    Ok(fs::metadata(path)?.modified()?)
}

/// Gives the contents of a file from a language's `runtime/queries/<lang>`
/// directory
pub fn load_runtime_file(language: &str, filename: &str) -> Result<String, std::io::Error> {
    let path = crate::RUNTIME_DIR
        .join("queries")
        .join(language)
        .join(filename);
    std::fs::read_to_string(&path)
}
: [], // Languages used for auto-detection }); let code_nodes = Array .from(document.querySelectorAll('code')) // Don't highlight `inline code` blocks in headers. .filter(function (node) {return !node.parentElement.classList.contains("header"); }); if (window.ace) { // language-rust class needs to be removed for editable // blocks or highlightjs will capture events Array .from(document.querySelectorAll('code.editable')) .forEach(function (block) { block.classList.remove('language-rust'); }); Array .from(document.querySelectorAll('code:not(.editable)')) .forEach(function (block) { hljs.highlightBlock(block); }); } else { code_nodes.forEach(function (block) { hljs.highlightBlock(block); }); } // Adding the hljs class gives code blocks the color css // even if highlighting doesn't apply code_nodes.forEach(function (block) { block.classList.add('hljs'); }); Array.from(document.querySelectorAll("code.language-rust")).forEach(function (block) { var lines = Array.from(block.querySelectorAll('.boring')); // If no lines were hidden, return if (!lines.length) { return; } block.classList.add("hide-boring"); var buttons = document.createElement('div'); buttons.className = 'buttons'; buttons.innerHTML = "<button class=\"fa fa-eye\" title=\"Show hidden lines\" aria-label=\"Show hidden lines\"></button>"; // add expand button var pre_block = block.parentNode; pre_block.insertBefore(buttons, pre_block.firstChild); pre_block.querySelector('.buttons').addEventListener('click', function (e) { if (e.target.classList.contains('fa-eye')) { e.target.classList.remove('fa-eye'); e.target.classList.add('fa-eye-slash'); e.target.title = 'Hide lines'; e.target.setAttribute('aria-label', e.target.title); block.classList.remove('hide-boring'); } else if (e.target.classList.contains('fa-eye-slash')) { e.target.classList.remove('fa-eye-slash'); e.target.classList.add('fa-eye'); e.target.title = 'Show hidden lines'; e.target.setAttribute('aria-label', e.target.title); block.classList.add('hide-boring'); } }); }); if (window.playground_copyable) { Array.from(document.querySelectorAll('pre code')).forEach(function (block) { var pre_block = block.parentNode; if (!pre_block.classList.contains('playground')) { var buttons = pre_block.querySelector(".buttons"); if (!buttons) { buttons = document.createElement('div'); buttons.className = 'buttons'; pre_block.insertBefore(buttons, pre_block.firstChild); } var clipButton = document.createElement('button'); clipButton.className = 'fa fa-copy clip-button'; clipButton.title = 'Copy to clipboard'; clipButton.setAttribute('aria-label', clipButton.title); clipButton.innerHTML = '<i class=\"tooltiptext\"></i>'; buttons.insertBefore(clipButton, buttons.firstChild); } }); } // Process playground code blocks Array.from(document.querySelectorAll(".playground")).forEach(function (pre_block) { // Add play button var buttons = pre_block.querySelector(".buttons"); if (!buttons) { buttons = document.createElement('div'); buttons.className = 'buttons'; pre_block.insertBefore(buttons, pre_block.firstChild); } var runCodeButton = document.createElement('button'); runCodeButton.className = 'fa fa-play play-button'; runCodeButton.hidden = true; runCodeButton.title = 'Run this code'; runCodeButton.setAttribute('aria-label', runCodeButton.title); buttons.insertBefore(runCodeButton, buttons.firstChild); runCodeButton.addEventListener('click', function (e) { run_rust_code(pre_block); }); if (window.playground_copyable) { var copyCodeClipboardButton = document.createElement('button'); copyCodeClipboardButton.className = 'fa fa-copy clip-button'; copyCodeClipboardButton.innerHTML = '<i class="tooltiptext"></i>'; copyCodeClipboardButton.title = 'Copy to clipboard'; copyCodeClipboardButton.setAttribute('aria-label', copyCodeClipboardButton.title); buttons.insertBefore(copyCodeClipboardButton, buttons.firstChild); } let code_block = pre_block.querySelector("code"); if (window.ace && code_block.classList.contains("editable")) { var undoChangesButton = document.createElement('button'); undoChangesButton.className = 'fa fa-history reset-button'; undoChangesButton.title = 'Undo changes'; undoChangesButton.setAttribute('aria-label', undoChangesButton.title); buttons.insertBefore(undoChangesButton, buttons.firstChild); undoChangesButton.addEventListener('click', function () { let editor = window.ace.edit(code_block); editor.setValue(editor.originalCode); editor.clearSelection(); }); } }); })(); (function themes() { var html = document.querySelector('html'); var themeToggleButton = document.getElementById('theme-toggle'); var themePopup = document.getElementById('theme-list'); var themeColorMetaTag = document.querySelector('meta[name="theme-color"]'); var stylesheets = { ayuHighlight: document.querySelector("[href$='ayu-highlight.css']"), tomorrowNight: document.querySelector("[href$='tomorrow-night.css']"), highlight: document.querySelector("[href$='highlight.css']"), }; function showThemes() { themePopup.style.display = 'block'; themeToggleButton.setAttribute('aria-expanded', true); themePopup.querySelector("button#" + get_theme()).focus(); } function hideThemes() { themePopup.style.display = 'none'; themeToggleButton.setAttribute('aria-expanded', false); themeToggleButton.focus(); } function get_theme() { var theme; try { theme = localStorage.getItem('mdbook-theme'); } catch (e) { } if (theme === null || theme === undefined) { return default_theme; } else { return theme; } } function set_theme(theme, store = true) { let ace_theme; if (theme == 'coal' || theme == 'navy') { stylesheets.ayuHighlight.disabled = true; stylesheets.tomorrowNight.disabled = false; stylesheets.highlight.disabled = true; ace_theme = "ace/theme/tomorrow_night"; } else if (theme == 'ayu') { stylesheets.ayuHighlight.disabled = false; stylesheets.tomorrowNight.disabled = true; stylesheets.highlight.disabled = true; ace_theme = "ace/theme/tomorrow_night"; } else { stylesheets.ayuHighlight.disabled = true; stylesheets.tomorrowNight.disabled = true; stylesheets.highlight.disabled = false; ace_theme = "ace/theme/dawn"; } setTimeout(function () { themeColorMetaTag.content = getComputedStyle(document.body).backgroundColor; }, 1); if (window.ace && window.editors) { window.editors.forEach(function (editor) { editor.setTheme(ace_theme); }); } var previousTheme = get_theme(); if (store) { try { localStorage.setItem('mdbook-theme', theme); } catch (e) { } } html.classList.remove(previousTheme); html.classList.add(theme); } // Set theme var theme = get_theme(); set_theme(theme, false); themeToggleButton.addEventListener('click', function () { if (themePopup.style.display === 'block') { hideThemes(); } else { showThemes(); } }); themePopup.addEventListener('click', function (e) { var theme = e.target.id || e.target.parentElement.id; set_theme(theme); }); themePopup.addEventListener('focusout', function(e) { // e.relatedTarget is null in Safari and Firefox on macOS (see workaround below) if (!!e.relatedTarget && !themeToggleButton.contains(e.relatedTarget) && !themePopup.contains(e.relatedTarget)) { hideThemes(); } }); // Should not be needed, but it works around an issue on macOS & iOS: https://github.com/rust-lang/mdBook/issues/628 document.addEventListener('click', function(e) { if (themePopup.style.display === 'block' && !themeToggleButton.contains(e.target) && !themePopup.contains(e.target)) { hideThemes(); } }); document.addEventListener('keydown', function (e) { if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; } if (!themePopup.contains(e.target)) { return; } switch (e.key) { case 'Escape': e.preventDefault(); hideThemes(); break; case 'ArrowUp': e.preventDefault(); var li = document.activeElement.parentElement; if (li && li.previousElementSibling) { li.previousElementSibling.querySelector('button').focus(); } break; case 'ArrowDown': e.preventDefault(); var li = document.activeElement.parentElement; if (li && li.nextElementSibling) { li.nextElementSibling.querySelector('button').focus(); } break; case 'Home': e.preventDefault(); themePopup.querySelector('li:first-child button').focus(); break; case 'End': e.preventDefault(); themePopup.querySelector('li:last-child button').focus(); break; } }); })(); (function sidebar() { var html = document.querySelector("html"); var sidebar = document.getElementById("sidebar"); var sidebarLinks = document.querySelectorAll('#sidebar a'); var sidebarToggleButton = document.getElementById("sidebar-toggle"); var sidebarResizeHandle = document.getElementById("sidebar-resize-handle"); var firstContact = null; function showSidebar() { html.classList.remove('sidebar-hidden') html.classList.add('sidebar-visible'); Array.from(sidebarLinks).forEach(function (link) { link.setAttribute('tabIndex', 0); }); sidebarToggleButton.setAttribute('aria-expanded', true); sidebar.setAttribute('aria-hidden', false); try { localStorage.setItem('mdbook-sidebar', 'visible'); } catch (e) { } } var sidebarAnchorToggles = document.querySelectorAll('#sidebar a.toggle'); function toggleSection(ev) { ev.currentTarget.parentElement.classList.toggle('expanded'); } Array.from(sidebarAnchorToggles).forEach(function (el) { el.addEventListener('click', toggleSection); }); function hideSidebar() { html.classList.remove('sidebar-visible') html.classList.add('sidebar-hidden'); Array.from(sidebarLinks).forEach(function (link) { link.setAttribute('tabIndex', -1); }); sidebarToggleButton.setAttribute('aria-expanded', false); sidebar.setAttribute('aria-hidden', true); try { localStorage.setItem('mdbook-sidebar', 'hidden'); } catch (e) { } } // Toggle sidebar sidebarToggleButton.addEventListener('click', function sidebarToggle() { if (html.classList.contains("sidebar-hidden")) { var current_width = parseInt( document.documentElement.style.getPropertyValue('--sidebar-width'), 10); if (current_width < 150) { document.documentElement.style.setProperty('--sidebar-width', '150px'); } showSidebar(); } else if (html.classList.contains("sidebar-visible")) { hideSidebar(); } else { if (getComputedStyle(sidebar)['transform'] === 'none') { hideSidebar(); } else { showSidebar(); } } }); sidebarResizeHandle.addEventListener('mousedown', initResize, false); function initResize(e) { window.addEventListener('mousemove', resize, false); window.addEventListener('mouseup', stopResize, false); html.classList.add('sidebar-resizing'); } function resize(e) { var pos = (e.clientX - sidebar.offsetLeft); if (pos < 20) { hideSidebar(); } else { if (html.classList.contains("sidebar-hidden")) { showSidebar(); } pos = Math.min(pos, window.innerWidth - 100); document.documentElement.style.setProperty('--sidebar-width', pos + 'px'); } } //on mouseup remove windows functions mousemove & mouseup function stopResize(e) { html.classList.remove('sidebar-resizing'); window.removeEventListener('mousemove', resize, false); window.removeEventListener('mouseup', stopResize, false); } document.addEventListener('touchstart', function (e) { firstContact = { x: e.touches[0].clientX, time: Date.now() }; }, { passive: true }); document.addEventListener('touchmove', function (e) { if (!firstContact) return; var curX = e.touches[0].clientX; var xDiff = curX - firstContact.x, tDiff = Date.now() - firstContact.time; if (tDiff < 250 && Math.abs(xDiff) >= 150) { if (xDiff >= 0 && firstContact.x < Math.min(document.body.clientWidth * 0.25, 300)) showSidebar(); else if (xDiff < 0 && curX < 300) hideSidebar(); firstContact = null; } }, { passive: true }); // Scroll sidebar to current active section var activeSection = document.getElementById("sidebar").querySelector(".active"); if (activeSection) { // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView activeSection.scrollIntoView({ block: 'center' }); } })(); (function chapterNavigation() { document.addEventListener('keydown', function (e) { if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; } if (window.search && window.search.hasFocus()) { return; } switch (e.key) { case 'ArrowRight': e.preventDefault(); var nextButton = document.querySelector('.nav-chapters.next'); if (nextButton) { window.location.href = nextButton.href; } break; case 'ArrowLeft': e.preventDefault(); var previousButton = document.querySelector('.nav-chapters.previous'); if (previousButton) { window.location.href = previousButton.href; } break; } }); })(); (function clipboard() { var clipButtons = document.querySelectorAll('.clip-button'); function hideTooltip(elem) { elem.firstChild.innerText = ""; elem.className = 'fa fa-copy clip-button'; } function showTooltip(elem, msg) { elem.firstChild.innerText = msg; elem.className = 'fa fa-copy tooltipped'; } var clipboardSnippets = new ClipboardJS('.clip-button', { text: function (trigger) { hideTooltip(trigger); let playground = trigger.closest("pre"); return playground_text(playground); } }); Array.from(clipButtons).forEach(function (clipButton) { clipButton.addEventListener('mouseout', function (e) { hideTooltip(e.currentTarget); }); }); clipboardSnippets.on('success', function (e) { e.clearSelection(); showTooltip(e.trigger, "Copied!"); }); clipboardSnippets.on('error', function (e) { showTooltip(e.trigger, "Clipboard error!"); }); })(); (function scrollToTop () { var menuTitle = document.querySelector('.menu-title'); menuTitle.addEventListener('click', function () { document.scrollingElement.scrollTo({ top: 0, behavior: 'smooth' }); }); })(); (function controlMenu() { var menu = document.getElementById('menu-bar'); (function controlPosition() { var scrollTop = document.scrollingElement.scrollTop; var prevScrollTop = scrollTop; var minMenuY = -menu.clientHeight - 50; // When the script loads, the page can be at any scroll (e.g. if you reforesh it). menu.style.top = scrollTop + 'px'; // Same as parseInt(menu.style.top.slice(0, -2), but faster var topCache = menu.style.top.slice(0, -2); menu.classList.remove('sticky'); var stickyCache = false; // Same as menu.classList.contains('sticky'), but faster document.addEventListener('scroll', function () { scrollTop = Math.max(document.scrollingElement.scrollTop, 0); // `null` means that it doesn't need to be updated var nextSticky = null; var nextTop = null; var scrollDown = scrollTop > prevScrollTop; var menuPosAbsoluteY = topCache - scrollTop; if (scrollDown) { nextSticky = false; if (menuPosAbsoluteY > 0) { nextTop = prevScrollTop; } } else { if (menuPosAbsoluteY > 0) { nextSticky = true; } else if (menuPosAbsoluteY < minMenuY) { nextTop = prevScrollTop + minMenuY; } } if (nextSticky === true && stickyCache === false) { menu.classList.add('sticky'); stickyCache = true; } else if (nextSticky === false && stickyCache === true) { menu.classList.remove('sticky'); stickyCache = false; } if (nextTop !== null) { menu.style.top = nextTop + 'px'; topCache = nextTop; } prevScrollTop = scrollTop; }, { passive: true }); })(); (function controlBorder() { menu.classList.remove('bordered'); document.addEventListener('scroll', function () { if (menu.offsetTop === 0) { menu.classList.remove('bordered'); } else { menu.classList.add('bordered'); } }, { passive: true }); })(); })();