Skip to content

Commit

Permalink
front: remove not rtk endpoints
Browse files Browse the repository at this point in the history
- use rtk in editor/data/api
  - getAttachedItems
  - getCompatibleRoutes
  - getRoutesFromWaypoint
  - getEntities
  - getRouteTrackRanges
- remove MapSearchSignalBox (not used anymore)
  • Loading branch information
clarani committed Oct 18, 2023
1 parent a6b9322 commit 941a073
Show file tree
Hide file tree
Showing 25 changed files with 415 additions and 466 deletions.
11 changes: 10 additions & 1 deletion editoast/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3344,6 +3344,10 @@ paths:
$ref: '#/components/schemas/DirectionalTrackRange'
minItems: 1
type: array
required:
- track_ranges
- detectors
- switches_directions
type: object
type: array
description: Paths, containing track ranges, detectors and switches with their directions. If no path is found, an empty list is returned.
Expand Down Expand Up @@ -3385,7 +3389,9 @@ paths:
schema:
description: A list of routes seperated by comma
example: route1,route2,route3
type: string
items:
type: string
type: array
responses:
'200':
content:
Expand Down Expand Up @@ -3446,6 +3452,9 @@ paths:
items:
type: string
type: array
required:
- starting
- ending
type: object
description: All routes that starting and ending by the given waypoint
summary: Retrieve all routes that starting and ending by the given waypoint (detector or buffer stop)
Expand Down
6 changes: 5 additions & 1 deletion editoast/openapi_legacy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,7 @@ paths:
items:
type: string
example: ["route3", "route4"]
required: [starting, ending]

/infra/{id}/routes/track_ranges/:
get:
Expand All @@ -720,7 +721,9 @@ paths:
- in: query
name: routes
schema:
type: string
type: array
items:
type: string
description: A list of routes seperated by comma
example: "route1,route2,route3"
required: true
Expand Down Expand Up @@ -800,6 +803,7 @@ paths:
example: { "switch1": "left", "switch2": "right" }
additionalProperties:
type: string
required: [track_ranges, detectors, switches_directions]

/infra/{id}/objects/{object_type}/:
post:
Expand Down
29 changes: 16 additions & 13 deletions front/src/applications/editor/Map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -211,20 +211,23 @@ const MapUnplugged: FC<PropsWithChildren<MapProps>> = ({
: e;
if (toolState.hovered && activeTool.onClickEntity) {
if (toolState.hovered.type) {
getEntity(infraID as number, toolState.hovered.id, toolState.hovered.type).then(
(entity) => {
if (activeTool.onClickEntity) {
// Those features lack a proper "geometry", and have a "_geometry"
// instead. This fixes it:
entity = {
...entity,
// eslint-disable-next-line no-underscore-dangle,@typescript-eslint/no-explicit-any
geometry: entity.geometry || (entity as any)._geometry,
};
activeTool.onClickEntity(entity, eventWithFeature, extendedContext);
}
getEntity(
infraID as number,
toolState.hovered.id,
toolState.hovered.type,
dispatch
).then((entity) => {
if (activeTool.onClickEntity) {
// Those features lack a proper "geometry", and have a "_geometry"
// instead. This fixes it:
entity = {
...entity,
// eslint-disable-next-line no-underscore-dangle,@typescript-eslint/no-explicit-any
geometry: entity.geometry || (entity as any)._geometry,
};
activeTool.onClickEntity(entity, eventWithFeature, extendedContext);
}
);
});
}
}
if (activeTool.onClickMap) {
Expand Down
37 changes: 22 additions & 15 deletions front/src/applications/editor/components/EntitySumUp.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { flatMap, forEach, isNumber, uniq } from 'lodash';
import { useSelector } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';
import { Dispatch } from 'redux';
import { TFunction } from 'i18next';
import cx from 'classnames';

Expand Down Expand Up @@ -46,7 +47,8 @@ const DEFAULT_CLASSES = {

async function getAdditionalEntities(
infra: number,
entity: EditorEntity
entity: EditorEntity,
dispatch: Dispatch
): Promise<Record<string, EditorEntity>> {
switch (entity.objType) {
case 'Signal':
Expand All @@ -55,7 +57,7 @@ async function getAdditionalEntities(
const trackId = (entity as SignalEntity).properties.track;
if (trackId) {
try {
return { [trackId]: await getEntity(infra, trackId, 'TrackSection') };
return { [trackId]: await getEntity(infra, trackId, 'TrackSection', dispatch) };
} catch (e) {
return {};
}
Expand All @@ -66,19 +68,21 @@ async function getAdditionalEntities(
const trackIDs = flatMap((entity as SwitchEntity).properties.ports, (port) =>
port.track ? [port.track] : []
);
return getEntities<TrackSectionEntity>(infra, trackIDs, 'TrackSection');
return getEntities<TrackSectionEntity>(infra, trackIDs, 'TrackSection', dispatch);
}
case 'Route': {
const route = entity as RouteEntity;
const entryPoint = await getEntity(
infra,
route.properties.entry_point.id,
route.properties.entry_point.type
route.properties.entry_point.type,
dispatch
);
const exitPoint = await getEntity(
infra,
route.properties.exit_point.id,
route.properties.exit_point.type
route.properties.exit_point.type,
dispatch
);
return { entryPoint, exitPoint };
}
Expand Down Expand Up @@ -282,6 +286,7 @@ const EntitySumUp: FC<
| { id: string; objType: EditoastType; entity?: undefined }
)
> = ({ entity, id, objType, classes, status }) => {
const dispatch = useDispatch();
const { t } = useTranslation();
const infraID = useSelector(getInfraID);
const [state, setState] = useState<
Expand All @@ -296,23 +301,25 @@ const EntitySumUp: FC<
setState({ type: 'loading' });

if (entity) {
getAdditionalEntities(infraID as number, entity).then((additionalEntities) => {
getAdditionalEntities(infraID as number, entity, dispatch).then((additionalEntities) => {
setState({
type: 'ready',
entity,
additionalEntities,
});
});
} else {
getEntity(infraID as number, id as string, objType as EditoastType).then(
getEntity(infraID as number, id as string, objType as EditoastType, dispatch).then(
(fetchedEntity) => {
getAdditionalEntities(infraID as number, fetchedEntity).then((additionalEntities) => {
setState({
type: 'ready',
entity: fetchedEntity,
additionalEntities,
});
});
getAdditionalEntities(infraID as number, fetchedEntity, dispatch).then(
(additionalEntities) => {
setState({
type: 'ready',
entity: fetchedEntity,
additionalEntities,
});
}
);
}
);
}
Expand Down
127 changes: 26 additions & 101 deletions front/src/applications/editor/data/api.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,12 @@
import { groupBy, uniq, toPairs } from 'lodash';
import { Dispatch } from 'redux';

import { get, post } from '../../../common/requests';
import {
PostInfraByIdObjectsAndObjectTypeApiResponse,
PostInfraByIdObjectsAndObjectTypeApiArg,
GetInfraByIdRoutesAndWaypointTypeWaypointIdApiResponse,
GetInfraByIdRoutesAndWaypointTypeWaypointIdApiArg,
GetInfraByIdRoutesTrackRangesApiResponse,
GetInfraByIdAttachedAndTrackIdApiResponse,
GetInfraByIdAttachedAndTrackIdApiArg,
} from '../../../common/api/osrdEditoastApi';
import {
Direction,
EditorEntity,
EditorEntityType,
TrackRange,
WayPoint,
WayPointEntity,
} from '../../../types';
import { EditoastType } from '../tools/types';
import { RouteCandidate } from '../tools/routeEdition/types';
osrdEditoastApi,
} from 'common/api/osrdEditoastApi';
import { EditoastType } from 'applications/editor/tools/types';
import { EditorEntity } from 'types/editor';

export function editoastToEditorEntity<T extends EditorEntity = EditorEntity>(
entity: PostInfraByIdObjectsAndObjectTypeApiResponse[0],
Expand All @@ -37,17 +24,21 @@ export function editoastToEditorEntity<T extends EditorEntity = EditorEntity>(
* Returns a list of entities from editoast
*/
export async function getEntities<T extends EditorEntity = EditorEntity>(
infra: number | string,
infraId: number,
ids: string[],
type: T['objType']
type: T['objType'],
dispatch: Dispatch
): Promise<Record<string, T>> {
const uniqIDs = uniq(ids);
const res = await post<
PostInfraByIdObjectsAndObjectTypeApiArg['body'],
PostInfraByIdObjectsAndObjectTypeApiResponse
>(`/editoast/infra/${infra}/objects/${type}/`, uniqIDs);
const results = await dispatch(
osrdEditoastApi.endpoints.postInfraByIdObjectsAndObjectType.initiate({
id: infraId as number,
objectType: type,
body: uniqIDs,
})
).unwrap();

return res.reduce(
return results.reduce(
(iter, entry, i) => ({
...iter,
[uniqIDs[i]]: editoastToEditorEntity<T>(entry, type),
Expand All @@ -60,97 +51,31 @@ export async function getEntities<T extends EditorEntity = EditorEntity>(
* Returns an entity from editoast:
*/
export async function getEntity<T extends EditorEntity = EditorEntity>(
infra: number | string,
infra: number,
id: string,
type: T['objType']
): Promise<T> {
const result = await getEntities<T>(infra, [id], type);
type: T['objType'],
dispatch: Dispatch
) {
const result = await getEntities<T>(infra, [id], type, dispatch);
if (!result || !result[id])
throw new Error(`getEntity: No entity found for type ${type} and id ${id}`);

return result[id];
}

export async function getMixedEntities<T extends EditorEntity = EditorEntity>(
infra: number | string,
defs: { id: string; type: EditoastType }[]
): Promise<Record<string, T>> {
infra: number,
defs: { id: string; type: EditoastType }[],
dispatch: Dispatch
) {
const groupedDefs = groupBy(defs, 'type');

const entities = await Promise.all(
toPairs(groupedDefs).map(([type, values]) => {
const ids = values.map(({ id }) => id);
return getEntities<T>(infra, ids, type as EditoastType);
return getEntities<T>(infra, ids, type as EditoastType, dispatch);
})
);

return entities.reduce((acc, curr) => ({ ...acc, ...curr }), {} as Record<string, T>);
}

/**
* Returns all routes starting from or ending to a waypoint:
*/
export async function getRoutesFromWaypoint(
infra: number | string,
type: EditorEntityType,
id: GetInfraByIdRoutesAndWaypointTypeWaypointIdApiArg['waypointId']
): Promise<GetInfraByIdRoutesAndWaypointTypeWaypointIdApiResponse> {
if (type !== 'BufferStop' && type !== 'Detector')
throw new Error(`${type} elements are not valid waypoints.`);
return get<GetInfraByIdRoutesAndWaypointTypeWaypointIdApiResponse>(
`/editoast/infra/${infra}/routes/${type}/${id}`
);
}

export async function getAttachedItems(
infra: number | string,
id: GetInfraByIdAttachedAndTrackIdApiArg['trackId']
): Promise<GetInfraByIdAttachedAndTrackIdApiResponse> {
return get<GetInfraByIdRoutesAndWaypointTypeWaypointIdApiResponse>(
`/editoast/infra/${infra}/attached/${id}`
);
}

export async function getRouteTrackRanges(
infra: number | string,
ids: string[]
): Promise<Record<string, TrackRange[] | null>> {
const res = await get<GetInfraByIdRoutesTrackRangesApiResponse>(
`/editoast/infra/${infra}/routes/track_ranges/?routes=${encodeURIComponent(ids.join(','))}`
);

return res.reduce(
(iter, o, i) => ({
...iter,
[ids[i]]: o.type === 'Computed' ? o.track_ranges : null,
}),
{} as Record<string, TrackRange[] | null>
);
}

export async function getCompatibleRoutes(
infra: number | string,
entryPoint: WayPoint,
entryPointDirection: Direction,
exitPoint: WayPoint
): Promise<Omit<RouteCandidate, 'color'>[]> {
const extremities = await getMixedEntities<WayPointEntity>(infra, [entryPoint, exitPoint]);
const entryPointEntity = extremities[entryPoint.id];
const exitPointEntity = extremities[exitPoint.id];

if (!entryPointEntity)
throw new Error(`Entry point ${entryPoint.id} (${entryPoint.type}) not found`);
if (!exitPointEntity) throw new Error(`Exit point ${exitPoint.id} (${exitPoint.type}) not found`);

return post(`/editoast/infra/${infra}/pathfinding/`, {
starting: {
track: entryPointEntity.properties.track as string,
position: entryPointEntity.properties.position as number,
direction: entryPointDirection,
},
ending: {
track: exitPointEntity.properties.track as string,
position: exitPointEntity.properties.position as number,
},
});
}
5 changes: 3 additions & 2 deletions front/src/applications/editor/nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,15 @@ const NavButtons: NavButton[][] = [
id: 'infra-errors',
icon: BsFillExclamationOctagonFill,
labelTranslationKey: 'Editor.nav.infra-errors',
async onClick({ openModal, closeModal, setViewport }, { switchTool }) {
async onClick({ openModal, closeModal, setViewport, dispatch }, { switchTool }) {
openModal(
<InfraErrorsModal
onErrorClick={async (infraID: number, item: InfraError) => {
const entity = await getEntity(
infraID,
item.information.obj_id,
item.information.obj_type
item.information.obj_type,
dispatch
);
// select the item in the editor scope
if (entity.objType === 'Route') {
Expand Down
Loading

0 comments on commit 941a073

Please sign in to comment.