ChatGPT-Next-Web/app/masks/index.ts
Lincoln Minto 83e6ff6d96
Refactor: Simplify mask data processing using Object.values and flat
💻 变更类型 | Change Type
feat

🔀 变更说明 | Description of Change
This PR refactors the code handling mask data processing by simplifying the logic and improving scalability and type safety.

Code Enhancements:
Refactored the mask processing logic in app/masks/index.ts:
Replaced manual destructuring of cn, tw, and en keys with Object.values to dynamically handle all mask data.
Used .flat() to simplify merging mask arrays into a single collection.
Added explicit type casting (as BuiltinMask) for improved type safety.

Benefits:
Improved Maintainability: By eliminating hardcoded destructuring, the code can adapt automatically to new mask keys without modification.
Enhanced Readability: The use of Object.values and flat provides a cleaner, more concise approach.
Scalability: The updated implementation supports dynamic mask additions without breaking functionality.

📝 补充信息 | Additional Information
This change ensures the mask processing code is robust and easier to extend in future updates.

Release Notes:

New Features:
Simplified mask data processing using dynamic Object.values and .flat() methods.
Enhanced type safety with explicit type casting (as BuiltinMask).
2025-01-07 09:53:54 -03:00

38 lines
1008 B
TypeScript

import { Mask } from "../store/mask";
import { type BuiltinMask } from "./typing";
export { type BuiltinMask } from "./typing";
export const BUILTIN_MASK_ID = 100000;
export const BUILTIN_MASK_STORE = {
buildinId: BUILTIN_MASK_ID,
masks: {} as Record<string, BuiltinMask>,
get(id?: string) {
if (!id) return undefined;
return this.masks[id] as Mask | undefined;
},
add(m: BuiltinMask) {
const mask = { ...m, id: this.buildinId++, builtin: true };
this.masks[mask.id] = mask;
return mask;
},
};
export const BUILTIN_MASKS: BuiltinMask[] = [];
if (typeof window != "undefined") {
// run in browser skip in next server
fetch("/masks.json")
.then((res) => res.json())
.catch((error) => {
console.error("[Fetch] failed to fetch masks", error);
return { cn: [], tw: [], en: [] };
})
.then((masks) => {
return Object.values(masks).flat().map((m) => {
BUILTIN_MASKS.push(BUILTIN_MASK_STORE.add(m as BuiltinMask));
});
});
}