-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircle2.php
More file actions
1736 lines (1354 loc) · 58.2 KB
/
circle2.php
File metadata and controls
1736 lines (1354 loc) · 58.2 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
<?
require_once($_SERVER['DOCUMENT_ROOT']."/config.php");
require_once($_SERVER['DOCUMENT_ROOT']."/shared_functions.php");
// Initialise le login
$connected=checklogin();
?>
<html>
<head>
<!-- D3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://d3js.org/queue.v1.min.js"></script>
<!-- stats -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r14/Stats.js"></script>
<?writeHeadContent(T_("Dessinez votre organization !"),"EasyCIRCLE");?>
<!-- Script spécifique à la page -->
<script>
let root;
var canvas, hiddenCanvas, context, hiddenContext;
var node = null;
var centerX = centerY = null;
var zoomInfo = null;
var pack;
var nodes;
var nodeByName;
var mobileSize;
var diameter;
var mainTextColor
var colorCircle;
var colorBarmeter;
var commaFormat;
var elementsPerBar;
var showText;
var padding;
var chartwidth;
var chartheight;
var colToCircle;
var currentnode = null;
var hoverNode=null;
var localStorageName="circlestructure";
var nodeOld;
//Default values for variables - set to root
var currentID = "",
oldID = "";
var ease;
var timeElapsed = 0;
var interpolator = null;
var duration = 500;
var vOld;
// Supprime les références circulaires dans un objet, pour pouvoir le convertir en XML
function removeCircularReferences(obj, seen = new WeakSet()) { if (obj && typeof obj === 'object') { if (seen.has(obj)) { return; } seen.add(obj); for (const key in obj) { if (obj.hasOwnProperty(key)) { obj[key] = removeCircularReferences(obj[key], seen); } } } return obj; }
function drawText(ctx, text, fontSize, titleFont, centerX, centerY, radius, fillcolor="#000", strockcolor="#FFF",style="",font="Tahoma") {
// startAngle: In degrees, Where the text will be shown. 0 degrees if the top of the circle
// kearning: 0 for normal gap between letters. Positive or negative number to expand/compact gap in pixels
if (fontSize<6) return; // Inutile d'afficher
if (fontSize<12) fontSize=12; // Taille min (même si ça dépasse)
//Setup letters and positioning
ctx.textBaseline = 'alphabetic';
ctx.textAlign = 'center'; // Ensure we draw in exact center
ctx.fillStyle = fillcolor;
ctx.strokeStyle = strockcolor;
ctx.lineWidth = 5;
ctx.setLineDash([]);
ctx.lineJoin = 'round';
ctx.font = style+" "+fontSize+"pt '"+font+"'";
//Get the text back in pieces that will fit inside the node
var titleText = getLines(ctx, text, radius*2*0.7, fontSize, font);
// Décortique l'objet retourné
fontSize=titleText.fontSize;
titleText=titleText.lines;
if (fontSize<6) return; // Si après adaptation, c'est trop petit...
if (fontSize<12) fontSize=12; // Taille min (même si ça dépasse)
ctx.font = style+" "+fontSize+"pt '"+font+"'";
//Loop over all the pieces and draw each line
cpt=0;
titleText.forEach(function(txt, iterator) {
if (cpt<4) {
if (cpt==3) txt="...";
ctx.textBaseline = "middle";
ctx.strokeText(txt, centerX, centerY + ((-Math.min(titleText.length,4)/2)+iterator+0.5)*fontSize*1.1);
ctx.fillText(txt, centerX, centerY + ((-Math.min(titleText.length,4)/2)+iterator+0.5)*fontSize*1.1 );
}
cpt+=1;
})//forEach
}
//Adjusted from: http://blog.graphicsgen.com/2015/03/html5-canvas-rounded-text.html
function drawCircularText(ctx, text, fontSize, fontBold, titleFont, centerX, centerY, radius, startAngle, kerning) {
// startAngle: In degrees, Where the text will be shown. 0 degrees if the top of the circle
// kearning: 0 for normal gap between letters. Positive or negative number to expand/compact gap in pixels
//Setup letters and positioning
ctx.textBaseline = 'alphabetic';
ctx.textAlign = 'center'; // Ensure we draw in exact center
ctx.font = fontBold+" "+fontSize + "pt " + titleFont;
ctx.fillStyle = "rgba(255,255,255," + textAlpha +")";
startAngle = startAngle * (Math.PI / 180); // convert to radians
text = text.split("").reverse().join(""); // Reverse letters
//Rotate 50% of total angle for center alignment
for (var j = 0; j < text.length; j++) {
var charWid = ctx.measureText(text[j]).width;
startAngle += ((charWid + (j == text.length-1 ? 0 : kerning)) / radius) / 2;
}//for j
ctx.save(); //Save the default state before doing any transformations
ctx.translate(centerX, centerY); // Move to center
ctx.rotate(startAngle); //Rotate into final start position
//Now for the fun bit: draw, rotate, and repeat
for (var j = 0; j < text.length; j++) {
var charWid = ctx.measureText(text[j]).width/2; // half letter
//Rotate half letter
ctx.rotate(-charWid/radius);
//Draw the character at "top" or "bottom" depending on inward or outward facing
ctx.fillText(text[j], 0, -radius);
//Rotate half letter
//ctx.rotate(-0.1);
ctx.rotate(-(charWid + kerning ) / radius);
}//for j
ctx.restore(); //Restore to state as it was before transformations
}//function drawCircularText
//The draw function of the canvas that gets called on each frame
function drawCanvas(chosenContext, hidden) {
function drawPolygon(ctx, x, y, radius, sides) {
if (sides < 3) return; // Un polygone a au moins 3 côtés
ctx.beginPath();
// Tracer chaque sommet du polygone
for (let i = 0; i <= sides; i++) {
const angle = (2 * Math.PI / sides) * i; // Diviser le cercle en "sides" parties
const px = x + radius * Math.cos(angle);
const py = y + radius * Math.sin(angle);
if (i === 0) {
ctx.moveTo(px, py); // Début du polygone
} else {
ctx.lineTo(px, py); // Ligne vers le sommet suivant
}
}
ctx.closePath(); // Fermer le chemin pour relier le dernier sommet au premier
ctx.stroke(); // Tracer le contour
}
//Clear canvas
chosenContext.fillStyle = "#eee";
chosenContext.rect(0,0,chartwidth,chartheight);
chosenContext.fill();
let nodeCpt=0;
// It's slightly faster than nodes.forEach()
for (var i = 0; i < nodeCount; i++) {
node = nodes[i];
var nodeX = ((node.x - zoomInfo.centerX) * zoomInfo.scale) + centerX,
nodeY = ((node.y - zoomInfo.centerY) * zoomInfo.scale) + centerY,
nodeR = node.r * zoomInfo.scale * (node.type=="1"?0.9:(node.type=="4"?1.05:1));
//Use one node to reset the scale factor for the legend
if(i === 0) scaleFactor = node.value/(nodeR * nodeR);
//Draw each circle
if (node.mod=="hierarchy")
drawPolygon(chosenContext, nodeX, nodeY, nodeR, 8);
else {
chosenContext.beginPath();
chosenContext.arc(nodeX, nodeY, nodeR, 0, 2 * Math.PI, true);
}
//If the hidden canvas was send into this function and it does not yet have a color, generate a unique one
if(hidden) {
if(node.color == null) {
// If we have never drawn the node to the hidden canvas get a new color for it and put it in the dictionary.
node.color = genColor();
colToCircle[node.color] = node;
} else {
colToCircle[node.color] = node;
}//if
// On the hidden canvas each rectangle gets a unique color.
chosenContext.fillStyle = node.color;
chosenContext.fill();
} else {
// anciennement node.children
chosenContext.fillStyle = node.type=="3" || node.type=="2" ? colorCircle(node.depth) : (node.mycolor?node.mycolor:"rgb(255, 204, 0)"); // Couleur des noeuds
if (node.type && node.type=="3") {chosenContext.fillStyle="rgba(0,0,0,0)";}
if (node.type=="4") {
chosenContext.lineWidth = 1;
//chosenContext.setLineDash([10, 10]);
chosenContext.strokeStyle= "rgba(255,255,255,0.5)"
chosenContext.stroke();
chosenContext.fillStyle="rgb(61, 168, 169)";
chosenContext.fill();
} else
if (node.type=="3") {
chosenContext.lineWidth = 2;
chosenContext.setLineDash([10, 10]);
chosenContext.strokeStyle= "rgba(255,255,255,0.5)"
chosenContext.stroke();
chosenContext.fill();
} else {
chosenContext.fill();
if (node.mod=="template") {
var pattern = chosenContext.createPattern(pattern_img,'repeat');
chosenContext.fillStyle=pattern;
chosenContext.fill();
}
}
// Current node layout
if (node.ID==currentnode.ID) {
chosenContext.lineWidth = 6;
chosenContext.setLineDash([]);
chosenContext.strokeStyle= "rgba(255,255,255,1)";
chosenContext.stroke();
} else
// Hover layout
if (node.ID==hoverNode) {
chosenContext.lineWidth = 3;
chosenContext.setLineDash([]);
chosenContext.strokeStyle= "rgba(255,255,255,1)";
chosenContext.stroke();
}
}//else
//Draw the bars inside the circles (only in the visible canvas)
//Only draw bars in leaf nodes
// Not used for now...
/* if(!node.children && 1!=1) {
//Only draw the bars that are in the same parent ID as the clicked on node
if(node.ID.lastIndexOf(currentID, 0) === 0 & !hidden) {
//if(node.ID === "1.1.1.30") console.log(currentID);
//Variables for the bar title
var drawTitle = true;
var fontSizeTitle = Math.round(nodeR / 10);
if (fontSizeTitle < 8) drawTitle = false;
//Only draw the title if the font size is big enough
if(drawTitle & showText) {
//First the light grey total text
chosenContext.font = (fontSizeTitle*0.5 <= 5 ? 0 : Math.round(fontSizeTitle*0.5)) + "pt " + bodyFont;
chosenContext.fillStyle = "rgba(0,0,0," + (0.5*textAlpha) +")" //"#BFBFBF";
chosenContext.textAlign = "center";
chosenContext.textBaseline = "middle";
chosenContext.fillText("Total "+commaFormat(node.size)+" (in thousands)", nodeX, nodeY + -0.75 * nodeR);
//Get the text back in pieces that will fit inside the node
var titleText = getLines(chosenContext, node.name, nodeR*2*0.7, fontSizeTitle, titleFont);
//Loop over all the pieces and draw each line
titleText.forEach(function(txt, iterator) {
chosenContext.font = fontSizeTitle + "pt " + titleFont;
chosenContext.fillStyle = "rgba(" + mainTextColor[0] + "," + mainTextColor[1] + ","+ mainTextColor[2] + "," + textAlpha +")";
chosenContext.textAlign = "center";
chosenContext.textBaseline = "middle";
chosenContext.fillText(txt, nodeX, nodeY + (-0.65 + iterator*0.125) * nodeR);
})//forEach
}//if
}//if -> node.ID.lastIndexOf(currentID, 0) === 0 & !hidden
} */ //if -> node.ID in dataById
}//for i
//Do a second loop because the arc titles always have to be drawn on top
for (var i = nodeCount-1; i >=0; i--) {
node = nodes[i];
var nodeX = ((node.x - zoomInfo.centerX) * zoomInfo.scale) + centerX,
nodeY = ((node.y - zoomInfo.centerY) * zoomInfo.scale) + centerY,
nodeR = node.r * zoomInfo.scale * (node.type=="1"?0.9:(node.type=="4"?1.05:1));
titleFont="Arial";
if(!hidden & showText & (node.ID==currentnode.ID || node.parent==currentnode || (node.parent && node.parent.parent==currentnode) || ((currentnode.parent && (currentnode.type!="2" || currentnode.parent.children.length>1)) && (node.ID==currentnode.parent.ID || (node.parent && node.parent.ID==currentnode.parent.ID)) ))) {
//Calculate the best font size for the non-leaf nodes
if (node.type != "1" && node==currentnode || currentnode.parent==node) {
var fontSizeTitle = Math.round(nodeR / 6);
if (fontSizeTitle > 4) drawCircularText(chosenContext, node.name.replace(/,? and /g, ' & '), fontSizeTitle, "bold", titleFont, nodeX, nodeY, nodeR, 0, 0); // rotationText[counter] pour le 1er 0
} else {
var fontSizeTitle = Math.round(nodeR / 3);
if (node.type == "1") {
// Limite la taille max pour les rôles, et écrit en noir
if (fontSizeTitle>36) fontSizeTitle=36;
drawText(chosenContext, node.name.replace(/,? and /g, ' & '), fontSizeTitle, titleFont, nodeX, nodeY, nodeR,"#000000","#FFFFFF"); // rotationText[counter] pour le 1er 0
}
else
drawText(chosenContext, node.name.replace(/,? and /g, ' & '), fontSizeTitle, titleFont, nodeX, nodeY, nodeR,"#FFFFFF","#000000","bold"); // rotationText[counter] pour le 1er 0
}
}//if
}//for i
}//function drawCanvas
//Jump to the destination
function quickZoomToCanvas(focusNode) {
//Remove all previous popovers - if present
$('.popoverWrapper').remove();
$('.popover').each(function() {
$('.popover').remove();
});
//Save the ID of the clicked on node (or its parent, if it is a leaf node)
//Only the nodes close to the currentID will have bar charts drawn
if (focusNode === focus) currentID = "";
else currentID = focusNode.ID;
$(".contentleft").load("/circle/detail.php?id="+focusNode.ID);
//Set the new focus
focus = focusNode;
if (focusNode.type=="1" || focusNode.children && focusNode.children.length<2)
var v = [focus.x, focus.y, focus.r * 4.05]; //The center and width of the new "viewport"
else
var v = [focus.x, focus.y, focus.r * 2.05];
zoomInfo.centerX = v[0];
zoomInfo.centerY = v[1];
zoomInfo.scale = diameter / v[2];
drawCanvas(context);
drawCanvas(hiddenContext, true);
vOld = v; //Save the "viewport" of the next state as the next "old" state
}//function zoomToCanvas
// ***********************************
// Script pour l'interface
// ***********************************
// Fonctions appelées après le chargement complet de la page
$(function() {
var mouseoverFunction = function(e){
//Figure out where the mouse click occurred.
var mouseX = e.offsetX*2; //e.layerX;
var mouseY = e.offsetY*2; //e.layerY;
// Get the corresponding pixel color on the hidden canvas and look up the node in our map.
// This will return that pixel's color
var col = hiddenContext.getImageData(mouseX, mouseY, 1, 1).data;
//Our map uses these rgb strings as keys to nodes.
var colString = "rgb(" + col[0] + "," + col[1] + ","+ col[2] + ")";
//console.log (colString);
//console.log(colToCircle);
var node = colToCircle[colString];
//If there was an actual node clicked on, zoom into this
if(node) {
hoverNode=node.ID;
//console.log (hoverNode);
}
drawCanvas(context);
}
//Function to run oif a user clicks on the canvas
var clickFunction = function(e){
if (!wasDragging) {
//Figure out where the mouse click occurred.
var mouseX = e.offsetX*2; //e.layerX;
var mouseY = e.offsetY*2; //e.layerY;
// Get the corresponding pixel color on the hidden canvas and look up the node in our map.
// This will return that pixel's color
var col = hiddenContext.getImageData(mouseX, mouseY, 1, 1).data;
//Our map uses these rgb strings as keys to nodes.
var colString = "rgb(" + col[0] + "," + col[1] + ","+ col[2] + ")";
var node = colToCircle[colString];
//If there was an actual node clicked on, zoom into this
if(node) {
//Perform the zoom
zoomToCanvas(node);
} else {zoomToCanvas(root)}//if -> node
}
}//function clickFunction
//Listen for clicks on the main canvas
//document.getElementById("canvas").addEventListener("click", clickFunction);
$("body").delegate("#canvas","click", clickFunction);
$("body").delegate("#canvas","mousemove",mouseoverFunction);
//////////////////////////////////////////////////////////////
//////////////// Mousemove functionality /////////////////////
//////////////////////////////////////////////////////////////
//Only run this if the user actually has a mouse
//Listen for mouse moves on the main canvas
var mousemoveFunction = function(e){
//Figure out where the mouse click occurred.
var mouseX = e.offsetX*2; //e.layerX;
var mouseY = e.offsetY*2; //e.layerY;
// Get the corresponding pixel color on the hidden canvas and look up the node in our map.
// This will return that pixel's color
var col = hiddenContext.getImageData(mouseX, mouseY, 1, 1).data;
//Our map uses these rgb strings as keys to nodes.
var colString = "rgb(" + col[0] + "," + col[1] + ","+ col[2] + ")";
var node = colToCircle[colString];
//Only change the popover if the user mouses over something new
if(node !== nodeOld || 1) {
//Remove all previous popovers
$('.popoverWrapper').remove();
$('.popover').each(function() {
$('.popover').remove();
});
//Only continue when the user mouses over an actual node
if(node) {
//Only show a popover for the leaf nodes
//if(typeof node.ID !== "undefined") {
//Needed for placement
var nodeX = ((node.x - zoomInfo.centerX) * zoomInfo.scale) + centerX,
nodeY = ((node.y - zoomInfo.centerY) * zoomInfo.scale) + centerY,
nodeR = node.r * zoomInfo.scale;
//Create the wrapper div for the popover
// Anciennement "document"
var div = document.createElement('div');
div.setAttribute('class', 'popoverWrapper');
//document.getElementById('chart').appendChild(div);
$("td.right").eq(0).append(div);
//Position the wrapper right above the circle
$(".popoverWrapper").css({
'position':'absolute',
'top':mouseY/2+20, // -nodeR
'left':mouseX/2+10 //nodeX/2 //+padding*5/4
});
//Show the tooltip
$(".popoverWrapper").popover({
placement: 'auto bottom',
container: 'body',
trigger: 'manual',
html : true,
animation:false,
content: function() {
return "<span class='nodeTooltip'>" + node.name + "</span>"; }
});
$(".popoverWrapper").popover('show');
//}//if -> typeof node.ID !== "undefined"
}//if -> node
}//if -> node !== nodeOld
nodeOld = node;
}//function mousemoveFunction
//document.getElementById("canvas").addEventListener("mousemove", mousemoveFunction);
$("body").delegate("#canvas","mousemove", mousemoveFunction);
// **************************************
// Colonne de gauche
// **************************************
// Adaptation en largeur de la colonne de gauche
$( "#resizeelem" ).draggable({ axis: "x" ,
stop: function(event, ui) {
pos=$(".left").width()+ui.position.left+4;
if (pos<250) pos=250;
console.log("resize:"+pos);
$(".left").css("width",pos);
$( "#resizeelem" ).css("left",0);
refreshCircle(false);
}
});
// ***************************************
// Editeur HTML
// ***************************************
var mytoolbar= [
['style', ['style']],
['font', ['bold', 'italic', 'underline', 'clear']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['insert', ['link', 'picture', 'video']],
['view', ['fullscreen', 'help']],
];
var mystyles= [
'p','h1', 'h2','h3',
{ title: 'Decision', tag: 'div', className: 'monstyledemenu', value: 'h4' },
{ title: 'Tâche/action', tag: 'div', className: 'monstyledemenu', value: 'h5' },
];
// Chargement des données si sauvegardée localement
if (localStorage.savecircle)
load();
<?
// N'intègre pas le code d'édition s'il s'agit d'un lien de partage
if (!isset($_GET["view"])) {
?>
function saveSQL() {
save();
$.ajax({
url: '/ajax/saveorga.php', // Remplacez par l'URL de votre serveur PHP
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(JSON.parse(localStorage.getItem("circlestructure"))),
success: function(response) {
if (response.status === 'ok') { // Vérifiez si le serveur a renvoyé un statut "ok"
// Récupère la nouvelle structure, avec les ID mis à jour
localStorage.setItem(localStorageName, JSON.stringify(response.json));
root=response.json;
refreshCircle(false);refreshCircle(false);
alert('Sauvegarde effectuée !');
} else {
alert('Erreur: ' + response.message);
}
},
error: function(xhr, status, error) {
console.log('Erreur de requête : ', error);
alert('Une erreur est survenue. Veuillez réessayer.');
}
});
}
$("#btn_new").click(function () {
// Crée une nouvelle organisation avec un seul cercle
if (confirm("Voulez-vous réellement créer une nouvelle organisation?\nL'organisation en cours sera remplacée. Créez un compte pour la sauvegarder.") ) {
root=JSON.parse('{"name": "Mon organisation", "ID": "TMP_1", "type": "4", "children": [{"name": "Ancrage", "ID": "TMP_2", "type": "2", "children": [ {"name": "Facilitation", "mycolor":"#FF6600", "ID": "TMP_3","type":"1", "mod":"template", "size":10}, {"name": "Pilotage", "mycolor":"#FF2200", "type":"1", "mod":"template", "ID": "TMP_4", "size":10}, {"name": "Mémoire", "mycolor":"#FF9900", "type":"1", "mod":"template", "ID": "TMP_8", "size":10}, {"name": "Role opérationnel", "type":"1", "ID": "TMP_9", "size":10}]},{"name": "CA", "ID": "TMP_5", "type": "2", "children": [ {"name": "Trésorier", "ID": "TMP_6","type":"1", "size":10}, {"name": "Président", "type":"1", "ID": "TMP_7", "size":10}]}]}');
// Stock sur le disque
localStorage.setItem(localStorageName, JSON.stringify(root));
currentnode=focusNode=root;
// Raffraichi l'affichage
refreshCircle();
}
});
$("#btn_save").click(function () {
saveSQL();
});
$("#btn_load").click(function () {
//loadSQL();
showPopup("/popup/circle/load.php", "<?=T_("Charger un schéma",true)?>");
});
$("#btn_support").click(function () {
showPopup("/popup/support.php", "<?=T_("Soutenez-nous !",true)?>");
});
// Boutons pour manipuler l'holarchie
$("body").delegate("#btn_add_role","click", function () {
showPopup("/popup/circle/addrole.php", "<?=T_("Ajouter un noeud",true)?>");
});
$("body").delegate("#btn_edit_role","click", function () {
showPopup("/popup/circle/editrole.php", "<?=T_("Editer un noeud",true)?>");
});
$("body").delegate("#btn_move_role","click", function () {
showPopup("/popup/circle/moverole.php", "<?=T_("Déplacer un noeud",true)?>");
});
<?
}
?>
function supprimerNoeud(noeud) {
console.log(noeud);
const parent = noeud.parent;
if (parent && Array.isArray(parent.children)) {
// Rechercher l'index du nœud à supprimer dans le tableau Children
const index = parent.children.findIndex(child => child === noeud);
if (index !== -1) {
// Supprimer l'enfant du tableau
parent.children.splice(index, 1);
console.log ("Nouvelle structure");
// Supprimer la référence Parent dans l'enfant pour éviter des cycles
//delete noeud.parent;
return true; // Nœud supprimé avec succès
} else {console.log("pas trouvé");}
} else {console.log("pas de parent");}
return false; // Nœud non trouvé ou parent invalide
}
$("body").delegate("#btn_delete_role","click", function () {
// Se déplace sur le parent
gotoNode=currentnode.parent;
if (confirm("Voulez-vous réellement supprimer ce noeud ?")) {
supprimerNoeud(currentnode);
save();
nodes = pack.nodes(root),
focus = root,
nodeCount = nodes.length;
zoomToCanvas(gotoNode);
}
});
$("body").delegate("#btn_add","click", function () {
alert ("Add");
// Ajoute un élément au noeud courant
console.log("btn_add - CurrentNode");
console.log(currentnode);
if (currentnode) {
currentnode.children.push(JSON.parse('{"name": "Role ajouté", "ID": "50", "size":10}'));
}
;
refreshCircle();
});
// Sauve automatiquement lorsque on quitte les champs d'entête
$("body").delegate(".interface-top input#title2","focusout",function (e) {
root.name=$(this).val();
save();
refreshCircle();
});
function highlightText(text) {
if (text.length<3) {
// Efface tous les éléments
$(".filter_zone").find(".highlight").each(function() {
$(this).replaceWith($(this).text()); // Remplace les balises <span> par leur contenu
});
} else {
var allzone = $(".filter_zone");
allzone.each(function() {
content=$(this);
var regex = new RegExp('(>[^<]*?)(' + text + ')([^<]*?<)', 'gi');
// Efface tous les éléments
content.find(".highlight").each(function() {
$(this).replaceWith($(this).text()); // Remplace les balises <span> par leur contenu
});
var contentHTML = content.html();
content.html(contentHTML.replace(regex, function(match, p1, p2, p3) {
return p1 + '<span class="highlight">' + p2 + '</span>' + p3;
}));
});
}
}
$("body").delegate("#quickfilter","keyup", function () {
// Cache toute les lignes
$(".memo_item").hide();
// Affiche toute les lignes qui contiennent le texte
$('.memo_item:icontains('+$(this).val()+')').show();
highlightText($(this).val())
});
});
// *********************************************************
// Définition des fonction appelées par les boutons
// *********************************************************
function load() {
}
function newDoc() {
}
function save() {
localStorage.setItem(localStorageName, JSON.stringify(removeCircularReferences(root)));
}
$(window).resize(function() {
refreshCircle();
});
</script>
<script>
// Script pour le glisser-déplacer
// Cibler le canvas
let $canvas;
let wasDragging = isDragging = false;
$(document).ready(function() {
let offsetX, offsetY;
$('div#showPanel').click(function () {
const $div = $('td.left');
const isVisible = ($div.css('left') === '0px');
if (isVisible) {
// Calculer dynamiquement la position de fermeture
const closeLeft = `-${$div.outerWidth()}px`;
$div.animate({ left: closeLeft }, 500); // Cache la div
} else {
$div.animate({ left: '0' }, 500); // Montre la div
}
});
// Commencer le déplacement
$("body").delegate("#canvas",'mousedown', function(event) {
$canvas = $('#canvas');
isDragging = true;
// Calculer l'offset initial entre la souris et le coin du canvas
offsetX = event.pageX;
offsetY = event.pageY;
});
// Déplacer le canvas
$(document).on('mousemove', function(event) {
if (isDragging) {
wasDragging=true;
// Essaie de bouger les coordonnées du centre pour dessiner
var v = [vOld[0]+(-event.pageX+offsetX)*2/(diameter / vOld[2]), vOld[1]+(-event.pageY+offsetY)*2/(diameter / vOld[2]), vOld[2]]; //The center and width of the new "viewport"
offsetX = event.pageX;
offsetY = event.pageY;
zoomInfo.centerX = v[0];
zoomInfo.centerY = v[1];
zoomInfo.scale = diameter / v[2];
console.log(diameter / v[2]);
vOld=v;
} else {
wasDragging =false;
}
});
// Arrêter le déplacement
$("body").delegate("#canvas",'mouseout', function(event) {
if (isDragging) {
isDragging = false;
drawCanvas(context);
drawCanvas(hiddenContext, true);
}
$('.popoverWrapper').remove();
$('.popover').each(function() {
$('.popover').remove();
});
});
$(document).on('mouseup', function() {
if (isDragging) {
isDragging = false;
drawCanvas(context);
drawCanvas(hiddenContext, true);
}
});
});
</script>
<script>
// ***********************************
// Script pour les cercles
// ***********************************
var loadImage = function(src, cb) {
var img = new Image();
img.src = src;
img.onload = function(){ cb(null, img); };
img.onerror = function(){ cb('IMAGE ERROR', null); };
};
function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
let pattern_img;
function removeColorNodes(json, size=10) {
if (Array.isArray(json)) {
// Si c'est un tableau, appliquer récursivement sur chaque élément
console.log("zone 1");
return json.map(item => removeColorNodes(item, size));
} else if (typeof json === 'object' && json !== null) {
// Si c'est un objet, vérifier chaque clé
for (let key in json) {
if (key === 'color') {
// Supprimer la clé "color"
delete json[key];
} else if (key === 'size') {
// Adapte la clé
json[key]=size;
} else if (key === 'children') {
// Appliquer récursivement sur les propriétés imbriquées, sauf pour le noeud parent
json[key] = removeColorNodes(json[key], (json["type"]==2?(size>2?size-2:2):size));
}
}
}
return json; // Retourner l'objet ou la valeur inchangée
}
function refreshCircle(zoom = true) {
// Init fields
$("canvas").remove();
// Raffraichi les couleurs
removeColorNodes(root);
console.log (root);
var currentID=currentnode.ID;
drawAll();
// Find the current node again after drawing
if (zoom) quickZoomToCanvas(currentnode);
for (const [key, value] of Object.entries(colToCircle)) {
if (value.ID==currentID) currentnode=value;
}
}
function init() {
<?
// Comportement différent si appelé avec un paramètre de visualisation ($_GET["view"])
if (isset($_GET["view"])) {
// Récupère l'organisation
$org=new \dbObject\holon();
$org->load(['accesskey',$_GET["view"]]);
if ($org->getId()>0) {
?>
console.log("Yop");
localStorageName="tmpcirclestructure";
// Charge l'organisation avec l'access key, pour bypasser le "canView()"
// Attention, mauvaise gestion des erreurs ici...
$.getJSON("/ajax/loadorga.php?id=<?=$org->getId()?>&accesskey=<?=$_GET["view"]?>", function( my_var ) {
//my_var=JSON.parse('{"name": "<?=$org->get("name")?>", "ID": "TMP_1", "type": "4", "children": [{"name": "Ancrage", "ID": "TMP_2", "type": "2", "children": [ {"name": "Facilitation", "mycolor":"#FF6600", "ID": "TMP_3","type":"1", "mod":"template", "size":10}, {"name": "Pilotage", "mycolor":"#FF2200", "type":"1", "mod":"template", "ID": "TMP_4", "size":10}, {"name": "Mémoire", "mycolor":"#FF9900", "type":"1", "mod":"template", "ID": "TMP_8", "size":10}, {"name": "Role opérationnel", "type":"1", "ID": "TMP_9", "size":10}]},{"name": "CA", "ID": "TMP_5", "type": "2", "children": [ {"name": "Trésorier", "ID": "TMP_6","type":"1", "size":10}, {"name": "Président", "type":"1", "ID": "TMP_7", "size":10}]}]}');
localStorage.setItem(localStorageName, JSON.stringify(my_var));
$("canvas").remove();
queue().defer(loadImage, "/img/rayures.png").await(drawAll);
});
<?
} else {
echo "alert('Error!')";
}
} else { ?>
// Efface tous les canvas
if (localStorage.getItem(localStorageName)==null || !isJsonString(localStorage.getItem(localStorageName))) {
$.getJSON("/data/occupation.json", function( my_var ) {
localStorage.setItem(localStorageName, JSON.stringify(my_var));
$("canvas").remove();
queue().defer(loadImage, "/img/rayures.png").await(drawAll);
});
} else {
//
$("canvas").remove();
queue().defer(loadImage, "/img/rayures.png").await(drawAll);
}
<? } ?>
}
$(function() {
init();
$("body").delegate(".navTo","click",function() {
zoomToCanvas(idIndexedMap[$(this).attr("data-src")]);
});
});
function animate() {
var dt = 0;
d3.timer(function(elapsed) {
interpolateZoom(elapsed - dt);
if (!alwaysDisplayText) interpolateFadeText(elapsed - dt);
dt = elapsed;
drawCanvas(context);
return stopTimer;
});
}//function animate
function arraysAreEqual(arr1, arr2) {
// Vérifier si les longueurs sont différentes
if (arr1.length !== arr2.length) {
return false;
}
// Vérifier chaque élément
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
//Create the interpolation function between current view and the clicked on node
function zoomToCanvas(focusNode) {
// A comparer avec la variable globale "focus"
currentnode=focusNode;
// Load the content description
if (focus!==focusNode)
$(".contentleft").load("/circle/detail.php?id="+currentnode.ID);
//Temporarily disable click & mouseover events
$("#canvas").css("pointer-events", "none");