diff --git a/src/hooks/useTable/useTableConfig.ts b/src/hooks/useTable/useTableConfig.ts index cb9fcbaf..93e0af43 100644 --- a/src/hooks/useTable/useTableConfig.ts +++ b/src/hooks/useTable/useTableConfig.ts @@ -6,7 +6,7 @@ import _sortBy from "lodash/sortBy"; import useDoc, { DocActions } from "../useDoc"; import { FieldType } from "@src/constants/fields"; -import { arrayMover, formatPath } from "../../utils/fns"; +import { formatPath } from "../../utils/fns"; import { db, deleteField } from "../../firebase"; export type ColumnConfig = { @@ -136,15 +136,21 @@ const useTableConfig = (tableId?: string) => { const { columns } = tableConfigState; const oldIndex = columns[draggedColumnKey].index; const newIndex = columns[droppedColumnKey].index; - const columnsArray = _sortBy(Object.values(columns), "index"); - arrayMover(columnsArray, oldIndex, newIndex); - let updatedColumns = columns; - columnsArray - .filter((c) => c) // arrayMover has a bug creating undefined items - .forEach((column: any, index) => { - updatedColumns[column.key] = { ...column, index }; - }); + //sort columns by index, remove drag col, insert it in drop position + const sortedColumns = _sortBy(Object.values(columns), "index"); + const removeCol = sortedColumns.splice(oldIndex, 1); + sortedColumns.splice(newIndex, 0, removeCol[0]); + + //itereate and update index to proper value + const updatedColumns = sortedColumns.reduce( + (acc: any, curr: any, index) => { + acc[curr.key] = { ...curr, index }; + return acc; + }, + {} + ); + documentDispatch({ action: DocActions.update, data: { columns: updatedColumns }, diff --git a/src/utils/fns.ts b/src/utils/fns.ts index 768128ac..3f20d77e 100644 --- a/src/utils/fns.ts +++ b/src/utils/fns.ts @@ -5,33 +5,6 @@ import _isPlainObject from "lodash/isPlainObject"; import { TABLE_GROUP_SCHEMAS, TABLE_SCHEMAS } from "@src/config/dbPaths"; -/** - * reposition an element in an array - * @param arr array - * @param old_index index of element to be moved - * @param new_index new position of the moved element - */ -export const arrayMover = ( - arr: any[], - old_index: number, - new_index: number -) => { - while (old_index < 0) { - old_index += arr.length; - } - while (new_index < 0) { - new_index += arr.length; - } - if (new_index >= arr.length) { - var k = new_index - arr.length + 1; - while (k--) { - arr.push(undefined); - } - } - arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); - return arr; // for testing purposes -}; - export const missingFieldsReducer = (data: any) => (acc: string[], curr: string) => { if (data[curr] === undefined) {