refactor: Optimize current character initialization in stores.ts

This commit is contained in:
kwaroran
2024-06-24 01:38:24 +09:00
parent 5f59349b84
commit 6e9940df2d

View File

@@ -2,6 +2,7 @@ import { get, writable, type Writable } from "svelte/store";
import { DataBase, type Chat, type character, type groupChat } from "./storage/database";
import { isEqual } from "lodash";
import type { simpleCharacterArgument } from "./parser";
import { sleep } from "./util";
function updateSize(){
SizeStore.set({
@@ -70,7 +71,9 @@ function createSimpleCharacter(char:character|groupChat){
}
function updateCurrentCharacter(){
async function preInit(){
await sleep(1)
function updateCurrentCharacter(){
const db = get(DataBase)
if(!db.characters){
@@ -97,9 +100,9 @@ function updateCurrentCharacter(){
}
updateCurrentChat()
}
}
function updateCurrentChat(){
function updateCurrentChat(){
const currentChar = get(CurrentCharacter)
if(!currentChar){
CurrentChat.set(null)
@@ -111,9 +114,9 @@ function updateCurrentChat(){
return
}
CurrentChat.set(structuredClone(chat))
}
}
DataBase.subscribe((data) => {
DataBase.subscribe((data) => {
updateCurrentCharacter()
if(data.username !== get(CurrentUsername)){
CurrentUsername.set(data.username)
@@ -124,14 +127,14 @@ DataBase.subscribe((data) => {
if(data.showMemoryLimit !== get(CurrentShowMemoryLimit)){
CurrentShowMemoryLimit.set(data.showMemoryLimit)
}
})
})
selectedCharID.subscribe((id) => {
selectedCharID.subscribe((id) => {
updateCurrentCharacter()
})
})
CurrentCharacter.subscribe((char) => {
CurrentCharacter.subscribe((char) => {
updateCurrentChat()
let db = get(DataBase)
let charId = get(selectedCharID)
@@ -144,9 +147,9 @@ CurrentCharacter.subscribe((char) => {
}
db.characters[charId] = structuredClone(char)
DataBase.set(db)
})
})
CurrentChat.subscribe((chat) => {
CurrentChat.subscribe((chat) => {
let currentChar = get(CurrentCharacter)
if(currentChar){
@@ -162,8 +165,10 @@ CurrentChat.subscribe((chat) => {
if(!isEqual(variablePointer, currentState)){
CurrentVariablePointer.set(currentState)
}
})
})
}
updateSize()
window.addEventListener("resize", updateSize);
preInit()