mirror of
https://github.com/Pandipipas/scoreko-dev.git
synced 2026-06-06 03:32:06 +00:00
refactor stores replicant and storage synchronization
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { playersReplicant } from '../../../browser_shared/replicants';
|
||||
import type { Schemas } from '../../../types';
|
||||
import { readStorageSnapshot, syncStateWithReplicant } from './store-sync';
|
||||
|
||||
type PlayersMap = Schemas.Players;
|
||||
type Player = PlayersMap[string];
|
||||
@@ -33,69 +34,15 @@ const normalizePlayers = (input: unknown): PlayersMap => {
|
||||
return result;
|
||||
};
|
||||
|
||||
const readStorage = (): PlayersMap | null => {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return normalizePlayers(parsed);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const writeStorage = (value: PlayersMap) => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value));
|
||||
} catch {
|
||||
// Ignore storage errors (quota, disabled, etc.)
|
||||
}
|
||||
};
|
||||
|
||||
export const usePlayersStore = defineStore('players', () => {
|
||||
const players = ref<PlayersMap>({});
|
||||
const replicant = playersReplicant;
|
||||
const storageSnapshot = readStorage();
|
||||
const storageSnapshot = readStorageSnapshot(STORAGE_KEY, normalizePlayers);
|
||||
if (storageSnapshot) {
|
||||
players.value = storageSnapshot;
|
||||
}
|
||||
|
||||
const isApplyingReplicant = ref(false);
|
||||
|
||||
watch(
|
||||
() => replicant?.data,
|
||||
(value) => {
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
isApplyingReplicant.value = true;
|
||||
players.value = normalizePlayers(value);
|
||||
isApplyingReplicant.value = false;
|
||||
writeStorage(players.value);
|
||||
},
|
||||
{ deep: true, immediate: true }
|
||||
);
|
||||
|
||||
watch(
|
||||
players,
|
||||
(value) => {
|
||||
writeStorage(value);
|
||||
if (isApplyingReplicant.value || !replicant) {
|
||||
return;
|
||||
}
|
||||
replicant.data = normalizePlayers(value);
|
||||
replicant.save();
|
||||
},
|
||||
{ deep: true, flush: 'sync' }
|
||||
);
|
||||
syncStateWithReplicant(players, replicant, normalizePlayers, STORAGE_KEY);
|
||||
|
||||
const setPlayers = (value: PlayersMap) => {
|
||||
players.value = normalizePlayers(value);
|
||||
|
||||
Reference in New Issue
Block a user