45 lines
1.6 KiB
TypeScript
45 lines
1.6 KiB
TypeScript
|
|
import { DEFAULT_AVATAR_SPEC, parseAvatarLoose, type CustomCandidate } from "@election2026/protocol";
|
|||
|
|
|
|||
|
|
/** 玩家捏好的角色存在這台瀏覽器裡(只是方便下次再用;讀不到就是空的) */
|
|||
|
|
const KEY = "tongsuan.characters";
|
|||
|
|
|
|||
|
|
export type SavedCharacter = Omit<CustomCandidate, "replace"> & { id: string };
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 讀存檔時清洗頭像(docs/24):照部件目錄檢查,看不懂的部件代號換成預設、壞掉的欄位丟掉,存檔壞掉也不會當機。
|
|||
|
|
* 舊存檔的頭像本來就合法,原封不動。
|
|||
|
|
*/
|
|||
|
|
function cleanCharacter(raw: unknown): SavedCharacter | null {
|
|||
|
|
if (!raw || typeof raw !== "object") return null;
|
|||
|
|
const c = raw as SavedCharacter;
|
|||
|
|
if (typeof c.id !== "string" || typeof c.name !== "string") return null;
|
|||
|
|
return { ...c, avatar: parseAvatarLoose(c.avatar) ?? DEFAULT_AVATAR_SPEC };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export function loadCharacters(): SavedCharacter[] {
|
|||
|
|
try {
|
|||
|
|
const raw = localStorage.getItem(KEY);
|
|||
|
|
const list: unknown = raw ? JSON.parse(raw) : [];
|
|||
|
|
return Array.isArray(list) ? list.map(cleanCharacter).filter((c): c is SavedCharacter => c !== null) : [];
|
|||
|
|
} catch {
|
|||
|
|
return [];
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export function saveCharacter(c: SavedCharacter): void {
|
|||
|
|
try {
|
|||
|
|
const list = loadCharacters().filter((x) => x.id !== c.id);
|
|||
|
|
localStorage.setItem(KEY, JSON.stringify([c, ...list].slice(0, 12)));
|
|||
|
|
} catch {
|
|||
|
|
// 存不了就算了,這次還是可以玩
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export function deleteCharacter(id: string): void {
|
|||
|
|
try {
|
|||
|
|
localStorage.setItem(KEY, JSON.stringify(loadCharacters().filter((x) => x.id !== id)));
|
|||
|
|
} catch {
|
|||
|
|
// 同上
|
|||
|
|
}
|
|||
|
|
}
|