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

editor: allows user to select infra #2069

Merged
merged 2 commits into from
Oct 12, 2022
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
4 changes: 3 additions & 1 deletion front/public/locales/fr/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
"tool-help": "Voir la description de l'outil actif",
"nav": {
"recenter": "Recentrer la carte",
"toggle-layers": "[TODO] Choisir les couches à afficher"
"toggle-layers": "[TODO] Choisir les couches à afficher",
"select-infra": "Choisir l'infrastructure à éditer",
"infra-changed": "Vous éditez maintenant l'infra \"{{label}}\" (id \"{{id}}\")."
},
"errors": {
"infra-not-found": "L'infrastructure {{id}} non trouvée",
Expand Down
130 changes: 78 additions & 52 deletions front/src/applications/editor/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import './Editor.scss';

import { LoaderState } from '../../common/Loader';
import { NotificationsState } from '../../common/Notifications';
import { EditorState, loadDataModel } from '../../reducers/editor';
import { EditorState, loadDataModel, reset } from '../../reducers/editor';
import { MainState, setFailure } from '../../reducers/main';
import { updateViewport } from '../../reducers/map';
import { updateInfraID } from '../../reducers/osrdconf';
Expand All @@ -24,6 +24,7 @@ import {
CommonToolState,
EditorContextType,
ExtendedEditorContextType,
FullTool,
ModalRequest,
OSRDConf,
Tool,
Expand All @@ -36,19 +37,51 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
const editorState = useSelector((state: { editor: EditorState }) => state.editor);
const { fullscreen } = useSelector((state: { main: MainState }) => state.main);
/* eslint-disable @typescript-eslint/no-explicit-any */
const [activeTool, activateTool] = useState<Tool<any>>(TOOLS[0]);
const [toolState, setToolState] = useState<any>(activeTool.getInitialState({ osrdConf }));
const [toolAndState, setToolAndState] = useState<FullTool<any>>({
tool: TOOLS[0],
state: TOOLS[0].getInitialState({ osrdConf }),
});
const [modal, setModal] = useState<ModalRequest<any, any> | null>(null);
/* eslint-enable @typescript-eslint/no-explicit-any */
const openModal = useCallback(
<ArgumentsType, SubmitArgumentsType>(
request: ModalRequest<ArgumentsType, SubmitArgumentsType>
) => {
setModal(request as ModalRequest<unknown, unknown>);
},
[setModal]
);
const switchTool = useCallback(
<S extends CommonToolState>(tool: Tool<S>, partialState?: Partial<S>) => {
const state = { ...tool.getInitialState({ osrdConf }), ...(partialState || {}) };
setToolAndState({
tool,
state,
});
},
[osrdConf, setToolAndState]
);
const setToolState = useCallback(
<S extends CommonToolState>(state?: S) => {
setToolAndState((s) => ({
...s,
state,
}));
},
[setToolAndState]
);
const resetState = useCallback(() => {
switchTool(TOOLS[0]);
dispatch(reset());
}, []);

const { infra, urlLat, urlLon, urlZoom, urlBearing, urlPitch } =
useParams<Record<string, string>>();
const { infra } = useParams<{ infra?: string }>();
const { mapStyle, viewport } = useSelector(
(state: { map: { mapStyle: string; viewport: ViewportProps } }) => state.map
);
const setViewport = useCallback(
(value) => {
dispatch(updateViewport(value, `/editor/${osrdConf.infraID || '-1'}`));
dispatch(updateViewport(value, `/editor/${osrdConf.infraID || '-1'}`, false));
},
[dispatch, osrdConf.infraID]
);
Expand All @@ -57,24 +90,16 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
() => ({
t,
modal,
openModal: <ArgumentsType, SubmitArgumentsType>(
request: ModalRequest<ArgumentsType, SubmitArgumentsType>
) => {
setModal(request as ModalRequest<unknown, unknown>);
},
openModal,
closeModal: () => {
setModal(null);
},
activeTool,
state: toolState,
activeTool: toolAndState.tool,
state: toolAndState.state,
setState: setToolState,
switchTool<S extends CommonToolState>(tool: Tool<S>, state?: Partial<S>) {
const fullState = { ...tool.getInitialState({ osrdConf }), ...(state || {}) };
activateTool(tool);
setToolState(fullState);
},
switchTool,
}),
[activeTool, modal, osrdConf, t, toolState]
[toolAndState, modal, osrdConf, t]
);
const extendedContext = useMemo<ExtendedEditorContextType<CommonToolState>>(
() => ({
Expand All @@ -90,25 +115,20 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
[context, dispatch, editorState, mapStyle, osrdConf, viewport]
);

const actionsGroups = activeTool.actions
.map((group) => group.filter((action) => !action.isHidden || !action.isHidden(extendedContext)))
.filter((group) => group.length);
const actionsGroups = useMemo(
() =>
toolAndState.tool.actions
.map((group) =>
group.filter((action) => !action.isHidden || !action.isHidden(extendedContext))
)
.filter((group) => group.length),
[toolAndState.tool]
);

// Initial viewport:
useEffect(() => {
// load the data model
dispatch(loadDataModel());
if (urlLat) {
setViewport({
...viewport,
latitude: parseFloat(urlLat || '0'),
longitude: parseFloat(urlLon || '0'),
zoom: parseFloat(urlZoom || '1'),
bearing: parseFloat(urlBearing || '1'),
pitch: parseFloat(urlPitch || '1'),
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

// Update the infrastructure in state
Expand All @@ -117,20 +137,23 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
useEffect(() => {
if (infra && parseInt(infra, 10) > 0) {
getInfrastructure(parseInt(infra, 10))
.then((infrastructure) => dispatch(updateInfraID(infrastructure.id)))
.then((infrastructure) => {
dispatch(updateInfraID(infrastructure.id));
resetState();
})
.catch(() => {
dispatch(setFailure(new Error(t('Editor.errors.infra-not-found', { id: infra }))));
dispatch(updateViewport({}, `/editor/`));
dispatch(updateViewport({}, `/editor/`, false));
});
} else if (osrdConf.infraID) {
dispatch(updateViewport({}, `/editor/${osrdConf.infraID}`));
dispatch(updateViewport({}, `/editor/${osrdConf.infraID}`, false));
} else {
getInfrastructures()
.then((infras) => {
if (infras && infras.length > 0) {
const infrastructure = infras[0];
dispatch(updateInfraID(infrastructure.id));
dispatch(updateViewport({}, `/editor/${infrastructure.id}`));
dispatch(updateViewport({}, `/editor/${infrastructure.id}`, false));
} else {
dispatch(setFailure(new Error(t('Editor.errors.no-infra-available'))));
}
Expand All @@ -139,17 +162,17 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
dispatch(setFailure(new Error(t('Editor.errors.technical', { msg: e.message }))));
});
}
}, [dispatch, infra, osrdConf.infraID, t]);
}, [infra, osrdConf.infraID]);

// Lifecycle events on tools:
useEffect(() => {
if (activeTool.onMount) activeTool.onMount(extendedContext);
if (toolAndState.tool.onMount) toolAndState.tool.onMount(extendedContext);

return () => {
if (activeTool.onUnmount) activeTool.onUnmount(extendedContext);
if (toolAndState.tool.onUnmount) toolAndState.tool.onUnmount(extendedContext);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeTool]);
}, [toolAndState.tool]);

return (
<EditorContext.Provider value={extendedContext as EditorContextType<unknown>}>
Expand All @@ -166,10 +189,13 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
<Tipped key={id} mode="right">
<button
type="button"
className={cx('btn-rounded', id === activeTool.id && 'active', 'editor-btn')}
className={cx(
'btn-rounded',
id === toolAndState.tool.id && 'active',
'editor-btn'
)}
onClick={() => {
activateTool(tool);
setToolState(tool.getInitialState({ osrdConf }));
switchTool(tool);
}}
disabled={isDisabled && isDisabled(extendedContext)}
>
Expand Down Expand Up @@ -224,21 +250,21 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
: actions;
})}
</div>
{activeTool.leftPanelComponent && (
{toolAndState.tool.leftPanelComponent && (
<div className="panel-box">
<activeTool.leftPanelComponent />
<toolAndState.tool.leftPanelComponent />
</div>
)}
<div className="map-wrapper">
<div className="map">
<Map
{...{
toolState,
setToolState,
mapStyle,
viewport,
setViewport,
activeTool,
mapStyle,
toolState: toolAndState.state,
activeTool: toolAndState.tool,
setToolState,
}}
/>

Expand Down Expand Up @@ -267,7 +293,7 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
)}
onClick={() => {
if (onClick) {
onClick({ dispatch, setViewport, viewport }, editorState);
onClick({ dispatch, setViewport, viewport, openModal }, editorState);
}
}}
disabled={isDisabled && isDisabled(editorState)}
Expand All @@ -287,7 +313,7 @@ const EditorUnplugged: FC<{ t: TFunction }> = ({ t }) => {
</div>
</div>
<div className="messages-bar">
{activeTool.messagesComponent && <activeTool.messagesComponent />}
{toolAndState.tool.messagesComponent && <toolAndState.tool.messagesComponent />}
</div>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion front/src/applications/editor/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class HomeEditorUnplugged extends React.Component {
<Routes>
<Route path="/" element={<Editor urlmap={config.proxy} />} />
<Route
path="/:infra/:urlLat/:urlLon/:urlZoom/:urlBearing/:urlPitch"
path="/:infra"
element={<Editor urlmap={config.proxy} />}
/>
</Routes>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import React, { FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';
import { datetime2string } from 'utils/timeManipulation';
import { useNavigate } from 'react-router';

import { ModalProps } from '../tools/types';
import Modal from './Modal';
import { get } from '../../../common/requests';
import { addNotification, setFailure } from '../../../reducers/main';

const infraURL = '/infra/';
type InfrasList = {
id: string;
name: string;
modified: number;
}[];

async function getInfrasList(): Promise<InfrasList> {
const response = await get<{ results: InfrasList }>(infraURL, {});
return response.results;
}

const InfraSelectorModal: FC<ModalProps<{}>> = ({ submit, cancel }) => {
const dispatch = useDispatch();
const navigate = useNavigate();
const { t } = useTranslation(['translation', 'osrdconf']);
const [infras, setInfras] = useState<InfrasList | null>(null);

useEffect(() => {
getInfrasList()
.then((list) => setInfras(list))
.catch((e) => {
dispatch(
setFailure({
name: t('errorMessages.unableToRetrieveInfraList'),
message: e.message,
})
);
console.log('ERROR', e);
});
}, []);

return (
<Modal onClose={cancel} title={t('osrdconf:infrachoose')}>
<div className="mb-3 osrd-config-infraselector">
{infras?.map((infra) => (
<div
role="button"
tabIndex={-1}
onClick={() => {
dispatch(
addNotification({
type: 'info',
text: t('Editor.nav.infra-changed', { id: infra.id, label: infra.name }),
})
);
navigate(`/editor/${infra.id}`);
submit({});
}}
key={infra.id}
data-dismiss="modal"
className="osrd-config-infraselector-item mb-2"
>
<div className="d-flex align-items-center">
<div className="text-primary small mr-2">{infra.id}</div>
<div className="flex-grow-1">{infra.name}</div>
<div className="small">{datetime2string(infra.modified)}</div>
</div>
</div>
))}
{!infras && (
<div className="d-flex align-items-center justify-content-center" style={{ width: 100 }}>
<div className="spinner-border" role="status">
<span className="sr-only">Loading...</span>
</div>
</div>
)}
</div>

<div className="text-right">
<button type="button" className="btn btn-danger mr-2" onClick={cancel}>
{t('common.cancel')}
</button>
<button
type="button"
className="btn btn-primary"
onClick={() => submit({})}
disabled={!infras}
>
{t('common.confirm')}
</button>
</div>
</Modal>
);
};

export default InfraSelectorModal;
Loading