-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLayoutEditorHelpers.ts
More file actions
1186 lines (1031 loc) · 44.9 KB
/
LayoutEditorHelpers.ts
File metadata and controls
1186 lines (1031 loc) · 44.9 KB
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* * Copyright (c) 2025 Board of Regents of the University of Wisconsin System
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
// Layout Editor Helpers
import * as d3 from 'd3';
import { zoomTransform } from 'd3';
import {
defaultTypeToRackType,
getSvgSize,
getTypeClassFromElement,
parseLongId,
parseRoomItemNum,
parseRoomItemType,
roomItemToString
} from './helpers';
import {
Cage,
CageDirection,
CageModification,
CageModifications,
CageNumber,
CageWithMods,
DefaultRackId,
DefaultRackTypes,
GroupId,
LayoutHistoryData,
LocationCoords,
ModLocations,
PrevRoom,
Rack,
RackGroup,
RackStringType,
RackTypes,
RealRackId,
Room,
RoomItemClass,
RoomItemStringType,
RoomItemType,
RoomObject,
RoomObjectTypes,
UnitLocations,
UnitType
} from '../types/typings';
import {
ExtraContext,
LayoutDragProps,
MergeProps,
OffsetProps,
RackActions,
SelectedObj,
StartDragProps
} from '../types/layoutEditorTypes';
import { labkeyActionSelectWithPromise } from '../api/labkeyActions';
import * as React from 'react';
import { MutableRefObject } from 'react';
import { SelectRowsOptions } from '@labkey/api/dist/labkey/query/SelectRows';
import { Filter, Security } from '@labkey/api';
import { GetUserPermissionsResponse } from '@labkey/api/dist/labkey/security/Permission';
import { CELL_SIZE } from './constants';
export const isTemplateCreator = (user: GetUserPermissionsResponse) => {
return Security.hasEffectivePermission(user.container.effectivePermissions, 'org.labkey.cageui.security.permissions.CageUITemplateCreatorPermission');
}
export const isRoomCreator = (user: GetUserPermissionsResponse) => {
return Security.hasEffectivePermission(user.container.effectivePermissions, 'org.labkey.cageui.security.permissions.CageUIRoomCreatorPermission');
}
export const isRoomModifier = (user: GetUserPermissionsResponse) => {
return Security.hasEffectivePermission(user.container.effectivePermissions, 'org.labkey.cageui.security.permissions.CageUIRoomModifierPermission');
}
export const getTranslation = (transform) => {
// Regex to extract the translate(x, y) values
const translate = transform.match(/translate\(([^)]+)\)/);
if (translate) {
const [x, y] = translate[1].split(',').map(Number);
return { x, y };
}
return { x: 0, y: 0 }; // Default to (0, 0) if no translation is found
}
export const convertCageNumToNum = (num: CageNumber) => {
const parts = num.split('-');
const cageNum = parts[1];
return parseInt(cageNum);
}
export const createEmptyUnitLoc = (): UnitLocations => {
return (
Object.fromEntries(
Object.values(RackTypes)
.filter((value) => typeof value === "number") // Filter out the numeric values from enum
.map((rackType) => [
roomItemToString(rackType as RackTypes),
[] as LocationCoords[],
])
) as UnitLocations
);
}
export const parseWrapperId = (input: string): RoomItemStringType => {
const regex = /^[a-zA-Z]+/; // matches "x_template_wrapper"
const match = input.match(regex);
if (match) { // if a match return whatever x is (any string of chars)
return match[0] as RoomItemStringType;
}
return;
}
export const drawGrid = (layoutSvg: d3.Selection<SVGElement, unknown, any, any>, updateGridProps) => {
const transform = zoomTransform(layoutSvg.node());
layoutSvg.select('.grid').remove();
layoutSvg.append("g")
.attr("class", "grid")
.attr("id", "layout-grid")
.attr("width", updateGridProps.width)
.attr('height', updateGridProps.height)
.attr('transform', `translate(0,0) scale(${transform.k})`);
updateGrid(zoomTransform(layoutSvg.node()), updateGridProps.width, updateGridProps.height, updateGridProps.gridSize); // Draw grid with the initial view
}
export const updateGrid = (transform, width, height, gridSize) => {
const g = d3.select("g.grid");
g.selectAll(".cell").remove(); // Clear existing grid
// Calculate grid bounds (starting and ending points) based on transform
const xMin = Math.floor(-transform.x / transform.k / gridSize) * gridSize;
const yMin = Math.floor(-transform.y / transform.k / gridSize) * gridSize;
const xMax = Math.ceil((width - transform.x) / transform.k / gridSize) * gridSize;
const yMax = Math.ceil((height - transform.y) / transform.k / gridSize) * gridSize;
// Draw the grid within the current visible area
for (let x = xMin; x < xMax; x += gridSize) {
for (let y = yMin; y < yMax; y += gridSize) {
g.append("rect")
.attr("x", x)
.attr("y", y)
.attr("class", "cell")
.attr("width", gridSize)
.attr("height", gridSize)
.attr("fill", "none")
.attr("stroke", "lightgray");
}
}
}
// Confirmation popup for merging two racks, built using d3 svg manipulation.
function showConfirmationPopup(): Promise<RackActions> {
return new Promise((resolve) => {
const overlay = d3.select('body').append('div')
.attr('class', 'overlay')
.style('position', 'fixed')
.style('top', '0')
.style('left', '0')
.style('width', '100vw')
.style('height', '100vh')
.style('background', 'rgba(0, 0, 0, 0.5)')
.style('z-index', '999') // Ensure it's above other content
.style('display', 'block'); // Initially hidden
// Create a simple popup
const popup = overlay.append('div')
.attr('class', 'popup')
.style('position', 'absolute')
.style('top', '50%')
.style('left', '50%')
.style('transform', 'translate(-50%, -50%)')
.style('background', 'white')
.style('padding', '20px')
.style('border', '1px solid black');
popup.append('p')
.text('What action would you like to perform?');
// Merge button
popup.append('button')
.text('Merge Cages')
.on('click', () => {
overlay.remove();
resolve('merge');
});
// Connect button
popup.append('button')
.text('Connect Racks')
.on('click', () => {
overlay.remove();
resolve('connect');
});
// Cancel button
popup.append('button')
.text('Cancel')
.on('click', () => {
overlay.remove();
resolve('cancel');
});
});
}
export function showLayoutEditorConfirmation(msg: string) {
return new Promise((resolve) => {
const overlay = d3.select('body').append('div')
.attr('class', 'overlay')
.style('position', 'fixed')
.style('top', '0')
.style('left', '0')
.style('width', '100vw')
.style('height', '100vh')
.style('background', 'rgba(0, 0, 0, 0.5)')
.style('z-index', '999') // Ensure it's above other content
.style('display', 'block'); // Initially hidden
// Create a simple popup
const popup = overlay.append('div')
.attr('class', 'popup')
.style('position', 'absolute')
.style('top', '50%')
.style('left', '50%')
.style('transform', 'translate(-50%, -50%)')
.style('background', 'white')
.style('padding', '20px')
.style('border', '1px solid black');
popup.append('p')
.text(msg);
popup.append('button')
.text('Yes')
.on('click', () => {
overlay.remove();
resolve(true);
});
popup.append('button')
.text('No')
.on('click', () => {
overlay.remove();
resolve(false);
});
});
}
// Confirmation popup for merging two racks
export function showLayoutEditorError(errorMsg: string) {
return new Promise((resolve) => {
// Create a simple popup
const overlay = d3.select('body').append('div')
.attr('class', 'overlay')
.style('position', 'fixed')
.style('top', '0')
.style('left', '0')
.style('width', '100vw')
.style('height', '100vh')
.style('background', 'rgba(0, 0, 0, 0.5)')
.style('z-index', '999') // Ensure it's above other content
.style('display', 'block'); // Initially hidden
const popup = overlay.append('div')
.attr('class', 'popup')
.style('position', 'absolute')
.style('top', '50%')
.style('left', '50%')
.style('transform', 'translate(-50%, -50%)')
.style('background', 'white')
.style('padding', '20px')
.style('border', '1px solid black');
popup.append('p')
.text(errorMsg);
// Cancel button
popup.append('button')
.text('Ok')
.on('click', () => {
overlay.remove();
resolve(true);
});
});
}
// Function to help merge/connect racks together by resetting groups to local coords
function resetNodeTranslationsWithZoom(targetNode, draggedNode, layoutSvg) {
// Get the zoom transform of the layout SVG
const layoutTransform = d3.zoomTransform(layoutSvg.node());
// Get the translations of the two nodes (current positions)
const {x: translateX1, y: translateY1} = getTranslation(targetNode.getAttribute('transform'));
const {x: translateX2, y: translateY2} = getTranslation(draggedNode.getAttribute('transform'));
// Calculate the dynamic distance between the two nodes before resetting
// Remove the zoom scale from the distance to keep it zoom-independent
const distanceX = (translateX2 - translateX1) / layoutTransform.k; // Correct the distance using zoom scale
const distanceY = (translateY2 - translateY1) / layoutTransform.k; // Correct Y in case there's any Y translation
// Reset the first node to (0, 0) in the new group
targetNode.setAttribute("transform", `translate(0, 0)`);
// Set the second node to be exactly at the dynamic distance relative to the first node
draggedNode.setAttribute("transform", `translate(${distanceX}, ${distanceY})`);
}
export function setupEditCageEvent(
cageGroupElement: SVGGElement,
setSelectedObj: React.Dispatch<React.SetStateAction<SelectedObj>>,
localRoomRef: MutableRefObject<Room>,
setCtxMenuStyle?: React.Dispatch<React.SetStateAction<{ display: string, top: string, left: string }>>,
rackTypeString?: RackStringType
): () => void {
const handleContextMenu = (event: MouseEvent)=> {
event.preventDefault();
const localRoom = localRoomRef.current;
let tempObj: SelectedObj;
const element = event.currentTarget as SVGGElement;
//set selected object to either room object or cage
if(d3.select(element).classed('room-obj')){
tempObj = localRoom.objects.find((obj) => obj.itemId === element.id);
}else{
const cageGroupElement = element.closest(`[id^=${rackTypeString}-]`) as SVGGElement | null;
localRoom.rackGroups.forEach((g) => {
g.racks.forEach((r) => {
if(tempObj){
return;
}
tempObj = r.cages.find(c => c.cageNum === cageGroupElement.id);
})
})
}
setSelectedObj(tempObj);
if(setCtxMenuStyle){
setCtxMenuStyle((prevState) => ({
...prevState,
display: 'block',
left: `${event.pageX - 10}px`,
top: `${event.pageY - 10}px`,
}));
}
};
// Attach context menu to the lowest level group for that cFage.
cageGroupElement.style.pointerEvents = 'bounding-box';
cageGroupElement.addEventListener('contextmenu', handleContextMenu);
return () => {
cageGroupElement.removeEventListener('contextmenu', handleContextMenu);
};
}
/*
Helper function to either connect racks or merge cages
One can think of a merge as at the cage level and connections are at a rack level.
Even though cages can not be added/removed from racks in reality, for layout building purposes they can.
*/
export async function mergeRacks(props: MergeProps) {
const {
contextMenuRef,
targetRack,
draggedRack,
targetRackGroup,
dragRackGroup,
doRackAction,
layoutDrag,
cageActionProps,
dragCageNum,
targetCageNum
} = props;
if(!d3.select('.popup').empty()) return false;
const action: RackActions = await showConfirmationPopup();
const layoutSvg: d3.Selection<SVGElement, {}, HTMLElement, any> = d3.select('[id=layout-svg]');
function isConnected(selectionNode){
return !!selectionNode.closest(`[id*='group']`);
}
// Make sure cages don't have the wrong styles, give merged cages a grouped class
function resetElementProperties(element: SVGGElement, shapeType, action) {
if(action === 'merge'){
element.setAttribute('class',`grouped-${shapeType}`);
element.setAttribute('style', "");
}
setupEditCageEvent(element, cageActionProps.setSelectedObj, contextMenuRef, cageActionProps.setCtxMenuStyle, shapeType);
}
// add starting x and y for each group to then increment its local subgroup coords by.
// Example: 2 nodes, 0,0 and 120,0 start at 0,0 add 120,0
// second 2 nodes, 0,0 and 120,0 start at 240,0 add 0,0 and 120,0. etc
function processChildNodes(element: SVGGElement, mergedGroup, action: RackActions) {
const {x: startX, y: startY} = getTranslation(element.getAttribute('transform'))
d3.select(element).selectAll(':scope > g').each(function () {
const targetShape = d3.select(this);
let shapeType: RackStringType;
if(action === 'merge'){
shapeType = parseRoomItemType(targetShape.attr('id')) as RackStringType;
}else{
shapeType = getTypeClassFromElement(targetShape.node()) as RackStringType;
}
const {x: localX, y: localY} = getTranslation(targetShape.attr('transform'));
const newX = startX + localX;
const newY = startY + localY;
targetShape.attr('transform', `translate(${newX},${newY})`);
// When connecting merged groups that have been connected before make sure to reset each cage but
// add the rack shape instead of cage shape
const mergedChildren = d3.select(this).selectAll(':scope > g');
if(!mergedChildren.empty()){
mergedChildren.each(function () {
resetElementProperties(this as SVGGElement, shapeType, action);
})
}else{
resetElementProperties(this as SVGGElement, shapeType, action);
}
mergedGroup.node().appendChild(this);
});
}
function processShape(shape, action, mergedGroup) {
if(action === 'merge'){
processChildNodes(shape, mergedGroup, action);
}else{
if(shape.getAttribute('class').includes('rack-group')){
processChildNodes(shape, mergedGroup, action);
}else{// When connecting racks for the first time
// this iteration is for connecting a merged rack, have to reset each cage in the rack but add the rack shape not the cage shape
d3.select(shape).selectAll(':scope > g').each(function () {
resetElementProperties(this as SVGGElement, getTypeClassFromElement(shape), action);
});
mergedGroup.node().appendChild(shape);
}
}
}
if (action !== 'cancel') {
let targetRackShape: d3.Selection<SVGGElement, {}, HTMLElement, any>
= layoutSvg.select(`[id=${targetRack.itemId}]`);
let draggedRackShape: d3.Selection<SVGGElement, {}, HTMLElement, any>
= layoutSvg.select(`[id=${draggedRack.itemId}]`);
let newGroup: d3.Selection<SVGGElement, {}, HTMLElement, any>;
// Clone the target and dragged shapes before using
let clonedTargetShape = targetRackShape.node().cloneNode(true) as Element;
let clonedDraggedShape = draggedRackShape.node().cloneNode(true) as Element;
let targetRackId = clonedTargetShape.id;
let draggedRackId = clonedDraggedShape.id;
if(action === 'merge'){
if(isConnected(draggedRackShape.node()) || isConnected(targetRackShape.node())){
await showLayoutEditorError("Invalid Configuration: Please do not merge connected racks");
return;
}
if(draggedRack.type.type !== targetRack.type.type){
await showLayoutEditorError("Invalid Configuration: Please do not merge cages of different types, use connection instead");
return;
}
newGroup = layoutSvg.append('g')
.attr('class', targetRackShape.attr('class'))
.attr('id', targetRackShape.attr('id'));
//Reset translates to new local group
resetNodeTranslationsWithZoom(clonedTargetShape, clonedDraggedShape, layoutSvg);
processShape(clonedTargetShape, action, newGroup);
processShape(clonedDraggedShape, action, newGroup);
// Copy any inline styles from the targetShape to the merged group
const styleAttr = targetRackShape.attr('style');
if (styleAttr) {
newGroup.attr('style', styleAttr);
}
}
else{ // action = connect
// If connecting already connected groups these will be populated
const connectedTargetGroupShape: d3.Selection<SVGGElement, {}, HTMLElement, any>
= layoutSvg.select(`#${targetRackGroup.groupId}`);
const connectedDragGroupShape: d3.Selection<SVGGElement, {}, HTMLElement, any>
= layoutSvg.select(`#${dragRackGroup.groupId}`);
if(!connectedTargetGroupShape.empty()){
clonedTargetShape = connectedTargetGroupShape.node().cloneNode(true) as Element;
targetRackShape = connectedTargetGroupShape;
}
if(!connectedDragGroupShape.empty()){
clonedDraggedShape = connectedDragGroupShape.node().cloneNode(true) as Element;
draggedRackShape = connectedDragGroupShape;
}
newGroup = layoutSvg.append('g')
.attr('class', 'draggable rack-group')
.attr('id', targetRackGroup.groupId);
resetNodeTranslationsWithZoom(clonedTargetShape, clonedDraggedShape, layoutSvg);
d3.select(clonedTargetShape).classed('draggable', false);
d3.select(clonedDraggedShape).classed('draggable', false);
processShape(clonedTargetShape, action, newGroup);
processShape(clonedDraggedShape,action, newGroup);
}
// Copy the transform attribute from the targetShape to the merged group
const transformAttr = targetRackShape.attr('transform');
if (transformAttr) {
newGroup.attr('transform', transformAttr);
}
//Attach data from target to new shape
const targetData = targetRackShape.datum() as { x: number; y: number };
if(targetData) {
newGroup.data([{x: targetData.x, y: targetData.y}])
}
newGroup.call(layoutDrag);
doRackAction(action,targetRackId, draggedRackId, targetCageNum, dragCageNum, newGroup);
// Remove the original shapes from the DOM
targetRackShape.remove();
draggedRackShape.remove();
return true;
}else{
return false;
}
}
export const getAdjDirection = (
draggedX,
draggedY,
targetX,
targetY,
draggedWidth,
draggedHeight,
targetWidth,
targetHeight): CageDirection => {
// Check right side of A to left side of B
if (draggedX + draggedWidth === targetX) {
return CageDirection.Right;
}
// Check left side of A to right side of B
if (draggedX === targetX + targetWidth) {
return CageDirection.Left;
}
// Check bottom side of A to top side of B
if (draggedY + draggedHeight === targetY) {
return CageDirection.Bottom;
}
// Check top side of A to bottom side of B
if (draggedY === targetY + targetHeight) {
return CageDirection.Top;
}
}
// This checks the adjacency of two racks to determine if they can be merged
export function checkAdjacent(targetCage: LocationCoords, draggedCage: LocationCoords, draggedSize: number, targetSize: number) {
const targetX = targetCage.cellX;
const targetY = targetCage.cellY;
const draggedX = draggedCage.cellX;
const draggedY = draggedCage.cellY;
// Calculate widths and heights in pixels
const draggedWidth = draggedSize * CELL_SIZE;
const draggedHeight = draggedSize * CELL_SIZE;
const targetWidth = targetSize * CELL_SIZE;
const targetHeight = targetSize * CELL_SIZE;
// Calculate corners of the dragged square
const draggedCorners = [
{ x: draggedX, y: draggedY }, // Top-left
{ x: draggedX + draggedWidth, y: draggedY }, // Top-right
{ x: draggedX, y: draggedY + draggedHeight }, // Bottom-left
{ x: draggedX + draggedWidth, y: draggedY + draggedHeight }, // Bottom-right
];
// Calculate corners of the target square
const targetCorners = [
{ x: targetX, y: targetY }, // Top-left
{ x: targetX + targetWidth, y: targetY }, // Top-right
{ x: targetX, y: targetY + targetHeight }, // Bottom-left
{ x: targetX + targetWidth, y: targetY + targetHeight }, // Bottom-right
];
/* True if valid bounds exist. In short this fixes the issue with the corner checking where corners
themselves count as adjacent with no sides touching.
*/
const checkBounds = (corner) => {
let valid = false;
if(corner === 0){ // top left corner match of drag cage
if(draggedCorners[corner].x === targetCorners[3].x && draggedCorners[corner].y === targetCorners[3].y){
valid = true;
}
}else if(corner === 1){ // top right corner match of drag cage
if(draggedCorners[corner].x === targetCorners[2].x && draggedCorners[corner].y === targetCorners[2].y){
valid = true;
}
}else if(corner === 2){ // bottom left corner match of drag cage
if(draggedCorners[corner].x === targetCorners[1].x && draggedCorners[corner].y === targetCorners[1].y){
valid = true;
}
}else if(corner === 3){ // bottom right corner match of drag cage
if(draggedCorners[corner].x === targetCorners[0].x && draggedCorners[corner].y === targetCorners[0].y){
valid = true;
}
}
return valid;
}
// Check if any corner of the dragged square matches any corner of the target square with a matching side.
for (let i = 0; i < draggedCorners.length; i++) {
for (let j = 0; j < targetCorners.length; j++) {
if (draggedCorners[i].x === targetCorners[j].x && draggedCorners[i].y === targetCorners[j].y) {
if(checkBounds(i)){
continue;
}
const direction = getAdjDirection(draggedX, draggedY, targetX, targetY, draggedWidth, draggedHeight, targetWidth, targetHeight);
// Determine the direction of adjacency based on the matching corner
if (draggedCorners[i].x === draggedX && draggedCorners[i].y === draggedY) {
return {isAdjacent: true, direction: direction};
} else if (draggedCorners[i].x === draggedX + draggedWidth && draggedCorners[i].y === draggedY) {
return {isAdjacent: true, direction: direction};
} else if (draggedCorners[i].x === draggedX && draggedCorners[i].y === draggedY + draggedHeight) {
return {isAdjacent: true, direction: direction};
} else if (draggedCorners[i].x === draggedX + draggedWidth && draggedCorners[i].y === draggedY + draggedHeight) {
return {isAdjacent: true, direction: direction};
}
}
}
}
return {isAdjacent: false, direction: "0"};
}
//Offset for the top left corner of the layout, without doing this objects will randomly jump when dragging and placing
export const getLayoutOffset = (props: OffsetProps) => {
const {layoutSvg, clientX, clientY} = props;
const svgRect = (layoutSvg.node() as SVGRectElement).getBoundingClientRect();
const x = clientX - svgRect.left;
const y = clientY - svgRect.top;
return {x: x, y: y};
}
export const getTargetRect =(x, y, gridSize, transform) => {
// Adjust the coordinates based on the current zoom and pan transform
const adjustedX = transform.invertX(x);
const adjustedY = transform.invertY(y);
// Calculate the column and row index based on the adjusted grid size
const col = Math.floor(adjustedX / gridSize);
const row = Math.floor(adjustedY / gridSize);
// Return the top-left corner coordinates of the rectangle
return {
x: col * gridSize,
y: row * gridSize,
};
}
// Layout Drag Helpers
export function createStartDragInLayout(startDragProps: StartDragProps) {
return(
function startDragInLayout(event) {
const {setSelectedObj, localRoomRef} = startDragProps;
const localRoom = localRoomRef.current;
const id = d3.select(this).attr('id');
let foundObj: SelectedObj = localRoom.objects.find(obj => obj.itemId === id);
if(foundObj){
setSelectedObj(foundObj);
}else{
localRoom.rackGroups.forEach((group) => {
if(foundObj) return;
if(group.groupId === id){
foundObj = group;
return;
}
foundObj = group.racks.find((rack) => rack.itemId === id)
})
if(foundObj){
setSelectedObj(foundObj);
}
}
d3.select(this).raise().classed('active', true);
}
);
}
export function createDragInLayout() {
return(
function dragInLayout(event) {
const layoutSvg: d3.Selection<SVGElement, {}, HTMLElement, any> = d3.select('#layout-svg');
const element = d3.select(this);
const transform = d3.zoomTransform(layoutSvg.node());
const scale = transform.k;
const [newX, newY] = d3.pointer(event.sourceEvent, this.parentNode);
element.attr('transform', `translate(${newX},${newY}) scale(${scale})`);
}
)
}
export function createEndDragInLayout(props: LayoutDragProps) {
return (
function endDragInLayout(event) {
const {
gridSize,
moveItem
} = props;
const shape = d3.select(this);
shape.classed('active', false);
const layoutSvg: d3.Selection<SVGElement, {}, HTMLElement, any> = d3.select('[id=layout-svg]');
const transform = d3.zoomTransform(layoutSvg.node());
const [pointerX,pointerY] = d3.pointer(event, layoutSvg.node()); // mouse position with respect to layout svg
const {x,y} = getLayoutOffset({
clientX: pointerX,
clientY: pointerY,
layoutSvg: layoutSvg});
const targetCell = getTargetRect(pointerX, pointerY, gridSize, transform);
if (targetCell) {
const cellX = targetCell.x;
const cellY = targetCell.y;
const shapeType: RoomItemClass = shape.classed('room-obj') ? 'roomObj' : 'caging';
placeAndScaleGroup(shape, cellX, cellY, transform);
// make sure border template is below all other shapes on the layout
if(shape.attr('id') === 'layout-border'){
shape.lower();
}
moveItem(shape.attr('id'),shapeType, cellX, cellY, transform.k);
}
}
);
}
export const placeAndScaleGroup = (group, x, y, transform) => {
// Scale the group to match the grid size relative to the current zoom level
const scale = transform.k; // Scale inversely to zoom
// Adjust x and y for transform
const newX = transform.applyX(x);
const newY = transform.applyY(y);
// Apply the transform (translate to snap to the grid, and scale)
group.attr("transform", `translate(${newX}, ${newY}) scale(${scale})`)
.data([{x: x, y: y}]); // keep data x and y because these are pre transform coords
}
export const areCagesInSameRack = (rack: Rack, cage1: LocationCoords, cage2: LocationCoords) => {
if (!rack.cages || !Array.isArray(rack.cages)) {
return false;
}
const nums = rack.cages.map(item => item.cageNum);
return nums.includes(cage1.num) && nums.includes(cage2.num);
}
// input is the enum number for rack, default rack, or room obj type. Return true if it is in Rack or Default rack types
export const isRackEnum = (itemType: RoomItemType): itemType is RackTypes | DefaultRackTypes => {
return itemType in RackTypes || itemType in DefaultRackTypes;
};
export const isRackDefault = (itemType: RoomItemType): itemType is DefaultRackTypes => {
return itemType in DefaultRackTypes;
};
// finds a cage by cageNum in group of racks if it exists
export const findSelectObjRack = (racks: Rack[], obj: string): Rack => {
return racks.find(rack => {
return rack.cages.find((cage) => cage.cageNum === obj)
});
}
// finds a rack in room/groups of racks if it exists and return the rack and rack group it is apart of
export const findRackInGroup = (targetId: string, groups: RackGroup[]): {rack: Rack, rackGroup: RackGroup} | undefined => {
for (const group of groups) {
const targetRack = group.racks.find(rack => rack.itemId === targetId);
if (targetRack) {
return { rack: targetRack, rackGroup: group };
}
}
return undefined;
};
// finds a cage in room/groups of racks if it exists and return the rack, rack group and cage state
export const findCageInGroup = (targetId: CageNumber, groups: RackGroup[]): {cage: Cage, rack: Rack, rackGroup: RackGroup} | undefined => {
for (const group of groups) {
for (const rack of group.racks) {
const targetCage = rack.cages.find(cage => cage.cageNum === targetId);
if (targetCage) {
return { cage: targetCage, rack: rack, rackGroup: group };
}
}
}
return undefined;
};
// FUNCTIONS FOR LOADING IN PREVIOUS DATA
export const buildNewLocs = (prevRoomData: LayoutHistoryData[]): UnitLocations => {
// Empty Unit locations object
const newUnitLocs: UnitLocations = createEmptyUnitLoc();
prevRoomData.forEach(roomItem => {
if(!isRackEnum(roomItem.object_type)) return; // ignore room objects here
let rackType: RoomItemStringType;
if(isRackDefault(roomItem.object_type)){
rackType = roomItemToString(defaultTypeToRackType(roomItem.object_type));
}else{
rackType = roomItemToString(roomItem.object_type);
}
newUnitLocs[rackType].push({
num: `${rackType}-${parseInt(roomItem.cage)}` as CageNumber,
cellX: roomItem.x_coord,
cellY: roomItem.y_coord
});
})
return newUnitLocs;
}
export const buildNewLocalRoom = async (prevRoom: PrevRoom): Promise<Room> => {
const newLocalRoom: Room = {
name: prevRoom.name,
rackGroups: [],
objects: [],
layoutData: null
};
let roomObjNum = 1;
const loadMods: boolean = !!prevRoom.modData;
//check if a group exists for the groupId, if it does return, else create new group for the room
const findOrAddGroup = (rackItem: LayoutHistoryData): RackGroup => {
// groupId is a single number so check if the GroupId string contains it
let rackGroup: RackGroup = newLocalRoom.rackGroups.find(group => parseLongId(group.groupId) === rackItem.rack_group)
if (!rackGroup) {
//create new rack group if it doesn't exist
rackGroup = {
groupId: `rack-group-${rackItem.rack_group}` as GroupId,
selectionType: 'rackGroup',
scale: prevRoom.layoutData.scale,
x: rackItem.x_coord,
y: rackItem.y_coord,
racks: []
};
newLocalRoom.rackGroups.push(rackGroup);
}
return rackGroup;
}
//check if a rack exists for the rackId, if it does return, else create new rack for the group
const findOrAddRack = async (rackGroup: RackGroup, rackItem: LayoutHistoryData): Promise<Rack> => {
const isDefault = isRackDefault(rackItem.object_type);
let rackIdNum;
let rowId;
let extraContext: ExtraContext;
let rackData;
// if rack is default, use default rack id instead
if(rackItem.extra_context){
extraContext = JSON.parse(rackItem.extra_context);
if(extraContext?.rack?.rackId){
rackIdNum = extraContext.rack.rackId;
}
}
if(!isDefault){
const optConfig: SelectRowsOptions = {
schemaName: "cageui",
queryName: "racks",
filterArray: [
Filter.create('rowid', rackItem.rack, Filter.Types.EQUALS)
]
}
rackData = await labkeyActionSelectWithPromise(optConfig);
if(rackData.rowCount > 0){
rackIdNum = rackData.rows[0].rackid;
rowId = rackData.rows[0].rowid;
}
}
let rack: Rack = rackGroup.racks.find(r => parseRoomItemNum(r.itemId) === rackIdNum);
if (!rack) {
//create new rack if it doesn't exist
let type: UnitType;
let rackId: DefaultRackId | RealRackId;
let typeRowId;
const rackPrefix = isDefault ? 'default-rack' : 'rack';
if(!isDefault){
typeRowId = rackData.rows[0].rack_type;
rackId = `${rackPrefix}-${rackIdNum}` as RealRackId;
}else{
rackId = `${rackPrefix}-${rackIdNum}` as DefaultRackId;
}
// if default get base type, else get rack type from rack id
const optConfig = {
schemaName: "cageui",
queryName: "rack_types",
filterArray: [
Filter.create(isDefault ? 'type' : 'rowid', isDefault ? rackItem.object_type : typeRowId, Filter.Types.EQUALS)
]
}
const rackTypesData = await labkeyActionSelectWithPromise(optConfig);
type = {
rowid: typeRowId,
name: rackTypesData.rows[0].name,
type: isDefault ? defaultTypeToRackType(rackTypesData.rows[0].type) : rackTypesData.rows[0].type,
isDefault: isDefault,
};
rack = {
rowid: rowId,
selectionType: 'rack',
cages: [],
isActive: !isDefault,
itemId: rackId,
type: type,
x: rackItem.x_coord - rackGroup.x, // subtract group coords from layout coords to get rack coords
y: rackItem.y_coord - rackGroup.y,
extraContext: extraContext?.rack
};
rackGroup.racks.push(rack);
}
return rack;
}
const addCageToRack = async (rack: Rack, rackItem: LayoutHistoryData, group: RackGroup) => {
// only string for RackTypes, not DefaultRackTypes, since cageNum is used for location tracking which uses RackTypes
let cageNumType: RoomItemStringType;
let extraContext: ExtraContext;
let cageNum = parseInt(rackItem.cage);
let cageMods: CageModifications = {
mods: {
[ModLocations.Top]: [],
[ModLocations.Bottom]: [],
[ModLocations.Left]: [],
[ModLocations.Right]: [],
[ModLocations.Direct]: []
},
isDirty: false,
}
if(rack.type.isDefault){
cageNumType = roomItemToString(defaultTypeToRackType(rackItem.object_type as DefaultRackTypes));
}else{
cageNumType = roomItemToString(rackItem.object_type);
}
if(rackItem.extra_context){
extraContext = JSON.parse(rackItem.extra_context);
}
const svgSize = await getSvgSize(rack.type.type);
//TODO Add mods if needed here
if(loadMods && !rack.type.isDefault){
prevRoom.modData.forEach((mod) => {
if(rack.rowid === mod.rack && cageNum === mod.cage){
(cageMods.mods[mod.location] as CageModification[]).push({
id: mod.locationId,