This commit is contained in:
2026-01-13 23:02:07 +08:00
parent a1e42127e6
commit 804baa64b2
71 changed files with 658 additions and 925 deletions

View File

@@ -1,62 +0,0 @@
"use client";
import {
TranslationHistoryArraySchema,
TranslationHistorySchema,
} from "@/lib/interfaces";
import z from "zod";
import { shallowEqual } from "../utils";
import { logger } from "@/lib/logger";
export const getLocalStorageOperator = <T extends z.ZodTypeAny>(
key: string,
schema: T,
) => {
return {
get: (): z.infer<T> => {
try {
if (!globalThis.localStorage) return [] as z.infer<T>;
const item = globalThis.localStorage.getItem(key);
if (!item) return [] as z.infer<T>;
const rawData = JSON.parse(item) as z.infer<T>;
const result = schema.safeParse(rawData);
if (result.success) {
return result.data;
} else {
logger.error(
"Invalid data structure in localStorage:",
result.error,
);
return [] as z.infer<T>;
}
} catch (e) {
logger.error(`Failed to parse ${key} data:`, e);
return [] as z.infer<T>;
}
},
set: (data: z.infer<T>) => {
if (!globalThis.localStorage) return;
globalThis.localStorage.setItem(key, JSON.stringify(data));
return data;
},
};
};
const MAX_HISTORY_LENGTH = 50;
export const tlso = getLocalStorageOperator<
typeof TranslationHistoryArraySchema
>("translator", TranslationHistoryArraySchema);
export const tlsoPush = (item: z.infer<typeof TranslationHistorySchema>) => {
const oldHistory = tlso.get();
if (oldHistory.some((v) => shallowEqual(v, item))) return oldHistory;
const newHistory = [...oldHistory, item].slice(-MAX_HISTORY_LENGTH);
tlso.set(newHistory);
return newHistory;
};