-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsvgeditor.js
1691 lines (1512 loc) · 60.8 KB
/
svgeditor.js
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
// parametric SVG editor
// by Harmen G. Zijp (2011)
// distributed under the Simple Public License: http://www.opensource.org/licenses/simpl-2.0
// code available at git.giplt.nl
//
// TODO
// check cross browser behaviour
// add tools (rotate, scale, translate) & guides (rulers, axes, crossmark)
// autocombine milling paths
// mill optional parameter symmetricA, symmetricB, asymmetric
// joint variable string of extension parameters for polyline element
// check use of official SVG param(x)
// validate code on the fly
// svg load/insert preview
var code; // parametric svg code (xml) //used for code fields
var svg; // concrete svg code? (used for preview) (xml)
var index; // object with all parametric svg objects, listed by their id (xml)
var selected; // id of selected. For example: "smiley,eyes,lefteye"
var drag;
var dragnode; // concrete svg node that is draged (set during p2c, thus buildsvg)
var offset = null;
var translate;
var viewbox;
var extraData = []; // array with extra data per object, content: {collapsed,hasChildren}
var ieV;
var psvgE = ".psvg"; // parametric svg file extension
var svgE = ".svg"; // svg file extension
var selectionPSVG; // svg node that shows selection (that's put into code)
const RESULT_STATE_SVG = "svg";
const RESULT_STATE_HELP = "help";
const RESULT_STATE_EXPORT = "export";
const RESULT_STATE_LOAD = "load";
const RESULT_STATE_SAVE = "save";
var resultState = RESULT_STATE_SVG;
var selectedCode = ""; // selected code from code textarea
var storedCode = ""; // code stored for the memory button
var codeCursorPos = -1; // cursor position in code edit field
var keepCodeCursorPos = false; // boolean that prevents alterations to codeCursorPos
// we store the following seperatly since we need to overrulde them to display the svg properly in the editor
var units;
var docWidth;
var docHeight;
function init(demo) {
//console.group("init");
ieV = getInternetExplorerVersion();
if(ieV > -1)
{
var ieError = document.getElementById('ieerror');
ieError.style.display = "block";
ieError.innerHTML = ieError.innerHTML.replace("{version}",ieV);
}
if(ieV == -1 || ieV >= 9.0)
{
// setup example code, build index and setup svg image
code = loadxml(demo ? '<svg width="210mm" height="297mm" transform=""><defs><ref param="size" default="100"/><ref param="dist" default="0.4*size"/><ref param="mood" default="0"/><ref param="x" default="105"/></defs><title>smiley</title><desc>example code for parametric SVG editor</desc><rect x="0" y="0" width="210" height="297" style="fill:none;stroke:#87cccc;"/>\n\n<circle cx="{x}" cy="105" r="{size}" style="fill:yellow;stroke:black;stroke-width:3"/><g transform="translate({x} 95)"><title>eyes</title><circle cx="{-dist}" cy="0" r="{size/10}" style="fill:black; stroke:black;"/>\n\n<circle cx="{dist}" cy="0" r="{size/10}" style="fill:black; stroke:black;"/></g><g transform="translate({x} 105)"><title>mouth</title><path d="M{-size/2},{+size/2} a 2 1 0 0 {mood} {size},0" style="fill:none;stroke:black;stroke-width:3"/></g></svg>' : '<svg width="210mm" height="297mm" transform=""><defs></defs><title>new project</title><desc></desc></svg>');
buildindex();
setupsvg();
createSelectionSVG();
select('project');
//console.log("code: ",code);
//var codeStr = getNodeXML(code)
//console.log("codeStr: ",codeStr);
}
//console.groupEnd();
}
function buildindex()
{
//if(//console) console.log("buildindex");
index = addToIndex(code.documentElement, new Array());
document.getElementById('title').innerHTML = getNodeTitle(code.documentElement);
document.getElementById('index_title').innerHTML = 'index';
var html = '<div class="indexItem" id="project" onclick="select(\'project\');">project settings</div>';
html += '<div class="indexItem" id="parameters" onclick="select(\'parameters\');">  parameters</div>';
html += '<hr/>';
for (var id in index)
{
var itemExtraData = getExtraData(id);
var indent = new Array(id.split(',').length).join('  ');
var collapseIcon = " ";
if(itemExtraData.hasChildren) collapseIcon = (itemExtraData.collapsed)? "+ " : "- ";
var name = id.substr(id.lastIndexOf(',')+1);
var classes = "indexItem";
classes += (selected == id)? ' selected' : '';
html += '<div class="'+classes+'" id="' + id + '" onclick="clickedIndexItem(\'' + id + '\');">' + indent + collapseIcon + name + '</div>'
}
document.getElementById('index').innerHTML = html;
}
function clickedIndexItem(id)
{
//if(//console) console.log("clickedIndexItem, id: ",id, "was selected: ",(selected == id));
if(selected == id)
{
var selectedExtraData = getExtraData(id);
selectedExtraData.collapsed = !selectedExtraData.collapsed;
buildindex();
}
else
{
select(id);
}
//console.groupEnd();
}
function addToIndex(node, index) {
var id = getId(node);
index[id] = node;
var itemExtraData = getExtraData(id);
if(!itemExtraData.collapsed)
{
itemExtraData.hasChildren = false;
for (var i=0;i<node.childNodes.length;i++)
{
if (node.childNodes[i].tagName=='g')
{
index = addToIndex(node.childNodes[i], index);
itemExtraData.hasChildren = true;
}
}
}
return index;
}
// generates nested id. For example: "smiley,eyes,lefteye"
function getId(node) {
var id = getNodeTitle(node);
var parent = node.parentNode;
while (parent!=node.ownerDocument) {
id = getNodeTitle(parent) + ',' + id;
parent = parent.parentNode;
}
return node == node.ownerDocument.documentElement ? 'root element' : id;
}
function setupsvg() {
//console.group("setupsvg");
// create svg object
svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
//svg = document.createElement('svg');
svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
// add other namespaces from original file
var attributes = code.documentElement.attributes;
for(var i = 0;i<attributes.length;i++)
{
var attribute = attributes[i];
if(attribute.name.indexOf('xmlns') != -1)
{
svg.setAttribute(attribute.name, attribute.value);
}
}
// store original values
docWidth = parseFloat(code.documentElement.getAttribute('width'));
docHeight = parseFloat(code.documentElement.getAttribute('height'));
units = code.documentElement.getAttribute('width').replace(/[0-9 ]*/ig,"");
//console.log("docWidth: ",docWidth);
//console.log("docHeight: ",docHeight);
//console.log("units: ",units);
var size = Math.max(docWidth, docHeight);
//console.log("maxsize: ",size);
//var size = "400";
//svg.setAttribute('viewBox', '100px 100px 400px 400px');
//svg.setAttribute('viewBox', '50px 50px 20px 20px');
//svg.setAttribute('viewBox', '0 0 ' + size + units + ' ' + size + units);
//svg.setAttribute('viewBox', '0mm 0mm 50mm 50mm');
//svg.setAttribute('viewBox', '0 0 50 50');
//svg.setAttribute('viewBox', '0 0 ' + size + ' ' + size);
//svg.setAttribute('width', size + units);
//svg.setAttribute('height', size + units);
svg.setAttribute('width','400px');
svg.setAttribute('height','400px');
//svg.setAttribute('viewBox', '0 0 400 400');
svg.setAttribute('viewBox', '0 0 ' + size + ' ' + size);
//svg.setAttribute('preserveAspectRatio', 'xMinYMin meet');
svg.setAttribute('preserveAspectRatio', 'xMinYMin');
svg.setAttribute('style', 'cursor:pointer;');
// setup routines for dragging image (parts)
svg.onmousedown = function(e) {
//console.group("onmousedown");
drag = true;
if (selected.indexOf(',')!=-1) {
//console.log("selected.indexOf(',')!=-1");
//console.log("dragnode: ",dragnode);
update('transform');
//console.log("dragnode: ",dragnode);
translate = getTranslate(index[selected]);
//console.log("dragnode: ",dragnode);
}
else
{
//console.log("else");
dragnode = svg;
}
//console.log("dragnode: ",dragnode);
//console.log("svg: ",svg);
offset = mouseCoords(e);
viewbox = getViewbox(svg);
//console.groupEnd();
return false;
}
svg.onmouseup = function(e) {
drag = false;
}
svg.onmousemove = function(e){
if(drag)
{
e = e || window.event;
var pos = mouseCoords(e);
var dx = (pos.x - offset.x) * viewbox.w/document.getElementById('result').offsetWidth;
var dy = (pos.y - offset.y) * viewbox.h/document.getElementById('result').offsetHeight;
//console.log("dragnode: ",dragnode);
if (dragnode==svg)
{
var vx = (viewbox.x - dx).toPrecision(3);
var vy = (viewbox.y - dy).toPrecision(3);
var vw = viewbox.w;
var vh = viewbox.h;
svg.setAttribute('viewBox', vx + ' ' + vy + ' ' + vw + ' ' + vh);
document.getElementById('viewbox').innerHTML = svg.getAttribute('viewBox');
}
else
{
//console.log("else");
dx = (translate.x + dx).toPrecision(3);
dy = (translate.y + dy).toPrecision(3);
transform = document.getElementById('edittransform').value.replace(/translate\(.*?\)/, 'translate(' + (translate.px!=''?'{'+translate.px+'}':'') + (dx<0?'':'+') + dx + ' ' + (translate.py!=''?'{'+translate.py+'}':'') + (dy<0?'':'+') + dy + ')');
index[selected].setAttribute('transform', transform);
document.getElementById('edittransform').value = transform;
transform = document.getElementById('edittransform').value.replace(/translate\(.*?\)/, 'translate({' + translate.px + (dx<0?'':'+') + dx + '} {' + translate.py + (dy<0?'':'+') + dy + '})');
transform = transform.replace(/({.*?})/g, function(match) { return eval(match); } );
dragnode.setAttribute('transform', transform);
}
return false;
}
}
//console.log("svg: ",svg);
//console.groupEnd();
}
function getViewbox(e)
{
viewbox = e.getAttribute('viewBox').split(" ");
var obj = { x: parseInt(viewbox[0]), y: parseInt(viewbox[1]), w: parseInt(viewbox[2]), h: parseInt(viewbox[3]) };
return obj
}
function mouseCoords(e) {
if(e.pageX || e.pageY) {
return { x:e.pageX, y:e.pageY };
}
return {
x:e.clientX + document.body.scrollLeft - document.body.clientLeft,
y:e.clientY + document.body.scrollTop - document.body.clientTop
};
}
function zoom(type) {
//console.group("zoom");
//console.log("type: ",type);
viewbox = getViewbox(svg);
//console.log("viewbox: ",viewbox);
var vx, vy, vw, vh;
switch(type) {
case -1:
vx = (viewbox.x - 0.1*viewbox.w/2).toPrecision(3);
vy = (viewbox.y - 0.1*viewbox.h/2).toPrecision(3);
vw = (viewbox.w*1.1).toPrecision(3);
vh = (viewbox.h*1.1).toPrecision(3);
break;
case 0:
var size = Math.max(parseFloat(code.documentElement.getAttribute('width')), parseFloat(code.documentElement.getAttribute('height')));
//console.log("width: ",code.documentElement.getAttribute('width'));
vx = 0;
vy = 0;
vw = size;
vh = size;
break;
case 1:
vx = (viewbox.x + 0.1*viewbox.w/2).toPrecision(3);
vy = (viewbox.y + 0.1*viewbox.h/2).toPrecision(3);
vw = (viewbox.w/1.1).toPrecision(3);
vh = (viewbox.h/1.1).toPrecision(3);
break;
}
svg.setAttribute('viewBox',vx+' '+vy+' '+vw+' '+vh);
document.getElementById('viewbox').innerHTML = svg.getAttribute('viewBox');
//console.groupEnd();
}
function select(id) {
//console.group("select");
//if(//console) console.log("select, id: "+id);
var html = '';
var menu = '';
switch(id) {
case 'project':
document.getElementById('edit_title').innerHTML = 'project settings';
html+= '<h3>title</h3><br/><input id="edittitle" type="text" class="text" value="' + getNodeTitle(code.documentElement) + '" onblur="update(\'title\');" /><br/>';
html+= '<h3>description</h3><br/><textarea id="editdesc" onblur="update(\'description\');">' + getDescription(code.documentElement) + '</textarea><br/>';
var doc = code.documentElement;
var width = doc.getAttribute('width').replace(/[a-z ]*/ig,"");
var height = doc.getAttribute('height').replace(/[a-z ]*/ig,"");
//var units = doc.getAttribute('width').replace(/[0-9 ]*/ig,"");
//console.log("width: ",width);
//console.log("height: ",height);
//console.log("units: ",units);
html+= '<h3>document size (width × height)</h3><br/><input id="editwidth" type="text" class="text" value="' + width + '" onblur="update(\'width\');" /> ×<input id="editheight" type="text" class="text" value="' + height + '" onblur="update(\'height\');" /><select id="units" onblur="update(\'units\');"><option>em</option><option>ex</option><option>px</option><option>pt</option><option>pc</option><option>cm</option><option>mm</option><option>in</option></select>';
menu = '<input type="button" class="button" value="new" onclick="init();" title="new project" />';
menu+= '<input type="button" class="button" value="load" onclick="gotoLoad();" title="load code" />';
menu+= '<input type="button" class="button" value="save" onclick="gotoSave();" title="save code" />';
document.getElementById('edit').innerHTML = html;
document.getElementById('edit_menu').innerHTML = menu;
document.getElementById('index_menu').innerHTML = '';
var unitsSelect = document.getElementById('units');
var options = unitsSelect.options;
for(var i=0;i<options.length;i++)
{
if(options[i].value == units)
{
unitsSelect.selectedIndex = i;
}
}
break;
case 'parameters':
var params = '';
var defs = code.getElementsByTagName('defs')[0];
if (defs) for(var i=0; i<defs.childNodes.length; i++) if(defs.childNodes[i].tagName == 'ref') params+= defs.childNodes[i].getAttribute('param') + '=' + defs.childNodes[i].getAttribute('default') + '\n';
document.getElementById('edit_title').innerHTML = 'parameters';
html+= '<textarea id="params" class="code" onfocus="disableRenderButton(false);" onblur="update(\'params\');">' + params +'</textarea>'
document.getElementById('edit').innerHTML = html;
document.getElementById('edit_menu').innerHTML = '';
document.getElementById('index_menu').innerHTML = '';
break;
default:
node = index[id];
document.getElementById('edit_title').innerHTML = "code";
codeCursorPos = -1;
//console.log("codeCursorPos: ",codeCursorPos);
html+= '<h3 class="codeTitle">'+getNodeTitle(node)+'</h3><textarea id="editcode" class="code" onfocus="disableRenderButton(false);" onblur="update(\'code\');" onselect="onCodeSelect(this)" onmousedown="onCodeMouseDown(this)">' + getCode(node) + '</textarea><br/>';
if (node!=code.documentElement)
{
var transform = node.getAttribute('transform');
if(transform == null)
transform = 'translate(0 0)';
html+= '<h3>transform</h3><br/><input id="edittransform" class="code text" type="text" value="' + transform + '" onfocus="disableRenderButton(false);" onblur="update(\'transform\');" />';
}
document.getElementById('edit').innerHTML = html;
var indexmenu = '';
if (node!=code.documentElement) {
// code menu
menu+= '<input type="button" class="button" value="rename" onclick="renameobject();" title="rename group" />';
menu+= '<input type="button" class="button" value="duplicate" onclick="duplicateObject();" title="duplicate group" />';
menu+= '<input type="button" class="button" value="remove" onclick="removeobject();" title="remove group" />';
// index menu
var prev = '';
var next = node;
var siblings = node.parentNode.childNodes;
for (var i=0; i<siblings.length; i++) if(siblings[i].tagName == 'g') {
if (siblings[i] == node) next = '';
else if (next) prev = siblings[i];
else {
next = siblings[i];
break;
}
}
//indexmenu+= '<input type="button" class="button" value="<"' + (prev ? ' onclick="moveUp(\'' + id + '\');"' : ' disabled="disabled"') + '"/>';
indexmenu+= '<input type="button" class="button" value="∧"' + (prev ? ' onclick="swapobjects(\'' + id + '\', \'' + getId(prev) + '\');"' : ' disabled="disabled"') + '"/>';
indexmenu+= '<input type="button" class="button" value="∨"' + (next ? ' onclick="swapobjects(\'' + id + '\', \'' + getId(next) + '\');"' : ' disabled="disabled"') + '"/>';
}
// code menu
menu+= '<input type="button" class="button" value="add new" onclick="addobject();" title="add new group" />';
menu+= '<input type="button" class="button" value="load into" onclick="gotoLoad();" title="load svg into project" />';
menu+= '<br/><h3>add: <\/h3>'
menu+= '<input type="button" class="button" value="o" onclick="addCode(\'circle\');" title="add circle code" />';
menu+= '<input type="button" class="button" value="[]" onclick="addCode(\'rect\');" style="letter-spacing:-0.2em" title="add rectangle code" />';
menu+= '<input type="button" class="button" value="0" onclick="addCode(\'ellipse\');" title="add ellipse code" />';
menu+= '<input type="button" class="button" value="/" onclick="addCode(\'line\');" title="add line code" />'; //⁄
menu+= '<input type="button" class="button" value="∠" onclick="addCode(\'path\');" title="add path code" />';
menu+= '<input type="button" class="button" id="memoryButton" value="M" title="" onClick="onMemoryClicked()" '+((storedCode == "")? 'disabled="true"' : '')+' />';
document.getElementById('edit_menu').innerHTML = menu;
document.getElementById('index_menu').innerHTML = indexmenu;
updateMemoryButtonLabel();
}
//if (selected) document.getElementById(selected).style.fontWeight = 'normal';
if (selected) document.getElementById(selected).setAttribute("class","indexItem");
selected = id;
//document.getElementById(selected).style.fontWeight = 'bold';
document.getElementById(selected).setAttribute("class","indexItem selected");
updateVisualSelect();
buildsvg();
//console.groupEnd();
}
function createSelectionSVG()
{
selectionPSVG = code.createElement('rect');
selectionPSVG.setAttributeNS(null,'id', "selector");
selectionPSVG.setAttributeNS(null,'fill', "none");
selectionPSVG.setAttributeNS(null,'stroke', "#84CAFF");
selectionPSVG.setAttributeNS(null,'stroke-width', "2");
selectionPSVG.setAttributeNS(null,'stroke-dasharray', "5,5");
selectionPSVG.setAttributeNS(null,'opacity', "0.9");
selectionPSVG.setAttributeNS(null,'transform', 'translate(0 0)');
selectionPSVG.setAttributeNS(null,'width', '100');
selectionPSVG.setAttributeNS(null,'height', '100');
}
function removeVisualSelect()
{
if(selectionPSVG.parentNode != undefined)
selectionPSVG.parentNode.removeChild(selectionPSVG);
selectedSVG = null;
}
function updateVisualSelect()
{
//console.group("updateVisualSelect");
var selectedNode = index[selected];
//console.log("selectedNode: ",selectedNode);
if(selectedNode == undefined)
{
removeVisualSelect();
}
else
{
var selectedSVG = getSelectedSVG();
if(selectedSVG)
{
//var bb = dragnode.getBBox();
//var bb = selectedSVG.getBounds();
//var bb = selectedSVG.getBoundingClientRect();
var bb = selectedSVG.getBBox();
var strokeWidth = parseFloat(selectionPSVG.getAttributeNS(null,'stroke-width'));
//console.log("strokeWidth: ",strokeWidth);
selectionPSVG.setAttributeNS(null,'x', bb.x-strokeWidth/2);
selectionPSVG.setAttributeNS(null,'y', bb.y-strokeWidth/2);
selectionPSVG.setAttributeNS(null,'width', bb.width+strokeWidth);
selectionPSVG.setAttributeNS(null,'height', bb.height+strokeWidth);
selectedNode.appendChild(selectionPSVG); // insertBefore
}
}
//console.log("selectionPSVG: ",selectionPSVG);
//buildsvg();
//console.groupEnd();
}
function getSelectedSVG()
{
//console.group("getSelectedSVG");
var titles = selected.split(',');
//console.log("titles: ",titles);
var svgNode;
if(titles.length > 0)
{
svgNode = svg;
}
if(titles.length > 1)
{
for(var i=1;i<titles.length;i++)
{
svgNode = getChildByTitle(svgNode,titles[i]);
}
}
//console.log("final svgNode: ",svgNode);
//console.groupEnd();
return svgNode;
}
function getChildByTitle(svgNode,title)
{
//console.group("getChildByTitle");
var childNodes = svgNode.childNodes;
for(var i=0;i<childNodes.length;i++)
{
var child = childNodes[i];
if(child.tagName != "g" && child.tagName != "svg:g") continue;
var groupChildNodes = child.childNodes;
for(var j=0;j<groupChildNodes.length;j++)
{
var groupChild = groupChildNodes[j];
if(groupChild.tagName == "title" || groupChild.tagName == "svg:title")
{
var textContent = groupChild.firstChild.textContent;
if(textContent == title)
{
//console.groupEnd();
return child;
}
}
}
}
//console.groupEnd();
}
function update(element) {
//console.group("update");
//console.log("element: ",element);
//console.log("resultState: ",resultState);
switch(element) {
case 'title':
var editTitleNode = document.getElementById('edittitle');
// update parametric svg code
setNodeXML(code.getElementsByTagName('title')[0], editTitleNode.value);
// update title
document.getElementById('title').innerHTML = editTitleNode.value;
if(resultState == RESULT_STATE_SAVE)
{
document.getElementById('saveTitle').value = editTitleNode.value;
var filenameLibrary = document.getElementById('filenameLibrary');
filenameLibrary.value = editTitleNode.value+psvgE;
//console.log("filenameLibrary.value: ",filenameLibrary.value);
validateSaveForm();
}
//console.log("resultState: ",resultState);
//console.log(" resultState: ",resultState);
//console.log(" RESULT_STATE_SAVE: ",RESULT_STATE_SAVE);
if(resultState != RESULT_STATE_SAVE)
{
buildindex();
select('project');
}
break;
case 'saveTitle':
var saveTitleNode = document.getElementById('saveTitle');
var editTitleNode = document.getElementById('edittitle');
editTitleNode.value = saveTitleNode.value;
//console.log(" editTitleNode.value: ",editTitleNode.value);
update('title');
break;
case 'description':
setNodeXML(code.getElementsByTagName('desc')[0], document.getElementById('editdesc').value);
break;
case 'width':
//code.documentElement.setAttribute('width', document.getElementById('editwidth').value);
docWidth = document.getElementById('editwidth').value;
code.firstChild.setAttribute("width",docWidth+units);
//console.log("code: ",code);
//console.log("code.firstChild: ",code.firstChild);
break;
case 'height':
//code.documentElement.setAttribute('height', document.getElementById('editheight').value);
docHeight = document.getElementById('editheight').value;
code.firstChild.setAttribute("height",docHeight+units);
break;
case 'units':
var unitsSelect = document.getElementById('units');
units = unitsSelect.options[unitsSelect.selectedIndex].value;
code.firstChild.setAttribute("width",docWidth+units);
code.firstChild.setAttribute("height",docHeight+units);
//setupsvg();
break;
case 'params':
defs = code.getElementsByTagName('defs')[0];
while(defs.childNodes.length) defs.removeChild(defs.childNodes[0]);
lines = document.getElementById('params').value.replace(/ /g,'').split("\n");
for (var i=0; i<lines.length; i++) if (lines[i]) {
newnode = code.createElement('ref');
attributes = lines[i].split("=");
newnode.setAttribute('param', attributes[0])
newnode.setAttribute('default', attributes[1])
defs.appendChild(newnode)
}
break;
case 'transform':
index[selected].setAttribute('transform', document.getElementById('edittransform').value);
break;
case 'code':
var editCodeNode = document.getElementById('editcode');
// store cursor position so we can add code from memory at that location
if(!keepCodeCursorPos)
{
codeCursorPos = editCodeNode.selectionStart;
//console.log("codeCursorPos: ",codeCursorPos);
}
setNodeXML(index[selected], editCodeNode.value);
break;
}
//console.log("dragnode: ",dragnode);
if(!((element == 'title' || element == 'saveTitle' || element == 'description') && resultState == RESULT_STATE_SAVE))
{
buildsvg();
}
//console.log("dragnode: ",dragnode);
//console.groupEnd();
}
function swapobjects(idA, idB) {
var svgA = index[idA];
var svgB = index[idB];
cloneB = svgB.cloneNode(true);
var parentSVG = svgA.parentNode;
parentSVG.insertBefore(cloneB, svgA);
parentSVG.replaceChild(svgA, svgB);
buildindex();
select(selected);
}
function addobject(name) {
var parentNode = index[selected];
if(!name) name = prompt('please enter name for new object', 'newobject');
while(parentNode.childNodes.length > 0 && nameExists(parentNode.childNodes[0],name)) name = prompt('name exists, please try a different name', name);
if (name) {
newgroup = code.createElement('g');
newgroup.setAttribute('transform', 'translate(0 0)');
var title = code.createElement('title')
title.appendChild(code.createTextNode(name));
newgroup.appendChild(title);
parentNode.appendChild(newgroup);
selected = getId(newgroup);
buildindex();
select(selected);
return newgroup;
}
}
function removeobject() {
if (confirm('Are you sure you want to remove \'' + getNodeTitle(index[selected]) + '\'?')) {
var node = index[selected];
selected = getId(node.parentNode);
node.parentNode.removeChild(node);
buildindex();
select(selected);
}
}
function renameobject() {
var selectedSVG = index[selected];
var name = prompt('enter new name', getNodeTitle(selectedSVG));
while(nameExists(selectedSVG,name) && name != getNodeTitle(selectedSVG)) name = prompt('name exists, please try a different name', name);
if (name) {
setNodeTitle(selectedSVG,name);
selected = getId(selectedSVG);
buildindex();
select(selected);
}
}
function duplicateObject() {
var selectedSVG = index[selected];
removeVisualSelect();
var cloneSVG = selectedSVG.cloneNode(true);
var selectedName = getNodeTitle(cloneSVG);
var cloneName = prompt('enter new name',selectedName+" copy");
while(nameExists(selectedSVG,cloneName)) cloneName = prompt('name exists, please try a different name', cloneName);
if (name) {
setNodeTitle(cloneSVG,cloneName);
selectedSVG.parentNode.appendChild(cloneSVG);
buildindex();
//selected = getId(cloneSVG);
//select(selected);
select(getId(cloneSVG));
}
}
// adds basic shapes code to edit code field.
function addCode(type)
{
var newCode = "";
if(type != "memory") newCode += "\r\n\r\n";
switch(type)
{
case "circle":
newCode += '<circle cx="50" cy="50" r="25" style="fill:none;stroke:black;stroke-width:1"/>';
break;
case "rect":
newCode += '<rect x="10" y="10" height="100" width="100" style="fill:none;stroke:black;stroke-width:1"/>';
break;
case "ellipse":
newCode += '<ellipse cx="50" cy="50" rx="20" ry="30" style="fill:none;stroke:black;stroke-width:1"/>';
break;
case "line":
newCode += '<line x1="10" y1="10" x2="70" y2="30" style="fill:none;stroke:black;stroke-width:1"/>';
break;
case "path":
newCode += '<path d="M50,50 100,50 75,75 Z" style="fill:none;stroke:black;stroke-width:1"/>';
break;
case "memory":
//console.log("storedCode: ",storedCode);
newCode += storedCode;
break;
}
codeField = document.getElementById('editcode');
//console.log("codeCursorPos: ",codeCursorPos);
if(codeCursorPos == -1)
{
codeField.value += newCode;
}
else
{
var before = codeField.value.slice(0,codeCursorPos);
var after = codeField.value.slice(codeCursorPos);
codeField.value = before+newCode+after;
}
keepCodeCursorPos = true;
update('code');
keepCodeCursorPos = false;
}
// update svg code for display
function buildsvg()
{
resultState = RESULT_STATE_SVG;
//console.log("resultState: ",resultState);
//console.group("buildsvg");
// set parameters, i.e. evaluate names and values for variables defined in the 'defs' node
var defs = code.getElementsByTagName('defs')[0];
if (defs) for (var i=0; i<defs.childNodes.length; i++) if (defs.childNodes[i].nodeType == 1) eval(defs.childNodes[i].getAttribute('param') + '=' + defs.childNodes[i].getAttribute('default') +';');
// empty svg node
while(svg.childNodes.length) svg.removeChild(svg.childNodes[0]);
// convert all non-defs node to svgnodes
var nodelist = code.documentElement.childNodes;
for (var i=0; i<nodelist.length;i++)
{
if(nodelist[i].tagName && nodelist[i].tagName!='defs')
{
svg.appendChild(p2c(nodelist[i]));
}
}
// setup image in html
document.getElementById('result_title').innerHTML = 'image';
html = '<h3>viewbox</h3> <span id="viewbox" style="font-family:sans; font-size:small;">' + svg.getAttribute('viewBox');
// html+= '</span><span style="float:right;"><input id="tools" type="checkbox" value="" disabled="disabled"/><h3>tools<h3><input id="guides" type="checkbox" value="" disabled="disabled"/><h3>guides<h3></span>';
menu = '<input type="button" class="button" value="render" id="render" onclick="buildsvg();" title="render code" />';
menu+= '<input type="button" class="button" value="export" onclick="gotoExport();" title="export result as concrete svg file" />';
menu+= '<input type="button" class="button" value="+" onclick="zoom(1);" title="zoom in" />';
menu+= '<input type="button" class="button" value="⊕" onclick="zoom(0);" title="default viewbox" />';
menu+= '<input type="button" class="button" value="−" onclick="zoom(-1);" title="zoom out" />';
menu+= '<input type="button" class="button" value="?" onclick="gotoHelp();" title="click for help" />';
document.getElementById('result_menu').innerHTML = menu;
document.getElementById('result_footer').innerHTML = html;
disableRenderButton(true);
document.getElementById('result').setAttribute('class', 'image');
document.getElementById('result').innerHTML = '';
document.getElementById('result').appendChild(svg);
// trying to support SVGWEB
/*//document.getElementById('result').innerHTML = '<script type="image/svg+xml"></script>';
//var resultNode = document.getElementById('result')
//var scriptNode = resultNode.childNodes[0];
//scriptNode.appendChild(svg);*/
/*//document.getElementById('result').innerHTML = "<script type='image/svg+xml' id='resultSVGScript'></script>";
document.getElementById('result').innerHTML = "<div id='resultSVGScript' class='image'></div>";
//document.getElementById('resultSVGScript').setAttribute('class', 'image');
//document.getElementById('resultSVGScript').innerHTML = 'test';
//document.getElementById('resultSVGScript').appendChild(svg);
//document.getElementById('resultSVGScript') = svg;*/
/*document.getElementById('result').setAttribute('class', 'image');
document.getElementById('result').innerHTML = '<object data="svgweb/samples/svg-files/helloworld.svg" type="image/svg+xml" width="200" height="200" id="mySVGObject">';
var doc = document.getElementById('mySVGObject').contentDocument;
//doc.appendChild(svg);*/
/*document.getElementById('result').setAttribute('class', 'image');
document.getElementById('result').innerHTML = ''
var container = document.getElementById('result');
currentSVGObject = svgweb.appendChild(svg, container);*/
if(ieV >= 9.0)
{
setupsvg();
}
//console.groupEnd();
}
function gotoHelp()
{
resultState = RESULT_STATE_HELP;
//console.log("resultState: ",resultState);
var ajaxRequest = ( window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP") );
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4) document.getElementById('result').innerHTML = ajaxRequest.responseText;
}
ajaxRequest.open("GET", "help.html", true);
ajaxRequest.send(null);
menu = '<input type="button" class="button" value="×" onclick="buildsvg();" title="close help" />';
document.getElementById('result_title').innerHTML = 'help';
document.getElementById('result_footer').innerHTML = '';
document.getElementById('result_menu').innerHTML = menu;
document.getElementById('result').setAttribute('class', 'help');
document.getElementById('result').innerHTML = 'loading...';
}
function checkTitles(node, id) {
if (!getNodeTitle(node)) {
var title = node.ownerDocument.createElement('title')
title.appendChild(node.ownerDocument.createTextNode(id ? 'sub' + id : 'new'));
node.appendChild(title);
}
var id = 1;
for (var i=0;i<node.childNodes.length; i++) if (node.childNodes[i].tagName == 'g') checkTitles(node.childNodes[i], id++);
}
function loadFileFromServer(filename) {
if (!filename) document.getElementById('progressbar').innerHTML = 'no file';
else {
var ajaxRequest = ( window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP") );
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4) {
document.getElementById('progressbar').innerHTML = '';
if (selected == 'project') {
code = loadxml(ajaxRequest.responseText);
checkTitles(code.documentElement);
if (!getDescription(code.documentElement)) {
var desc = code.createElement('title')
desc.appendChild(code.createTextNode(''));
code.documentElement.appendChild(desc);
}
if (!code.documentElement.getAttribute('width')) code.documentElement.setAttribute('width', "210mm"); //Q why 210mm?
if (!code.documentElement.getAttribute('height')) code.documentElement.setAttribute('height', "297mm"); //Q why 297mm?
setupsvg();
}
else {
var loadnode = loadxml(ajaxRequest.responseText).documentElement;
checkTitles(loadnode);
var newnode = addobject(getNodeTitle(loadnode));
for(var i=0; i<loadnode.childNodes.length; i++) switch(loadnode.childNodes[i].tagName) {
case 'defs': while (loadnode.childNodes[i].childNodes.length) code.getElementsByTagName('defs')[0].appendChild(loadnode.childNodes[i].childNodes[0]); break;
default: newnode.appendChild(loadnode.childNodes[i].cloneNode(true)); break;
}
selected = getId(newnode);
}
buildindex();
select(selected);
buildsvg();
}
}
document.getElementById('progressbar').innerHTML = 'loading...';
ajaxRequest.open("GET", "svg.php?id=loadFile&filename=" + filename, true);
ajaxRequest.send(null);
}
}
function saveFileToServer(html) {
document.getElementById('progressbar').innerHTML = html;
}
function startUpload(){
//console.group("startUpload");
//console.log("code: ",code);
document.getElementById('uploadcode').value = getNodeXML(code);
document.getElementById('svgcode').value = getNodeXML(svg);
document.getElementById('progressbar').innerHTML = 'uploading...';
document.getElementById('uploadform').style.visibility = 'hidden';
document.getElementById('uploadform').target = 'upload_target';
document.getElementById('uploadform').submit();
//console.groupEnd();
return true;
}
function ajaxGet(param, id) {
var request = ( window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP") );
request.onreadystatechange = function() {
if(request.readyState == 4) document.getElementById(id).innerHTML = request.responseText;
}
request.open('GET', param, true);
request.send(null);
}
function gotoLoad()
{
resultState = RESULT_STATE_LOAD;
//console.log("resultState: ",resultState);
html = '<div>';
html+= '<h3>load svg code from disk</h3>';
html+= '<form id="uploadform" action="svg.php?id=uploadFile&destination=client" method="post" enctype="multipart/form-data">';
html+= '<input type="file" name="loadfile" size="20" onchange="startUpload();"/>';
html+= '<input type="hidden" id="uploadcode" name="uploadcode" value=""/>';
html+= '<input type="hidden" id="svgcode" name="svgcode" value=""/>';
html+= '<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>';
html+= '</form>';
html+= '</div>';
html+= '<hr/>';
html+= '<div>';
html+= '<h3>load svg code from online template library</h3>';
html+= '';
html+= '<label>category</label> <span id="libraryCategories">loading...</span>';
html+= '<div id="libraryFiles">';
//html+= '<tr><th></th><td id="libraryFiles"><input type="submit" id="load" value="load" onclick="loadFileFromServer(\'library/\' + document.getElementById(\'loadCategory\').value + \'/\' +document.getElementById(\'loadFile\').value);" title="import file" disabled="true"/></td></tr>';
html+= '</div>';
html+= '<span id="progressbar"></span>';
menu = '<input type="button" class="button" value="×" onclick="buildsvg();" title="close load menu" />';
document.getElementById('result_title').innerHTML = 'load code';
document.getElementById('result_menu').innerHTML = menu;
document.getElementById('result').setAttribute('class', 'help');
document.getElementById('result').innerHTML = html;
ajaxGet('svg.php?id=getLibraryCategories&purpose=load', 'libraryCategories');
}
function saveFile() {
//console.group("saveFile");
var svgNode = code.firstChild;
///console.log("download code",svgNode);
downloadCode(code);
//console.groupEnd();
}
function exportFile() {
//console.group("exportFile");
//console.log("svg",svg);
// locate selector inside svg and temporarily remove it
var selectedSVG = getSelectedSVG();
var selectionSVGParent;
if(selectedSVG != null)
{
var selectionSVG;
var selectionPSVGID = selectionPSVG.getAttribute('id');
var childNodes = selectedSVG.childNodes;
for(var i=0;i<childNodes.length;i++)
{
var child = childNodes[i];
if(child.id == selectionPSVGID)
{
selectionSVG = child;
}
}
if(selectionSVG != undefined)
{
var selectionSVGParent = selectionSVG.parentNode;
selectionSVGParent.removeChild(selectionSVG);
}
}
var vb = getViewbox(svg);
svg.setAttribute("width",docWidth+units);
svg.setAttribute("height",docHeight+units);
svg.setAttribute("viewBox","0 0 "+docWidth+" "+docHeight);
//console.log(" download code:",svg);
downloadCode(svg);
svg.setAttribute("width","400px");
svg.setAttribute("height","400px");
svg.setAttribute("viewBox",vb.x+" "+vb.y+" "+vb.w+" "+vb.h);
//console.log(" restored code",svg);
// restore removed selector
if(selectionSVGParent != undefined)