my_blog/public/js/themes.js

83 lines
2.3 KiB
JavaScript

/**
*
* @source http://tilde.club/~chmod777/js/themes.js
*
* @license AGPL-3.0-only
* @licstart
* Copyright (c) 2021 chmod777
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* @licend
*/
const color_theme_id = "color-theme";
const font_id = "fonts";
function save_theme_settings(theme, font) {
document.cookie = "theme=" + theme + "; path=/";
document.cookie = "font=" + font +"; path=/";
}
function get_saved_theme_settings() {
let cookies = document.cookie.split("; ");
let theme = null;
let font = null;
for (let cookie of cookies) {
let [key, value] = cookie.split("=");
if (key == "theme") {
theme = value;
}
if (key == "font") {
font = value;
}
}
if (theme != null) {
let color_theme = document.getElementById(color_theme_id);
for (option of color_theme.options) {
if (option.value == theme) {
option.selected = true;
break;
}
}
}
if (font != null) {
let fonts = document.getElementById(font_id);
for (option of fonts.options) {
if (option.value == font) {
option.selected = true;
break;
}
}
}
return [theme, font];
}
function load_theme_settings(theme, font) {
const body = document.getElementsByTagName("body")[0];
if (theme && theme.length != 0) {
body.setAttribute("class", theme);
}
if (font && font.length != 0) {
let class_attribute = body.getAttribute("class");
body.setAttribute("class", class_attribute+" "+font);
}
}
function apply_theme_options() {
const theme = document.getElementById(color_theme_id).value;
const font = document.getElementById(font_id).value;
save_theme_settings(theme, font);
load_theme_settings(theme, font);
}
function first_load() {
let [theme, font] = get_saved_theme_settings();
load_theme_settings(theme, font);
}