fix-bug unpredictable state of tableAction.reorder's function

This commit is contained in:
gibsonliketheguitar
2021-12-28 18:18:58 +07:00
parent 813d68064e
commit ac6a92dbd1
2 changed files with 12 additions and 39 deletions

View File

@@ -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 = {
@@ -130,17 +130,17 @@ const useTableConfig = (tablePath?: string) => {
*/
const reorder = (draggedColumnKey: string, droppedColumnKey: 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 };
});
const updatedColumns = _sortBy(Object.values(columns), "index").reduce(
(acc: any, curr: any, index: number) => {
if (curr.key === droppedColumnKey)
acc[draggedColumnKey] = { ...columns[draggedColumnKey], index };
else if (curr.key === draggedColumnKey)
acc[droppedColumnKey] = { ...columns[droppedColumnKey], index };
else acc[curr.key] = { ...columns[curr.key], index };
return acc;
},
{}
);
documentDispatch({
action: DocActions.update,
data: { columns: updatedColumns },

View File

@@ -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) {