refactor(FE): Add table state management with path grouping logic

This commit is contained in:
rstubryan
2026-03-03 10:33:03 +07:00
parent cbab7f52f2
commit 3d2e40518b
3 changed files with 63 additions and 5 deletions
+51 -4
View File
@@ -1,13 +1,34 @@
import { StateCreator } from 'zustand';
import { TableUISlice } from '@/types/stores';
export interface TableState {
key: string;
path: string;
searchValue: string;
}
export interface TableUISlice {
searchValue: string;
setSearchValue: (value: string) => void;
resetSearchValue: () => void;
function getPathGroup(path: string): string {
const segments = path.split('/').filter(Boolean);
const subPaths = ['add', 'detail', 'edit'];
const lastSegment = segments[segments.length - 1];
// If last segment is a sub-path or numeric ID, remove it
if (
lastSegment &&
(subPaths.includes(lastSegment) || /^\d+$/.test(lastSegment))
) {
segments.pop();
}
return segments.length > 0 ? '/' + segments.join('/') : path;
}
function isSamePathGroup(
currentPath: string,
previousPath: string | null
): boolean {
if (!previousPath) return false;
return getPathGroup(currentPath) === getPathGroup(previousPath);
}
export const createTableUISlice: StateCreator<
@@ -17,7 +38,10 @@ export const createTableUISlice: StateCreator<
TableUISlice
> = (set) => ({
// Initial state
key: '',
path: '',
searchValue: '',
previousPath: null,
// Actions
setSearchValue: (value) => set({ searchValue: value }),
@@ -25,4 +49,27 @@ export const createTableUISlice: StateCreator<
resetSearchValue: () => {
return set({ searchValue: '' });
},
setTableState: (key, path, searchValue = '') => {
set((state) => {
const isSameGroup = isSamePathGroup(path, state.path);
return {
key,
path,
previousPath: state.path,
// Reset search if path group changed, otherwise keep existing search
searchValue: isSameGroup ? state.searchValue : searchValue,
};
});
},
resetTableState: () => {
set({
key: '',
path: '',
searchValue: '',
previousPath: null,
});
},
});
+4 -1
View File
@@ -19,9 +19,12 @@ export const useUiStore = create<UIStore>()(
...createNavbarActionsSlice(...args),
}),
{
name: 'ui-cache',
name: 'search-store',
partialize: (state) => ({
key: state.key,
path: state.path,
searchValue: state.searchValue,
previousPath: state.previousPath,
}),
}
),
+8
View File
@@ -28,9 +28,17 @@ type DrawerUISlice = {
};
type TableUISlice = {
// State
key: string;
path: string;
searchValue: string;
previousPath: string | null;
// Actions
setSearchValue: (value: string) => void;
resetSearchValue: () => void;
setTableState: (key: string, path: string, searchValue?: string) => void;
resetTableState: () => void;
};
// Navbar Actions Slice