"use client"; import { atom, type PrimitiveAtom } from "jotai"; import { setLocalStorage, getLocalStorage, removeLocalStorage, setSessionStorage, getSessionStorage, removeSessionStorage } from "@/store/storage/secure-storage"; import {StorageKey} from "@/store/storage/storage-keys"; const loadInitialState = (storageType: "local"|"session", key: StorageKey, initialValue: T): T => { if (typeof window === "undefined") { // SSR 시에는 그냥 기본값 사용 return initialValue; } const stored = storageType == "local" ? getLocalStorage(key) : getSessionStorage(key); if (stored && typeof stored === "object") { return stored as T; } return initialValue; } /** * localStorage(AES 암호화) + Jotai 연동용 Atom 생성기 * - initialValue: SSR 시/최초 렌더 시 기본값 * - 마운트 후 localStorage에서 실제 값 읽어와서 덮어씀 */ export const createLocalStorageAtom = ( key: StorageKey, initialValue: T, ) => { const realInitialValue = loadInitialState("local", key, initialValue); const baseAtom: PrimitiveAtom = atom(realInitialValue); // 하이드레이션(저장소 주입)과 사용자 set 경합 방지용 플래그 let wasOverridden = false; // 마운트 이후 사용자가 값을 쓴 적이 있는지 const persistentAtom = atom( (get) => get(baseAtom), (get, set, update: T | ((prev: T) => T)) => { const prev = get(baseAtom); const next = typeof update === "function" ? (update as (prev: T) => T)(prev) : update; // 메모리 상태 갱신 set(baseAtom, next); // 사용자 쓰기 발생 표시 (하이드레이션이 도착해도 무시하도록) wasOverridden = true; if (next === null || (next as unknown) === undefined) { // 암호화 localStorage 및 캐시 제거 removeLocalStorage(key); } else { // 동기 API로 캐시를 먼저 기록하고 암호화 저장은 백그라운드 처리 setLocalStorage(key, next); } }, ); return persistentAtom; } /** * sessionStorage + Jotai 연동용 Atom 생성기 * - 탭 단위로 유지, 탭/브라우저 닫히면 삭제 * - 새로고침 시 유지 */ export const createSessionStorageAtom = ( key: StorageKey, initialValue: T, ) => { const realInitialValue = loadInitialState("session", key, initialValue); const baseAtom: PrimitiveAtom = atom(realInitialValue); const persistentAtom = atom( (get) => get(baseAtom), (get, set, update: T | ((prev: T) => T)) => { const prev = get(baseAtom); const next = typeof update === "function" ? (update as (prev: T) => T)(prev) : update; set(baseAtom, next); if (typeof window === "undefined") return; try { if (next === null || (next as unknown) === undefined) { removeSessionStorage(key) } else { setSessionStorage(key, next); } } catch { // sessionStorage 에러는 조용히 무시 } }, ); return persistentAtom; }