Commit 26607ca0 authored by KesaubeEire's avatar KesaubeEire

feat: add store.js && localStorage persist.

parent 0154d47c
<script>
import { onMount } from 'svelte';
import { _theme } from './stores';
/**主题*/
const themes = [
'light',
......@@ -70,9 +72,19 @@
}
}
];
onMount(() => {
// 1. 读取 localstorage
// -- 1.1. 读取 theme
document.documentElement.setAttribute('data-theme', $_theme);
// 2. 检测 darkreader 是否开启
const has_darkreader = document.querySelector('.darkreader');
if (has_darkreader) toast.push('检测到 dark reader, 建议关闭当前网站的 darkreader, 可点击导航栏的主题更改相应的主题', { initial: 0 });
});
</script>
<!-- <div class="top">决斗编年史</div> -->
<!-- ----------------------------------------------- DOM ----------------------------------------------- -->
<!-- 导航栏 -->
<div class="drawer">
......@@ -109,7 +121,8 @@
<button
data-theme={theme}
on:click={() => {
document.body.parentElement.setAttribute('data-theme', theme);
document.documentElement.setAttribute('data-theme', theme);
$_theme = theme;
console.log('切换主题:\t', theme);
}}
class="rounded my-1 flex justify-between items-center"
......
import { writable } from 'svelte/store';
// ----------------------------------------------------------------
// localstorage 持久化处理 -------------------------------------
/**localstorage 里存储字段对象的 key 名称*/
const persistName = 'Kesa:rrpg_link';
/** localstorage 数据持久化 svelte stores 函数
* @param {*} key 在 localstorage 存储对象里的 key 值
* @param {*} startValue 初始化默认值
* @returns svelte stores 对象
*/
function persistStore(key, startValue) {
// 判断 localstorage 中有无存储字段对象
if (!localStorage.getItem(persistName)) localStorage.setItem(persistName, "{}");
// 有 ls 中的值就挂载, 没有就从默认值创建, 并根据值注册 svelte store 初始化对象
const savedValue = JSON.parse(localStorage.getItem(persistName))[key];
const initialValue = savedValue ?? startValue;
const store = writable(initialValue);
// 对 svelte store 对象进行订阅以取得全局变化调用
store.subscribe(value => {
const data = JSON.parse(localStorage.getItem(persistName)) ?? {};
data[key] = value;
localStorage.setItem(persistName, JSON.stringify(data));
});
// FIXME: 对旧版本词条的处理, 过几个月也许可以去掉这个玩意儿, 减少损害其他东西的可能性
if (localStorage.getItem(key)) localStorage.removeItem(key)
return store;
}
// 变量 -------------------------------------
/** 主题 */
export const _theme = persistStore('_theme', "light");
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment