From a3c6c9fa76973a4e3d309c49c8dff411306ee5e2 Mon Sep 17 00:00:00 2001 From: SrJuggernaut Date: Thu, 14 Aug 2025 18:18:00 -0600 Subject: [PATCH] feat: random word macros --- src/index.ts | 2 ++ src/macros/initializeMacros.ts | 7 ++++++ src/macros/randomWord.ts | 43 ++++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 src/macros/initializeMacros.ts create mode 100644 src/macros/randomWord.ts diff --git a/src/index.ts b/src/index.ts index e6d62c5..63e1e77 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,5 @@ import renderSettingsGui from '@/gui' +import initializeMacros from '@/macros/initializeMacros' renderSettingsGui() +initializeMacros() diff --git a/src/macros/initializeMacros.ts b/src/macros/initializeMacros.ts new file mode 100644 index 0000000..c7e711b --- /dev/null +++ b/src/macros/initializeMacros.ts @@ -0,0 +1,7 @@ +import randomWord from '@/macros/randomWord' + +const initializeMacros = () => { + randomWord() +} + +export default initializeMacros diff --git a/src/macros/randomWord.ts b/src/macros/randomWord.ts new file mode 100644 index 0000000..506650a --- /dev/null +++ b/src/macros/randomWord.ts @@ -0,0 +1,43 @@ +import { useStore } from '@/store' + +const randomWord = () => { + const { registerMacro, unregisterMacro } = SillyTavern.getContext() + + useStore.subscribe( + (state) => Object.keys(state.wordLists), + (wordLists, oldWordLists) => { + const wordListsSet = new Set(wordLists) + const oldWordListsSet = new Set(oldWordLists) + const deletedWordLists = oldWordListsSet.difference(wordListsSet) + const newWordLists = wordListsSet.difference(oldWordListsSet) + + for (const wordList of deletedWordLists) { + unregisterMacro(`rndWord::${wordList}`) + } + + for (const wordList of newWordLists) { + registerMacro( + `rndWord::${wordList}`, + () => { + const words = useStore.getState().wordLists[wordList] as string[] + return words[Math.floor(Math.random() * words.length)] as string + }, + `Generates a random word from the word list '${wordList}'` + ) + } + } + ) + + for (const wordList of Object.keys(useStore.getState().wordLists)) { + registerMacro( + `rndWord::${wordList}`, + () => { + const words = useStore.getState().wordLists[wordList] as string[] + return words[Math.floor(Math.random() * words.length)] as string + }, + `Generates a random word from the word list '${wordList}'` + ) + } +} + +export default randomWord