Improvements and corrections
gitea/salix-front/pipeline/pr-dev This commit looks good Details

This commit is contained in:
William Buezas 2024-02-19 09:23:44 -03:00
parent f230090711
commit 433444c869
2 changed files with 46 additions and 15 deletions

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref, computed, onMounted } from 'vue'; import { ref, computed } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { onMounted, ref, computed } from 'vue'; import { onMounted, ref, computed, watch } from 'vue';
import { QBtn } from 'quasar'; import { QBtn } from 'quasar';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
@ -46,8 +46,8 @@ const arrayData = useArrayData('ExtraCommunity', {
}, },
}); });
const rows = computed(() => arrayData.store.data || []); const rows = ref([]);
const originalRowDataCopy = ref(null); const originalRowDataCopy = ref([]);
const draggedRowIndex = ref(null); const draggedRowIndex = ref(null);
const targetRowIndex = ref(null); const targetRowIndex = ref(null);
const entryRowIndex = ref(null); const entryRowIndex = ref(null);
@ -89,7 +89,7 @@ const tableColumnComponents = {
}, },
kg: { kg: {
component: VnInput, component: VnInput,
attrs: { dense: true }, attrs: { dense: true, type: 'number', min: 0, class: 'input-number' },
event: (val, field, rowIndex) => ({ event: (val, field, rowIndex) => ({
'keyup.enter': () => saveFieldValue(val, field, rowIndex), 'keyup.enter': () => saveFieldValue(val, field, rowIndex),
blur: () => saveFieldValue(val, field, rowIndex), blur: () => saveFieldValue(val, field, rowIndex),
@ -242,6 +242,22 @@ async function getData() {
await arrayData.fetch({ append: false }); await arrayData.fetch({ append: false });
} }
const onStoreDataChange = () => {
const newData = JSON.parse(JSON.stringify(arrayData.store.data)) || [];
rows.value = newData;
// el objetivo de esto es guardar una copia de los valores iniciales de todas las rows para corroborar si la data cambio antes de guardar los cambios
originalRowDataCopy.value = JSON.parse(JSON.stringify(newData));
};
watch(
arrayData.store,
() => {
if (!arrayData.store.data) return;
onStoreDataChange();
},
{ deep: true, immediate: true }
);
const openReportPdf = () => { const openReportPdf = () => {
const params = { const params = {
...arrayData.store.userParams, ...arrayData.store.userParams,
@ -253,11 +269,13 @@ const openReportPdf = () => {
const saveFieldValue = async (val, field, index) => { const saveFieldValue = async (val, field, index) => {
try { try {
// Evitar la solicitud de guardado si el valor no ha cambiado
if (originalRowDataCopy.value[index][field] == val) return; if (originalRowDataCopy.value[index][field] == val) return;
const id = rows.value[index].id; const id = rows.value[index].id;
const params = { [field]: val }; const params = { [field]: val };
await axios.patch(`Travels/${id}`, params); await axios.patch(`Travels/${id}`, params);
// Actualizar la copia de los datos originales con el nuevo valor
originalRowDataCopy.value[index][field] = val; originalRowDataCopy.value[index][field] = val;
} catch (err) { } catch (err) {
console.error('Error updating travel'); console.error('Error updating travel');
@ -269,6 +287,7 @@ const navigateToTravelId = (id) => {
}; };
const stopEventPropagation = (event, col) => { const stopEventPropagation = (event, col) => {
// Detener la propagación del evento de los siguientes elementos para evitar el click sobre la row que dispararía la función navigateToTravelId
if (!['ref', 'id', 'cargoSupplierNickname', 'kg'].includes(col.name)) return; if (!['ref', 'id', 'cargoSupplierNickname', 'kg'].includes(col.name)) return;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
@ -283,17 +302,16 @@ onMounted(async () => {
landedTo.value.setDate(landedTo.value.getDate() + 7); landedTo.value.setDate(landedTo.value.getDate() + 7);
landedTo.value.setHours(23, 59, 59, 59); landedTo.value.setHours(23, 59, 59, 59);
await getData(); await getData();
// el objetivo de esto es guardar una copia de los valores iniciales de todas las rows para evitar guardar cambios si la data no cambió al disparar los eventos
originalRowDataCopy.value = JSON.parse(JSON.stringify(rows.value));
}); });
// Handler del evento @dragstart (inicio del drag) y guarda información inicial
const handleDragStart = (event, rowIndex, entryIndex) => { const handleDragStart = (event, rowIndex, entryIndex) => {
draggedRowIndex.value = rowIndex; draggedRowIndex.value = rowIndex;
entryRowIndex.value = entryIndex; entryRowIndex.value = entryIndex;
event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.effectAllowed = 'move';
}; };
// Handler del evento @dragenter (cuando haces drag sobre une elemento y lo arrastras sobre un posible target de drop) y actualiza el targetIndex
const handleDragEnter = (_, targetIndex) => { const handleDragEnter = (_, targetIndex) => {
targetRowIndex.value = targetIndex; targetRowIndex.value = targetIndex;
}; };
@ -321,6 +339,13 @@ const moveRow = async (draggedRowIndex, targetRowIndex, entryIndex) => {
} }
}; };
// Handler de cuando haces un drop tanto dentro como fuera de la tabla para limpiar acciones y data
const handleDragEnd = () => {
stopScroll();
cleanDragAndDropData();
};
// Handler del evento @drop (cuando soltas el elemento draggeado sobre un target)
const handleDrop = () => { const handleDrop = () => {
if ( if (
!draggedRowIndex.value && !draggedRowIndex.value &&
@ -330,8 +355,7 @@ const handleDrop = () => {
) )
return; return;
moveRow(draggedRowIndex.value, targetRowIndex.value, entryRowIndex.value); moveRow(draggedRowIndex.value, targetRowIndex.value, entryRowIndex.value);
stopScroll(); handleDragEnd();
cleanDragAndDropData();
}; };
const cleanDragAndDropData = () => { const cleanDragAndDropData = () => {
@ -344,6 +368,7 @@ const cleanDragAndDropData = () => {
const scrollInterval = ref(null); const scrollInterval = ref(null);
const startScroll = (direction) => { const startScroll = (direction) => {
// Iniciar el scroll en la dirección especificada
if (!scrollInterval.value) { if (!scrollInterval.value) {
scrollInterval.value = requestAnimationFrame(() => scroll(direction)); scrollInterval.value = requestAnimationFrame(() => scroll(direction));
} }
@ -357,12 +382,14 @@ const stopScroll = () => {
}; };
const scroll = (direction) => { const scroll = (direction) => {
const yOffset = direction === 'up' ? -2 : 2; // Ajusta la velocidad del scroll // Controlar el desplazamiento en la dirección especificada
const yOffset = direction === 'up' ? -2 : 2;
window.scrollBy(0, yOffset); window.scrollBy(0, yOffset);
const windowHeight = window.innerHeight; const windowHeight = window.innerHeight;
const documentHeight = document.body.offsetHeight; const documentHeight = document.body.offsetHeight;
// Verificar si se alcanzaron los límites de la ventana para detener el desplazamiento
if ( if (
(direction === 'up' && window.scrollY > 0) || (direction === 'up' && window.scrollY > 0) ||
(direction === 'down' && windowHeight + window.scrollY < documentHeight) (direction === 'down' && windowHeight + window.scrollY < documentHeight)
@ -373,9 +400,13 @@ const scroll = (direction) => {
} }
}; };
const handleDrag = (event) => { // Handler del scroll mientras se hace el drag de una row
const handleDragScroll = (event) => {
// Obtener la posición y dimensiones del cursor
const y = event.clientY; const y = event.clientY;
const windowHeight = window.innerHeight; const windowHeight = window.innerHeight;
// Verificar si el cursor está cerca del borde superior o inferior de la ventana
const nearTop = y < 150; const nearTop = y < 150;
const nearBottom = y > windowHeight - 100; const nearBottom = y > windowHeight - 100;
@ -427,8 +458,8 @@ const handleDrag = (event) => {
:pagination="{ rowsPerPage: 0 }" :pagination="{ rowsPerPage: 0 }"
class="full-width" class="full-width"
table-style="user-select: none;" table-style="user-select: none;"
@drag="handleDrag($event)" @drag="handleDragScroll($event)"
@dragend="handleDrop($event)" @dragend="handleDragEnd($event)"
:separator="!targetRowIndex && targetRowIndex !== 0 ? 'horizontal' : 'none'" :separator="!targetRowIndex && targetRowIndex !== 0 ? 'horizontal' : 'none'"
> >
<template #body="props"> <template #body="props">
@ -548,7 +579,7 @@ const handleDrag = (event) => {
</template> </template>
<style scoped lang="scss"> <style scoped lang="scss">
::v-deep .q-table { :deep(.q-table) {
border-collapse: collapse; border-collapse: collapse;
} }