import type { LockInfo, Nullable } from '@eciol/types'; import { context } from '../context'; import { acceptHMRUpdate, defineStore } from '../index'; interface LockState { lockInfo: Nullable; } export const useLockStore = defineStore({ id: 'shared-lock', persist: { // 持久化 paths: ['lockInfo'], }, state: (): LockState => ({ lockInfo: null, }), getters: { getLockInfo(state): Nullable { return state.lockInfo ?? {}; }, }, actions: { setLockInfo(info: LockInfo) { this.lockInfo = Object.assign({}, this.lockInfo, info); }, resetLockInfo() { this.lockInfo = null; }, // Unlock async unLock(password?: string) { const userStore = context.useUserStore(); if (this.lockInfo?.pwd === password) { this.resetLockInfo(); return true; } const tryLogin = async () => { try { const username = userStore.getUserInfo?.username; const res = await userStore.login({ username, password, goHome: false, mode: 'none', }); if (res) { this.resetLockInfo(); } return res; } catch (error) { return false; } }; return await tryLogin(); }, }, }); // 解决热更新问题 const hot = import.meta.hot; if (hot) { hot.accept(acceptHMRUpdate(useLockStore, hot)); }