Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

front: add multi select on scenario timetable trainschedule, allow su… #4770

Merged
merged 1 commit into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion front/public/locales/en/common/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"split": "Split",
"translate": "Translate",
"zoom-in": "Zoom in",
"zoom-out": "Zoom out"
"zoom-out": "Zoom out",
"deleteSelectionCount": "Do you confirm the deletion of {{items}} ?"
},
"begin": "Start",
"end": "End"
Expand Down
4 changes: 4 additions & 0 deletions front/public/locales/en/common/itemTypes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"trains_one": "{{count}} train",
"trains_other": "{{count}} trains"
}
5 changes: 4 additions & 1 deletion front/public/locales/en/operationalStudies/scenario.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@
"stopsCount_other": "{{ count }} stops",
"trainAdded": "Train added",
"trainDeleted": "{{ name }} train has been deleted.",
"update": "Edit"
"update": "Edit",
"trainsSelectionDeletedCount_one": "The train has been deleted.",
"trainsSelectionDeletedCount_other": "The {{count}} trains have been deleted."

},
"trainCount_one": "1 train",
"trainCount_other": "{{ count }} trains",
Expand Down
3 changes: 2 additions & 1 deletion front/public/locales/fr/common/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"split": "Diviser",
"translate": "Translater",
"zoom-in": "Agrandir",
"Zoom-out": "Réduire"
"Zoom-out": "Réduire",
"deleteSelectionCount": "Confirmez-vous la suppression de {{items}}?"
},
"begin": "Début",
"end": "Fin"
Expand Down
4 changes: 4 additions & 0 deletions front/public/locales/fr/common/itemTypes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"trains_one": "{{count}} train",
"trains_other": "{{count}} trains"
}
4 changes: 3 additions & 1 deletion front/public/locales/fr/operationalStudies/scenario.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@
"stopsCount_other": "{{count}} arrêts",
"trainAdded": "Train ajouté",
"trainDeleted": "Le train {{name}} a bien été supprimé.",
"update": "Modifier"
"update": "Modifier",
"trainsSelectionDeletedCount_one": "Le train a bien été supprimé.",
"trainsSelectionDeletedCount_other": "Les {{count}} trains ont bien été supprimés."
},
"trainCount_one": "1 train",
"trainCount_other": "{{count}} trains",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { useEffect, useState } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { FaDownload, FaPlus } from 'react-icons/fa';
import { FaDownload, FaPlus, FaTrash } from 'react-icons/fa';
import { BiSelectMultiple } from 'react-icons/bi';
import cx from 'classnames';

import InputSNCF from 'common/BootstrapSNCF/InputSNCF';
Expand All @@ -28,6 +29,8 @@ import { durationInSeconds } from 'utils/timeManipulation';
import { getSelectedTrainId } from 'reducers/osrdsimulation/selectors';
import { isEmpty } from 'lodash';
import { BsFillExclamationTriangleFill } from 'react-icons/bs';
import DeleteModal from 'common/BootstrapSNCF/ModalSNCF/DeleteModal';
import { ModalContext } from 'common/BootstrapSNCF/ModalSNCF/ModalProvider';
import getTimetable from './getTimetable';
import TimetableTrainCard from './TimetableTrainCard';
import findTrainsDurationsIntervals from '../ManageTrainSchedule/helpers/trainsDurationsIntervals';
Expand Down Expand Up @@ -57,12 +60,17 @@ export default function Timetable({
const [conflictsListExpanded, setConflictsListExpanded] = useState(false);
const [timetable, setTimetable] = useState<GetTimetableByIdApiResponse>();
const [conflicts, setConflicts] = useState<Conflict[]>([]);
const [multiselectOn, setMultiselectOn] = useState<boolean>(false);
const [selectedTrainIds, setSelectedTrainIds] = useState<number[]>([]);
const { openModal } = useContext(ModalContext);

const dispatch = useDispatch();
const { t } = useTranslation(['operationalStudies/scenario']);
const { t } = useTranslation(['operationalStudies/scenario', 'common/itemTypes']);

const debouncedTerm = useDebounce(filter, 500) as string;

const [deleteTrainSchedules] = osrdEditoastApi.endpoints.deleteTrainSchedule.useMutation();

const [getTimetableWithTrainSchedulesDetails] = osrdEditoastApi.useLazyGetTimetableByIdQuery();
const [getTimetableConflicts] = osrdEditoastApi.useLazyGetTimetableByIdConflictsQuery();

Expand All @@ -71,21 +79,24 @@ export default function Timetable({
dispatch(updateMustRedraw(true));
};

const refreshTimeTable = async () => {
dispatch(updateReloadTimetable(true));
const currentTimetable = await getTimetableWithTrainSchedulesDetails({
id: timetableID as number,
}).unwrap();
getTimetable(currentTimetable);
dispatch(updateReloadTimetable(false));
};
const deleteTrain = async (train: ScheduledTrain) => {
try {
await deleteRequest(`${trainscheduleURI}${train.id}/`);
dispatch(updateReloadTimetable(true));
const currentTimetable = await getTimetableWithTrainSchedulesDetails({
id: timetableID as number,
}).unwrap();
getTimetable(currentTimetable);
refreshTimeTable();
dispatch(
setSuccess({
title: t('timetable.trainDeleted', { name: train.train_name }),
text: '',
})
);
dispatch(updateReloadTimetable(false));
} catch (e) {
console.error(e);
if (e instanceof Error) {
Expand Down Expand Up @@ -127,19 +138,13 @@ export default function Timetable({
}
try {
await post(`${trainscheduleURI}standalone_simulation/`, params);
dispatch(updateReloadTimetable(true));

const currentTimetable = await getTimetableWithTrainSchedulesDetails({
id: timetableID as number,
}).unwrap();
getTimetable(currentTimetable);
refreshTimeTable();
dispatch(
setSuccess({
title: t('timetable.trainAdded'),
text: `${trainName}`,
})
);
dispatch(updateReloadTimetable(false));
} catch (e) {
console.error(e);
if (e instanceof Error) {
Expand Down Expand Up @@ -194,6 +199,63 @@ export default function Timetable({
const timeTableHasInvalidTrain = (trains: ScheduledTrain[]) =>
trains.some((train) => train.invalid_reasons && train.invalid_reasons.length > 0);

const toggleTrainSelection = (id: number) => {
const currentSelectedTrainIds = [...selectedTrainIds];
const index = currentSelectedTrainIds.indexOf(id); // Find the index of the ID in the array

if (index === -1) {
currentSelectedTrainIds.push(id);
} else {
currentSelectedTrainIds.splice(index, 1);
}

setSelectedTrainIds(currentSelectedTrainIds);
};

const selectAllTrains = () => {
if (
trainsList &&
trainsList.filter((train: ScheduledTrain) => !train.isFiltered).length ===
selectedTrainIds.length
) {
setSelectedTrainIds([]);
} else {
const trainIds = trainsList?.map((train) => train.id) || [];
setSelectedTrainIds(trainIds);
}
};

const handleTrainsDelete = async () => {
const trainsCount = selectedTrainIds.length;
await deleteTrainSchedules({ body: { ids: selectedTrainIds } })
.unwrap()
.then(() => {
refreshTimeTable();
setMultiselectOn(false);
dispatch(
setSuccess({
title: t('timetable.trainsSelectionDeletedCount', { count: trainsCount }),
text: '',
})
);
})
.catch((e) => {
console.error(e);
if (e instanceof Error) {
dispatch(
setFailure({
name: e.name,
message: e.message,
})
);
}
});
};

useEffect(() => {
if (!multiselectOn) setSelectedTrainIds([]);
}, [multiselectOn]);

useEffect(() => {
if (timetable && timetable.train_schedule_summaries) {
const scheduledTrains = timetable.train_schedule_summaries;
Expand Down Expand Up @@ -280,7 +342,20 @@ export default function Timetable({
</button>
</div>
<div className="scenario-timetable-toolbar">
{multiselectOn && (
<input
type="checkbox"
className="mr-2"
checked={
trainsList &&
selectedTrainIds.length ===
trainsList.filter((train: ScheduledTrain) => !train.isFiltered).length
}
onChange={() => selectAllTrains()}
/>
)}
<div className="small">
{multiselectOn && <span>{selectedTrainIds.length} / </span>}
{t('trainCount', {
count: trainsList
? trainsList.filter((train: ScheduledTrain) => !train.isFiltered).length
Expand All @@ -302,7 +377,36 @@ export default function Timetable({
data-testid="scenarios-filter"
/>
</div>
{!isEmpty(trainsList) && (
<button
type="button"
className={cx('multiselect-toggle', multiselectOn ? 'on' : '')}
onClick={() => setMultiselectOn(!multiselectOn)}
>
<BiSelectMultiple />
</button>
)}

{multiselectOn && (
<button
disabled={!selectedTrainIds.length}
className={cx('multiselect-delete', !selectedTrainIds.length && 'disabled')}
type="button"
onClick={() =>
openModal(
<DeleteModal
handleDelete={handleTrainsDelete}
items={t('common/itemTypes:trains', { count: selectedTrainIds.length })}
/>,
'sm'
)
}
>
<FaTrash />
</button>
)}
</div>

<div
className={cx(
'scenario-timetable-trains',
Expand All @@ -318,6 +422,9 @@ export default function Timetable({
(train: ScheduledTrain, idx: number) =>
!train.isFiltered && (
<TimetableTrainCard
isSelectable={multiselectOn}
isInSelection={selectedTrainIds.includes(train.id)}
toggleTrainSelection={toggleTrainSelection}
train={train}
intervalPosition={valueToInterval(train.duration, trainsDurationsIntervals)}
key={`timetable-train-card-${train.id}-${train.path_id}`}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,25 @@ const invalidTrainValues: {
};

type Props = {
isSelectable: boolean;
isInSelection: boolean;
train: ScheduledTrain;
intervalPosition?: number;
isSelected: boolean;
isModified?: boolean;
projectionPathIsUsed: boolean;
idx: number;
changeSelectedTrainId: (trainId: number) => void;
toggleTrainSelection: (trainId: number) => void;
deleteTrain: (train: ScheduledTrain) => void;
selectPathProjection: (train: ScheduledTrain) => void;
duplicateTrain: (train: ScheduledTrain) => void;
setDisplayTrainScheduleManagement: (arg0: string) => void;
};

function TimetableTrainCard({
isSelectable,
isInSelection,
train,
intervalPosition,
isSelected,
Expand All @@ -51,6 +56,7 @@ function TimetableTrainCard({
selectPathProjection,
duplicateTrain,
setDisplayTrainScheduleManagement,
toggleTrainSelection,
}: Props) {
const [getTrainSchedule] = osrdMiddlewareApi.endpoints.getTrainScheduleById.useLazyQuery({});
const [getRollingStock, { data: rollingStock }] =
Expand Down Expand Up @@ -81,9 +87,18 @@ function TimetableTrainCard({
isSelected && 'selected',
isModified && 'modified',
train.invalid_reasons && train.invalid_reasons.length > 0 && 'invalid',
isInSelection && 'in-selection',
`colored-border-${intervalPosition}`
)}
>
{isSelectable && (
<input
type="checkbox"
className="mr-2"
checked={isInSelection}
onChange={() => toggleTrainSelection(train.id)}
/>
)}
<div
className="scenario-timetable-train-container"
role="button"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const withOSRDData = (Component) =>
const allowancesSettings = useSelector(getAllowancesSettings);
const positionValues = useSelector(getPositionValues);
const selectedTrain = useSelector(getSelectedTrain);
// implement selector for all selected trains ids
const selectedProjection = useSelector(getSelectedProjection);
const timePosition = useSelector(getTimePosition);
const simulation = useSelector(getPresentSimulation);
Expand Down Expand Up @@ -114,6 +115,7 @@ const withOSRDData = (Component) =>
dispatchUpdateSelectedTrainId={dispatchUpdateSelectedTrainId}
dispatchUpdateTimePositionValues={dispatchUpdateTimePositionValues}
inputSelectedTrain={selectedTrain}
// add selected trains ids
onOffsetTimeByDragging={onOffsetTimeByDragging}
positionValues={positionValues}
selectedProjection={selectedProjection}
Expand Down
40 changes: 40 additions & 0 deletions front/src/common/BootstrapSNCF/ModalSNCF/DeleteModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import React from 'react';
import { ModalBodySNCF, ModalFooterSNCF, useModal } from 'common/BootstrapSNCF/ModalSNCF';
import { useTranslation } from 'react-i18next';

export default function DeleteModal({
handleDelete,
items,
}: {
handleDelete: () => void;
items: string;
}) {
const { t } = useTranslation(['translation', 'common/common']);
const { closeModal } = useModal();
return (
<>
<ModalBodySNCF>
<div className="lead my-4 w-100 text-center">
{t('common/common:actions.deleteSelectionCount', { items })}
</div>
</ModalBodySNCF>
<ModalFooterSNCF>
<div className="d-flex align-items-center">
<button className="btn btn-secondary flex-grow-1" type="button" onClick={closeModal}>
{t('translation:common.cancel')}
</button>
<button
className="btn btn-danger flex-grow-1 ml-1"
type="button"
onClick={() => {
handleDelete();
closeModal();
}}
>
{t('translation:common.delete')}
</button>
</div>
</ModalFooterSNCF>
</>
);
}
Loading