Skip to content

Commit

Permalink
clean code clara
Browse files Browse the repository at this point in the history
  • Loading branch information
clarani committed Jul 5, 2024
1 parent b032b9a commit 56e7f56
Show file tree
Hide file tree
Showing 44 changed files with 1,278 additions and 1,242 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@
"powerRestrictionExplanationText": "By default, the simulation will use the nominal power.",
"powerRestrictionEmptyExplanationText": "The selected rolling stock does not have any power restrictions. You can edit it in the rolling stock editor.",
"removeVia": "Remove this waypoint",
"resetPowerRestrictions": "Reset power restrictions",
"restartPathfinding": "Restart search",
"rollingstock": "Rolling stock",
"saving": "Saving... please wait",
Expand Down Expand Up @@ -130,10 +129,11 @@
"electrification": "Electrification",
"inconsistent_one": "The interval below has inconsistencies. The default speed effort curve will be used for this.",
"inconsistent_other": "The intervals below contain inconsistencies. The default speed effort curves will be used for these.",
"powerRestrictionInvalidCombination": "- {{powerRestrictionCode}} is incompatible with electrification {{electrification}} of the path between {{begin}}m and {{end}}m",
"marginsAndPowerRestrictionsReset": "Margins and power restrictions have been reset.",
"missingPowerRestriction": "- Missing power restriction between {{begin}}m and {{end}}m.",
"modeNotHandled": "- No power restriction should be given between {{begin}}m and {{end}}m since the electrification mode {{electrification}} is not handled.",
"pathfindingChange": "Pathfinding changed",
"marginsAndPowerRestrictionsReset": "Margins and power restrictions have been reset."
"powerRestrictionInvalidCombination": "- {{powerRestrictionCode}} is incompatible with electrification {{electrification}} of the path between {{begin}}m and {{end}}m",
"powerRestrictionsReset": "Power restrictions have been reset."
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@
"powerRestrictionEmptyExplanationText": "Le matériel roulant sélectionné ne possède pas de restrictions de puissance. Vous pouvez en créer dans l'éditeur de matériel roulant.",
"removeVia": "Retirer ce via",
"restartPathfinding": "Relancer la recherche",
"resetPowerRestrictions": "Réinitialiser les restrictions de puissance",
"rollingstock": "Matériel",
"saving": "Enregistrement en cours... veuillez patienter",
"simulation": "Simulation",
Expand Down Expand Up @@ -131,10 +130,11 @@
"electrification": "Électrification",
"inconsistent_one": "Un intervalle comporte des incohérences. La courbe effort vitesse par défaut sera utilisée pour celui-ci.",
"inconsistent_other": "Plusieurs intervalles comportent des incohérences. Les courbes effort vitesse par défaut seront utilisées pour ceux-ci.",
"powerRestrictionInvalidCombination": "- Code {{powerRestrictionCode}} incompatible avec l'électrification à {{electrification}} de l'itinéraire entre {{begin}}m et {{end}}m. ",
"marginsAndPowerRestrictionsReset": "Les marges et les restrictions de puissance ont été réinitialisées.",
"missingPowerRestriction": "- Restriction de puissance manquante entre {{begin}}m et {{end}}m.",
"modeNotHandled": "- Aucune restriction de puissance ne devrait être renseignée entre {{begin}}m and {{end}}m comme le matériel roulant ne supporte pas l'électrification {{electrification}}.",
"pathfindingChange": "Changement de chemin",
"marginsAndPowerRestrictionsReset": "Les marges et les restrictions de puissance ont été réinitialisées."
"powerRestrictionInvalidCombination": "- Code {{powerRestrictionCode}} incompatible avec l'électrification à {{electrification}} de l'itinéraire entre {{begin}}m et {{end}}m.",
"powerRestrictionsReset": "Les restrictions de puissance ont été réinitialisées."
}
}
6 changes: 0 additions & 6 deletions front/src/applications/operationalStudies/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,6 @@ export type StudyType = typeof STUDY_TYPES;

export type PowerRestrictionRange = LinearMetadataItem<{ value: string }>;

export type PowerRestrictionV2 = {
from: string;
to: string;
code: string;
};

// electrical profiles
interface Profile {
mode: string;
Expand Down
22 changes: 14 additions & 8 deletions front/src/applications/operationalStudies/types.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import type {
PathProperties,
PathResponse,
PathfindingResult,
PathfindingResultSuccess,
ProjectPathTrainResult,
RangedValue,
SimulationResponse,
TrainScheduleBase,
} from 'common/api/osrdEditoastApi';
import type { SuggestedOP } from 'modules/trainschedule/components/ManageTrainSchedule/types';
import type { ArrayElement } from 'utils/types';

export interface Destination {
uic: number;
Expand Down Expand Up @@ -81,7 +84,7 @@ export type TrainScheduleImportConfig = {
startTime: string;
endTime: string;
};
type SuccesfulPathfindingResult = Extract<PathfindingResult, { status: 'success' }>;

// Extraction of some required and non nullable properties from osrdEditoastApi's PathProperties type
export type ManageTrainSchedulePathProperties = {
electrifications: NonNullable<PathProperties['electrifications']>;
Expand All @@ -90,7 +93,7 @@ export type ManageTrainSchedulePathProperties = {
/** Operational points along the path (including origin and destination) and vias added by clicking on map */
allWaypoints: SuggestedOP[];
length: number;
trackSectionRanges: NonNullable<SuccesfulPathfindingResult['track_section_ranges']>;
trackSectionRanges: NonNullable<PathfindingResultSuccess['track_section_ranges']>;
};

/**
Expand All @@ -108,6 +111,7 @@ export type PositionData<T extends 'gradient' | 'radius'> = {
position: number;
};

/** Start and stop are in meters */
export type ElectrificationRangeV2 = {
electrificationUsage: ElectrificationUsageV2;
start: number;
Expand Down Expand Up @@ -145,19 +149,21 @@ export type ElectricalProfileValue = Extract<
{ status: 'success' }
>['electrical_profiles']['values'][number];

/**
* Electrifications start and stop are in meters
*/
/** Electrifications start and stop are in meters */
export type PathPropertiesFormatted = {
electrifications: ElectrificationRangeV2[];
curves: PositionData<'radius'>[];
slopes: PositionData<'gradient'>[];
operationalPoints: NonNullable<PathProperties['operational_points']>;
geometry: NonNullable<PathProperties['geometry']>;
voltages: RangedValue[];
};

export type PowerRestrictionV2 = ArrayElement<TrainScheduleBase['power_restrictions']>;

export type SimulationResponseSuccess = Extract<SimulationResponse, { status: 'success' }>;
export interface ElectrificationVoltage {

export type ElectrificationVoltage = {
type: string;
voltage?: string;
}
};
21 changes: 8 additions & 13 deletions front/src/applications/operationalStudies/utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { omit } from 'lodash';

import type {
PathProperties,
ProjectPathTrainResult,
RangedValue,
} from 'common/api/osrdEditoastApi';
import type { PathProperties, ProjectPathTrainResult } from 'common/api/osrdEditoastApi';
import getPathVoltages from 'modules/pathfinding/helpers/getPathVoltages';
import { convertUTCDateToLocalDate, isoDateToMs } from 'utils/date';
import { mmToM } from 'utils/physics';
import { ms2sec } from 'utils/timeManipulation';
Expand Down Expand Up @@ -86,14 +83,6 @@ export const transformBoundariesDataToRangesData = <
return formatedData;
};

export const addRange = (ranges: RangedValue[], begin: number, end: number, value: string) => {
ranges.push({
begin,
end,
value,
});
};

export const formatElectrificationRanges = (
electrifications: ElectricalRangesData<ElectrificationValue>[],
electricalProfiles: ElectricalRangesData<ElectricalProfileValue>[]
Expand Down Expand Up @@ -191,12 +180,18 @@ export const preparePathPropertiesData = (
electricalProfilesRanges
);

const voltageRanges = getPathVoltages(
electrifications as NonNullable<PathProperties['electrifications']>,
pathLength
);

return {
electrifications: electrificationRanges,
curves: formattedCurves,
slopes: formattedSlopes,
operationalPoints: operational_points as NonNullable<PathProperties['operational_points']>,
geometry: geometry as NonNullable<PathProperties['geometry']>,
voltages: voltageRanges,
};
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,16 @@ import { compact } from 'lodash';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';

import type {
ElectrificationVoltage,
ManageTrainSchedulePathProperties,
} from 'applications/operationalStudies/types';
import { addRange } from 'applications/operationalStudies/utils';
import type { ManageTrainSchedulePathProperties } from 'applications/operationalStudies/types';
import allowancesPic from 'assets/pictures/components/allowances.svg';
import pahtFindingPic from 'assets/pictures/components/pathfinding.svg';
import simulationSettings from 'assets/pictures/components/simulationSettings.svg';
import rollingStockPic from 'assets/pictures/components/train.svg';
import type { IntervalItem } from 'common/IntervalsEditor/types';
import { useOsrdConfSelectors } from 'common/osrdContext';
import { useStoreDataForSpeedLimitByTagSelector } from 'common/SpeedLimitByTagSelector/useStoreDataForSpeedLimitByTagSelector';
import Tabs from 'common/Tabs';
import ItineraryV2 from 'modules/pathfinding/components/Itinerary/ItineraryV2';
import getPathVoltages from 'modules/pathfinding/helpers/getPathVoltages';
import { upsertViasInOPs } from 'modules/pathfinding/utils';
import PowerRestrictionsSelectorV2 from 'modules/powerRestriction/components/PowerRestrictionsSelectorV2';
import RollingStock2Img from 'modules/rollingStock/components/RollingStock2Img';
Expand All @@ -29,8 +25,6 @@ import { Map } from 'modules/trainschedule/components/ManageTrainSchedule';
import SimulationSettings from 'modules/trainschedule/components/ManageTrainSchedule/SimulationSettings';
import TrainSettings from 'modules/trainschedule/components/ManageTrainSchedule/TrainSettings';
import { formatKmValue } from 'utils/strings';
import { upsertViasInOPs } from 'modules/pathfinding/utils';
import { compact } from 'lodash';

const ManageTrainScheduleV2 = () => {
const { t } = useTranslation(['operationalStudies/manageTrainSchedule']);
Expand Down Expand Up @@ -61,67 +55,12 @@ const ManageTrainScheduleV2 = () => {
allWaypoints,
});
}
}, [])

const [initialPowerRestrictions, setInitialPowerRestrictions] = useState<RangedValueV2[]>([]);

const isElectrification = (
value: ElectrificationVoltage
): value is { type: 'electrification'; voltage: string } => value.type === 'electrification';
}, []);

type RangedValueV2 = {
begin: number;
end: number;
value: string;
};

useEffect(() => {
if (pathProperties) {
const allVias = upsertViasInOPs(
pathProperties.suggestedOperationalPoints,
compact(pathSteps)
);
setPathProperties({
...pathProperties,
allVias,
});
}
}, [pathSteps]);

const pathElectrificationRanges = (): IntervalItem[] => {
if (!pathProperties || !pathProperties.electrifications) return [];

const boundaries = [0, ...pathProperties.electrifications.boundaries, pathProperties.length];
const values = [...pathProperties.electrifications.values];

const ranges: RangedValueV2[] = [];
let start = boundaries[0];
let currentVoltage = isElectrification(values[0]) ? values[0].voltage : '';

for (let i = 1; i < values.length; i += 1) {
const currentValue = values[i];
if (isElectrification(currentValue) && currentValue.voltage !== currentVoltage) {
addRange(ranges, start, boundaries[i], currentVoltage);
start = boundaries[i];
currentVoltage = currentValue.voltage;
}
}

// Add the last segment
addRange(ranges, start, boundaries[boundaries.length - 1], currentVoltage);
setInitialPowerRestrictions(ranges);
return ranges;
};

useMemo(() => {
if (!pathProperties) return [];

return pathElectrificationRanges().map((electrificationRange) => ({
begin: electrificationRange.begin,
end: electrificationRange.end,
value: `${electrificationRange.value}`,
}));
}, [pathProperties]);
const voltageRanges = useMemo(
() => getPathVoltages(pathProperties?.electrifications, pathProperties?.length),
[pathProperties]
);

const tabRollingStock = {
id: 'rollingstock',
Expand Down Expand Up @@ -211,11 +150,11 @@ const ManageTrainScheduleV2 = () => {
dispatchUpdateSpeedLimitByTag={dispatchUpdateSpeedLimitByTag}
constraintDistribution={constraintDistribution}
/>
{rollingStock && isElectric(rollingStock.effort_curves.modes) && (
{rollingStock && isElectric(rollingStock.effort_curves.modes) && pathProperties && (
<PowerRestrictionsSelectorV2
rollingStockModes={rollingStock.effort_curves.modes}
rollingStockPowerRestrictions={rollingStock.power_restrictions}
pathElectrificationRanges={initialPowerRestrictions}
voltageRanges={voltageRanges}
pathProperties={pathProperties}
/>
)}
Expand Down
4 changes: 2 additions & 2 deletions front/src/applications/stdcmV2/components/StdcmVias.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const StdcmVias = ({ disabled = false, setCurrentSimulationInputs }: StdcmConfig

const updatePathStepsList = (pathStep: PathStep | null, index: number) => {
const newPathSteps = replaceElementAtIndex(pathSteps, index, pathStep);
dispatch(updatePathSteps(newPathSteps));
dispatch(updatePathSteps({ pathSteps: newPathSteps }));
};

const updatePathStepStopTime = (stopTime: string, index: number) => {
Expand Down Expand Up @@ -95,7 +95,7 @@ const StdcmVias = ({ disabled = false, setCurrentSimulationInputs }: StdcmConfig
Icon={<Location size="lg" variant="base" />}
onClick={() => {
const newPathSteps = addElementAtIndex(pathSteps, pathSteps.length - 1, null);
dispatch(updatePathSteps(newPathSteps));
dispatch(updatePathSteps({ pathSteps: newPathSteps }));
}}
/>
</div>
Expand Down
1 change: 1 addition & 0 deletions front/src/common/IntervalsDataViz/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,7 @@ export function splitAt<T>(
if (linearMetadata.length < 1) throw new Error('linear metadata is empty');
if (distance >= (last(linearMetadata)?.end || 0) || distance <= 0)
throw new Error('split point is outside the geometry');

return linearMetadata
.map((item) => {
if (item.begin <= distance && distance <= item.end) {
Expand Down
2 changes: 1 addition & 1 deletion front/src/common/IntervalsDataViz/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ $resize-width: 3px;
div.resize {
width: $resize-width;
height: 100%;
// cursor: col-resize;
cursor: col-resize;
z-index: 2;
background-color: #fff;

Expand Down
5 changes: 2 additions & 3 deletions front/src/common/IntervalsEditor/IntervalsEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
import { createEmptySegmentAt, removeSegment } from './utils';
import ZoomButtons from './ZoomButtons';

type IntervalsEditorProps = {
export type IntervalsEditorProps = {
/** Additionnal read-only data that will be displayed along the path, below the intervals editor */
additionalData?: AdditionalDataItem[];
/** Default value used when a new range is created */
Expand All @@ -54,9 +54,8 @@ type IntervalsEditorProps = {
disableDrag?: boolean;
onResizeFromInput?: (
intervalIndex: number,
newEnd: number,
context: 'begin' | 'end',
newBegin: number
newPosition: number
) => void;
} & (
| {
Expand Down
19 changes: 5 additions & 14 deletions front/src/common/IntervalsEditor/IntervalsEditorCommonForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,15 @@ import DebouncedNumberInputSNCF from 'common/BootstrapSNCF/FormSNCF/DebouncedNum
import { fixLinearMetadataItems, resizeSegment } from 'common/IntervalsDataViz/data';
import { notEmpty } from 'common/IntervalsDataViz/utils';

import type { IntervalsEditorProps } from './IntervalsEditor';
import type { IntervalItem } from './types';

type IntervalsEditorFormProps = {
data: IntervalItem[];
interval: IntervalItem;
selectedIntervalIndex: number;
setData: (newData: IntervalItem[], selectedIntervalIndex?: number) => void;
onInputChange?: (
intervalIndex: number,
newEnd: number,
context: 'begin' | 'end',
newBegin: number
) => void;
onInputChange?: IntervalsEditorProps['onResizeFromInput'];
setSelectedIntervalIndex: (selectedIntervalIndex: number) => void;
totalLength: number;
defaultValue: string | number;
Expand All @@ -36,8 +32,8 @@ const IntervalsEditorCommonForm = ({
}: IntervalsEditorFormProps) => {
const { t } = useTranslation('common/common');

const [begin, setBegin] = useState<number>(Math.round(interval.begin));
const [end, setEnd] = useState<number>(Math.round(interval.end));
const [begin, setBegin] = useState(Math.round(interval.begin));
const [end, setEnd] = useState(Math.round(interval.end));

useEffect(() => {
setBegin(Math.round(interval.begin));
Expand All @@ -62,12 +58,7 @@ const IntervalsEditorCommonForm = ({
defaultValue,
});
if (onInputChange) {
onInputChange(
selectedIntervalIndex,
context === 'end' ? newPosition : interval.end,
context,
context === 'begin' ? newPosition : interval.begin
); // Pass newBegin when context is 'begin'
onInputChange(selectedIntervalIndex, context, newPosition);
} else {
setData(fixedResults, selectedIntervalIndex);
}
Expand Down
Loading

0 comments on commit 56e7f56

Please sign in to comment.