-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.ts
More file actions
1316 lines (1154 loc) · 51.5 KB
/
helpers.ts
File metadata and controls
1316 lines (1154 loc) · 51.5 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) 2026 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.
*
*/
import {
AllHistoryData,
Cage,
CageModification,
CageModificationsType,
CageMods,
CageNumber,
CageSvgId,
DefaultRackStringType,
DefaultRackTypes,
FetchRoomData,
FullCageHistory,
FullObjectHistoryData,
GroupId,
GroupRotation,
LayoutData,
LayoutHistoryData,
ModData,
ModLocations,
ModTypes,
PrevRoom,
Rack,
RackConditionOption,
RackConditions,
RackData,
RackGroup,
RackStringType,
RackTypes,
Room,
RoomItemStringType,
RoomItemType,
RoomMods,
RoomObject,
RoomObjectStringType,
RoomObjectTypes,
TemplateHistoryData,
UnitLocations,
UnitType
} from '../types/typings';
import * as d3 from 'd3';
import { zoomTransform } from 'd3';
import { MutableRefObject } from 'react';
import { ActionURL, Filter, Utils } from '@labkey/api';
import {
addModEntries,
areAllRacksNonDefault,
createEmptyUnitLoc,
findCageInGroup,
isRackEnum,
isRoomHomogeneousDefault,
placeAndScaleGroup,
processRealLayoutHistory,
setupEditCageEvent
} from './LayoutEditorHelpers';
import { SelectDistinctOptions } from '@labkey/api/dist/labkey/query/SelectDistinctRows';
import { selectDistinctRows } from '@labkey/components';
import { CELL_SIZE, Modifications, roomSizeOptions, SVG_HEIGHT, SVG_WIDTH } from './constants';
import { ExtraContext, LayoutSaveResult } from '../types/layoutEditorTypes';
import { SelectRowsOptions } from '@labkey/api/dist/labkey/query/SelectRows';
import { labkeyActionSelectWithPromise, saveRoomLayout } from '../api/labkeyActions';
import { cageModLookup } from '../api/popularQueries';
import { ConnectedCages, ConnectedRacks } from '../types/homeTypes';
export const generateCageId = (objectId: string): CageSvgId => {
return `cageSVG_${objectId}` as CageSvgId;
};
export const generateUUID = (): string => {
return Utils.generateUUID().toUpperCase();
}
// Changes stroke color of svg element nodes keeping the other styles.
export const changeStyleProperty = (element: Element, property: string, newValue: string): void => {
const styleAttr = element.getAttribute('style');
if (styleAttr) {
const styles = styleAttr.split(';').map(style => style.trim()).filter(style => style !== '');
let updated = false;
const updatedStyles = styles.map(style => {
const [prop, value] = style.split(':').map(prop => prop.trim()).filter(prop => prop !== '');
if (prop.toLowerCase() === property.toLowerCase()) {
updated = true;
return `${property}: ${newValue}`;
} else {
return `${prop}: ${value}`;
}
});
if (!updated) {
updatedStyles.push(`${property}: ${newValue}`);
}
const updatedStyleAttr = updatedStyles.join(';');
element.setAttribute('style', updatedStyleAttr);
} else {
element.setAttribute('style', `${property}: ${newValue}`);
}
};
export const getSvgSize = async (type: RackTypes) => {
const config: SelectDistinctOptions = {
schemaName: 'ehr_lookups',
queryName: 'cageui_item_types',
column: 'description',
filterArray: [Filter.create('value', type, Filter.Types.EQUAL)]
};
const res = await selectDistinctRows(config);
if (res.values.length === 1) {
return res.values[0];
}
return;
};
// matches "string-number", if a match return the number
export const parseRoomItemNum = (input: string): number => {
const regex = /\w+-(\d+)/;
const match = input.match(regex);
if (match) {
return parseInt(match[1]);
}
return;
};
// matches "string-number", if a match return the type/string
export const parseRoomItemType = (input: string): string => {
const regex = /^(\w+)-\d+$/;
const match = input.match(regex);
if (match) {
return match[1];
}
return;
};
export const getTypeClassFromElement = (element) => {
const classes: string[] = Array.from(element.classList);
// Define a regex to capture the part after "type-"
const regex = /^type-(\w+)/;
// Find the class that matches the regex and capture the relevant part
const typeClass = classes.find(cls => regex.test(cls));
if (typeClass) {
const match = typeClass.match(regex);
return match[1]; // Return only the captured part (after "type-")
}
return null;
};
export const parseLongId = (input: string) => {
const regex = /\w+-\w+-(\d+)/; // matches "string-string-number"
const match = input.match(regex);
if (match) { // if a match return the number
return parseInt(match[1]);
}
return;
};
export const formatCageNum = (str: string) => {
// Split the string by hyphens
try {// if the rack is default split and correctly display it
const parts = str.split('-');
// Process each part
const formattedParts = parts.map(part => {
// Capitalize first letter and lowercase the rest (if it's a word)
if (part.length > 0) {
return convertToTitleCase(part);
}
return part;
});
// Join with spaces
return formattedParts.join(' ');
}
catch {// if the rack is real display it like so
return `Rack ${str}`;
}
};
export const getNextDefaultRackId = (groups: RackGroup[]): number => {
// Extract & parse only "default-rack-*" IDs
const allRackNumbers = groups
.flatMap(group =>
group.racks
.map(rack => rack.type.isDefault ? rack.itemId : 0)
.filter(num => num > 0) // Only keep valid default-rack numbers
)
.sort((a, b) => a - b); // Sort ascending
// Find the first missing number (starting from 1)
let expectedNumber = 1;
for (const num of allRackNumbers) {
if (num > expectedNumber) {
// Gap found! Use the missing number
return expectedNumber;
}
expectedNumber = num + 1;
}
// No gaps? Use the next number after the max
return expectedNumber;
};
export const convertToTitleCase = (str: string) => {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};
const generateTypeMaps = () => {
const rackTypeToDefaultTypeMap: { [key in RackTypes]?: DefaultRackTypes } = {};
const defaultTypeToRackTypeMap: { [key in DefaultRackTypes]?: RackTypes } = {};
// Iterate through the enum keys and filter out numeric ones
Object.keys(RackTypes)
.filter((key) => isNaN(Number(key))) // Filters out numeric keys
.forEach((key) => {
const rackTypeKey = RackTypes[key as keyof typeof RackTypes];
const defaultRackTypeKey = `Default${key}` as keyof typeof DefaultRackTypes;
// Check if the corresponding DefaultRackType key exists
if (DefaultRackTypes[defaultRackTypeKey] !== undefined) {
const defaultRackType = DefaultRackTypes[defaultRackTypeKey];
// Assign mappings
rackTypeToDefaultTypeMap[rackTypeKey as RackTypes] = defaultRackType;
defaultTypeToRackTypeMap[defaultRackType] = rackTypeKey as RackTypes;
}
});
return {rackTypeToDefaultTypeMap, defaultTypeToRackTypeMap};
};
// These two maps can be imported and used to convert between the string and number of the rack type enum
const {rackTypeToDefaultTypeMap, defaultTypeToRackTypeMap} = generateTypeMaps();
export const rackTypeToDefaultType = (type: RackTypes) => {
return rackTypeToDefaultTypeMap[type];
};
export const defaultTypeToRackType = (type: DefaultRackTypes) => {
return defaultTypeToRackTypeMap[type];
};
/*
parse a room iteam to a string
*/
export const roomItemToString = (item: RoomItemType): RoomItemStringType => {
let itemString: RoomItemStringType;
// Uppercase the first letter of the string
const rackString = RackTypes[item];
const roomObjString = RoomObjectTypes[item];
const defaultRackString = DefaultRackTypes[item];
if (rackString) {
itemString = rackString.charAt(0).toLowerCase() + rackString.slice(1) as RackStringType;
} else if (defaultRackString) {
itemString = defaultRackString.charAt(0).toLowerCase() + defaultRackString.slice(1) as DefaultRackStringType;
} else {
itemString = roomObjString.charAt(0).toLowerCase() + roomObjString.slice(1) as RoomObjectStringType;
}
return itemString;
};
/*
Extract the item type from a string
*/
export const stringToRoomItem = (formattedString: RoomItemStringType): RoomItemType => {
// Uppercase the first letter of the string
const itemKey = formattedString.charAt(0).toUpperCase() + formattedString.slice(1);
const rackItem = RackTypes[itemKey as keyof typeof RackTypes];
const objItem = RoomObjectTypes[itemKey as keyof typeof RoomObjectTypes];
const defaultRackItem = DefaultRackTypes[itemKey as keyof typeof DefaultRackTypes];
// Use the EnumType object to look up the value
return rackItem || defaultRackItem || objItem;
};
export const fetchRoomData = async (roomName: string, abortSignal?: AbortSignal): Promise<FetchRoomData> => {
const prevRoomData: FetchRoomData = {
prevRoomData: undefined,
selectedSize: undefined,
showSelectionPopup: false,
error: undefined
};
// Make call to all_history for room and determine if template or not.
const allHistoryCfg: SelectRowsOptions = {
schemaName: 'cageui',
queryName: 'all_history',
columns: [],
filterArray: [
Filter.create('room', roomName, Filter.Types.EQUALS),
Filter.create('end_date', null, Filter.Types.ISBLANK)
]
};
const allHistRes = await labkeyActionSelectWithPromise(allHistoryCfg, abortSignal);
if (allHistRes.rowCount === 1) {
const allHistObj: AllHistoryData = {
endDate: allHistRes.rows[0].end_date,
historyId: allHistRes.rows[0].historyid,
historyType: allHistRes.rows[0].history_type,
room: allHistRes.rows[0].room,
rowid: allHistRes.rows[0].rowid,
startDate: allHistRes.rows[0].start_date,
valid: allHistRes.rows[0].valid
};
let historyTable: string = allHistObj.historyType === 'template' ? 'template_layout_history' : 'layout_history';
const isDefaultRoom: boolean = allHistObj.historyType === 'template';
const prevRoomConfig: SelectRowsOptions = {
schemaName: 'cageui',
queryName: historyTable,
columns: [],
filterArray: [
Filter.create('historyid', allHistObj.historyId, Filter.Types.EQUALS),
Filter.create('end_date', null, Filter.Types.ISBLANK)
]
};
const prevRoomBorderConfig: SelectRowsOptions = {
schemaName: 'cageui',
queryName: 'room_history',
columns: ['scale', 'border_width', 'border_height'],
filterArray: [
Filter.create('historyid', allHistObj.historyId, Filter.Types.EQUALS)
]
};
const modHistoryConfig = {
schemaName: 'cageui',
queryName: 'cage_modifications_history',
columns: [],
filterArray: [
Filter.create('historyid', allHistObj.historyId, Filter.Types.EQUALS),
]
};
const [prevRoomResult, borderResult, modResult] = await Promise.all([
labkeyActionSelectWithPromise(prevRoomConfig, abortSignal),
labkeyActionSelectWithPromise(prevRoomBorderConfig, abortSignal),
labkeyActionSelectWithPromise(modHistoryConfig, abortSignal)
]);
let borderObj: LayoutData;
let cagingData: FullObjectHistoryData[] = [];
let modData: ModData[];
if (borderResult.rowCount === 0) {
throw new Error(`No room found in EHR for ${roomName}`);
} else {
borderObj = {
scale: borderResult.rows[0].scale || 1,
borderHeight: borderResult.rows[0].border_height || SVG_HEIGHT - 1,
borderWidth: borderResult.rows[0].border_width || SVG_WIDTH - 1,
};
prevRoomData.selectedSize = roomSizeOptions.find(opt => opt.scale === borderObj.scale);
prevRoomData.showSelectionPopup = false;
}
if (prevRoomResult.rowCount > 0) {
if (isDefaultRoom) {
cagingData = prevRoomResult.rows.map((row: TemplateHistoryData) => ({
objectType: row.object_type,
extraContext: row.extra_context,
rackGroup: row.rack_group,
groupRotation: row.group_rotation,
rack: row.rack,
cage: row.cage,
xCoord: row.x_coord,
yCoord: row.y_coord,
}));
} else {
const layoutHistoryData: LayoutHistoryData[] = prevRoomResult.rows.map(row => ({
historyId: row.historyid,
cage: row.cage,
objectType: row.object_type,
extraContext: row.extra_context,
xCoord: row.x_coord,
yCoord: row.y_coord,
rowid: row.rowid,
}));
const layoutHistoryResults = await processRealLayoutHistory(layoutHistoryData);
console.log('Layout history results', layoutHistoryResults);
if (layoutHistoryResults.rejected.length > 0) {
throw new Error(`Error processing layout history for ${roomName}: \n ${layoutHistoryResults.rejected.join(`\n`)}`);
} else {
cagingData = layoutHistoryResults.fulfilled;
}
}
}
if (modResult.rowCount > 0) {
modData = modResult.rows.map(row => ({
location: row.location,
modId: row.modid,
parentModId: row.parent_modid,
subId: row.subid,
cage: row.cage,
modification: row.modification,
historyId: row.historyid
}));
}
prevRoomData.prevRoomData = {
name: roomName,
cagingData: cagingData,
layoutData: borderObj,
isDefault: isDefaultRoom,
modData: modData
};
return prevRoomData;
}
return prevRoomData;
};
// Adds the svgs from the saved layouts to the DOM. Mode edit is version displayed in the layout editor and view is the one in the home views.
// roomForMods is passed if the unitsToRender is not room but needs access to the room object. This is for loading mods.
export const addPrevRoomSvgs = (mode: 'edit' | 'view', unitsToRender: Room | RackGroup | Rack | Cage, layoutSvg: d3.Selection<SVGElement, {}, HTMLElement, any>, currRoom?: Room, modsToLoad?: RoomMods, setSelectedObj?, contextMenuRef?: MutableRefObject<Room>, setCtxMenuStyle?, closeMenuThenDrag?) => {
let renderType: 'room' | 'group' | 'rack' | 'cage';
if ((unitsToRender as Room)?.rackGroups) {
renderType = 'room';
} else if ((unitsToRender as RackGroup)?.racks) { // we are rendering a single rack group
renderType = 'group';
} else if ((unitsToRender as Rack)?.cages) { // we are rendering a single rack
renderType = 'rack';
} else { // we are rendering a single cage
renderType = 'cage';
}
// Loads modifications from constant styles and ids to inject into the svgs
const loadCageMods = (cageToLoad: Cage, shape: d3.Selection<SVGElement, unknown, null, undefined>, rotation: GroupRotation) => {
if (!cageToLoad.mods) {
return;
}
Object.entries(cageToLoad.mods).forEach(([loc, modSubList]: [string, CageModification[]]) => {
const modLoc = parseInt(loc) as ModLocations;
modSubList.forEach((modList) => {
const subId = modList.subId;
modList.modKeys.forEach(modMap => {
const currMod = modsToLoad[modMap.modId];
const modObj = Modifications[currMod.value];// find mod in mod constants array
// for each id in the location map the style if it exists
modObj.svgIds[modLoc][rotation].forEach((svgId, idx) => {
// If ids contain "-" they are split and searched left to right, helpful for listing parent-child ids
const svgIdSplit = svgId.split('-');
let currentSelection: d3.Selection<SVGElement, unknown, null, undefined> = shape.select(`[id=${svgIdSplit[0]}-${subId}]`);
for (let i = 1; i < svgIdSplit.length; i++) {
currentSelection = currentSelection.select(`#${svgIdSplit[i]}`);
}
modObj.styles.forEach((style) => {
changeStyleProperty(currentSelection.node() as SVGElement, style.property, style.value);
});
});
});
});
});
};
// this function renders the actual visible svg in some groups
const createRackGroup = (parentGroup, rack: Rack, isSingleRack, groupRotation: GroupRotation) => {
const rackTypeString: RackStringType = roomItemToString(rack.type.type) as RackStringType;
const rackGroup = isSingleRack ? parentGroup : parentGroup.append('g')
.attr('id', rack.objectId)
.attr('class', `rack type-${rackTypeString}`)
.attr('transform', `translate(${rack.x},${rack.y})`)
.style('pointer-events', 'bounding-box');
// This is where the cage svg group is created.
rack.cages.forEach(async (cage) => {
const cageGroup = rackGroup.append('g')
.attr('id', cage.svgId)
.attr('name', cage.cageNum)
.attr('transform', `translate(${cage.x},${cage.y})`);
let unitSvg: SVGElement;
// If we are editing we can simply copy the svg from the ones displayed.
// If we are in view mode they aren't on the page so we must fetch and load them in
if (mode === 'edit') {
unitSvg = (d3.select(`[id=${rackTypeString}_template_wrapper]`) as d3.Selection<SVGElement, {}, HTMLElement, any>)
.node().cloneNode(true) as SVGElement;
} else if (mode === 'view') {
await d3.svg(`${ActionURL.getContextPath()}/cageui/static/${rackTypeString}.svg`).then((d) => {
unitSvg = d.querySelector(`svg[id*=template]`);
});
}
// Only needed for layout editor to attach context menus
const shape = d3.select(unitSvg);
shape.classed('draggable', false);
shape.style('pointer-events', 'none');
const cageGroupContext = shape.select(`#${rackTypeString}`).node() as SVGGElement;
// in order to set the event pass in the context menu ref and styles to show/hide it
setupEditCageEvent(cageGroupContext, setSelectedObj, contextMenuRef, mode, setCtxMenuStyle);
(shape.select('tspan').node() as SVGTSpanElement).textContent = `${parseRoomItemNum(cage.cageNum)}`;
if (mode === 'view') {
loadCageMods(cage, shape, groupRotation);
}
cageGroup.append(() => shape.node());
});
return rackGroup;
};
const createGroup = (group: RackGroup) => {
const isSingleRack = group.racks.length === 1;
const parentGroup = isSingleRack
? layoutSvg.append('g')
.attr('id', group.racks[0].svgId)
.attr('class', `draggable rack type-${roomItemToString(group.racks[0].type.type)}`)
.style('pointer-events', 'bounding-box')
: layoutSvg.append('g')
.attr('id', group.groupId)
.attr('class', 'draggable rack-group');
group.racks.forEach(async rack => {
// Use parent group as rackGroup if only 1 rack, otherwise create a new rack group
await createRackGroup(parentGroup, rack, isSingleRack, group.rotation);
});
let groupX = renderType === 'room' ? group.x : group.racks[0].x;
let groupY = renderType === 'room' ? group.y : group.racks[0].y;
placeAndScaleGroup(parentGroup, groupX, groupY, zoomTransform(layoutSvg.node()));
if (mode === 'edit') {
parentGroup.call(closeMenuThenDrag);
}
};
// We are loading an entire room into the svg
if (renderType === 'room') {
(unitsToRender as Room).rackGroups.forEach((group) => {
createGroup(group);
});
(unitsToRender as Room).objects.forEach(async (roomObj) => {
const roomObjGroup = layoutSvg.append('g')
.data([{x: roomObj.x, y: roomObj.y}])
.attr('id', roomObj.itemId)
.attr('class', 'draggable room-obj')
.attr('transform', `translate(${roomObj.x}, ${roomObj.y}) scale(${mode === 'edit' ? roomObj.scale : 1})`)
.style('pointer-events', 'bounding-box');
let objSvg: SVGElement;
if (mode === 'edit') {
objSvg = (d3.select(`[id=${roomItemToString(roomObj.type)}_template_wrapper]`) as d3.Selection<SVGElement, {}, HTMLElement, any>).node().cloneNode(true) as SVGElement;
} else if (mode === 'view') {
await d3.svg(`${ActionURL.getContextPath()}/cageui/static/${roomItemToString(roomObj.type)}.svg`).then((d) => {
(roomObjGroup.node() as SVGElement).appendChild(d.documentElement);
});
return;
}
const shape = d3.select(objSvg)
.classed('draggable', false)
.attr('pointer-events', 'none');
roomObjGroup.append(() => shape.node());
placeAndScaleGroup(roomObjGroup, roomObj.x, roomObj.y, zoomTransform(layoutSvg.node()));
setupEditCageEvent(roomObjGroup.node() as SVGGElement, setSelectedObj, contextMenuRef, setCtxMenuStyle);
roomObjGroup.call(closeMenuThenDrag);
});
} else if (renderType === 'group') { // we are rendering a single rack group
createGroup(unitsToRender as RackGroup);
} else if (renderType === 'rack') { // we are rendering a single rack
} else { // we are rendering a single cage
const cage: Cage = unitsToRender as Cage;
const rackGroup = findCageInGroup(cage.svgId, currRoom.rackGroups).rackGroup;
const cageGroup = layoutSvg.append('g')
.attr('id', cage.cageNum)
.attr('transform', `translate(0,0)`);
let unitSvg: SVGElement;
d3.svg(`${ActionURL.getContextPath()}/cageui/static/${parseRoomItemType((unitsToRender as Cage).cageNum)}.svg`).then((d) => {
unitSvg = d.querySelector(`svg[id*=template]`);
const shape = d3.select(unitSvg);
(shape.select('tspan').node() as SVGTSpanElement).textContent = `${parseRoomItemNum((unitsToRender as Cage).cageNum)}`;
if (mode === 'view') {
loadCageMods(cage, shape, rackGroup.rotation);
}
cageGroup.append(() => shape.node());
});
}
};
export const buildNewLocalRoom = async (prevRoom: PrevRoom): Promise<[Room, UnitLocations]> => {
const newLocalRoom: Room = {
name: prevRoom.name,
rackGroups: [],
valid: false,
objects: [],
layoutData: null,
mods: null
};
const newUnitLocs: UnitLocations = createEmptyUnitLoc();
let newMods: RoomMods = {};
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: FullObjectHistoryData): 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.rackGroup);
if (!rackGroup) {
//create new rack group if it doesn't exist
rackGroup = {
groupId: `rack-group-${rackItem.rackGroup}` as GroupId,
selectionType: 'rackGroup',
scale: prevRoom.layoutData.scale,
rotation: rackItem.groupRotation,
x: rackItem.xCoord,
y: rackItem.yCoord,
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: FullObjectHistoryData): Promise<Rack> => {
let rackIdNum;
let rackObjectId;
let extraContext: ExtraContext;
let rackData = rackItem.rack as RackData;
let rack: Rack;
let rackCondition: RackConditions = RackConditions.Operational;
if (!prevRoom.isDefault) {
rackIdNum = rackData.rackId;
rackObjectId = rackData.objectId;
rackCondition = rackData.condition;
} else {
rackIdNum = rackItem.rack;
rackObjectId = `default-rack-${rackIdNum}`;
}
rack = rackGroup.racks.find(r => rackObjectId === r.objectId);
if (!rack) {
//create new rack if it doesn't exist
let type: UnitType;
let typeRowId;
const rackPrefix = prevRoom.isDefault ? 'default-rack' : 'rack';
if (!prevRoom.isDefault) {
typeRowId = rackData.rackType;
}
// if default get base type, else get rack type from rack id
const optConfig = {
schemaName: 'cageui',
queryName: 'rack_types',
columns: ['rowid', 'type', 'displayName', 'size', 'manufacturer/value', 'manufacturer/title', 'stationary'],
filterArray: [
Filter.create(prevRoom.isDefault ? 'type' : 'rowid', prevRoom.isDefault ? rackItem.objectType : typeRowId, Filter.Types.EQUALS)
]
};
const rackTypesData = await labkeyActionSelectWithPromise(optConfig);
if (rackTypesData.rowCount === 0) {
return;
}
let rackEnumType: RackTypes = rackTypesData.rows[0].type;
if(prevRoom.isDefault) {
rackEnumType = defaultTypeToRackType(rackTypesData.rows[0].type);
}
type = {
rowid: rackTypesData.rows[0].rowid as number,
displayName: rackTypesData.rows[0].displayName as string,
type: rackEnumType,
size: rackTypesData.rows[0].size,
manufacturer: {
value: rackTypesData.rows[0]['manufacturer/value'],
title: rackTypesData.rows[0]['manufacturer/title'],
},
isDefault: prevRoom.isDefault,
stationary: rackTypesData.rows[0].stationary,
};
rack = {
isNew: prevRoom.isDefault,
objectId: rackObjectId,
svgId: `rack_${rackObjectId}`,
selectionType: 'rack',
cages: [],
condition: rackCondition,
isActive: !prevRoom.isDefault,
itemId: rackIdNum,
type: type,
x: rackItem.xCoord - rackGroup.x, // subtract group coords from layout coords to get rack coords
y: rackItem.yCoord - rackGroup.y,
extraContext: extraContext?.rack
};
rackGroup.racks.push(rack);
}
return rack;
};
const addCageToRack = async (rack: Rack, rackItem: FullObjectHistoryData, 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 cageHistoryData = (rackItem.cage as FullCageHistory)?.cageHistory;
let cageData = (rackItem.cage as FullCageHistory)?.cageData;
let cageObjId: string;
let cageNum;
let cagePositionId;
if (!prevRoom.isDefault) {
cageNum = cageHistoryData.cageNum;
cageObjId = cageHistoryData.cage;
cagePositionId = cageData.positionId;
cageNumType = roomItemToString(rackItem.objectType);
} else {
cageNum = rackItem.cage;
cageObjId = generateUUID();
cagePositionId = rack.cages.length + 1;
cageNumType = roomItemToString(defaultTypeToRackType(rackItem.objectType as DefaultRackTypes));
}
let cageMods: CageModificationsType;
if (rackItem.extraContext) {
extraContext = JSON.parse(rackItem.extraContext);
}
const svgSize = await getSvgSize(rack.type.type);
// This is where mods are loaded into state for the room
if (loadMods && !rack.type.isDefault) {
cageMods = {
[ModLocations.Top]: [],
[ModLocations.Bottom]: [],
[ModLocations.Left]: [],
[ModLocations.Right]: [],
[ModLocations.Direct]: []
};
const modReturnData = await cageModLookup([], []);
const availMods = modReturnData.map(row => ({value: row.value, label: row.title}));
const prevMods = prevRoom.modData.filter((mod) => mod.cage === cageData.objectId);
prevMods.forEach((mod) => {
// If Mod id exists in newMods we can skip adding it to newMods
if (!Object.keys(newMods).find(key => key === mod.modId)) {
newMods[mod.modId] = availMods.find(am => am.value === mod.modification);
}
// if subId already exists add the mod to that subsection
if (cageMods[mod.location].find(m => m.subId === mod.subId)) {
cageMods[mod.location] = cageMods[mod.location].map(mods => {
if (mods.subId === mod.subId) {
return {
...mods,
modKeys: [...mods.modKeys, {modId: mod.modId, parentModId: mod.parentModId}]
};
}
});
} else {
cageMods[mod.location] = [...cageMods[mod.location], {
subId: mod.subId,
modKeys: [{modId: mod.modId, parentModId: mod.parentModId}]
}];
}
});
}
const newCageId = generateCageId(cageObjId);
const cage: Cage = {
objectId: cageObjId,
svgId: newCageId,
cageNum: `${cageNumType}-${cageNum}` as CageNumber,
extraContext: extraContext?.cage,
selectionType: 'cage',
positionId: cagePositionId,
x: rackItem.xCoord - rack.x - group.x, // get cage coords by subtracting from both rack and group
y: rackItem.yCoord - rack.y - group.y,
size: svgSize,
mods: cageMods
};
newUnitLocs[cageNumType].push({
cageId: newCageId,
cellX: group.x + rack.x + cage.x, // global coords
cellY: group.y + rack.y + cage.y
});
rack.cages.push(cage);
};
const handleRackItem = async (rackItem: FullObjectHistoryData) => {
const rackGroup: RackGroup = findOrAddGroup(rackItem);
const rack: Rack = await findOrAddRack(rackGroup, rackItem);
await addCageToRack(rack, rackItem, rackGroup);
};
// generates room object state for room objects from layout history data
const generateRoomObj = (roomObjItem: FullObjectHistoryData): RoomObject => {
let context;
if (roomObjItem.extraContext) {
context = JSON.parse(roomObjItem.extraContext);
}
return ({
itemId: `${roomItemToString(roomObjItem.objectType)}-${roomObjNum++}`, // update room obj num after it is used to next num
type: roomObjItem.objectType as RoomObjectTypes,
selectionType: 'obj',
x: roomObjItem.xCoord,
y: roomObjItem.yCoord,
scale: prevRoom.layoutData.scale,
extraContext: context
});
};
for (const roomItem of prevRoom.cagingData) {
if (isRackEnum(roomItem.objectType)) { // Room item is an enclosure for animals
await handleRackItem(roomItem);
} else { // Room item is something else in the room, ex. Door
newLocalRoom.objects.push(generateRoomObj(roomItem));
}
}
newLocalRoom.mods = newMods;
return ([newLocalRoom, newUnitLocs]);
};
// Sadly we kind of have to hard code this function.
export const getAdjLocation = (loc: ModLocations): ModLocations => {
switch (loc) {
case ModLocations.Left:
return ModLocations.Right;
case ModLocations.Right:
return ModLocations.Left;
case ModLocations.Top:
return ModLocations.Bottom;
case ModLocations.Bottom:
return ModLocations.Top;
default:
return ModLocations.Direct;
}
};
export const getDefaultMod = (loc: ModLocations): ModTypes | null => {
if (loc === ModLocations.Top || loc === ModLocations.Bottom) {
return ModTypes.StandardFloor;
}
if (loc === ModLocations.Left || loc === ModLocations.Right) {
return ModTypes.SolidDivider;
}
return null;
};
function getGlobalPosition(box: Cage, rack: Rack, group?: RackGroup): { x: number; y: number } {
// Calculate the global position of the box
let x;
let y;
if (group) {
x = group.x + rack.x + box.x;
y = group.y + rack.y + box.y;
} else {
x = rack.x + box.x;
y = rack.y + box.y;
}
return {
x: x,
y: y,
};
}
// Helper: robust float comparison
const EPS = 0.0001;
// Helper: clamp intersection range along one axis
function getOverlapRange(aStart: number, aEnd: number, bStart: number, bEnd: number): {
start: number;
end: number
} | null {
const start = Math.max(aStart, bStart);
const end = Math.min(aEnd, bEnd);
return end - start > EPS ? {start, end} : null;
}
// Helper: compute which segment indices intersect an overlap range.
// sideLenPx: total length in px of the side (height for left/right; width for top/bottom)
// numSections: number of polyline segments on that side (from UnitType.sides[side].sections)
// localStartPx/localEndPx: overlap range relative to the cage's local side start (0..sideLenPx)
function getIntersectingSectionIndices(
sideLenPx: number,
numSections: number,
localStartPx: number,
localEndPx: number
): number[] {
if (numSections <= 0) {
return [];
}
if (sideLenPx <= 0) {
return [];
}
const segLen = sideLenPx / numSections;
const indices: number[] = [];
// Find first and last segments that have any overlap with [localStartPx, localEndPx]
// We expand slightly by EPS to avoid precision misses on boundaries.
const firstIdx = Math.max(0, Math.floor((localStartPx - EPS) / segLen));
const lastIdx = Math.min(numSections - 1, Math.floor((localEndPx - EPS) / segLen));
for (let i = firstIdx; i <= lastIdx; i++) {
const segStart = i * segLen;
const segEnd = segStart + segLen;
if (segEnd > localStartPx + EPS && segStart < localEndPx - EPS) {
indices.push(i);
}
}
return indices;
}
// Helper: build side-id strings (e.g., "left-2") from indices (0-based -> 1-based)
function buildSideIds(sideName: 'left' | 'right' | 'top' | 'bottom', indices: number[]): string[] {
// ensure unique & sorted
const uniqSorted = Array.from(new Set(indices)).sort((a, b) => a - b);
return uniqSorted.map(i => `${sideName}-${i + 1}`);
}
function areAdjacent(
currCage: Cage,
currRack: Rack,
adjCage: Cage,
adjRack: Rack,
rotation: GroupRotation,
group?: RackGroup
): {
location: ModLocations | null,
currLines: string[],
adjLines: string[]
} {
const cellSize = CELL_SIZE;
// Global positions (top-left of each cage in px)
const currGlobalPos = getGlobalPosition(currCage, currRack, group);
const adjGlobalPos = getGlobalPosition(adjCage, adjRack, group);
// Cages are squares of size "cage.size" cells
const width1 = currCage.size * cellSize;
const height1 = width1;
const width2 = adjCage.size * cellSize;
const height2 = width2;
// Box edges
const left1 = currGlobalPos.x;
const right1 = currGlobalPos.x + width1;
const top1 = currGlobalPos.y;
const bottom1 = currGlobalPos.y + height1;
const left2 = adjGlobalPos.x;
const right2 = adjGlobalPos.x + width2;
const top2 = adjGlobalPos.y;
const bottom2 = adjGlobalPos.y + height2;
// Section counts per side from UnitType
const currSides = currCage.size / 4;
const adjSides = adjCage.size / 4;
// Early guard