-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathcomponents.tsx
480 lines (454 loc) · 16.3 KB
/
components.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
470
471
472
473
474
475
476
477
478
479
480
import React, { FC, useContext, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Layer, Source } from 'react-map-gl/maplibre';
import { useTranslation } from 'react-i18next';
import { last } from 'lodash';
import { Position } from 'geojson';
import { BsBoxArrowInRight } from 'react-icons/bs';
import EditorForm from 'applications/editor/components/EditorForm';
import EntitySumUp from 'applications/editor/components/EntitySumUp';
import EntityError from 'applications/editor/components/EntityError';
import { getEntities } from 'applications/editor/data/api';
import { NEW_ENTITY_ID } from 'applications/editor/data/utils';
import EditorContext from 'applications/editor/context';
import {
getEditCatenaryState,
getEditSpeedSectionState,
} from 'applications/editor/tools/rangeEdition/utils';
import TOOL_TYPES from 'applications/editor/tools/toolTypes';
import { ExtendedEditorContextType } from 'applications/editor/tools/editorContextTypes';
import { osrdEditoastApi } from 'common/api/osrdEditoastApi';
import { Spinner } from 'common/Loader';
import GeoJSONs from 'common/Map/Layers/GeoJSONs';
import colors from 'common/Map/Consts/colors';
import { save } from 'reducers/editor';
import { getMap } from 'reducers/map/selectors';
import { getInfraID } from 'reducers/osrdconf/selectors';
import { CatenaryEntity, SpeedSectionEntity, TrackSectionEntity } from 'types';
import DebouncedNumberInputSNCF from 'common/BootstrapSNCF/FormSNCF/DebouncedNumberInputSNCF';
import { WidgetProps } from '@rjsf/core';
import { TrackEditionState } from './types';
import { injectGeometry, removeInvalidRanges } from './utils';
export const TRACK_LAYER_ID = 'trackEditionTool/new-track-path';
export const POINTS_LAYER_ID = 'trackEditionTool/new-track-points';
const TRACK_COLOR = '#666';
const TRACK_STYLE = { 'line-color': TRACK_COLOR, 'line-dasharray': [2, 1], 'line-width': 2 };
const DEFAULT_DISPLAYED_RANGES_COUNT = 3;
/**
* Generic component to show attached ranges items of a specific type for an edited track section:
*/
export const AttachedRangesItemsList: FC<{ id: string; itemType: 'SpeedSection' | 'Catenary' }> = ({
id,
itemType,
}) => {
const dispatch = useDispatch();
const { t } = useTranslation();
const infraID = useSelector(getInfraID);
const [itemsState, setItemsState] = useState<
| { type: 'idle' }
| { type: 'loading' }
| { type: 'ready'; itemEntities: SpeedSectionEntity[] | CatenaryEntity[] }
| { type: 'error'; message: string }
>({ type: 'idle' });
const { switchTool } = useContext(EditorContext) as ExtendedEditorContextType<unknown>;
const [showAll, setShowAll] = useState(false);
const [getAttachedItems] =
osrdEditoastApi.endpoints.getInfraByIdAttachedAndTrackId.useLazyQuery();
useEffect(() => {
if (itemsState.type === 'idle' && infraID) {
setItemsState({ type: 'loading' });
getAttachedItems({ id: infraID, trackId: id })
.unwrap()
.then((res: { [key: string]: string[] }) => {
if (res[itemType]?.length) {
getEntities(infraID, res[itemType], itemType, dispatch)
.then((entities) => {
if (itemType === 'SpeedSection') {
setItemsState({
type: 'ready',
itemEntities: (res[itemType] || []).map(
(s) => entities[s] as SpeedSectionEntity
),
});
} else {
setItemsState({
type: 'ready',
itemEntities: (res[itemType] || []).map((s) => entities[s] as CatenaryEntity),
});
}
})
.catch((err) => {
setItemsState({ type: 'error', message: err.message });
});
} else {
setItemsState({ type: 'ready', itemEntities: [] });
}
})
.catch((err) => {
setItemsState({ type: 'error', message: err.message });
});
}
}, [itemsState]);
useEffect(() => {
setItemsState({ type: 'idle' });
}, [id]);
if (itemsState.type === 'loading' || itemsState.type === 'idle')
return (
<div className="loader mt-4">
<Spinner />
</div>
);
if (itemsState.type === 'error')
return (
<div className="form-error mt-3 mb-3">
<p>
{itemsState.message ||
(itemType === 'SpeedSection'
? t('Editor.tools.track-edition.default-speed-sections-error')
: t('Editor.tools.track-edition.default-catenaries-error'))}
</p>
</div>
);
return (
<>
{!!itemsState.itemEntities.length && (
<>
<ul className="list-unstyled">
{(showAll
? itemsState.itemEntities
: itemsState.itemEntities.slice(0, DEFAULT_DISPLAYED_RANGES_COUNT)
).map((entity: SpeedSectionEntity | CatenaryEntity) => (
<li key={entity.properties.id} className="d-flex align-items-center mb-2">
<div className="flex-shrink-0 mr-3">
<button
type="button"
className="btn btn-primary btn-sm"
title={t('common.open')}
onClick={() => {
if (entity.objType === 'SpeedSection') {
switchTool({
toolType: TOOL_TYPES.SPEED_SECTION_EDITION,
toolState: getEditSpeedSectionState(entity as SpeedSectionEntity),
});
} else
switchTool({
toolType: TOOL_TYPES.CATENARY_EDITION,
toolState: getEditCatenaryState(entity as CatenaryEntity),
});
}}
>
<BsBoxArrowInRight />
</button>
</div>
<div className="flex-grow-1 flex-shrink-1">
<EntitySumUp entity={entity} />
</div>
</li>
))}
</ul>
{itemsState.itemEntities.length > DEFAULT_DISPLAYED_RANGES_COUNT && (
<div className="mt-4">
<button
type="button"
className="btn btn-secondary"
onClick={() => setShowAll((v) => !v)}
>
{showAll
? t('Editor.tools.track-edition.only-show-n', {
count: DEFAULT_DISPLAYED_RANGES_COUNT,
})
: t('Editor.tools.track-edition.show-more-ranges', {
count: itemsState.itemEntities.length - DEFAULT_DISPLAYED_RANGES_COUNT,
})}
</button>
</div>
)}
</>
)}
{!itemsState.itemEntities.length && (
<div className="text-center">
{itemType === 'SpeedSection'
? t('Editor.tools.track-edition.no-linked-speed-section')
: t('Editor.tools.track-edition.no-linked-catenary')}
</div>
)}
</>
);
};
export const TrackEditionLayers: FC = () => {
const {
state,
renderingFingerprint,
editorState: { editorLayers },
} = useContext(EditorContext) as ExtendedEditorContextType<TrackEditionState>;
const { mapStyle, layersSettings, issuesSettings } = useSelector(getMap);
const isAddingPointOnExistingSection =
typeof state.nearestPoint?.properties?.sectionIndex === 'number';
const points = state.track.geometry.coordinates;
let additionalSegment: typeof points = [];
if (
points.length &&
state.editionState.type === 'addPoint' &&
state.mousePosition &&
!isAddingPointOnExistingSection
) {
const lastPosition =
state.anchorLinePoints &&
state.nearestPoint &&
typeof state.nearestPoint.properties?.sectionIndex !== 'number'
? (state.nearestPoint.geometry.coordinates as [number, number])
: state.mousePosition;
if (state.addNewPointsAtStart) {
additionalSegment = [lastPosition, points[0]];
} else {
additionalSegment = [last(points) as [number, number], lastPosition];
}
}
let highlightedPoint: Position | undefined;
if (state.editionState.type === 'movePoint') {
if (typeof state.editionState.draggedPointIndex === 'number') {
highlightedPoint = state.track.geometry.coordinates[state.editionState.draggedPointIndex];
} else if (typeof state.editionState.hoveredPointIndex === 'number') {
highlightedPoint = state.track.geometry.coordinates[state.editionState.hoveredPointIndex];
}
} else if (state.editionState.type === 'deletePoint') {
if (typeof state.editionState.hoveredPointIndex === 'number') {
highlightedPoint = state.track.geometry.coordinates[state.editionState.hoveredPointIndex];
}
}
return (
<>
{/* Editor data layer */}
<GeoJSONs
colors={colors[mapStyle]}
hidden={state.track.properties.id ? [state.track.properties.id] : undefined}
layers={editorLayers}
fingerprint={renderingFingerprint}
layersSettings={layersSettings}
issuesSettings={issuesSettings}
/>
{/* Track path */}
<Source
type="geojson"
data={{
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: points,
},
}}
>
<Layer id={TRACK_LAYER_ID} type="line" paint={TRACK_STYLE} />
</Source>
{additionalSegment.length > 0 && (
<Source
type="geojson"
data={{
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: additionalSegment,
},
}}
>
<Layer type="line" paint={TRACK_STYLE} />
</Source>
)}
{/* Highlighted nearest point from data */}
{state.editionState.type === 'addPoint' && state.nearestPoint && (
<Source type="geojson" data={state.nearestPoint}>
<Layer
type="circle"
paint={{
'circle-radius': 4,
'circle-color': '#fff',
'circle-stroke-color': '#009EED',
'circle-stroke-width': 2,
}}
/>
</Source>
)}
{/* Track points */}
<Source
type="geojson"
data={{
type: 'FeatureCollection',
features: points.map((point, index) => ({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: point,
},
properties: { index },
})),
}}
>
<Layer
id={POINTS_LAYER_ID}
type="circle"
paint={{
'circle-radius': state.editionState.type !== 'addPoint' ? 4 : 2,
'circle-color': '#fff',
'circle-stroke-color': TRACK_COLOR,
'circle-stroke-width': 1,
}}
/>
</Source>
{/* Highlighted nearest point or dragged point from track */}
<Source
type="geojson"
data={{
type: 'FeatureCollection',
features: highlightedPoint
? [
{
type: 'Feature',
properties: {},
geometry: {
type: 'Point',
coordinates: highlightedPoint,
},
},
]
: [],
}}
>
<Layer
type="circle"
paint={{
'circle-radius': 4,
'circle-color': '#fff',
'circle-stroke-color': TRACK_COLOR,
'circle-stroke-width': 3,
}}
/>
</Source>
</>
);
};
export const CustomLengthInput: React.FC<WidgetProps> = (props) => {
const { onChange, value } = props;
return (
<DebouncedNumberInputSNCF debouncedDelay={1500} input={value} setInput={onChange} label="" />
);
};
export const TrackEditionLeftPanel: FC = () => {
const dispatch = useDispatch();
const { t } = useTranslation();
const infraID = useSelector(getInfraID);
const { state, setState, isFormSubmited, setIsFormSubmited } = useContext(
EditorContext
) as ExtendedEditorContextType<TrackEditionState>;
const submitBtnRef = useRef<HTMLButtonElement>(null);
const { track, initialTrack } = state;
const isNew = track.properties.id === NEW_ENTITY_ID;
// Hack to be able to launch the submit event from the rjsf form by using
// the toolbar button instead of the form one.
// See https://github.com/rjsf-team/react-jsonschema-form/issues/500
useEffect(() => {
if (isFormSubmited && setIsFormSubmited && submitBtnRef.current) {
submitBtnRef.current.click();
setIsFormSubmited(false);
}
}, [isFormSubmited]);
return (
<>
<EditorForm
data={track}
overrideUiSchema={{
length: {
'ui:widget': CustomLengthInput,
},
}}
onSubmit={async (savedEntity) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const res: any = await dispatch(
save(
infraID,
track.properties.id !== NEW_ENTITY_ID
? {
update: [
{
source: state.initialTrack,
target: injectGeometry(savedEntity),
},
],
}
: { create: [injectGeometry(savedEntity)] }
)
);
const { railjson } = res[0];
const savedTrack = {
objType: 'TrackSection',
type: 'Feature',
properties: railjson,
geometry: railjson.geo,
} as TrackSectionEntity;
setState({
...state,
initialTrack: savedTrack,
track: savedTrack,
});
}}
onChange={(newTrack) => {
let checkedTrack = { ...newTrack };
if (initialTrack.properties.length !== newTrack.properties.length) {
const { loading_gauge_limits, slopes, curves, length: newLength } = newTrack.properties;
const validLoadingGaugeLimits = removeInvalidRanges(loading_gauge_limits, newLength);
const validCurves = removeInvalidRanges(curves, newLength);
const validSlopes = removeInvalidRanges(slopes, newLength);
checkedTrack = {
...checkedTrack,
properties: {
...checkedTrack.properties,
loading_gauge_limits: validLoadingGaugeLimits,
slopes: validSlopes,
curves: validCurves,
},
};
}
setState({
...state,
track: checkedTrack as TrackSectionEntity,
});
}}
>
<div>
{/* We don't want to see the button but just be able to click on it */}
<button type="submit" ref={submitBtnRef} style={{ display: 'none' }}>
{t('common.save')}
</button>
</div>
</EditorForm>
<div className="border-bottom" />
{!isNew && (
<>
{!isNew && <EntityError className="border-bottom mb-1" entity={track} />}
<h3>{t('Editor.tools.track-edition.attached-speed-sections')}</h3>
<AttachedRangesItemsList id={track.properties.id} itemType="SpeedSection" />
<div className="border-bottom" />
<h3>{t('Editor.tools.track-edition.attached-catenaries')}</h3>
<AttachedRangesItemsList id={track.properties.id} itemType="Catenary" />
</>
)}
</>
);
};
export const TrackEditionMessages: FC = () => {
const { t, state } = useContext(EditorContext) as ExtendedEditorContextType<TrackEditionState>;
switch (state.editionState.type) {
case 'addPoint':
if (!state.anchorLinePoints) return t('Editor.tools.track-edition.help.add-point').toString();
return t('Editor.tools.track-edition.help.add-anchor-point').toString();
case 'movePoint':
if (!state.editionState.draggedPointIndex)
return t('Editor.tools.track-edition.help.move-point').toString();
return t('Editor.tools.track-edition.help.move-point-end').toString();
case 'deletePoint':
return t('Editor.tools.track-edition.help.delete-point').toString();
default:
return null;
}
};