-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathdata.ts
757 lines (692 loc) · 26 KB
/
data.ts
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
import { Feature, Point, LineString, Position } from 'geojson';
import { last, differenceWith, cloneDeep, isEqual, isArray, isNil, isEmpty, sortBy } from 'lodash';
import { JSONSchema7, JSONSchema7Definition } from 'json-schema';
import { utils } from '@rjsf/core';
import lineSplit from '@turf/line-split';
import fnLength from '@turf/length';
import { EditorEntity } from 'types/editor';
import { LinearMetadataItem, OperationalPoint } from './types';
export const LINEAR_METADATA_FIELDS = ['slopes', 'curves'];
// Min size of a linear metadata segment
export const SEGMENT_MIN_SIZE = 1;
// Delta error between the user length input and the length of the geometry
export const DISTANCE_ERROR_RANGE = 0.01;
// Zoom by 25%
const ZOOM_RATIO = 0.75;
// Min size (in meter) of the viewbox
const MIN_SIZE_TO_DISPLAY = 10;
/**
* Cast a coordinate to its Feature representation.
*/
function coordinateToFeature(coordinates: Position): Feature<Point> {
return {
type: 'Feature',
properties: {},
geometry: {
type: 'Point',
coordinates,
},
};
}
/**
* Cast a coordinate to its Feature representation.
*/
function lineStringToFeature(line: LineString): Feature<LineString> {
return {
type: 'Feature',
properties: {},
geometry: line,
};
}
/**
* Returns the length of a lineString in meters.
*/
export function getLineStringDistance(line: LineString): number {
return Math.round(fnLength(lineStringToFeature(line)) * 1000);
}
/**
* Given a array of linearMetadata and a position, returns the first item
* containing the position
*
* @param linearMetadata linearMetadata in which we search
* @param hoveredPostion hoveredPosition
*/
export function getHoveredItem<T>(
linearMetadata: Array<LinearMetadataItem<T>>,
hoveredPostion: number
): { hoveredItem: LinearMetadataItem<T>; hoveredItemIndex: number } | null {
const hoveredItemIndex = linearMetadata.findIndex(
(item) => item.begin <= hoveredPostion && hoveredPostion <= item.end
);
return hoveredItemIndex !== -1
? { hoveredItem: linearMetadata[hoveredItemIndex], hoveredItemIndex }
: null;
}
/**
* When you change the size of a segment, you need to impact it on the chain.
* What we do is to substract the gap from its neighbor (see beginOrEnd).
*
* @param linearMetadata The linear metadata we work on, already sorted
* @param itemChangeIndex The index in the linearMetadata of the changed element
* @param gap The size we need to add (or remove if negative)
* @param beginOrEnd do the change at begin or the end of the item ?
* @param opts Options of this functions (like the min size of segment)
* @throws An error if the given index doesn't exist
* @returns An object composed of the new linearMetadata and its new position
*/
export function resizeSegment<T>(
linearMetadata: Array<LinearMetadataItem<T>>,
itemChangeIndex: number,
gap: number,
beginOrEnd: 'begin' | 'end' = 'end',
preventBoundsChanges = true
): { result: Array<LinearMetadataItem<T>>; newIndexMapping: Record<number, number | null> } {
if (itemChangeIndex >= linearMetadata.length) throw new Error("Given index doesn't exist");
const newIndexMapping = linearMetadata.reduce((acc, _curr, index) => {
acc[index] = index;
return acc;
}, {} as Record<number, number | null>);
if (preventBoundsChanges && itemChangeIndex === 0 && beginOrEnd === 'begin')
return { result: linearMetadata, newIndexMapping };
if (preventBoundsChanges && itemChangeIndex === linearMetadata.length - 1 && beginOrEnd === 'end')
return { result: linearMetadata, newIndexMapping };
const min = linearMetadata[0].begin;
const max = last(linearMetadata)?.end || 0;
// apply the modification on the segment
let result = cloneDeep(linearMetadata);
if (beginOrEnd === 'begin') result[itemChangeIndex].begin += gap;
else result[itemChangeIndex].end += gap;
// can't move before min.
if (result[itemChangeIndex].begin < min) result[itemChangeIndex].begin = 0;
// can't move after max.
if (result[itemChangeIndex].end > max) result[itemChangeIndex].end = max;
// compute new width
const newWidth = result[itemChangeIndex].end - result[itemChangeIndex].begin;
const oldWidth = linearMetadata[itemChangeIndex].end - linearMetadata[itemChangeIndex].begin;
if (newWidth > 0) {
// if element width has reduced, the impact is easy (only sibling)
if (newWidth < oldWidth) {
if (itemChangeIndex > 0) {
result[itemChangeIndex - 1].end = result[itemChangeIndex].begin;
}
if (itemChangeIndex < result.length - 1) {
result[itemChangeIndex + 1].begin = result[itemChangeIndex].end;
}
return { result, newIndexMapping };
}
// if element width has increase, the impact is easy (only sibling)
// fix the LM for the overlap
const itemChanged = result[itemChangeIndex];
const newIndex = [] as Array<number>;
result = result.flatMap((item, index) => {
if (index === itemChangeIndex) {
if (newWidth > 0) {
newIndex.push(index);
return [item];
}
// else
newIndexMapping[index] = null;
return [];
}
// case full overlap => remove
if (item.begin >= itemChanged.begin && item.end <= itemChanged.end) {
newIndexMapping[index] = null;
return [];
}
// case partial overlap at the end
if (item.begin <= itemChanged.begin && item.end >= itemChanged.begin) {
newIndex.push(index);
return [{ ...item, end: itemChanged.begin }];
}
// case partial overlap at the start
if (item.begin <= itemChanged.end && item.end >= itemChanged.end) {
newIndex.push(index);
return [{ ...item, begin: itemChanged.end }];
}
newIndex.push(index);
return [item];
});
// update newIndexMapping with the newIndex
newIndex.forEach((o, n) => {
newIndexMapping[o] = n;
});
return { result, newIndexMapping };
}
// else
return resizeSegment(result, itemChangeIndex + 1, newWidth - oldWidth, 'begin');
}
/**
* Merge a segment with one of its sibling, define by the policy.
* NOTE: Property of selected item will override the sibling one.
* @param linearMetadata The linear metadata we work on
* @param index The element that will be merged
* @returns A new linear metadata with one segment merged
* @throws An error when the index or the sibling element is outside
*/
export function mergeIn<T>(
linearMetadata: Array<LinearMetadataItem<T>>,
index: number,
policy: 'left' | 'right'
): Array<LinearMetadataItem<T>> {
if (!(index >= 0 && index < linearMetadata.length)) throw new Error('Bad merge index');
if (policy === 'left' && index === 0)
throw new Error('Target segment is outside the linear metadata');
if (policy === 'right' && index === linearMetadata.length - 1)
throw new Error('Target segment is outside the linear metadata');
if (policy === 'left') {
const left = linearMetadata[index - 1];
const element = linearMetadata[index];
return [
...linearMetadata.slice(0, index - 1),
{ ...element, begin: left.begin },
...linearMetadata.slice(index + 1),
];
}
const right = linearMetadata[index + 1];
const element = linearMetadata[index];
return [
...linearMetadata.slice(0, index),
{ ...element, end: right.end },
...linearMetadata.slice(index + 2),
];
}
/**
* Fix a linear metadata
* - if empty it generate one
* - if there is a gap at begin/end or inside, it is created
* - if there is an overlaps, remove it
* @param value The linear metadata
* @param lineLength The full length of the linearmetadata (should be computed from the LineString or given by the user)
* @param opts If defined, it allows the function to fill gaps with default field value
*/
export function fixLinearMetadataItems<T>(
value: Array<LinearMetadataItem<T>> | undefined,
lineLength: number,
opts?: { fieldName: string; defaultValue: unknown }
): Array<LinearMetadataItem<T>> {
// simple scenario
if (!value || value.length === 0) {
return [
{
begin: 0,
end: lineLength,
...(opts ? { [opts.fieldName]: opts.defaultValue } : {}),
} as LinearMetadataItem<T>,
];
}
function haveAdditionalKeys(item: LinearMetadataItem, itemToCompare: LinearMetadataItem) {
const keys = Object.keys(item);
const keysToCompare = Object.keys(itemToCompare);
return (
keys.some((key) => key !== 'begin' && key !== 'end') ||
keysToCompare.some((key) => key !== 'begin' && key !== 'end')
);
}
// merge empty adjacent items
let fixedLinearMetadata: Array<LinearMetadataItem<T>> = sortBy(value, ['begin']);
// Order the array and fix it by filling gaps if there are some
fixedLinearMetadata = fixedLinearMetadata.flatMap((item, index, array) => {
const result: Array<LinearMetadataItem<T>> = [];
// we remove the item if it begins after the end of the line
if (item.begin >= lineLength) return [];
// check for no gap at start
if (index === 0) {
if (item.begin !== 0) {
result.push({
...(opts ? { [opts.fieldName]: opts.defaultValue } : {}),
begin: 0,
end: item.begin,
} as LinearMetadataItem<T>);
}
result.push(item);
}
if (index > 0) {
const prev = array[index - 1];
// normal way
if (prev.end === item.begin) {
result.push({
...(opts ? { [opts.fieldName]: opts.defaultValue } : {}),
...item,
});
}
// if there is gap with the previous
if (prev.end < item.begin) {
result.push({
...(opts ? { [opts.fieldName]: opts.defaultValue } : {}),
begin: prev.end,
end: item.begin,
} as LinearMetadataItem<T>);
result.push({
...(opts ? { [opts.fieldName]: opts.defaultValue } : {}),
...item,
});
}
}
// Check for gap at the end
if (index === array.length - 1 && item.end < lineLength) {
result.push({
...(opts ? { [opts.fieldName]: opts.defaultValue } : {}),
begin: item.end,
end: lineLength,
} as LinearMetadataItem<T>);
}
return result;
});
let noEmptyAdjacentItems = false;
while (!noEmptyAdjacentItems) {
noEmptyAdjacentItems = true;
for (let i = 0; i < fixedLinearMetadata.length; i += 1) {
if (i >= 1) {
const item = fixedLinearMetadata[i];
const prev = fixedLinearMetadata[i - 1];
if (item.begin === prev.end && !haveAdditionalKeys(item, prev)) {
fixedLinearMetadata = mergeIn(fixedLinearMetadata, i, 'left');
noEmptyAdjacentItems = false;
break;
}
}
}
}
// if the fixed lm is bigger than the lineLeight (the opposite is not possible, we already fix gaps)
const tail = last(fixedLinearMetadata);
if (tail && tail.end > lineLength) {
let reduceLeft = tail.end - lineLength;
let index = fixedLinearMetadata.length - 1;
while (reduceLeft > 0 && index >= 0) {
const itemLength = fixedLinearMetadata[index].end - fixedLinearMetadata[index].begin;
if (itemLength > SEGMENT_MIN_SIZE) {
const gap =
itemLength - SEGMENT_MIN_SIZE < reduceLeft ? itemLength - SEGMENT_MIN_SIZE : reduceLeft;
fixedLinearMetadata = resizeSegment(fixedLinearMetadata, index, -1 * gap).result;
reduceLeft -= gap;
}
index -= 1;
}
}
return fixedLinearMetadata;
}
/**
* Do the impact on the linear metadata when the LineString changed.
* (recompute all the begin / end).
* We change only one segment, others stay the same or are just translated.
* This method should be call at every (unitary) change on the LineString.
* TODO: cases on extremities
*
* @param sourceLine The Geo lineString, before the unitary changement
* @param targetLine The Geo lineString, after the unitary changement
* @param wrapper The linear metadata array (should be sorted)
* @returns The linear metadata array.
* @throws an error if the from params is not found in the linear metadata array.
*/
export function update<T>(
sourceLine: LineString,
targetLine: LineString,
linearMetadata: Array<LinearMetadataItem<T>>
): Array<LinearMetadataItem<T>> {
if (linearMetadata.length === 0) return [];
// Compute the source coordinates of the changed point
// by doing
// - a diff between source & target for change
// - a diff between source & target for deletion
// - a diff between target & source for addition
let diff = differenceWith(sourceLine.coordinates, targetLine.coordinates, isEqual);
if (diff.length === 0)
diff = differenceWith(targetLine.coordinates, sourceLine.coordinates, isEqual);
// if no diff, we return the original linear metadata
if (diff.length === 0) return linearMetadata;
// We take the first one
// TODO: an impovment can be to take the one in the middle if there are many
const sourcePoint = diff[0];
// Searching the closest segment (in distance) from the source point
// To do it we compute the distance from the origin to the point,
// and we search the closest in the linear array
const sourceLineToPoint = lineSplit(
lineStringToFeature(sourceLine),
coordinateToFeature(sourcePoint)
).features[0];
const pointDistance = fnLength(sourceLineToPoint) * 1000;
const closestLinearItem = linearMetadata.reduce(
(acc, curr, index) => {
const distanceToPoint = Math.min(
Math.abs(pointDistance - curr.begin),
Math.abs(pointDistance - curr.end)
);
if (distanceToPoint < acc.min) {
acc = { min: distanceToPoint, index };
}
return acc;
},
{ min: Infinity, index: 0 }
);
// Now we know where we need to start the recomputation
// - We keep the left part
// - for each item on the right part we do a delta translate
// - and for the impacted item, we add the delta
// NOTE: the delta can be negative (ex: deletion)
const delta =
(fnLength(lineStringToFeature(targetLine)) - fnLength(lineStringToFeature(sourceLine))) * 1000;
return [
...linearMetadata.slice(0, closestLinearItem.index),
{
...linearMetadata[closestLinearItem.index],
end: linearMetadata[closestLinearItem.index].end + delta,
},
...linearMetadata.slice(closestLinearItem.index + 1).map((item) => ({
...item,
begin: item.begin + delta,
end: item.end + delta,
})),
];
}
/**
* Split the linear metadata at the given distance.
*
* @param linearMetadata The linear metadata we work on
* @param distance The distance where we split the linear metadata
* @returns A new linear metadata with one more segment
* @throws An error when linear metadata is empty, or when the distance is outside
*/
export function splitAt<T>(
linearMetadata: Array<LinearMetadataItem<T>>,
distance: number
): Array<LinearMetadataItem<T>> {
if (linearMetadata.length < 1) throw new Error('linear metadata is empty');
if (distance >= (last(linearMetadata)?.end || 0) || distance <= 0)
throw new Error('split point is outside the geometry');
return linearMetadata
.map((item) => {
if (item.begin <= distance && distance <= item.end) {
return [
{ ...item, begin: item.begin, end: distance },
{ ...item, begin: distance, end: item.end },
];
}
return [item];
})
.flat();
}
/**
* Create a new segment
*
* @param linearMetadata The linear metadata we work on
* @param distanceFrom The distance where the new segment will start from
* @param distanceTo The distance where the new segment will end to
* @param lineLength The full length of the linearmetadata (should be computed from the LineString or given by the user)
* @param opts what is the valueFiled (nae of the value, and the default value - strongly recommended)
* @returns An object composed of the new linearMetadata and its new position without the removed element
*/
export function createSegmentAt<T>(
linearMetadata: Array<LinearMetadataItem<T>>,
distanceFrom: number,
distanceTo: number,
lineLength: number,
opts?: { fieldName: string; defaultValue: unknown; tagNew?: boolean }
): Array<LinearMetadataItem<T>> {
// apply the modification on the segment
let result = cloneDeep(linearMetadata);
result.push({
...(opts ? { [opts.fieldName]: opts.defaultValue } : {}),
...(opts && opts.tagNew ? { new: true } : {}),
begin: distanceFrom,
end: distanceTo,
} as LinearMetadataItem<T>);
result = fixLinearMetadataItems(result, lineLength);
return result;
}
/**
* Compute the new viewbox after a zoom.
*
* @param data The linear data
* @param currentViewBox The actual viewbox (so before the zoom)
* @param zoom The zoom operation (in or out)
* @param point The point on the line on which the user zoom (in meter from the point 0)
* @returns The zoomed viewbox, or null if the newbox is equal to the full display
*/
export function getZoomedViewBox<T>(
data: Array<LinearMetadataItem<T>>,
currentViewBox: [number, number] | null,
zoom: 'IN' | 'OUT',
onPoint?: number
): [number, number] | null {
if (data.length === 0) return null;
const min = data[0].begin;
const max = last(data)?.end || 0;
const fullDistance = max - min;
const viewBox: [number, number] = currentViewBox || [min, max];
let distanceToDisplay =
(viewBox[1] - viewBox[0]) * (zoom === 'IN' ? ZOOM_RATIO : 1 - ZOOM_RATIO + 1);
// if the distance to display if higher than the original one
// we display everything, so return null
if (distanceToDisplay >= fullDistance) return null;
// if distance is too small we are at the max zoom level
if (distanceToDisplay < MIN_SIZE_TO_DISPLAY) distanceToDisplay = MIN_SIZE_TO_DISPLAY;
// Compute the point on which we do the zoom
const point = onPoint || viewBox[0] + (viewBox[1] - viewBox[0]) / 2;
// let's try to add the distance on each side
const begin = point - distanceToDisplay / 2;
const end = point + distanceToDisplay / 2;
if (min <= begin && end <= max) {
return [begin, end];
}
// if begin < min, it means that the begin is outside
// so we need to add the diff at the end
// otherwise, it means that the end is outside
// so we need to add the diff at the begin
if (begin < min) {
return [min, end + (min - begin)];
}
return [begin - (end - max), max];
}
/**
* Compute the new viewbox after a translation.
*
* @param data The linear data
* @param currentViewBox The actual viewbox (so before the zoom)
* @param translation The translation in meter
* @returns The zoomed viewbox, or null if the newbox is equal to the full display
*/
export function transalteViewBox<T>(
data: Array<LinearMetadataItem<T>>,
currentViewBox: [number, number] | null,
translation: number
): [number, number] | null {
// can't perform a translation on no data
if (data.length === 0) return null;
// can't perform a translation if not zoomed
if (!currentViewBox) return null;
const max = last(data)?.end || 0;
const distanceToDisplay = currentViewBox[1] - currentViewBox[0];
// if translation on the left, we do it on the min
if (translation < 0) {
// new min is the min minus the transaltion or 0
const newMin = currentViewBox[0] + translation > 0 ? currentViewBox[0] + translation : 0;
return [newMin, newMin + distanceToDisplay];
}
// if translation on the right, we do it on the max
// new max is the max plus the transaltion or max
const newMax = currentViewBox[1] + translation < max ? currentViewBox[1] + translation : max;
return [newMax - distanceToDisplay, newMax];
}
/**
* Given a linearmetadata and viewbox, this function returns
* the cropped linearmetadata (and also add the index)
*/
export function cropForDatavizViewbox(
data: Array<LinearMetadataItem>,
currentViewBox: [number, number] | null
): Array<LinearMetadataItem & { index: number }> {
return (
[...data]
// we add the index so events are able to send the index
.map((segment, index) => ({ ...segment, index }))
// we filter elements that cross or are inside the viewbox
.filter((e) => {
if (!currentViewBox) return true;
// if one extrimity is in (ie. overlaps or full in)
if (currentViewBox[0] <= e.begin && e.begin <= currentViewBox[1]) return true;
if (currentViewBox[0] <= e.end && e.end <= currentViewBox[1]) return true;
// if include the viewbox
if (e.begin <= currentViewBox[0] && currentViewBox[1] <= e.end) return true;
// else
return false;
})
// we crop the extremities if needed
.map((e) => {
if (!currentViewBox) return e;
return {
...e,
begin: e.begin < currentViewBox[0] ? currentViewBox[0] : e.begin,
end: e.end > currentViewBox[1] ? currentViewBox[1] : e.end,
};
})
);
}
/**
* Given operationalPoints and viewbox, this function returns
* the cropped operationalPoints (and the computed position of the line in px)
*/
export function cropOperationPointsForDatavizViewbox(
operationalPoints: Array<OperationalPoint>,
currentViewBox: [number, number] | null,
wrapper: React.MutableRefObject<HTMLDivElement | null>,
fullLength: number
): Array<OperationalPoint & { positionInPx: number }> {
if (wrapper.current !== null && fullLength > 0) {
const wrapperWidth = wrapper.current.offsetWidth;
return (
[...operationalPoints]
// we filter operational points that are inside the viewbox
.filter(({ position }) => {
if (!currentViewBox) return true;
return !(position < currentViewBox[0] || currentViewBox[1] < position);
})
// we compute the vertical line position in px
.map((operationalPoint) => {
const lengthToDisplay = currentViewBox
? operationalPoint.position - currentViewBox[0]
: operationalPoint.position;
// subtract 2px for the display
const positionInPx = (lengthToDisplay * wrapperWidth) / fullLength - 2;
return {
...operationalPoint,
positionInPx,
};
})
);
}
return [];
}
/**
* Given operationalPoints and a point, this function returns
* the closest operationalPoint if it is closer than 10px to the point, else return null
*/
export function getClosestOperationalPoint(
position: number,
operationalPoints: Array<OperationalPoint & { positionInPx: number }>
): (OperationalPoint & { positionInPx: number }) | null {
if (isEmpty(operationalPoints)) return null;
const sortedOperationalPoints = sortBy(operationalPoints, (op) =>
Math.abs(position - op.positionInPx)
);
const closestPoint = sortedOperationalPoints[0];
return Math.abs(position - closestPoint.positionInPx) <= 10 ? closestPoint : null;
}
/**
* TODO: need to be check and tested (specially the underlying update function)
* Do the impact on the linear metadata for a modification on lineString.
*
* @param entity The entity that has been modified and need to be impacted
* @param sourceLine The original LineString (before the change)
* @returns The entity modified in adquation
*/
export function entityDoUpdate<T extends EditorEntity>(entity: T, sourceLine: LineString): T {
if (entity.geometry.type === 'LineString' && !isNil(entity.properties)) {
const newProps: EditorEntity['properties'] = { id: entity.properties.id };
Object.keys(entity.properties).forEach((name) => {
const value = (entity.properties as { [key: string]: unknown })[name];
// is a LM ?
if (isArray(value) && value.length > 0 && !isNil(value[0].begin) && !isNil(value[0].end)) {
newProps[name] = update(sourceLine, entity.geometry as LineString, value);
} else {
newProps[name] = value;
}
});
// eslint-disable-next-line dot-notation
newProps['length'] = getLineStringDistance(entity.geometry as LineString);
return { ...entity, properties: newProps };
}
return entity;
}
/**
* In a form for a field, compute/enhance its JSON schema,
* By adding min & max on 'begin' & 'end' sub-fields if needed.
* For a linear Metadata
*/
export function getFieldJsonSchema(
fieldSchema: JSONSchema7,
rootSchema: JSONSchema7,
requiredFilter?: (required: string[]) => string[],
enhancement: { [key: string]: JSONSchema7Definition } = {}
): JSONSchema7 {
let result = { ...fieldSchema };
if (fieldSchema.items) {
const itemsSchema = utils.retrieveSchema(fieldSchema.items as JSONSchema7, rootSchema);
if (itemsSchema.properties?.begin && itemsSchema.properties?.end) {
result = {
...result,
items: {
...itemsSchema,
required:
requiredFilter && itemsSchema.required && isArray(itemsSchema.required)
? requiredFilter(itemsSchema.required)
: itemsSchema.required,
properties: {
begin: {
...(itemsSchema.properties?.begin as JSONSchema7),
...(enhancement.begin as JSONSchema7),
},
end: {
...(itemsSchema.properties?.end as JSONSchema7),
...(enhancement.end as JSONSchema7),
},
...Object.keys(itemsSchema.properties || {})
.filter((k) => !['begin', 'end'].includes(k))
.map((k) => ({
name: k,
schema: itemsSchema.properties ? itemsSchema.properties[k] : {},
}))
.reduce((acc, curr) => {
acc[curr.name] = {
...(curr.schema as JSONSchema7),
...(enhancement[curr.name] as JSONSchema7),
};
return acc;
}, {} as { [key: string]: JSONSchema7Definition }),
},
},
definitions: rootSchema.definitions,
} as JSONSchema7;
}
}
return result;
}
/**
* Helper function that move the viewbox so the selected element is visible.
*/
export function viewboxForSelection(
data: Array<LinearMetadataItem>,
vb: [number, number] | null,
selected: number
): [number, number] | null {
// case of no zoom
if (vb === null) return null;
// if the selected is left outside
if (data[selected].end <= vb[0]) {
return transalteViewBox(data, vb, data[selected].begin - vb[0]);
}
// if the selected is right outside
if (vb[1] <= data[selected].begin) {
return transalteViewBox(data, vb, data[selected].end - vb[1]);
}
return vb;
}