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 editor slice #5682

Merged
merged 2 commits into from
Nov 22, 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
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { isNil, sortBy, uniqueId } from 'lodash';
import { FaDiamondTurnRight } from 'react-icons/fa6';
import { useDispatch, useSelector } from 'react-redux';

import { getEditorIssue } from 'reducers/editor/selectors';
import { getEditorIssues } from 'reducers/editor/selectors';
import { updateFiltersIssue } from 'reducers/editor';
import { LoaderFill, Spinner } from 'common/Loader';
import OptionsSNCF from 'common/BootstrapSNCF/OptionsSNCF';
Expand All @@ -31,7 +31,7 @@ const InfraErrorsList: React.FC<InfraErrorsListProps> = ({ infraID, onErrorClick
const dispatch = useDispatch();
const [total, setTotal] = useState<number | null>(null);
const [next, setNext] = useState<number | null>(null);
const { filterLevel, filterType } = useSelector(getEditorIssue);
const { filterLevel, filterType } = useSelector(getEditorIssues);
const [loading, setLoading] = useState<boolean>(false);

// list of issues
Expand Down
57 changes: 57 additions & 0 deletions front/src/reducers/editor/__tests__/editorReducer.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { EditorState } from 'applications/editor/tools/types';
import { createStoreWithoutMiddleware } from 'Store';
import editorTestDataBuilder from './editorTestDataBuilder';
import {
editorInitialState,
selectLayers,
editorSlice,
loadDataModelAction,
updateTotalsIssueAction,
updateFiltersIssueAction,
} from '..';

const createStore = (initialStateExtra?: EditorState) =>
createStoreWithoutMiddleware({
[editorSlice.name]: initialStateExtra,
});
let store: ReturnType<typeof createStore>;

beforeEach(() => {
store = createStore();
});

describe('editorReducer', () => {
const testDataBuilder = editorTestDataBuilder();
it('should return initial state', () => {
const editorState = store.getState()[editorSlice.name];
expect(editorState).toEqual(editorInitialState);
});

it('should handle selectLayers', () => {
const editorLayers = testDataBuilder.buildEditorLayers(['catenaries', 'routes']);
store.dispatch(selectLayers(editorLayers));
const editorState = store.getState()[editorSlice.name];
expect(editorState.editorLayers).toEqual(new Set(['catenaries', 'routes']));
});

it('should handle loadDataModelAction and update editorSchema', () => {
const editorSchema = testDataBuilder.buildEditorSchema();
store.dispatch(loadDataModelAction(editorSchema));
const editorState = store.getState()[editorSlice.name];
expect(editorState.editorSchema).toEqual(editorSchema);
});

it('should handle updateTotalIssueAction', () => {
const newIssues = testDataBuilder.buildTotalIssue(5, 10);
store.dispatch(updateTotalsIssueAction(newIssues));
const editorState = store.getState()[editorSlice.name];
expect(editorState.issues).toEqual({ ...editorInitialState.issues, ...newIssues });
});

it('should handle updateFiltersIssueAction', () => {
const newIssues = testDataBuilder.buildFilterIssue('warnings', 'empty_object');
store.dispatch(updateFiltersIssueAction(newIssues));
const editorState = store.getState()[editorSlice.name];
expect(editorState.issues).toEqual({ ...editorInitialState.issues, ...newIssues });
});
});
26 changes: 26 additions & 0 deletions front/src/reducers/editor/__tests__/editorTestDataBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { LayerType, EditorState } from 'applications/editor/tools/types';

export default function editorTestDataBuilder() {
anisometropie marked this conversation as resolved.
Show resolved Hide resolved
return {
buildEditorLayers: (layers: Array<LayerType>): EditorState['editorLayers'] => new Set(layers),
buildEditorSchema: (): EditorState['editorSchema'] => [
{ layer: 'layerA', objType: 'BufferStop', schema: {} },
{ layer: 'layerA', objType: 'Route', schema: {} },
{ layer: 'layerA', objType: 'SwitchType', schema: {} },
],
buildTotalIssue: (
total: EditorState['issues']['total'],
filterTotal: EditorState['issues']['filterTotal']
): Pick<EditorState['issues'], 'total' | 'filterTotal'> => ({
total,
filterTotal,
}),
buildFilterIssue: (
filterLevel: EditorState['issues']['filterLevel'],
filterType: EditorState['issues']['filterType']
): Pick<EditorState['issues'], 'filterLevel' | 'filterType'> => ({
filterLevel,
filterType,
}),
};
}
175 changes: 66 additions & 109 deletions front/src/reducers/editor/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import produce from 'immer';
import { Feature } from 'geojson';
import { omit, clone, isNil, isUndefined } from 'lodash';
import { JSONSchema7, JSONSchema7Definition } from 'json-schema';
import { Action, AnyAction, Dispatch, Reducer } from '@reduxjs/toolkit';

import type { AnyAction, Dispatch, PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';
import { setLoading, setSuccess, setFailure, setSuccessWithoutMessage } from 'reducers/main';
import { updateIssuesSettings } from 'reducers/map';
import { osrdEditoastApi } from 'common/api/osrdEditoastApi';
Expand All @@ -12,45 +11,69 @@ import {
allInfraErrorTypes,
infraErrorTypeList,
} from 'applications/editor/components/InfraErrors/types';
import { EditorState, LayerType } from 'applications/editor/tools/types';
import { EditorState } from 'applications/editor/tools/types';
import {
entityToCreateOperation,
entityToUpdateOperation,
entityToDeleteOperation,
} from 'applications/editor/data/utils';
import infra_schema from '../osrdconf/infra_schema.json';

//
// Actions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
export const editorInitialState: EditorState = {
// Definition of entities (json schema)
editorSchema: [],
// ID of selected layers on which we are working
editorLayers: new Set(['track_sections', 'errors']),
// Editor issue management
issues: {
total: 0,
filterTotal: 0,
filterLevel: 'all',
filterType: null,
},
};

const SELECT_LAYERS = 'editor/SELECT_LAYERS';
export interface ActionSelectLayers extends AnyAction {
type: typeof SELECT_LAYERS;
layers: Set<LayerType>;
}
export function selectLayers(
layers: ActionSelectLayers['layers']
): ThunkAction<ActionSelectLayers> {
return (dispatch) => {
dispatch({
type: SELECT_LAYERS,
layers,
});
};
}
export const editorSlice = createSlice({
name: 'editor',
initialState: editorInitialState,
reducers: {
selectLayers(state, action: PayloadAction<EditorState['editorLayers']>) {
state.editorLayers = action.payload;
},
loadDataModelAction(state, action: PayloadAction<EditorState['editorSchema']>) {
state.editorSchema = action.payload;
},
updateTotalsIssueAction(
state,
action: PayloadAction<Pick<EditorState['issues'], 'total' | 'filterTotal'>>
) {
state.issues = {
...state.issues,
...action.payload,
};
},
updateFiltersIssueAction(
state,
action: PayloadAction<Pick<EditorState['issues'], 'filterLevel' | 'filterType'>>
) {
state.issues = {
...state.issues,
...action.payload,
};
},
},
});

//
// Verify if the data model definition is already loaded.
// If not we do it and store it in the state
//
export const LOAD_DATA_MODEL = 'editor/LOAD_DATA_MODEL';
export interface ActionLoadDataModel extends AnyAction {
type: typeof LOAD_DATA_MODEL;
schema: EditorSchema;
}
export const {
selectLayers,
loadDataModelAction,
updateTotalsIssueAction,
updateFiltersIssueAction,
} = editorSlice.actions;

export type editorSliceActionsType = typeof editorSlice.actions;

export function loadDataModel(): ThunkAction<ActionLoadDataModel> {
export function loadDataModel(): ThunkAction<editorSliceActionsType['loadDataModelAction']> {
return async (dispatch: Dispatch, getState) => {
// check if we need to load the model
if (!Object.keys(getState().editor.editorSchema).length) {
Expand Down Expand Up @@ -87,10 +110,7 @@ export function loadDataModel(): ThunkAction<ActionLoadDataModel> {
} as EditorSchema[0];
});
dispatch(setSuccessWithoutMessage());
dispatch({
type: LOAD_DATA_MODEL,
schema,
});
dispatch(loadDataModelAction(schema));
} catch (e) {
console.error(e);
dispatch(setFailure(e as Error));
Expand All @@ -99,14 +119,9 @@ export function loadDataModel(): ThunkAction<ActionLoadDataModel> {
};
}

const UPDATE_TOTALS_ISSUE = 'editor/UPDATE_TOTALS_ISSUE';
export interface ActionUpdateTotalsIssue extends AnyAction {
type: typeof UPDATE_TOTALS_ISSUE;
issues: Pick<EditorState['issues'], 'total' | 'filterTotal'>;
}
export function updateTotalsIssue(
infraID: number | undefined
): ThunkAction<ActionUpdateTotalsIssue> {
): ThunkAction<editorSliceActionsType['updateTotalsIssueAction']> {
return async (dispatch: Dispatch, getState) => {
const { editor } = getState();
dispatch(setLoading());
Expand Down Expand Up @@ -142,10 +157,7 @@ export function updateTotalsIssue(
const filterResult = await filterResp;
filterTotal = filterResult.data?.count || 0;
}
dispatch({
type: UPDATE_TOTALS_ISSUE,
issues: { total, filterTotal },
});
dispatch(updateTotalsIssueAction({ total, filterTotal }));
} catch (e) {
dispatch(setFailure(e as Error));
throw e;
Expand All @@ -155,15 +167,10 @@ export function updateTotalsIssue(
};
}

const UPDATE_FILTERS_ISSUE = 'editor/UPDATE_FILTERS_ISSUE';
export interface ActionUpdateFiltersIssue extends AnyAction {
type: typeof UPDATE_FILTERS_ISSUE;
issues: Omit<EditorState['issues'], 'total' | 'filterTotal'>;
}
export function updateFiltersIssue(
infraID: number | undefined,
filters: Partial<Pick<EditorState['issues'], 'filterLevel' | 'filterType'>>
): ThunkAction<ActionUpdateTotalsIssue> {
): ThunkAction<editorSliceActionsType['updateFiltersIssueAction']> {
return async (dispatch: Dispatch, getState) => {
const { editor } = getState() as { editor: EditorState };
let level = isUndefined(filters.filterLevel) ? editor.issues.filterLevel : filters.filterLevel;
Expand All @@ -187,10 +194,7 @@ export function updateFiltersIssue(
}
}

dispatch({
type: UPDATE_FILTERS_ISSUE,
issues: { filterLevel: level, filterType: type },
});
dispatch(updateFiltersIssueAction({ filterLevel: level, filterType: type }));
dispatch(updateTotalsIssue(infraID));

// dispatch the list of types matched by the filter to the map
Expand Down Expand Up @@ -261,57 +265,10 @@ export function save(
}

export type EditorActions =
| ActionLoadDataModel
| ActionSave
| ActionSelectLayers
| ActionUpdateTotalsIssue
| ActionUpdateFiltersIssue;

//
// State definition
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
export const initialState: EditorState = {
// Definition of entities (json schema)
editorSchema: [],
// ID of selected layers on which we are working
editorLayers: new Set(['track_sections', 'errors']),
// Editor issue management
issues: {
total: 0,
filterTotal: 0,
filterLevel: 'all',
filterType: null,
},
};

//
// State reducer
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const reducer = (inputState: EditorState | undefined, action: EditorActions) => {
const state = inputState || initialState;

return produce(state, (draft) => {
switch (action.type) {
case SELECT_LAYERS:
draft.editorLayers = action.layers;
break;
case LOAD_DATA_MODEL:
draft.editorSchema = action.schema;
break;
case UPDATE_FILTERS_ISSUE:
case UPDATE_TOTALS_ISSUE:
draft.issues = {
...state.issues,
...action.issues,
};
break;
default:
// Nothing to do here
break;
}
});
};
| editorSliceActionsType['loadDataModelAction']
| editorSliceActionsType['selectLayers']
| editorSliceActionsType['updateFiltersIssueAction']
| editorSliceActionsType['updateTotalsIssueAction']
| ActionSave;
anisometropie marked this conversation as resolved.
Show resolved Hide resolved

// TODO: to avoid error "Type 'Action<any>' is not assignable to type 'EditorActions'"
// We need to migrate the editor store with slice
export default reducer as Reducer<EditorState, Action>;
export default editorSlice.reducer;
6 changes: 5 additions & 1 deletion front/src/reducers/editor/selectors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { EditorState } from 'applications/editor/tools/types';
import { RootState } from 'reducers';
import { makeSubSelector } from 'utils/selectors';

export const getEditorState = (state: RootState) => state.editor;
export const getEditorIssue = (state: RootState) => state.editor.issues;
const makeEditorSelector = makeSubSelector<EditorState>(getEditorState);

export const getEditorIssues = makeEditorSelector('issues');
10 changes: 5 additions & 5 deletions front/src/reducers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import { osrdGatewayApi } from 'common/api/osrdGatewayApi';

import userReducer, { UserState, userInitialState } from 'reducers/user';
import mainReducer, { MainState, mainInitialState } from 'reducers/main';
import mapReducer, { MapState, mapInitialState } from './map';
import editorReducer, { EditorActions, initialState as editorInitialState } from './editor';
import mapReducer, { MapState, mapInitialState } from 'reducers/map';
import editorReducer, { EditorActions, editorInitialState, editorSlice } from 'reducers/editor';
import osrdconfReducer, { initialState as osrdconfInitialState } from './osrdconf';
// Dependency cycle will be removed during the refactoring of store
// eslint-disable-next-line import/no-cycle
Expand Down Expand Up @@ -84,7 +84,7 @@ type AllActions = EditorActions | Action;
export interface RootState {
user: UserState;
map: MapState;
editor: EditorState;
[editorSlice.name]: EditorState;
main: MainState;
[stdcmConfSlice.name]: OsrdStdcmConfState;
[simulationConfSlice.name]: OsrdConfState;
Expand All @@ -98,7 +98,7 @@ export interface RootState {
export const rootInitialState: RootState = {
user: userInitialState,
map: mapInitialState,
editor: editorInitialState,
[editorSlice.name]: editorInitialState,
main: mainInitialState,
[stdcmConfSlice.name]: stdcmConfInitialState,
[simulationConfSlice.name]: simulationConfInitialState,
Expand All @@ -121,7 +121,7 @@ export type AnyReducerState =
export const rootReducer: ReducersMapObject<RootState> = {
user: userReducer,
map: mapReducer,
editor: editorReducer,
[editorSlice.name]: editorReducer,
main: mainReducer,
[stdcmConfSlice.name]: stdcmConfReducer,
[simulationConfSlice.name]: simulationConfReducer,
Expand Down