sort number section

This commit is contained in:
hamid zarghami
2025-08-05 12:18:08 +03:30
parent af935ba2b5
commit dcd5ab07e0
4 changed files with 69 additions and 14 deletions
+46 -5
View File
@@ -13,11 +13,26 @@ import {
SelectedElement,
} from "../types/Types";
export const usePersonalityStore = create<PersonalityStore>((set) => ({
// Helper function to get sections sorted by sortNumber
export const getSortedSectionKeys = (data: PersonalityDataType): string[] => {
return Object.keys(data).sort((a, b) => {
const sortA = data[a].sortNumber || 0;
const sortB = data[b].sortNumber || 0;
return sortA - sortB;
});
};
export const usePersonalityStore = create<PersonalityStore>((set, get) => ({
data: {
header: { name: "هدر", columnsCount: 1, items: [] },
content: { name: "محتوا", columnsCount: 1, items: [], isContent: true },
footer: { name: "فوتر", columnsCount: 1, items: [] },
header: { name: "هدر", columnsCount: 1, items: [], sortNumber: 1 },
content: {
name: "محتوا",
columnsCount: 1,
items: [],
isContent: true,
sortNumber: 2,
},
footer: { name: "فوتر", columnsCount: 1, items: [], sortNumber: 3 },
},
activeSection: "",
@@ -129,18 +144,42 @@ export const usePersonalityStore = create<PersonalityStore>((set) => ({
return state; // Section already exists
}
// Calculate the sortNumber for the new section
let newSortNumber = 1;
if (afterSectionKey) {
const afterSection = state.data[afterSectionKey];
if (afterSection) {
// Insert after the specified section, so sortNumber should be higher
newSortNumber = afterSection.sortNumber + 1;
// Update sortNumbers of sections that come after
Object.keys(state.data).forEach((key) => {
if (state.data[key].sortNumber > afterSection.sortNumber) {
state.data[key].sortNumber += 1;
}
});
}
} else {
// Add at the end - find the highest sortNumber and add 1
const maxSortNumber = Math.max(
...Object.values(state.data).map((section) => section.sortNumber || 0)
);
newSortNumber = maxSortNumber + 1;
}
// Create new section data
const newSection = {
name: sectionName,
columnsCount: 1,
items: [],
sortNumber: newSortNumber,
};
// If afterSectionKey is provided, insert after that section
if (afterSectionKey) {
const keys = Object.keys(state.data);
const afterIndex = keys.indexOf(afterSectionKey);
// TODO all index expect that increase +
if (afterIndex !== -1) {
const newData: typeof state.data = {};
@@ -732,4 +771,6 @@ export const usePersonalityStore = create<PersonalityStore>((set) => ({
selectedElement: null,
isEditMode: false,
})),
getSortedSectionKeys: () => getSortedSectionKeys(get().data),
}));