prevent lag effect when changing order

This commit is contained in:
grimhilt 2023-07-31 01:57:00 +02:00
parent 6697844239
commit ca2262403b

View File

@ -39,35 +39,37 @@ const Content = ({ form, playlistId }) => {
}; };
const changePositionValue = (from, to) => { const changePositionValue = (from, to) => {
const formFiles = form.values.files; return new Promise((resolve, reject) => {
let below_position = to === 0 ? 0 : formFiles[to].position; const formFiles = form.values.files;
let above_position = formFiles[to].position; let below_position = to === 0 ? 0 : formFiles[to].position;
if (to > from) { let above_position = formFiles[to].position;
if (to === formFiles.length - 1) { if (to > from) {
// last element so nothing above if (to === formFiles.length - 1) {
above_position = formFiles.length + 1; // last element so nothing above
} else { above_position = formFiles.length + 1;
// not last to taking element above
above_position = formFiles[to + 1].position;
}
}
let newPosition = (below_position + above_position) / 2;
// sending modification to server
API.playlistChangeOrder(playlistId, { file_id: formFiles[from].id, position: newPosition })
.then((res) => {
if (res.status !== 200) {
form.values.files[from].position = newPosition;
return true;
} else { } else {
setNotification(true, `Error when changing order (${res.status})`); // not last to taking element above
return false; above_position = formFiles[to + 1].position;
} }
}) }
.catch((err) => { let newPosition = (below_position + above_position) / 2;
setNotification(true, err.message);
return false; // sending modification to server
}); API.playlistChangeOrder(playlistId, { file_id: formFiles[from].id, position: newPosition })
.then((res) => {
if (res.status == 200) {
form.values.files[from].position = newPosition;
resolve(true);
} else {
setNotification(true, `Error when changing order (${res.status})`);
resolve(false);
}
})
.catch((err) => {
setNotification(true, err.message);
resolve(false);
});
});
}; };
const handleDelete = (index) => { const handleDelete = (index) => {
@ -115,9 +117,10 @@ const Content = ({ form, playlistId }) => {
<Box mx="auto"> <Box mx="auto">
<DragDropContext <DragDropContext
onDragEnd={({ destination, source }) => { onDragEnd={({ destination, source }) => {
form.reorderListItem('files', { from: source.index, to: destination.index });
changePositionValue(source.index, destination.index).then((success) => { changePositionValue(source.index, destination.index).then((success) => {
if (success) { if (!success) {
form.reorderListItem('files', { from: source.index, to: destination.index }); form.reorderListItem('files', { from: destination.index, to: source.index });
} }
}); });
}} }}