feat: 1-to-1 message render + web data-lake backend
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import { browser } from "$app/environment";
|
||||
import { listAccounts } from "$lib/api/endpoints";
|
||||
import type { Account } from "$lib/api/types";
|
||||
|
||||
const STORAGE_KEY = "bg.account";
|
||||
|
||||
function readSelected(): number | null {
|
||||
if (!browser) {
|
||||
return null;
|
||||
}
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
return stored === null ? null : Number(stored);
|
||||
}
|
||||
|
||||
function createAccounts() {
|
||||
let list = $state<Account[]>([]);
|
||||
let selectedId = $state<number | null>(readSelected());
|
||||
let loaded = $state(false);
|
||||
|
||||
const selected = $derived(
|
||||
list.find((account) => account.account_id === selectedId) ?? null
|
||||
);
|
||||
|
||||
function persist(id: number | null) {
|
||||
if (!browser) {
|
||||
return;
|
||||
}
|
||||
if (id === null) {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} else {
|
||||
localStorage.setItem(STORAGE_KEY, String(id));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get list() {
|
||||
return list;
|
||||
},
|
||||
get selectedId() {
|
||||
return selectedId;
|
||||
},
|
||||
get selected() {
|
||||
return selected;
|
||||
},
|
||||
get loaded() {
|
||||
return loaded;
|
||||
},
|
||||
async load() {
|
||||
list = await listAccounts();
|
||||
loaded = true;
|
||||
const exists = list.some((account) => account.account_id === selectedId);
|
||||
if (!exists) {
|
||||
const fallback =
|
||||
list.find((account) => account.is_active) ?? list.at(0) ?? null;
|
||||
selectedId = fallback ? fallback.account_id : null;
|
||||
persist(selectedId);
|
||||
}
|
||||
},
|
||||
select(id: number) {
|
||||
selectedId = id;
|
||||
persist(id);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const accounts = createAccounts();
|
||||
Reference in New Issue
Block a user