From c3c8ef9b45d06157cec50b4c8e41375a5d2d0745 Mon Sep 17 00:00:00 2001 From: Benjamin Bannier Date: Fri, 24 Jan 2025 11:55:20 +0100 Subject: [PATCH] Add js to disable solutions on 'F10' --- book.toml | 1 + src/js/solutions.js | 46 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/js/solutions.js diff --git a/book.toml b/book.toml index fafbca2..b66468f 100644 --- a/book.toml +++ b/book.toml @@ -8,6 +8,7 @@ title = "Introduction to Spicy" [output.html] additional-css = ["./src/css/mdbook-admonish.css", "./mdbook-admonish.css"] additional-js = [ + "./src/js/solutions.js", "./src/js/highlight-evt.js", "./src/js/highlight-spicy.js", "./src/js/highlight-spicy_batch.js", diff --git a/src/js/solutions.js b/src/js/solutions.js new file mode 100644 index 0000000..5746d30 --- /dev/null +++ b/src/js/solutions.js @@ -0,0 +1,46 @@ +const HIDE_SOLUTIONS = "hide_solutions"; + +/** + * Change the visibility state of solutions. + * @param {boolean} show whether to show solutions + */ +function set_solutions(show) { + document.querySelectorAll("details") + .forEach((div) => { + const classes = div.classList; + if (!show) + classes.add("hidden"); + else + classes.remove("hidden"); + }); +} + +/** + * Query whether we are configured to hide solutions. + * @returns {boolean} + */ +function hide_solutions() { + const hide = localStorage.getItem(HIDE_SOLUTIONS); + return !!hide; +} + +/** + * Toggle the visibility status of solutions + */ +function toggle_show_solutions() { + if (hide_solutions()) { + localStorage.removeItem(HIDE_SOLUTIONS); + set_solutions(true); + } else { + localStorage.setItem(HIDE_SOLUTIONS, "true"); + set_solutions(false); + } +} + +// Register for keydown and a slightly obscure function key to not interfere +// with mdbook's search bar functionality (in `searcher.js`). +document.addEventListener("keydown", function (event) { + if (event.key == 'F10') { + toggle_show_solutions(); + } +});