75 lines
2.4 KiB
TypeScript
75 lines
2.4 KiB
TypeScript
'use client';
|
|
import { create } from 'zustand';
|
|
import type { TaskCategory, CategoryGroup } from '@/lib/task-category';
|
|
import { PRESET_CATEGORIES, ensureTaskCategoryByName, normalizeTaskCategories } from '@/lib/task-category';
|
|
import { loadServerData, saveServerData } from '@/lib/server-data';
|
|
|
|
function saveStored(items: TaskCategory[]) {
|
|
saveServerData('task-categories', items).catch(() => {});
|
|
}
|
|
|
|
async function loadStored(): Promise<TaskCategory[] | null> {
|
|
try {
|
|
return await loadServerData<TaskCategory[]>('task-categories');
|
|
} catch {}
|
|
return null;
|
|
}
|
|
|
|
interface TaskCategoryState {
|
|
categories: TaskCategory[];
|
|
fetchCategories: () => Promise<void>;
|
|
addCategory: (name: string, group: CategoryGroup, color?: string) => void;
|
|
ensureCategory: (name: string, group: CategoryGroup) => TaskCategory;
|
|
updateCategory: (id: string, data: Partial<TaskCategory>) => void;
|
|
deleteCategory: (id: string) => boolean;
|
|
}
|
|
|
|
export const useTaskCategoryStore = create<TaskCategoryState>((set, get) => ({
|
|
categories: PRESET_CATEGORIES,
|
|
|
|
fetchCategories: async () => {
|
|
const cached = await loadStored();
|
|
if (cached) set({ categories: normalizeTaskCategories(cached) });
|
|
},
|
|
|
|
addCategory: (name, group, color) => {
|
|
const list = get().categories;
|
|
const item: TaskCategory = {
|
|
id: `cat-${Date.now()}`,
|
|
code: name.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '_').replace(/^_+|_+$/g, '') || `cat_${Date.now()}`,
|
|
name,
|
|
group,
|
|
color,
|
|
sortOrder: list.length + 1,
|
|
isSystem: false,
|
|
};
|
|
const updated = [...list, item];
|
|
set({ categories: updated });
|
|
saveStored(updated);
|
|
},
|
|
|
|
ensureCategory: (name, group) => {
|
|
const result = ensureTaskCategoryByName(get().categories, name, group);
|
|
if (result.created) {
|
|
set({ categories: result.categories });
|
|
saveStored(result.categories);
|
|
}
|
|
return result.category;
|
|
},
|
|
|
|
updateCategory: (id, data) => {
|
|
const updated = get().categories.map((c) => (c.id === id ? { ...c, ...data } : c));
|
|
set({ categories: updated });
|
|
saveStored(updated);
|
|
},
|
|
|
|
deleteCategory: (id) => {
|
|
const target = get().categories.find((c) => c.id === id);
|
|
if (!target || target.isSystem) return false;
|
|
const updated = get().categories.filter((c) => c.id !== id);
|
|
set({ categories: updated });
|
|
saveStored(updated);
|
|
return true;
|
|
},
|
|
}));
|