feat: add state management using zustand

This commit is contained in:
2025-08-13 12:24:47 -06:00
parent 2c59ce43ad
commit 22d10902fb
4 changed files with 63 additions and 3 deletions

View File

@@ -8,8 +8,13 @@
"@commitlint/cli": "^19.8.1", "@commitlint/cli": "^19.8.1",
"@commitlint/config-conventional": "^19.8.1", "@commitlint/config-conventional": "^19.8.1",
"@types/bun": "latest", "@types/bun": "latest",
"@types/react-dom": "^19.1.7",
"husky": "^9.1.7", "husky": "^9.1.7",
"lint-staged": "^16.1.5" "lint-staged": "^16.1.5",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"zod": "^4.0.17",
"zustand": "^5.0.7"
}, },
"peerDependencies": { "peerDependencies": {
"typescript": "^5" "typescript": "^5"

1
src/constants.ts Normal file
View File

@@ -0,0 +1 @@
export const MODULE_NAME = 'st-randomness-helpers'

36
src/store/configSlice.ts Normal file
View File

@@ -0,0 +1,36 @@
import type { StateCreator } from 'zustand'
import { MODULE_NAME } from '@/constants'
export interface Config {
wordLists: Record<string, string[]>
}
export interface ConfigSlice extends Config {
addWordList: (name: string, words: string[]) => void
updateWordList: (name: string, words: string[]) => void
removeWordList: (name: string) => void
}
export const createConfigSlice: StateCreator<ConfigSlice> = (set) => {
const context = SillyTavern.getContext()
// biome-ignore lint/suspicious/noExplicitAny: SillyTavern's extensionSettings is not properly typed
const extensionSettings: Record<string, any> = context.extensionSettings
const settings: Config =
extensionSettings[MODULE_NAME] === undefined
? { wordLists: {} }
: extensionSettings[MODULE_NAME]
return {
wordLists: settings.wordLists,
addWordList: (name, words) =>
set({ wordLists: { ...settings.wordLists, [name]: words } }),
updateWordList: (name, words) =>
set({ wordLists: { ...settings.wordLists, [name]: words } }),
removeWordList: (name) => {
const newWordLists = { ...settings.wordLists }
delete newWordLists[name]
set({ wordLists: newWordLists })
}
}
}

18
src/store/index.ts Normal file
View File

@@ -0,0 +1,18 @@
import { createStore } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'
import { MODULE_NAME } from '@/constants'
import { type ConfigSlice, createConfigSlice } from '@/store/configSlice'
export const useStore = createStore<ConfigSlice>()(
subscribeWithSelector(createConfigSlice)
)
useStore.subscribe(
(state) => state.wordLists,
(wordLists) => {
const context = SillyTavern.getContext()
// biome-ignore lint/suspicious/noExplicitAny: SillyTavern's extensionSettings is not properly typed
const extensionSettings: Record<string, any> = context.extensionSettings
extensionSettings[MODULE_NAME] = { wordLists }
}
)