44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
/** 데스크톱 메인↔위젯 창 상태 동기화 (localStorage) */
|
|
export const DESKTOP_SYNC_KEY = 'gc_desktop_sync';
|
|
|
|
export interface DesktopSyncState {
|
|
selectedMarket?: string;
|
|
selectedStrategyId?: number | null;
|
|
theme?: string;
|
|
updatedAt: number;
|
|
}
|
|
|
|
export function readDesktopSync(): DesktopSyncState | null {
|
|
try {
|
|
const raw = localStorage.getItem(DESKTOP_SYNC_KEY);
|
|
if (!raw) return null;
|
|
return JSON.parse(raw) as DesktopSyncState;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function writeDesktopSync(partial: Omit<DesktopSyncState, 'updatedAt'>): void {
|
|
const prev = readDesktopSync() ?? { updatedAt: 0 };
|
|
const next: DesktopSyncState = {
|
|
...prev,
|
|
...partial,
|
|
updatedAt: Date.now(),
|
|
};
|
|
try {
|
|
localStorage.setItem(DESKTOP_SYNC_KEY, JSON.stringify(next));
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
|
|
export function subscribeDesktopSync(cb: (state: DesktopSyncState) => void): () => void {
|
|
const onStorage = (e: StorageEvent) => {
|
|
if (e.key !== DESKTOP_SYNC_KEY) return;
|
|
const state = readDesktopSync();
|
|
if (state) cb(state);
|
|
};
|
|
window.addEventListener('storage', onStorage);
|
|
return () => window.removeEventListener('storage', onStorage);
|
|
}
|