Skip to content

Commit

Permalink
refactor(CSP): make toggle theme JS logic not inline
Browse files Browse the repository at this point in the history
  • Loading branch information
micahkepe committed Feb 9, 2025
1 parent efa033a commit db9a41b
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 90 deletions.
10 changes: 5 additions & 5 deletions config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ taxonomies = [

# When set to "true", a search index is built from the pages and section
# content for `default_language`.
build_search_index = true
build_search_index = true

[markdown]
# Whether to do syntax highlighting
Expand All @@ -33,14 +33,14 @@ radion_menu = [
]
radion_title = "My Example Site"

# Nicer codeblocks with copy to clipboard
# Nicer codeblocks with copy to clipboard
codeblock = true

# Enable MathJax support
latex = true

# Enable search bar
enable_search = true
# Enable search bar
enable_search = true

# Light/Dark Mode set
# Light/Dark Mode set
theme = "toggle" # options: {light, dark, auto, toggle}
96 changes: 50 additions & 46 deletions static/js/toggle-theme.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,57 +3,44 @@
* https://github.com/not-matthias/apollo/blob/main/static/js/themetoggle.js
*/

/**
* Update the theme mode in local storage.
* @param {string} mode - The theme mode to set ("light" or "dark")
* @returns {void}
*/
function setTheme(mode) {
localStorage.setItem("theme-storage", mode);
}
document.addEventListener("DOMContentLoaded", function () {
const storedTheme = localStorage.getItem("theme-storage");
const defaultTheme = document.documentElement.dataset.theme || "toggle";

let currentTheme;

/** Fetch the current theme mode from local storage or the browser settings.
* @returns {string} The current theme mode ("light" or "dark")
* */
function getSavedTheme() {
let currentTheme = localStorage.getItem("theme-storage");
if (!currentTheme) {
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
currentTheme = "dark";
} else {
currentTheme = "light";
}
// Prioritize config.extra.theme over localStorage if available
if (
defaultTheme === "dark" ||
defaultTheme === "light" ||
defaultTheme === "auto"
) {
currentTheme = defaultTheme;
} else if (storedTheme) {
currentTheme = storedTheme;
} else {
currentTheme = "dark"; // Default to dark
}

return currentTheme;
}
// Apply the theme
setTheme(currentTheme);

/**
* Toggle the theme between light and dark mode
* @returns {void}
*/
function toggleTheme() {
if (localStorage.getItem("theme-storage") === "light") {
setTheme("dark");
updateItemToggleTheme();
} else if (localStorage.getItem("theme-storage") === "dark") {
setTheme("light");
updateItemToggleTheme();
// Add event listener for the theme toggle button
const toggleButton = document.getElementById("dark-mode-toggle");
if (toggleButton) {
toggleButton.addEventListener("click", function (event) {
event.preventDefault();
toggleTheme();
});
}
}
});

/**
* Update the theme UI icon based on the current theme mode.
* @returns {void}
* Updates the theme mode in local storage and applies it to the page.
* @param {string} mode - The theme mode to set ("light" or "dark").
*/
function updateItemToggleTheme() {
const mode = getSavedTheme();
const sunIcon = document.getElementById("sun-icon");
const moonIcon = document.getElementById("moon-icon");

function setTheme(mode) {
localStorage.setItem("theme-storage", mode);
document.documentElement.classList.remove("light", "dark");
document.body.classList.remove("light", "dark");

Expand All @@ -65,11 +52,28 @@ function updateItemToggleTheme() {
document.body.classList.add("light");
}

updateThemeIcons(mode);
}

/**
* Toggles between light and dark mode.
*/
function toggleTheme() {
const newTheme = document.documentElement.classList.contains("dark")
? "light"
: "dark";
setTheme(newTheme);
}

/**
* Updates the visibility of the sun and moon icons based on the theme.
*/
function updateThemeIcons(mode) {
const sunIcon = document.getElementById("sun-icon");
const moonIcon = document.getElementById("moon-icon");

if (sunIcon && moonIcon) {
sunIcon.style.display = mode === "dark" ? "inline-block" : "none";
moonIcon.style.display = mode === "light" ? "inline-block" : "none";
}
}

// Update the toggle theme on page load
updateItemToggleTheme();
54 changes: 15 additions & 39 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<!-- Enable responsiveness on mobile devices-->
<!-- Enable responsiveness on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

{% if page %} {% if page.description %}
Expand All @@ -26,12 +26,19 @@
title="RSS"
href="{{ get_url(path='atom.xml') | safe }}"
/>
{% endif %} {% block css %}
{% endif %}

<!-- Load Styles -->
<link
rel="stylesheet"
href="{{ get_url(path='site.css', trailing_slash=false) | safe }}"
/>
{% endblock css %} {% block extra_head %} {% endblock extra_head %}

<!-- Pass Theme Preference as Data Attribute -->
<script>
document.documentElement.dataset.theme =
"{{ config.extra.theme | default(value='toggle') }}";
</script>
</head>

<body class="hack dark main container">
Expand All @@ -46,11 +53,11 @@
{% for item in config.extra.radion_menu %}
<a
itemprop="url"
class="{% if item.url | replace(from='$BASE_URL', to=config.base_url)==current_url %}active{% endif %}"
class="{% if item.url | replace(from='$BASE_URL', to=config.base_url) == current_url %}active{% endif %}"
href="{{ item.url | safe | replace(from='$BASE_URL', to=config.base_url) | safe }}"
>
<span itemprop="name">{{ item.name }}</span></a
>
<span itemprop="name">{{ item.name }}</span>
</a>
{% endfor %}
</div>
</nav>
Expand All @@ -75,11 +82,7 @@
</div>
{% endif %} {% if config.extra.theme | default(value="toggle") ==
"toggle" %}
<a
id="dark-mode-toggle"
onclick="toggleTheme(); event.preventDefault();"
href="#"
>
<a id="dark-mode-toggle" href="#">
<img
src="{{ get_url(path='icons/sun.svg') }}"
id="sun-icon"
Expand Down Expand Up @@ -120,39 +123,12 @@
</a>
{% endif %}
</div>

{% set theme = config.extra.theme | default(value="toggle") %}
<!-- Set the correct theme in the script -->
<script src="{{ get_url(path='js/toggle-theme.js' ) }}"></script>
{% if theme == "dark" %}
<script>
setTheme("dark");
</script>
{% elif theme == "light" %}
<script>
setTheme("light");
</script>
{% elif theme == "auto" %}
<script>
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
setTheme("dark");
} else {
setTheme("light");
}
</script>
{% else %}
<script>
setTheme(getSavedTheme());
</script>
{% endif %}
</header>
{% endif %} {% endblock header %}

<main>
{% if config.extra.radion_title %}
<header>
<h1>{{ config.extra.radion_title }}</h1>
</header>
<header><h1>{{ config.extra.radion_title }}</h1></header>
{% endif %} {% for page in paginator.pages %} {{
post_macros::page_in_list(page=page) }} {% endfor %}

Expand Down

0 comments on commit db9a41b

Please sign in to comment.