-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathEditor.tsx
469 lines (437 loc) · 15.5 KB
/
Editor.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import cx from 'classnames';
import { isNil, toInteger } from 'lodash';
import { useTranslation } from 'react-i18next';
import type { MapRef } from 'react-map-gl/maplibre';
import { useSelector } from 'react-redux';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import InfraErrorCorrector from 'applications/editor/components/InfraErrors/InfraErrorCorrector';
import InfraErrorMapControl from 'applications/editor/components/InfraErrors/InfraErrorMapControl';
import EditorContext from 'applications/editor/context';
import { getEntity, getMixedEntities } from 'applications/editor/data/api';
import { NEW_ENTITY_ID } from 'applications/editor/data/utils';
import Map from 'applications/editor/Map';
import TOOL_NAMES from 'applications/editor/tools/constsToolNames';
import TOOLS from 'applications/editor/tools/constsTools';
import useSwitchTypes from 'applications/editor/tools/switchEdition/useSwitchTypes';
import type { switchProps } from 'applications/editor/tools/switchProps';
import type { CommonToolState } from 'applications/editor/tools/types';
import { centerMapOnObject, selectEntities } from 'applications/editor/tools/utils';
import type { ObjectType } from 'common/api/osrdEditoastApi';
import { useModal } from 'common/BootstrapSNCF/ModalSNCF';
import { LoaderState } from 'common/Loaders';
import MapButtons from 'common/Map/Buttons/MapButtons';
import MapSearch from 'common/Map/Search/MapSearch';
import { useInfraActions, useInfraID, useOsrdActions } from 'common/osrdContext';
import useInfra from 'modules/infra/useInfra';
import type { EditorSliceActions } from 'reducers/editor';
import { getEditorState, getInfraLockStatus } from 'reducers/editor/selectors';
import { loadDataModel, updateTotalsIssue } from 'reducers/editor/thunkActions';
import { setFailure } from 'reducers/main';
import { getIsLoading } from 'reducers/main/mainSelector';
import { updateViewport, type Viewport } from 'reducers/map';
import { getMap } from 'reducers/map/selectors';
import { useAppDispatch } from 'store';
import { castErrorToFailure } from 'utils/error';
import type { EditoastType, Layer } from './consts';
import type { EditorContextType, ExtendedEditorContextType, FullTool, Reducer } from './types';
import type { EditorEntity } from './typesEditorEntity';
const Editor = () => {
const { t } = useTranslation();
const dispatch = useAppDispatch();
const navigate = useNavigate();
const { openModal, closeModal } = useModal();
const { updateInfraID, selectLayers } = useOsrdActions() as EditorSliceActions;
const mapRef = useRef<MapRef>(null);
const { urlInfra } = useParams();
const infraID = useInfraID();
const [searchParams, setSearchParams] = useSearchParams();
const isLoading = useSelector(getIsLoading);
const isLocked = useSelector(getInfraLockStatus);
const editorState = useSelector(getEditorState);
const { data: switchTypes } = useSwitchTypes(infraID);
/* eslint-disable @typescript-eslint/no-explicit-any */
const [toolAndState, setToolAndState] = useState<FullTool<any>>({
tool: TOOLS[TOOL_NAMES.SELECTION],
state: TOOLS[TOOL_NAMES.SELECTION].getInitialState({ infraID, switchTypes }),
});
const [isSearchToolOpened, setIsSearchToolOpened] = useState(false);
const [renderingFingerprint, setRenderingFingerprint] = useState(Date.now());
const forceRender = useCallback(() => {
setRenderingFingerprint(Date.now());
}, [setRenderingFingerprint]);
const [isFormSubmited, setIsFormSubmited] = useState(false);
const { data: infra } = useInfra(infraID);
const { updateInfra } = useInfraActions();
const switchTool = useCallback(
({ toolType, toolState }: switchProps) => {
const tool = TOOLS[toolType];
const state = {
...tool.getInitialState({ infraID, switchTypes }),
...(toolState || {}),
};
setToolAndState({
tool,
state,
});
},
[infraID, switchTypes, setToolAndState]
);
const setToolState = useCallback(
<S extends CommonToolState>(stateOrReducer: Partial<S> | Reducer<S>) => {
setToolAndState((s) => ({
...s,
state: {
...s.state,
...(typeof stateOrReducer === 'function' ? stateOrReducer(s.state) : stateOrReducer),
},
}));
},
[setToolAndState]
);
const resetState = useCallback(() => {
switchTool({ toolType: TOOL_NAMES.SELECTION, toolState: {} });
forceRender();
}, [switchTool, forceRender]);
const { mapStyle, viewport } = useSelector(getMap);
const setViewport = useCallback(
(value: Partial<Viewport>) => {
dispatch(updateViewport(value));
},
[dispatch]
);
const resetPitchBearing = () => {
setViewport({
...viewport,
bearing: 0,
pitch: 0,
});
};
const context = useMemo<EditorContextType<CommonToolState>>(
() => ({
t,
openModal,
closeModal,
activeTool: toolAndState.tool,
state: toolAndState.state,
setState: setToolState,
switchTool,
forceRender,
renderingFingerprint,
}),
[
setToolState,
toolAndState,
openModal,
closeModal,
infraID,
t,
forceRender,
renderingFingerprint,
]
);
const extendedContext = useMemo<ExtendedEditorContextType<CommonToolState>>(
() => ({
...context,
dispatch,
editorState,
infraID,
isInfraLocked: isLocked,
isLoading,
isFormSubmited,
setIsFormSubmited,
switchTypes,
mapState: {
viewport,
mapStyle,
},
}),
[
context,
dispatch,
editorState,
mapStyle,
infraID,
switchTypes,
viewport,
isLoading,
isLocked,
isFormSubmited,
setIsFormSubmited,
]
);
const actionsGroups = useMemo(
() =>
toolAndState.tool.actions
.map((group) =>
group.filter((action) => !action.isHidden || !action.isHidden(extendedContext))
)
.filter((group) => group.length),
[toolAndState.tool, extendedContext]
);
/**
* When the component mounts
* => we load the data model
* => we check if url has no infra and the store one => navigate to the good url
*/
useEffect(() => {
// load the data model
dispatch(loadDataModel());
if (isNil(urlInfra) && !isNil(infraID)) {
navigate(`/editor/${infraID}`);
}
}, []);
/**
* When the component mounts
* => get the searchParams
* => if there is a selection param, select the entities and focus on them
*/
useEffect(() => {
if (urlInfra) {
const params = searchParams.get('selection');
if (!params && searchParams.size !== 0) {
dispatch(
setFailure({
name: t('Editor.tools.select-items.errors.unable-to-select'),
message: t('Editor.tools.select-items.errors.invalid-url'),
})
);
navigate(`/editor/${urlInfra}`);
}
const paramsList = params?.split('|');
if (paramsList && paramsList.length) {
const selectedEntities = paramsList.map((param) => {
const [objType, entityId] = param.split('~');
return {
id: entityId,
type: objType as EditoastType,
};
});
const selectObjectsAndFocus = async (
entitiesInfos: { id: string; type: EditoastType }[]
) => {
let entities: EditorEntity[];
if (!entitiesInfos.length) return;
try {
if (entitiesInfos.length === 1) {
const { type: objType, id: entityId } = selectedEntities[0];
const entity = await getEntity(+urlInfra, entityId, objType as ObjectType, dispatch);
entities = [entity];
} else {
const entitiesRecord = await getMixedEntities(+urlInfra, entitiesInfos, dispatch);
entities = Object.values(entitiesRecord);
}
selectEntities(entities, { switchTool, dispatch, editorState });
if (mapRef.current) centerMapOnObject(+urlInfra, entities, dispatch, mapRef.current);
} catch (e) {
dispatch(
setFailure(
castErrorToFailure(e, {
name: t('Editor.tools.select-items.errors.unable-to-select'),
message: t('Editor.tools.select-items.errors.invalid-url'),
})
)
);
}
};
selectObjectsAndFocus(selectedEntities);
}
}
}, []);
/**
* When infra change in the url
* => change the state
* => reset editor state
*/
useEffect(() => {
resetState();
if (!isNil(urlInfra)) {
const infradID = toInteger(urlInfra);
dispatch(updateInfraID(infradID));
dispatch(updateTotalsIssue(infradID));
}
}, [urlInfra]);
// Lifecycle events on tools:
useEffect(() => {
if (toolAndState.tool.onMount) toolAndState.tool.onMount(extendedContext);
const { requiredLayers, incompatibleLayers } = toolAndState.tool;
if (requiredLayers || incompatibleLayers) {
const newLayers: Set<Layer> = new Set([
...editorState.editorLayers,
...(requiredLayers ?? []),
]);
if (incompatibleLayers) incompatibleLayers.forEach((l) => newLayers.delete(l));
dispatch(selectLayers(newLayers));
}
return () => {
if (toolAndState.tool.onUnmount) toolAndState.tool.onUnmount(extendedContext);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [toolAndState.tool]);
/**
* When the current entity changes, update the search params accordingly.
* The replace in the setter nullifies the possibility for the user to "back" click on the browser
* to get the previous selection in the url because this feature is not possible right now.
* A solution would be to remove the auto zoom on object when sharing an url and
* add a "zoom" button in the selection panel to let the choice to the user.
*/
useEffect(() => {
const currentEntity = toolAndState.state.entity as EditorEntity;
if (currentEntity) {
if (currentEntity.properties.id !== NEW_ENTITY_ID) {
setSearchParams(
{ selection: `${currentEntity.objType}~${currentEntity.properties.id}` },
{ replace: true }
);
} else {
const param = searchParams.get('selection');
if (param) {
searchParams.delete('selection');
setSearchParams(searchParams, { replace: true });
}
}
}
}, [toolAndState.state.entity?.properties.id]);
useEffect(() => {
if (infra) {
dispatch(updateInfra(infra));
}
}, [infra]);
return (
<EditorContext.Provider value={extendedContext as EditorContextType<unknown>}>
<main
className={cx('editor-root mastcontainer mastcontainer-map', infraID && 'infra-selected')}
>
<div className="layout">
<div className="tool-box bg-primary">
{Object.values(TOOL_NAMES).map((toolType: TOOL_NAMES) => {
const tool = TOOLS[toolType];
const { id, icon: IconComponent, labelTranslationKey } = tool;
const label = t(labelTranslationKey);
if (tool.isHidden && tool.isHidden(extendedContext)) return null;
return (
<button
key={id}
type="button"
title={label}
className={cx(
'btn-rounded',
id === toolAndState.tool.id && 'active',
'editor-btn'
)}
onClick={() => {
if (tool.onClick) {
tool.onClick(extendedContext);
} else {
switchTool({ toolType, toolState: {} });
}
}}
>
<span className="sr-only">{label}</span>
<IconComponent />
</button>
);
})}
</div>
<div className="actions-box">
{actionsGroups.flatMap((actionsGroup, i, a) => {
const actions = actionsGroup.map((action) => {
const {
id,
icon: IconComponent,
labelTranslationKey,
isDisabled,
isActive,
onClick,
} = action;
const label = t(labelTranslationKey);
return (
<button
key={id}
type="button"
title={label}
className={cx('editor-btn', 'btn-rounded', {
active: isActive && isActive(extendedContext),
})}
onClick={() => {
if (onClick) {
onClick(extendedContext);
}
}}
disabled={isDisabled && isDisabled(extendedContext)}
>
<span className="sr-only">{label}</span>
<IconComponent />
</button>
);
});
return i < a.length - 1
? [...actions, <div key={`separator-${i}`} className="separator" />]
: actions;
})}
</div>
<div className="panel-container">
{isLocked && (
<div className="infra-locked bg-yellow">{t('Editor.infra-errors.infra-locked')}</div>
)}
{toolAndState.tool.leftPanelComponent && (
<div className="panel-box">
<toolAndState.tool.leftPanelComponent />
</div>
)}
</div>
<div className="map-wrapper">
<div className="map">
<Map
{...{
mapRef,
mapStyle,
viewport,
setViewport,
toolState: toolAndState.state,
activeTool: toolAndState.tool,
setToolState,
infraID,
}}
/>
{isSearchToolOpened && (
<MapSearch
map={mapRef.current!}
closeMapSearchPopUp={() => setIsSearchToolOpened(false)}
/>
)}
<MapButtons
map={mapRef.current ?? undefined}
resetPitchBearing={resetPitchBearing}
withInfraButton
bearing={viewport.bearing}
editorProps={{
toolState: toolAndState.state,
setToolState,
editorState,
activeTool: toolAndState.tool,
}}
viewPort={viewport}
/>
{mapRef.current &&
editorState.editorLayers.has('errors') &&
editorState.issues.total > 0 && (
<div className="error-box">
<InfraErrorMapControl mapRef={mapRef.current} switchTool={switchTool} />
<InfraErrorCorrector />
</div>
)}
</div>
<div className="messages-bar border-left">
<div className="px-1">
{toolAndState.tool.messagesComponent && <toolAndState.tool.messagesComponent />}
</div>
</div>
</div>
</div>
<LoaderState />
</main>
</EditorContext.Provider>
);
};
export default Editor;