Skip to content

Commit 93a141e

Browse files
authored
Merge pull request #1424 from dtolnay/jspatch
Perform mdbook js patching more exactly
2 parents e26474a + 8a742f1 commit 93a141e

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

book/build.js

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,17 @@ const opengraph = `\
2222
<meta name="twitter:card" content="summary" />\
2323
<meta name="twitter:title" content="CXX — safe interop between Rust and C++" />`;
2424

25-
const htmljs = `\
26-
var html = document.querySelector('html');
27-
html.classList.remove('no-js');
25+
const themejs = `\
26+
var theme;
27+
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) {}
28+
if (theme === null || theme === undefined) { theme = default_theme; }
29+
const html = document.documentElement;
30+
html.classList.remove('light')
31+
html.classList.add(theme);
32+
html.classList.add("js");`;
33+
34+
const themejsReplacement = `\
35+
const html = document.documentElement;
2836
html.classList.add('js');`;
2937

3038
const dirs = ['build'];
@@ -46,7 +54,6 @@ while (dirs.length) {
4654
const $ = cheerio.load(index, { decodeEntities: false });
4755

4856
$('head').append(opengraph);
49-
$('script:nth-of-type(3)').text(htmljs);
5057
$('nav#sidebar ol.chapter').append(githublink);
5158
$('head link[href="tomorrow-night.css"]').attr('disabled', true);
5259
$('head link[href="ayu-highlight.css"]').attr('disabled', true);
@@ -90,6 +97,19 @@ while (dirs.length) {
9097
$(this).addClass('hljs');
9198
});
9299

100+
var foundScript = false;
101+
$('body script').each(function () {
102+
const node = $(this);
103+
if (node.text().replace(/\s/g, '') === themejs.replace(/\s/g, '')) {
104+
node.text(themejsReplacement);
105+
foundScript = true;
106+
}
107+
});
108+
const pathsWithoutScript = ['build/toc.html', 'build/build/index.html', 'build/binding/index.html'];
109+
if (!foundScript && !pathsWithoutScript.includes(path)) {
110+
throw new Error('theme script not found');
111+
}
112+
93113
const out = $.html();
94114
fs.writeFileSync(path, out);
95115
});

0 commit comments

Comments
 (0)