-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVisualEditor.js
More file actions
2193 lines (2102 loc) · 67.1 KB
/
VisualEditor.js
File metadata and controls
2193 lines (2102 loc) · 67.1 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
/**
* Manages logic related to item selection.
*/
class VisualEditorSelection
{
/**
* This contains the actual selected items.
*/
selection = [];
/**
* Creates a new selection object.
*/
construct()
{
this.selection = [];
}
/**
* Adds items to the selection.
* @param {Array} items - items to be added
* @param {boolean} fireEvent - fires the SelectionChange event in the editor.
*/
add(items, fireEvent = true)
{
// first, remove the items to be added in case any are already in the selection
// explicitly do not fire the event
this.remove(items, false);
// add the items to the array
this.selection.push(...items);
// fire the event if requested
if(fireEvent)
VisualEditor.triggerSelectionChange();
}
/**
* Removes items from the selection.
* @param {Array} items - Items to be removed.
* @param {boolean} fireEvent - fires the SelectionChange event in the editor.
*/
remove(items, fireEvent = true)
{
// exclude items to be removed from the selection and set the new selection
this.selection = this.selection.filter(item=>!items.includes(item));
// fire the event if requested
if(fireEvent)
VisualEditor.triggerSelectionChange();
}
/**
* Empties the selection.
* @param {boolean} fireEvent - fires the SelectionChange event in the editor.
*/
clear(fireEvent = true)
{
this.selection = [];
// fire the event if requested.
if(fireEvent)
VisualEditor.triggerSelectionChange();
}
/**
* Replaces the selection with the given items.
* @param {Array} items - Items for the selection to contain.
* @param {boolean} fireEvent - fires the SelectionChange event in the editor.
*/
set(items, fireEvent = true)
{
// empty out the selection
this.clear(false);
// add the new items
this.add(items, false);
// fire the event if requested.
if(fireEvent)
VisualEditor.triggerSelectionChange();
}
}
class VisualEditor
{
/**
* Main edit modes.
*/
static EDIT_MODES = {POINTER: 0, WIRE: 1, LINK: 2, CODE: 3, INVENTORY: 4};
/**
* Submodes applicable to main edit modes.
*/
static SUB_MODES = {NONE: 0,
WIRE_MOVE: 1, WIRE_ADD: 2, WIRE_REMOVE: 3, WIRE_SELECTED: 4, WIRE_LINE_SELECT: 5,
LINK_END: 6
};
static #offsetX=0;
static #offsetY=0;
/**
Virtual canvas X offset.
*/
static get offsetX()
{
return this.#offsetX;
}
/**
Virtual canvas X offset, forced to integers.
*/
static set offsetX(value)
{
this.#offsetX=Math.round(value);
}
/**
Virtual canvas Y offset.
*/
static get offsetY()
{
return this.#offsetY;
}
/**
Virtual canvas Y offset, forced to integers.
*/
static set offsetY(value)
{
this.#offsetY=Math.round(value);
}
static draggingView = false;
static dragX=0;
static dragY=0;
static zoom = 1;
/**
* Default separator for full item references.
*/
static ITEM_REF_SEPARATOR = "$";
/**
* Current edit mode.
*/
static editMode = this.EDIT_MODES.POINTER;
/**
* Current submode.
*/
static subMode = this.SUB_MODES.NONE;
/**
* Indicates whether the Ctrl key is currently down.
*/
static ctrl = false;
/**
* Indicates whether the Shift key is currently down.
*/
static shift = false;
/**
* Indicates whether the mouse button is currently down.
*/
static mouseDownNow = false;
static mouseDownPrev = false;
/**
* Keeps track of the item currently selected out of multiple
* under the mouse.
*/
static currentDepth = 0;
/**
* Keeps track of currently selected objects in the editor.
*/
static currentSelection = new VisualEditorSelection();
/**
* Keeps track of currently highlighted (for example, by hovering) objects in the editor.
*/
static #highligthed = [];
static get currentHightlight()
{
return this.#highligthed;
}
static set currentHightlight(value)
{
this.#highligthed=value;
this.highlightLayer.canvas.title="";
if(value.length!=0)
{
this.highlightLayer.canvas.title=value.length>1?"Multiple items":value[0].getLabel();
}
}
/*
HW editor stuff
*/
static hwDisplay = null;
static hwBox = null;
static hwFrameList = null;
static hwBankList = null;
static hwConnectorList = null;
static hwCurrentItem = null;
static hwCurrentHighLight = null;
static hwElements = null;
static hwElementProps = null;
/**
* If exactly one item is selected, contains the item.
*/
static currentSingleItem = null;
/**
* If exactly one item is selected, contains the item's type.
*/
static currentSingleType = "";
/**
* Contains an object currently being moved by the mouse.
*/
static currentMoving = null;
/**
* X offset of the moved item, used to align the item to the mouse.
*/
static currentMovingX = 0;
/**
* Y offset of the moved item, used to align the item to the mouse.
*/
static currentMovingY = 0;
/**
* An object containing all "fixed" hardware, starting with Locations.
*/
static fixedMap = null;
/**
* An object containing all "movable" hardware, starting with Lines.
*/
static lineMap = null;
/**
* An object containing all hardware components available for use.
*/
static inventory = null;
/**
* A canvas used for rendering the items in the visual view.
*/
static mapLayer = null;
/**
* A canvas used for rendering highlight and selection outlines in the visual view.
*/
static highlightLayer = null;
/**
* A HTML element where the tree view will be displayed and updated.
*/
static treeViewContainer = null;
/**
* A HTML element where item property sheets will be displayed.
*/
static propSheetContainer = null;
/**
* A HTML element containing the visual view.
*/
static mouseArea = null;
/**
* A HTML element containing the toolbar buttons.
*/
static toolBar = null;
static templates={};
static dialogs={};
/**
* Contains the data: URL for the frame pre-render.
*/
static framePreRenderSrc ="";
static frameTypeRegistry = {};
static screenToCanvas(x,y)
{
return [(x-this.offsetX)/this.zoom,(y-this.offsetY)/this.zoom];
}
/**
* Checks if any registered component hitboxes intersect a given coordinate.
* @param {number} x - X coordinate
* @param {number} y - Y coordinate
* @param {boolean} onlyTopLevel - if true, only results with the highest selection priority will be returned
* @returns a list of components intersecting the coordinate.
*/
static getMouseHits(x, y, onlyTopLevel = false)
{
//[x,y] = this.screenToCanvas(x,y);
//console.log(x,y);
let results = VisualItem.hitboxMapping.filter(box=>{return box.hitbox.contains(x, y)});
results = results.filter(box=>box.item.testHit(x, y) && !box.item.collapseView);
results.sort((a, b)=>b.level-a.level);
if(results && onlyTopLevel)
{
results = results.filter(box=>box.level == results[0].level);
}
let hits = [];
results.forEach(box=>hits.push(box.item));
return hits;
}
/**
* Fetches all individual entries in the tree view pane.
* @returns {Array} - an array (possibly empty) of all items in the tree view pane.
*/
static getTreeItems()
{
return this.treeViewContainer ? this.treeViewContainer.querySelectorAll("span.tree_item_name") : [];
}
/**
* Loads hardware inventory (frame templates, connectors etc)
* @param {*} inventory
*/
static loadInventory(inventory)
{
VisualEditor.inventory = inventory;
// console.log(VisualEditor.inventory.subItems);
let frames = VisualEditor.inventory.subItems.filter(vi=>vi.type=="frame_tpl");
//console.log(frames);
// render all frame types into an image for dialog boxes
// #TODO use these prerenders in the interface
let framerenders = document.createElement("canvas");
framerenders.width = DIM_FRAME_WIDTH;
framerenders.height=DIM_FRAME_HEIGHT * (frames.length)
framerenders.id="framelist";
let ctx1 = framerenders.getContext("2d");
for(let i=0;i<frames.length;i++)
{
let f = new VisualFrame(inventory, " ");
f.label =" ";
f.frametype=frames[i].name;
f.commit(VisualEditor);
//f.updateSize();
f.cY=DIM_FRAME_HEIGHT *i-2;
f.cX=(-1 * DIM_FRAME_SIDES);
f.subItems.forEach((sub)=>{sub.updatePosition()});
f.drawTop(ctx1);
//console.log(f);
VisualEditor.frameTypeRegistry[frames[i].name] = {"index": i, "desc": frames[i].label};
}
VisualEditor.framePreRenderSrc = framerenders.toDataURL("png");
//VisualEditor.dialogs.addFrame.querySelector("#framelist").replaceWith(framerenders);
}
static initInventoryEditor()
{
VisualEditor.inventory.subItems.forEach((component)=>{
let list;
let number=0;
switch(component.type)
{
case "frame_tpl":
{
list=VisualEditor.hwFrameList;
number = VisualEditor.inventory.frameUsages[component.name] ?? 0;
break;
}
case "socket_tpl":
{
number = VisualEditor.inventory.conUsagesInventory[component.name] ?? 0;
list = VisualEditor.hwConnectorList;
break;
}
case "socket_bank":
{
number = VisualEditor.inventory.bankUsagesInventory[component.name] ?? 0;
list = VisualEditor.hwBankList;
break;
}
}
if(list)
{
let li=document.createElement("li");
let bbbb = document.createElement("strong");
bbbb.style.display="inline-block";
bbbb.style.width="2rem";
bbbb.style.paddingRight="1rem";
bbbb.append(number);
li.appendChild(bbbb);
li.append(component.name);
li.dataset.itemref=component.getFullName();
li.addEventListener("click",(e)=>{
VisualEditor.hwCurrentHighLight=null;
VisualEditor.updateHwCurrent(component.createClonedView(component.parent));
// console.log(VisualEditor.hwCurrentItem);
})
list.appendChild(li);
}
else
{
console.log(component);
}
});
}
static redrawHwDisplay()
{
let component = VisualEditor.hwCurrentItem;
VisualEditor.hwDisplay.resetTransform();
VisualEditor.hwDisplay.scale(2,2);
VisualEditor.hwDisplay.clearRect(0,0,640,72);
VisualEditor.hwDisplay.translate(5,0);
component.counter=0;
component.draw(VisualEditor.hwDisplay);
if(VisualEditor.hwCurrentHighLight)
{
VisualEditor.hwDisplay.strokeStyle="#FF0000";
// VisualEditor.hwD
let x=VisualEditor.hwCurrentHighLight.x;
let y=VisualEditor.hwCurrentHighLight.y;
let w=VisualEditor.hwCurrentHighLight.width;
let h=VisualEditor.hwCurrentHighLight.height;
VisualEditor.hwDisplay.strokeRect(x,y,w,h);
}
VisualEditor.hwDisplay.translate(-5,0);
VisualEditor.hwDisplay.lineWidth=1;
VisualEditor.hwDisplay.strokeStyle="#000000";
VisualEditor.hwDisplay.strokeRect(1,1,318,34);
}
static updateHwCurrent(component)
{
VisualEditor.hwCurrentItem = component;
this.redrawHwDisplay();
// console.log(component);
VisualEditor.hwElements.innerText="";
component.subItems.forEach((e)=>{
VisualEditor.hwElements.appendChild(VisualEditor.hwElementLine(e));
});
if(component.subItems.length==0 && component.type!="socket_tpl")
{
let b = document.createElement("button");
b.append("Add component");
b.addEventListener("click",VisualEditor.hwMakeInsert(component,0));
VisualEditor.hwElements.appendChild(b);
}
let props=VisualEditor.hwElementProps;
props.innerText="";
if(component.renderer)
{
let txtbox=document.createElement("textarea");
txtbox.style.width="100%";
txtbox.style.height="90%";
txtbox.value=component.renderer.toCode(0);
props.appendChild(txtbox);
let c_butt=document.createElement("button");
c_butt.style.width="100%";
c_butt.style.height="5%";
c_butt.append("Compile");
c_butt.addEventListener("click",(ev)=>{
// hijack the inventory parser
// preload it with a dummy root object
let pp = new VisualParser(txtbox.value,invparser,new VisualTEMPLATE(null,"null"));
pp.init();
// put a nice fresh renderer as the root object
pp.objectStack=[new VisualRenderer(pp.rootObject,"renderer")];
pp.go();
// should be in here
// #TODO: deal with any parsing issues at some point
component.renderer=pp.rootObject.subItems[0];
VisualEditor.updateHwCurrent(component);
});
props.appendChild(c_butt);
}
}
static buildHwPortOptionsEditor(item)
{
let tpl;
let value;
if(item.tpl!=undefined)
{
tpl =VisualEditor.templates['hwElTpl'].content.cloneNode(true);
value = item.tpl;
}
else
{
value = item.counter;
tpl =VisualEditor.templates['hwElCtr'].content.cloneNode(true);
}
let input=tpl.querySelector("#hw_value");
input.value=value;
input.addEventListener("input",(event)=>{
if(item.tpl!=undefined)
{
item.tpl=input.value;
}
else
{
item.counter=input.value;
}
VisualEditor.redrawHwDisplay();
});
return tpl.firstElementChild;
}
static buildHwElementEditor(item)
{
let tpl = VisualEditor.templates['hwElProps'].content.cloneNode(true);
let optlist = tpl.querySelector("#hwelement_id");
let others = VisualEditor.inventory.allOfType(item.type=="bank"?"socket_bank":"socket_tpl");
others.forEach((e)=>{
let opt = document.createElement("option");
opt.append(e.name);
if(e.name==item.ref)
{
opt.selected=true;
}
optlist.appendChild(opt);
});
let inX=tpl.querySelector("#hw_x");
let inY=tpl.querySelector("#hw_y");
inX.value=item.x;
inY.value=item.y;
inX.addEventListener("input",(event)=>{
item.x=Number(inX.value);
item.y=Number(inY.value);
VisualEditor.redrawHwDisplay();
});
inY.addEventListener("input",(event)=>{
item.x=Number(inX.value);
item.y=Number(inY.value);
VisualEditor.redrawHwDisplay();
});
optlist.addEventListener("change",(event)=>{
item.ref=optlist.value;
item.updateSize();
VisualEditor.redrawHwDisplay();
});
return tpl.firstElementChild;
}
static hwHighlightItem(item)
{
VisualEditor.hwCurrentHighLight=item;
VisualEditor.hwElements.childNodes.forEach((c)=>{
if(c.dataset.element==item.name)
{
c.dataset.selected="yes";
}
else
{
c.dataset.selected="no";
}
});
VisualEditor.redrawHwDisplay();
}
static hwElementLine(item)
{
let li;
if(item.type!="port_options")
{
li=VisualEditor.buildHwElementEditor(item);
li.addEventListener("click",(e)=>{
VisualEditor.hwHighlightItem(item);
// console.log(item);
});
}
else
{
li=VisualEditor.buildHwPortOptionsEditor(item);
}
VisualEditor.hwDoLineButtons(li,item);
li.dataset.element=item.name;
return li;
}
static hwMakeInsert(target_item, index)
{
return (ev)=>{
let dlg = VisualEditor.dialogs.addHwElement;
dlg.querySelector("#hw_element_counter_value").value=1;
dlg.querySelector("#hw_element_template_value").value="";
let optlist = dlg.querySelector("#hw_element_listbox");
optlist.innerText="";
let types=['socket_tpl'];
if(target_item.type=="frame_tpl")
{
types.push("socket_bank");
}
let others = VisualEditor.inventory.allOfTypes(types);
others.forEach((e)=>{
let opt = document.createElement("option");
opt.append(e.name);
optlist.appendChild(opt);
});
dlg.addEventListener("close",(event)=>{
if(dlg.returnValue!="")
{
let selectedItem=VisualEditor.inventory.find(dlg.returnValue);
let newItem;
let type=dlg.querySelector("input[name=hw_new_element_type]:checked").value;
switch(type)
{
case "component":
{
if(selectedItem.type=="socket_tpl")
{
newItem = new VisualConnectorPlacement(target_item,"c_"+target_item.getNextPrefixedSlot("c_"));
}
if(selectedItem.type=="socket_bank")
{
newItem = new VisualBankPlacement(target_item,"c_"+target_item.getNextPrefixedSlot("c_"));
}
newItem.ref=dlg.returnValue;
break;
}
case "counter":
{
let ctr=dlg.querySelector("#hw_element_counter_value").value;
newItem= new VisualPortOptions(target_item,"c_"+target_item.getNextPrefixedSlot("c_"));
newItem.counter=Number(ctr);
break;
}
case "template":
{
let tpl=dlg.querySelector("#hw_element_template_value").value;
tpl=tpl.trim();
if(tpl=="")
return;
newItem= new VisualPortOptions(target_item,"c_"+target_item.getNextPrefixedSlot("c_"));
newItem.tpl=tpl;
break;
}
}
target_item.insertAt(index,newItem);
target_item.updateSize();
VisualEditor.updateHwCurrent(target_item);
console.log(target_item);
}
},{once:true});
dlg.showModal();
};
}
static hwDoLineButtons(row,item)
{
let up=row.querySelector("#hw_moveup");
let dn=row.querySelector("#hw_movedn");
let iup=row.querySelector("#hw_insup");
let idn=row.querySelector("#hw_insdn");
let rm=row.querySelector("#hw_remove");
let index = item.parent.indexOf(item);
let pp=item.parent;
if(index==0)
{
up.parentElement.removeChild(up);
}
else
{
up.addEventListener("click",(e)=>{
pp.removeItem(item);
pp.insertAt(index-1, item);
VisualEditor.updateHwCurrent(pp);
});
}
if(index==pp.subItems.length-1)
{
dn.parentElement.removeChild(dn);
}
else
{
dn.addEventListener("click",(e)=>{
pp.removeItem(item);
pp.insertAt(index+1, item);
VisualEditor.updateHwCurrent(pp);
});
}
iup.addEventListener("click",VisualEditor.hwMakeInsert(pp,index+1));
idn.addEventListener("click",VisualEditor.hwMakeInsert(pp,index));
rm.addEventListener("click",(ev)=>{
pp.removeItem(item);
VisualEditor.hwCurrentHighLight=null;
VisualEditor.updateHwCurrent(pp);
// this is needed to prevent the click event on the row with the item firing
// and highlighting the nonexistent item
ev.stopPropagation();
});
}
static generateFramePreviewSprite(index, tagname="div")
{
let el = document.createElement(tagname);
el.style.backgroundImage="url(" + VisualEditor.framePreRenderSrc + ")";
el.style.width = DIM_FRAME_WIDTH+"px";
el.style.height= DIM_FRAME_HEIGHT+"px";
el.style.position="relative";
el.style.backgroundPositionX=0;
el.style.backgroundPositionY= index * -1 * DIM_FRAME_HEIGHT+"px";
return el;
}
/**
* Refreshes the highlight and selection outlines in both the visual view and the tree view.
*/
static redrawSelection()
{
// draw on the layer used for selections
const ctx = VisualEditor.highlightLayer;
ctx.resetTransform();
ctx.clearRect(0,0,5000,5000);
ctx.translate(VisualEditor.offsetX,VisualEditor.offsetY);
ctx.scale(VisualEditor.zoom,VisualEditor.zoom);
// line styles for highlights
let selectionOutline = {
strokeStyle : "rgb(255 0 0 / 80%)",
lineWidth: 5
};
let highlighter1 = {
strokeStyle : "red",
lineWidth: 3
};
let highlighter2 = {
strokeStyle :"rgb(255 0 0 / 30%)",
lineWidth: 3
};
// process selection
let itemIDs = [];
if(VisualEditor.currentSelection)
{
VisualEditor.currentSelection.selection.forEach((box)=>{
// render the item on this layer to make it more visible
box.drawTop(ctx);
// render this item's defined highlight (outline of item and possibly related items)
box.drawHighlight(ctx, selectionOutline);
// collect the item's full name to update the tree view
itemIDs.push(box.getFullName(VisualEditor.ITEM_REF_SEPARATOR));
});
// update the tree view with the collected items
VisualEditor.getTreeItems().forEach((item)=>{
// get a given entry's item reference
let objid = item.dataset.itemref;
// mark as selected if found,
if(itemIDs.find(id=>id==objid))
{
item.classList.add("selected");
}
// remove marking otherwise
else
{
item.classList.remove("selected");
}
});
}
// process highlights
itemIDs = [];
if(VisualEditor.currentHightlight)
{
VisualEditor.currentHightlight.forEach((box)=>{
// render this item's defined highlight (outline of item and possibly related items)
box.drawHighlight(ctx, highlighter1);
// collect the item's full name to update the tree view
itemIDs.push(box.getFullName(VisualEditor.ITEM_REF_SEPARATOR));
});
// update the tree view with the collected items
VisualEditor.getTreeItems().forEach((item)=>{
// get a given entry's item reference
let objid = item.dataset.itemref;
// mark as highlighted if found,
if(itemIDs.find(id=>id==objid))
{
item.classList.add("highlighted");
}
// remove marking otherwise
else
{
item.classList.remove("highlighted");
}
});
}
}
/**
* Performs a full redraw of all items on the visual view.
*/
static redrawItems()
{
// use the object/item layer
const ctx = VisualEditor.mapLayer;
ctx.resetTransform();
ctx.clearRect(0,0,5000,5000);
ctx.translate(VisualEditor.offsetX,VisualEditor.offsetY);
ctx.scale(VisualEditor.zoom,VisualEditor.zoom);
VisualEditor.drawCallCount=0;
// draw the "fixed" items (locations, racks etc)
VisualEditor.fixedMap.draw(ctx);
//console.log("Equipment draw calls: " + VisualEditor.drawCallCount);
VisualEditor.drawCallCount=0;
// draw the "movable" items (cabling)
VisualEditor.lineMap.draw(ctx);
//console.log("Linemap draw calls: " + VisualEditor.drawCallCount);
VisualEditor.drawCallCount=0;
// draw collapsed items
VisualEditor.fixedMap.drawCollapsed(ctx);
//console.log("Collapsed draw calls: " + VisualEditor.drawCallCount);
VisualEditor.drawCallCount=0;
}
/**
* Performs a complete refresh of all displays and item properties.
*/
static refreshView()
{
VisualEditor.redrawItems();
VisualItem.hitboxMapping = [];
VisualEditor.lineMap.updateSize();
VisualEditor.lineMap.updatePosition();
VisualEditor.lineMap.updateHitboxMapping();
VisualEditor.fixedMap.updateSize();
VisualEditor.fixedMap.updatePosition();
VisualEditor.fixedMap.updateHitboxMapping();
VisualEditor.redrawSelection()
}
/**
* Sets the current selection to a specific @type {VisualLine}.
* @param {string} name - name of the line to be selected. Silently fails if line not found.
*/
static selectLine(name)
{
const line = VisualEditor.lineMap.find(name);
// if the line is found, select it
if(line)
{
VisualEditor.currentSelection.set([line]);
VisualEditor.redrawSelection();
}
// else complain, but very quietly
else
{
console.log("Line <%s> was not found when trying to select it.", name);
}
}
/**
* Performs any tasks relevant to a selection change, and fires the event.
*/
static triggerSelectionChange()
{
// for contextual actions requiring a specific item type to be selected
if(VisualEditor.currentSelection.selection.length> 0)
{
//console.log("non-empty selection made");
// if exactly one item is selected, set the currentSingle* properties
if(VisualEditor.currentSelection.selection.length === 1)
{
VisualEditor.currentSingleItem = VisualEditor.currentSelection.selection[0];
VisualEditor.currentSingleType = VisualEditor.currentSingleItem.type;
//console.log("exactly one item of type <" + VisualEditor.currentSingleType + "> picked");
this.updateContextTools();
}
// otherwise, clear the currentSingle* properties
else
{
VisualEditor.currentSingleItem = null;
VisualEditor.currentSingleType = "";
}
}
// also clear the currentSingle* properties
else
{
//console.log("selection is empty now");
VisualEditor.currentSingleItem = null;
VisualEditor.currentSingleType = "";
}
// run the user-replaceable function (#TODO: proper event handling? does JS do that?)
this.selectionChange();
}
static updateContextTools()
{
VisualEditor.toolBar.querySelector("#add_line").disabled = VisualEditor.currentSingleType != "socket";
VisualEditor.toolBar.querySelector("#add_frame").disabled = VisualEditor.currentSingleType != "rack";
}
/**
* This is fired if the SelectionChange event is triggered - replace with event handler.
*/
static selectionChange = function()
{
};
/**
* Builds a property sheet for a given item, and inserts it into the sheet container.
* @param {VisualItem} target_object - the subject of the property sheet.
*/
static buildPropSheet(target_object, rebuild = false)
{
// load the template
let tpl = VisualEditor.templates['propSheet'].content.cloneNode(true);
// this reference will be stuck into every single HTML element downstream, for convenience
let itemref = target_object.getFullName();
tpl.firstElementChild.dataset.itemref=itemref;
// the item badge styles itself as needed with CSS
let item_badge = tpl.querySelector(".item_badge");
item_badge.dataset.itemref = itemref;
item_badge.dataset.itemtype = target_object.type;
// the item title is actually an <input>, mimicking as regular text
// this allows for fancy editing on click effect
let item_label = tpl.querySelector(".item_title");
item_label.dataset.itemref = itemref;
item_label.dataset.itemtype = target_object.type;
// while "inactive", displays either the label or the default name
item_label.value = target_object.getLabel();
// set this to the name to show the default if the text field is erased fully
item_label.placeholder = target_object.name;
// when the title is selected, clicked, tabbed to etc, triggering editing
item_label.addEventListener("focus",(e)=>
{
// swap out the value for the actual label, pre-fill with default if empty
item_label.value = target_object.label == "" ? target_object.getLabel() : target_object.label;
// activate editing - the CSS ensures the control is clearly a textbox in this state
item_label.readOnly = false;
});
// extra QoL - pressing Enter also saves the value
item_label.addEventListener("keydown",(e)=>
{
if(e.code == "Enter")
{
item_label.blur();
}
});
// when done editing, navigate away from the textbox or hit Enter
item_label.addEventListener("blur",(e)=>
{
// ensure a clean value without stray spaces gets entered
target_object.label = item_label.value.trim();
// "mask" the input as a regular text label again
item_label.readOnly = true;
// reset the displayed text to the proper labeling as defined by the item
item_label.value = target_object.getLabel();
// notify the editor that an item was changed
VisualEditor.reportUpdate(target_object);
// refresh everything (#TODO: is this really needed for one tiny label?)
VisualEditor.refreshView();
});
// get the reference to the container for any item type specific controls
let sheet = tpl.querySelector(".item_properties");
sheet.dataset.itemref = itemref;
let btn_rename = tpl.querySelector("#id_button");
tpl.querySelector("#item_id").innerText=target_object.name;
btn_rename.addEventListener("click",(e)=>{
VisualEditor.cancellablePrompt((value)=>{
return !target_object.parent?.checkName(value) || value===target_object.name;
},(value)=>{
VisualEditor.reportRename(target_object,value);
VisualEditor.refreshView();
},(value)=>{
return "Bad value <"+value+">";
},"Enter new ID value");
});
// fetch the item's property sheet and display
target_object.getPropSheet().forEach((el)=>sheet.appendChild(el));
// now shove all this stuff into the container
if(rebuild)
{
VisualEditor.propSheetContainer.querySelectorAll(".infoblock").forEach((b)=>{
if(b.dataset.itemref == itemref)
{
b.replaceWith(tpl.firstElementChild);
}
});
}
else
{
VisualEditor.propSheetContainer.appendChild(tpl.firstElementChild);
}
}
static addContextButtons()
{
VisualEditor.checkIfCanCreateGroup();
VisualEditor.checkIfCanAddToGroup();
VisualEditor.checkForCableCreateButton();
}
static checkForCableCreateButton()
{
const sel = VisualEditor.currentSelection.selection;
//console.warn(sel);
// require exactly 2 items
if(sel.length!=2)
return;
//console.log("2 items");
// require both to be frames
if(sel[0].type!="frame" || sel[1].type!="frame")
return;
//console.log("2 frames");
if(VisualEditor.fixedMap.cablesBetween(sel[0],sel[1]).length>0)
{
//console.warn("connected frames");
// #TODO some stuff for existing cable
return;
}
// require no prior cables attached
if(sel[0].getCables().length>0 || sel[1].getCables().length>0)
return;
//console.warn("frames have no cables");
let sheet = VisualEditor.propSheetContainer;
let addbutton = document.createElement("button");
addbutton.addEventListener("click",(e)=>{
VisualEditor.promptName((e)=>{
let cname = VisualEditor.dialogs.newItem.returnValue;
if(!cname)
return;
let c = new VisualCable(VisualEditor.fixedMap,cname);
c.from=sel[0];
c.to=sel[1];
c.commit();
VisualEditor.fixedMap.addItem(c);
VisualEditor.fixedMap.updatePosition();
VisualEditor.refreshView();
},"Cable name","OK");
});
addbutton.append("Create cable");
sheet.appendChild(addbutton);
}