| 1 |
import { safeLocalStorage } from '@shared/state/safe-local-storage'; |
| 2 |
import { create } from 'zustand'; |
| 3 |
import { createJSONStorage, devtools, persist } from 'zustand/middleware'; |
| 4 |
|
| 5 |
const initialState = { |
| 6 |
experienceLevel: 'beginner', |
| 7 |
currentQuestion: undefined, |
| 8 |
}; |
| 9 |
|
| 10 |
const state = (set, get) => ({ |
| 11 |
history: [], |
| 12 |
...initialState, |
| 13 |
setCurrentQuestion: (currentQuestion) => set({ currentQuestion }), |
| 14 |
setExperienceLevel: (experienceLevel) => set({ experienceLevel }), |
| 15 |
addHistory: (question) => |
| 16 |
set((state) => ({ |
| 17 |
// Save the latest 10 |
| 18 |
history: [ |
| 19 |
question, |
| 20 |
...state.history |
| 21 |
.filter(({ answerId }) => answerId !== question.answerId) |
| 22 |
.slice(0, 9), |
| 23 |
], |
| 24 |
})), |
| 25 |
hasHistory: () => get().history.length > 0, |
| 26 |
clearHistory: () => set({ history: [] }), |
| 27 |
deleteFromHistory: (question) => |
| 28 |
set((state) => ({ |
| 29 |
history: state.history.filter( |
| 30 |
({ answerId: id }) => id !== question.answerId, |
| 31 |
), |
| 32 |
})), |
| 33 |
historyCount: () => get().history.length, |
| 34 |
reset: () => set({ ...initialState }), |
| 35 |
}); |
| 36 |
|
| 37 |
export const useAIChatStore = create( |
| 38 |
persist(devtools(state, { name: 'Extendify Chat History' }), { |
| 39 |
name: `extendify-chat-history-${window.extSharedData.siteId}`, |
| 40 |
storage: createJSONStorage(() => safeLocalStorage), |
| 41 |
}), |
| 42 |
); |
| 43 |
|