File size: 1,957 Bytes
1f21206 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import { create } from 'zustand'
import type { RuntimeSelection } from '../types/runtime'
const STORAGE_KEY = 'cc-haha-session-runtime'
export const DRAFT_RUNTIME_SELECTION_KEY = '__draft__'
type SessionRuntimeStore = {
selections: Record<string, RuntimeSelection>
setSelection: (key: string, selection: RuntimeSelection) => void
clearSelection: (key: string) => void
moveSelection: (fromKey: string, toKey: string) => void
}
function loadSelections(): Record<string, RuntimeSelection> {
if (typeof localStorage === 'undefined') return {}
try {
const raw = localStorage.getItem(STORAGE_KEY)
if (!raw) return {}
const parsed = JSON.parse(raw) as Record<string, RuntimeSelection>
return parsed && typeof parsed === 'object' ? parsed : {}
} catch {
return {}
}
}
function persistSelections(selections: Record<string, RuntimeSelection>) {
if (typeof localStorage === 'undefined') return
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(selections))
} catch {
// noop
}
}
export const useSessionRuntimeStore = create<SessionRuntimeStore>((set) => ({
selections: loadSelections(),
setSelection: (key, selection) =>
set((state) => {
const selections = {
...state.selections,
[key]: selection,
}
persistSelections(selections)
return { selections }
}),
clearSelection: (key) =>
set((state) => {
if (!(key in state.selections)) return state
const { [key]: _removed, ...rest } = state.selections
persistSelections(rest)
return { selections: rest }
}),
moveSelection: (fromKey, toKey) =>
set((state) => {
const selection = state.selections[fromKey]
if (!selection) return state
const { [fromKey]: _removed, ...rest } = state.selections
const selections = {
...rest,
[toKey]: selection,
}
persistSelections(selections)
return { selections }
}),
}))
|