forked from xwiki-contrib/application-diagram
-
Notifications
You must be signed in to change notification settings - Fork 4
/
DiagramSheet.xml
1165 lines (1094 loc) · 40 KB
/
DiagramSheet.xml
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
<?xml version="1.0" encoding="UTF-8"?>
<!--
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-->
<xwikidoc version="1.2" reference="Diagram.DiagramSheet" locale="">
<web>Diagram</web>
<name>DiagramSheet</name>
<language/>
<defaultLanguage/>
<translation>0</translation>
<creator>xwiki:XWiki.Admin</creator>
<creationDate>1493978161000</creationDate>
<parent>Main.WebHome</parent>
<author>xwiki:XWiki.Admin</author>
<contentAuthor>xwiki:XWiki.Admin</contentAuthor>
<date>1547804940000</date>
<contentUpdateDate>1547804940000</contentUpdateDate>
<version>1.1</version>
<title/>
<comment/>
<minorEdit>false</minorEdit>
<syntaxId>xwiki/2.1</syntaxId>
<hidden>true</hidden>
<content>{{velocity}}
#set ($diagramObj = $doc.getObject('Diagram.DiagramClass'))
#if ($diagramObj)
#set ($diagramConfig = {
"debug": $services.debug.minify.equals(false),
"locale": $xcontext.locale,
"mxGraphClientBasePath": $services.webjars.url('org.xwiki.contrib:mxgraph-client', ''),
"mxGraphEditorBasePath": $services.webjars.url('org.xwiki.contrib:mxgraph-editor', ''),
"drawIOBasePath": $services.webjars.url('org.xwiki.contrib:draw.io', ''),
"exportURL": $xwiki.getDocument('Diagram.DiagramConfig').getValue('exportURL'),
"pdfImageExportZoom": $diagramObj.getValue('pdfImageExportZoom'),
"disableExternalServices": $xwiki.getDocument('Diagram.DiagramConfig').getValue('disableExternalServices')
})
#if ($xcontext.action == 'edit')
{{include reference="Diagram.DiagramEditSheet" /}}
#else
{{include reference="Diagram.DiagramViewSheet" /}}
#end
#end
{{/velocity}}</content>
<object>
<name>Diagram.DiagramSheet</name>
<number>1</number>
<className>XWiki.JavaScriptExtension</className>
<guid>ad4bd9bd-2932-40c3-a7b9-5caae1266b43</guid>
<class>
<name>XWiki.JavaScriptExtension</name>
<customClass/>
<customMapping/>
<defaultViewSheet/>
<defaultEditSheet/>
<defaultWeb/>
<nameField/>
<validationScript/>
<cache>
<cache>0</cache>
<disabled>0</disabled>
<displayType>select</displayType>
<multiSelect>0</multiSelect>
<name>cache</name>
<number>5</number>
<prettyName>Caching policy</prettyName>
<relationalStorage>0</relationalStorage>
<separator> </separator>
<separators>|, </separators>
<size>1</size>
<unmodifiable>0</unmodifiable>
<values>long|short|default|forbid</values>
<classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>
</cache>
<code>
<contenttype>PureText</contenttype>
<disabled>0</disabled>
<editor>PureText</editor>
<name>code</name>
<number>2</number>
<prettyName>Code</prettyName>
<rows>20</rows>
<size>50</size>
<unmodifiable>0</unmodifiable>
<classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>
</code>
<name>
<disabled>0</disabled>
<name>name</name>
<number>1</number>
<prettyName>Name</prettyName>
<size>30</size>
<unmodifiable>0</unmodifiable>
<classType>com.xpn.xwiki.objects.classes.StringClass</classType>
</name>
<parse>
<disabled>0</disabled>
<displayFormType>select</displayFormType>
<displayType>yesno</displayType>
<name>parse</name>
<number>4</number>
<prettyName>Parse content</prettyName>
<unmodifiable>0</unmodifiable>
<classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>
</parse>
<use>
<cache>0</cache>
<disabled>0</disabled>
<displayType>select</displayType>
<multiSelect>0</multiSelect>
<name>use</name>
<number>3</number>
<prettyName>Use this extension</prettyName>
<relationalStorage>0</relationalStorage>
<separator> </separator>
<separators>|, </separators>
<size>1</size>
<unmodifiable>0</unmodifiable>
<values>currentPage|onDemand|always</values>
<classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>
</use>
</class>
<property>
<cache>long</cache>
</property>
<property>
<code>/**
* Generic helper methods.
*/
define('xwiki-utils', ['jquery', 'xwiki-meta'], function($, xm) {
var getAttachmentURL = function(attachment, action, queryString) {
var docRef = xm.documentReference;
if (typeof attachment !== 'string') {
docRef = attachment.parent;
attachment = attachment.name;
}
if (typeof queryString === 'object') {
queryString = $.param(queryString);
}
var attachmentURL = new XWiki.Document(docRef).getURL(action || 'download') +
(docRef.name == 'WebHome' ? docRef.name : '') + '/' + attachment +
(queryString ? '?' + queryString : '');
return attachmentURL;
};
var uploadAttachment = function(blob, attachment) {
var documentReference = xm.documentReference;
if (typeof attachment !== 'string') {
documentReference = attachment.parent;
attachment = attachment.name;
}
var doc = new XWiki.Document(documentReference);
var url = doc.getURL('upload');
var formData = new FormData();
formData.append('filepath', blob);
formData.append('filename', attachment);
formData.append('form_token', xm.form_token);
// The default redirect adds more time for the upload and we don't need to render those pages.
formData.append('xredirect', doc.getURL('get', 'outputSyntax=plain'));
return $.post({
url : url,
data : formData,
processData : false,
contentType : false
});
};
var deleteAttachment = function(attachmentName) {
var attachmentURL = getAttachmentURL(attachmentName, 'delattachment', {
'form_token': xm.form_token,
'xredirect': XWiki.currentDocument.getURL('get', 'outputSyntax=plain')
});
return $.post(attachmentURL);
};
return {
getAttachmentURL: getAttachmentURL,
uploadAttachment: uploadAttachment,
deleteAttachment: deleteAttachment
};
});
/**
* Diagram application configuration received from the server side.
*/
define('diagram-config', ['jquery'], function($) {
return $('[data-diagram-config]').data('diagramConfig');
});
/**
* Diagram application setup.
*/
define('diagram-setup', ['diagram-config'], function(diagramConfig) {
// mxGraph client setup
window.mxBasePath = diagramConfig.mxGraphClientBasePath;
window.mxLanguage = diagramConfig.locale;
// draw.io setup
var drawIOBasePath = diagramConfig.drawIOBasePath;
window.RESOURCES_PATH = drawIOBasePath + 'resources';
window.RESOURCE_BASE = RESOURCES_PATH + '/dia';
window.STENCIL_PATH = drawIOBasePath + 'stencils';
window.IMAGE_PATH = drawIOBasePath + 'images';
window.STYLE_PATH = CSS_PATH = drawIOBasePath + 'styles';
window.SHAPES_PATH = drawIOBasePath + 'shapes';
window.GRAPH_IMAGE_PATH = drawIOBasePath + 'img';
window.TEMPLATE_PATH = drawIOBasePath + 'templates';
// This is used by File > Open Library from > Browser...
window.OPEN_FORM = drawIOBasePath + 'open.html';
window.OPEN_URL = new XWiki.Document('DiagramImporter', 'Diagram').getURL('get', 'outputSyntax=plain');
window.EXPORT_URL = diagramConfig.exportURL;
window.PROXY_URL = new XWiki.Document('DiagramProxy', 'Diagram').getURL('get');
window.isLocalStorage = true;
window.urlParams = (function(params) {
var pairs = window.location.search.substr(1).split('&');
pairs.forEach(function(pair) {
var parts = pair.split('=', 2);
if (parts.length === 2) {
params[parts[0]] = decodeURIComponent(parts[1].replace(/\+/g, " "));
}
});
return params;
})({
// Don't show the splash screen.
'splash': '0',
// Disable the tabbed UI.
'pages': '0',
// Disable the GitHub integration.
'gh': '0',
// Disable the GitLab integration.
'gl': '0',
// Disable the Dropbox integration.
'db': '0',
// Disable the Google Drive integration.
'gapi': '0',
// Disable Google Analytics.
'analytics': '0',
// Disable the One Drive integration.
'od': '0',
// Disable the Trello integration.
'tr': '0'
});
// Disabling the integration with these external services is not enough because the draw.io code has hard-coded
// references.
window.DriveFile = window.DropboxFile = window.GitHubFile = window.OneDriveFile = window.TrelloFile = false;
window.DriveLibrary = window.DropboxLibrary = window.GitHubLibrary = window.OneDriveLibrary = window.TrelloLibrary
= false;
var suffix = diagramConfig.debug ? '' : '.min';
var mxGraphEditorBasePath = diagramConfig.mxGraphEditorBasePath;
require.config({
paths: {
'base64': mxGraphEditorBasePath + 'deflate/base64.min',
'jscolor': mxGraphEditorBasePath + 'jscolor/jscolor.min',
'pako': mxGraphEditorBasePath + 'deflate/pako.min',
'sanitizer': mxGraphEditorBasePath + 'sanitizer/sanitizer.min',
'spin': drawIOBasePath + 'js/spin/spin.min',
'jszip': drawIOBasePath + 'js/jszip/jszip.min',
'mxgraph-init': drawIOBasePath + 'js/draw.io.init' + suffix,
'mxgraph-client': mxBasePath + 'mxClient.bundle' + suffix,
'mxgraph-editor': mxGraphEditorBasePath + 'mxGraphEditor' + suffix,
'mxgraph-viewer': mxGraphEditorBasePath + 'mxGraphViewer' + suffix,
'draw.io': drawIOBasePath + 'js/draw.io' + suffix,
'draw.io.viewer': drawIOBasePath + 'js/draw.io.viewer' + suffix,
'resourceSelector': new XWiki.Document('WebHome', 'Diagram.ResourceSelector').getURL('jsx', 'minify=' + !diagramConfig.debug)
},
shim: {
'mxgraph-client': ['mxgraph-init'],
'mxgraph-editor': ['mxgraph-client', 'jscolor', 'sanitizer'],
'mxgraph-viewer': ['mxgraph-client', 'sanitizer'],
'draw.io': ['mxgraph-editor', 'base64', 'pako-global', 'spin-global', 'jszip-global'],
'draw.io.viewer': ['mxgraph-viewer', 'pako-global', 'spin-global'],
}
})
define('pako-global', ['pako'], function(pako) {
// draw.io expects a global variable.
window.pako = pako;
});
define('spin-global', ['spin'], function(spin) {
// draw.io expects a global variable.
window.Spinner = spin;
});
define('jszip-global', ['jszip'], function(JSZip) {
// draw.io expects a global variable.
window.JSZip = JSZip;
});
});
/**
* Handles links to wiki pages (this is used by both the diagram viewer and the diagram editor).
*/
define('diagram-link-handler', ['xwiki-utils', 'draw.io.common'], function(xutils) {
// See https://about.draw.io/interactive-diagrams-with-custom-links-and-actions/
// See https://desk.draw.io/support/solutions/articles/16000080137
// See https://jgraph.github.io/drawio-tools/tools/link.html
var xwikiCustomLinkPrefix = 'data:xwiki/reference,';
var isXWikiCustomLink = function(href) {
return typeof href === 'string' && href.substring(0, xwikiCustomLinkPrefix.length) === xwikiCustomLinkPrefix;
};
var getResourceReferenceFromCustomLink = function(href) {
if (isXWikiCustomLink(href)) {
var resourceReference = href.substring(xwikiCustomLinkPrefix.length);
var typeSeparatorIndex = resourceReference.indexOf(':');
if (typeSeparatorIndex >= 0) {
return {
type: resourceReference.substring(0, typeSeparatorIndex),
reference: resourceReference.substring(typeSeparatorIndex + 1)
}
}
}
if (href) {
return {
type: 'url',
reference: href
};
}
};
var getCustomLinkFromResourceReference = function(resourceReference) {
if (resourceReference.type === 'url') {
return resourceReference.reference || '';
} else if (resourceReference.type) {
return xwikiCustomLinkPrefix + resourceReference.type + ':' + (resourceReference.reference || '');
} else {
// An empty link usually means that the link should be removed.
return '';
}
};
var getURLFromResourceReference = function(resourceReference, diagramReference) {
switch (resourceReference.type) {
case 'doc':
let documentReference = XWiki.Model.resolve(resourceReference.reference, XWiki.EntityType.DOCUMENT,
XWiki.currentDocument.documentReference);
return new XWiki.Document(documentReference).getURL();
case 'attach':
// The diagram reference is used for the attachment reference only if is specified. This is needed when the
// diagram is displayed on another page. See https://github.com/xwikisas/application-diagram/issues/121
let attachmentReference = XWiki.Model.resolve(resourceReference.reference, XWiki.EntityType.ATTACHMENT,
diagramReference || XWiki.currentDocument.documentReference);
return xutils.getAttachmentURL(attachmentReference);
default:
return resourceReference.reference;
}
};
var getURLFromCustomLink = function(href, diagramReference) {
let resourceReference = getResourceReferenceFromCustomLink(href);
return getURLFromResourceReference(resourceReference, diagramReference);
};
var originalHandleCustomLink = Graph.prototype.handleCustomLink;
Graph.prototype.handleCustomLink = function(href) {
let actualHref = href;
if (isXWikiCustomLink(href)) {
actualHref = 'data:action/json,' + JSON.stringify({'actions': [{'open': getURLFromCustomLink(href)}]});
}
return originalHandleCustomLink.call(this, actualHref);
};
var originalGetLinkTitle = EditorUi.prototype.getLinkTitle;
EditorUi.prototype.getLinkTitle = function(href) {
if (isXWikiCustomLink(href)) {
let resourceReference = getResourceReferenceFromCustomLink(href);
return resourceReference.type + ':' + resourceReference.reference;
} else {
return originalGetLinkTitle.apply(this, arguments);
}
};
var getFragmentIdentifierFromURL = function(url) {
if (typeof url === 'string' && url.substring(0, 5) !== 'data:') {
fragmentIdentifierPosition = url.indexOf('#');
if (fragmentIdentifierPosition >= 0) {
var fragmentIdentifier = url.substring(fragmentIdentifierPosition + 1);
try {
return decodeURIComponent(fragmentIdentifier);
} catch (e) {
// Malformed URI sequence. Return the fragment identifier as is.
return fragmentIdentifier;
}
}
}
};
var getCustomLinkFromURL = function(url) {
if (isXWikiCustomLink(url)) {
return url;
} else {
var fragmentIdentifier = getFragmentIdentifierFromURL(url);
if (isXWikiCustomLink(fragmentIdentifier)) {
return fragmentIdentifier;
}
}
};
return {
isXWikiCustomLink: isXWikiCustomLink,
getResourceReferenceFromCustomLink: getResourceReferenceFromCustomLink,
getCustomLinkFromResourceReference: getCustomLinkFromResourceReference,
getCustomLinkFromURL: getCustomLinkFromURL,
getURLFromCustomLink: getURLFromCustomLink,
getURLFromResourceReference: getURLFromResourceReference
};
});
/**
* Filters the Graph XML when:
* <ul>
* <li>
* the XML is <b>loaded</b> from the XWiki database
* <ul>
* <li>convert the draw.io WAR paths to draw.io WebJar paths (e.g. include the draw.io version)</li>
* <li>replace the attachment reference from the image source with the attachment URL</li>
* </ul>
* </li>
* <li>
* the XML is <b>saved</b> to the XWiki database
* <ul>
* <li>convert the draw.io WebJar paths to draw.io WAR paths (e.g. remove the draw.io version)</li>
* <li>internal links should be saved using the entity reference instead of the entity URL</li>
* <li>internal images should be saved using the attachment reference instead of the attachment URL</li>
* </ul>
* </li>
* <li>
* the XML is <b>imported</b> from an external source
* <ul>
* <li>convert the draw.io WAR paths to draw.io WebJar paths (e.g. include the draw.io version)</li>
* <li>replace absolute URLs with internal custom links, if the target entity reference is indicated</li>
* </ul>
* </li>
* <li>
* the XML is <b>exported</b> to an external source
* <ul>
* <li>convert the draw.io WebJar paths to draw.io WAR paths (e.g. remove the draw.io version)</li>
* <li>convert attached images to data URI (but keep some metadata to idicate the attachment reference)</li>
* <li>replace custom internal links with absolute URLs (but keep some metadata to indicate the entity reference)</li>
* </ul>
* </li>
* </ul>
*/
define('diagram-graph-xml-filter', ['jquery', 'diagram-config', 'diagram-link-handler'], function($, diagramConfig, diagramLinkHandler) {
var originalGetGraphXml = Editor.prototype.getGraphXml;
Editor.prototype.getGraphXml = function(ignoreSelection, forStorage) {
var node = originalGetGraphXml.apply(this, arguments);
var filterImage = forStorage === true ? onSaveImage : onExportImage;
var filterLink = forStorage === true ? onSaveLink : onExportLink;
var filterBackgroundImage = forStorage === true ? onSaveBackgroundImage : onExportBackgroundImage;
filter(this.graph, node, filterImage, filterLink, filterBackgroundImage);
return node;
};
var originalSetGraphXml = Editor.prototype.setGraphXml;
Editor.prototype.setGraphXml = function(node) {
var filterImage = node.fromStorage === true ? onLoadImage : onImportImage;
var filterLink = node.fromStorage === true ? onLoadLink : onImportLink;
var filterBackgroundImage = node.forStorage === true ? onLoadBackgroundImage : onImportBackgroundImage;
filter(this.graph, node, filterImage, filterLink, filterBackgroundImage);
originalSetGraphXml.call(this, node);
};
var originalImportGraphModel = Graph.prototype.importGraphModel;
Graph.prototype.importGraphModel = function(node, dx, dy, crop) {
filter(this, node, onImportImage, onImportLink, onImportBackgroundImage);
originalImportGraphModel.call(this, node, dx, dy, crop);
};
var filter = function(graph, node, filterImage, filterLink, filterBackgroundImage) {
findImageNodes(node).each(function() {
filterImage(this, graph);
});
findLinkNodes(node).each(function() {
filterLink(this, graph);
});
filterBackgroundImage(node);
};
var findImageNodes = function(node) {
return $(node).find('mxCell[style^="image;"], mxCell[style^="shape=image;"]');
};
var findLinkNodes = function(node) {
return $(node).find('UserObject[link], mxCell[value*="\\<a href"]');
};
// Convert the draw.io WebJar paths to draw.io WAR paths (e.g. remove the draw.io version from the path).
// Internal images should be saved using the attachment reference instead of the attachment URL.
var drawIOBasePath = diagramConfig.drawIOBasePath;
var onSaveImage = function(node, graph) {
var style = $(node).attr('style') || '';
var styleObject = graph.stylesheet.getCellStyle(style, {});
var oldSource = styleObject.image || '';
var newSource = oldSource;
if (oldSource.substring(0, drawIOBasePath.length) === drawIOBasePath) {
// Convert draw.io WebJar URL to draw.io WAR path.
// See https://github.com/xwikisas/application-diagram/issues/11
newSource = oldSource.substring(drawIOBasePath.length);
} else {
var customLink = diagramLinkHandler.getCustomLinkFromURL(oldSource);
if (customLink) {
// Save the XWiki attachment reference instead of the attachment URL.
// We have to encode the value in order to avoid breaking the style string.
newSource = encodeURIComponent(customLink);
}
}
if (newSource !== oldSource) {
$(node).attr('style', style.replace(oldSource, newSource));
}
};
// Convert the draw.io WAR paths to draw.io WebJar paths (e.g. include the draw.io version in the path).
// Replace the attachment reference from the image source with the attachment URL.
var onLoadImage = function(node, graph) {
var style = $(node).attr('style') || '';
var styleObject = graph.stylesheet.getCellStyle(style, {});
var oldSource = styleObject.image || '';
var newSource = oldSource;
if (oldSource.substring(0, 4) === 'img/') {
// Convert draw.io WAR path to draw.io WebJar URL.
// See https://github.com/xwikisas/application-diagram/issues/11
newSource = drawIOBasePath + oldSource;
} else {
try {
var decodedOldSource = decodeURIComponent(oldSource);
if (diagramLinkHandler.isXWikiCustomLink(decodedOldSource)) {
// Replace the attachment reference from the image source with the attachment URL, but keep the attachment
// reference in the fragment identifier in order to be able to restore it on save.
var diagramReference = XWiki.Model.resolve($(graph.container).data('reference'), XWiki.EntityType.DOCUMENT);
newSource = diagramLinkHandler.getURLFromCustomLink(decodedOldSource, diagramReference) + '#' + oldSource;
}
} catch (e) {
// Ignore.
}
}
if (newSource !== oldSource) {
$(node).attr('style', style.replace(oldSource, newSource));
}
};
// Convert the draw.io WebJar paths to draw.io WAR paths (e.g. remove the draw.io version).
// Convert attached images to data URI (but keep some metadata to idicate the attachment reference).
var onExportImage = function(node, graph) {
var style = $(node).attr('style') || '';
var styleObject = graph.stylesheet.getCellStyle(style, {});
var oldSource = styleObject.image || '';
var newSource = convertImageLink(oldSource, true);
var customLink = diagramLinkHandler.getCustomLinkFromURL(oldSource);
if (customLink) {
// For image attachments, keep some metadata to indicate the original source.
style = mxUtils.setStyle(style, 'xwikiImage', encodeURIComponent(customLink));
}
if (newSource !== oldSource) {
$(node).attr('style', style.replace(oldSource, newSource));
}
};
var onImportBackgroundImage = function(node) {
// Do nothing.
};
var onSaveBackgroundImage = function(node) {
// Do nothing.
};
var onLoadBackgroundImage = function(node) {
// Do nothing.
};
var onExportBackgroundImage = function(node) {
if (node.getAttribute('backgroundImage') == undefined) {
return;
}
var backgroundImage = JSON.parse(node.getAttribute('backgroundImage'));
var oldSource = backgroundImage.src;
var newSource = convertImageLink(oldSource);
var customLink = diagramLinkHandler.getCustomLinkFromURL(oldSource);
if (customLink) {
// For image attachments, keep some metadata to indicate the original source.
backgroundImage.xwikiImage = encodeURIComponent(customLink);
}
if (newSource !== oldSource) {
backgroundImage.src = newSource;
node.setAttribute('backgroundImage', JSON.stringify(backgroundImage));
}
};
var convertImageLink = function(oldSource, removeBase) {
var newSource = oldSource;
if (oldSource.substring(0, drawIOBasePath.length) === drawIOBasePath) {
// Convert the draw.io WebJar paths to draw.io WAR paths (e.g. remove the draw.io version).
newSource = oldSource.substring(drawIOBasePath.length);
} else if (oldSource.substring(0, 5) !== 'data:') {
// Convert other images to data URI.
newSource = maybeConvertToDataURI(oldSource, removeBase);
}
return newSource;
};
var maybeConvertToDataURI = function(url, removeBase) {
var image = getCachedImageByURL(url);
if (image) {
var canvas = document.createElement('canvas');
var context2D = canvas.getContext('2d');
canvas.height = image.naturalHeight;
canvas.width = image.naturalWidth;
context2D.drawImage(image, 0, 0);
try {
url = canvas.toDataURL();
var semicolonIndex = url.indexOf(';');
// Remove temporarily 'base64,' when the url is used in a style attribute, since a split is done by ',' afterwards.
if (semicolonIndex > 0 && removeBase ) {
url = url.substring(0, semicolonIndex) + url.substring(url.indexOf(',', semicolonIndex + 1));
}
} catch (e) {
// Ignore.
}
}
return url;
};
var diagramImages = {};
var collectImages = function() {
$(this.diagramContainer).find('image').each(function() {
var absoluteURL = $(this).attr('xlink:href');
if (diagramImages.hasOwnProperty(absoluteURL)) {
return;
}
var image = diagramImages[absoluteURL] = new Image();
image.crossOrigin = 'use-credentials';
image.src = absoluteURL;
});
};
$(document).on('diagramEditorCreated', function(event, editorUI) {
editorUI.editor.addListener('fileLoaded', $.proxy(collectImages, editorUI));
editorUI.editor.graph.model.addListener(mxEvent.CHANGE, $.proxy(collectImages, editorUI));
});
var getCachedImageByURL = function(url) {
var absoluteURL = $('<a/>').attr('href', url).prop('href');
var image = diagramImages[absoluteURL];
if (image && image.complete && image.naturalWidth) {
return image;
}
};
// Convert the draw.io WAR paths to draw.io WebJar paths (e.g. include the draw.io version in the path).
var onImportImage = function(node, graph) {
onLoadImage(node, graph);
};
var onSaveLink = function(node) {
// Nothing to do here (save the link as is).
};
var onLoadLink = function(node) {
// Nothing to do here (keep the link as is).
};
// Replace custom internal links with absolute URLs (but keep some metadata to indicate the entity reference).
// Consider both the cases when the node is UserObject or mxCell.
var onExportLink = function(node) {
var tagName = node.tagName.toLowerCase();
var value = $(node).attr('value');
var href = $('<div></div>').html(value).find('a[href]').attr('href');
var link = tagName == 'userobject' ? $(node).attr('link') : href;
if (diagramLinkHandler.isXWikiCustomLink(link)) {
var url = diagramLinkHandler.getURLFromCustomLink(link);
var absoluteURL = $('<a/>').attr('href', url).prop('href');
updateLinkAttributes(node, value, link, absoluteURL);
}
};
// Replace absolute URLs with internal custom links, if the target entity reference is indicated.
var onImportLink = function(node) {
var link = $(node).attr('data-link');
if (diagramLinkHandler.isXWikiCustomLink(link)) {
var value = $(node).attr('value');
var href = $('<div></div>').html(value).find('a[href]').attr('href');
updateLinkAttributes(node, value, href, link);
}
};
var updateLinkAttributes = function(node, value, oldURL, newURL) {
var attributesMap = {'data-link': null};
if (node.tagName.toLowerCase() == 'userobject') {
attributesMap.link = newURL;
} else {
attributesMap.value = value.replace(oldURL, newURL);
}
$(node).attr(attributesMap);
};
});
/**
* Utility functions used in both view and edit modes.
*/
define('diagram-utils', ['jquery', 'diagram-link-handler'], function($, diagramLinkHandler) {
//
// Get a XML diagram from hash.
// The hash begins with 'R' & continues with the encoded diagram.
//
var getDiagramXMLFromURL = function(url) {
let hashIndex = url.indexOf('#R');
if (hashIndex > -1) {
// Exclude first 2 letters from hash (#R).
let hash = url.substring(hashIndex+2);
try {
let decodedData = decodeURIComponent(hash);
let graph = new Graph();
let rawDiagram = graph.decompress(decodedData);
return rawDiagram;
} catch (e) {
console.error(e.stack)
}
}
return null;
};
//
// Load the translation file and the default theme.
//
var loadTranslationAndTheme = function() {
var deferred = $.Deferred();
mxResources.loadDefaultBundle = false;
var bundle = mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) ||
mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage);
// The theme is important because it controls how the shapes are rendered.
mxUtils.getAll([bundle, STYLE_PATH + '/default.xml'], function(response) {
// Adds bundle text to resources.
mxResources.parse(response[0].getText());
deferred.resolve(response[1].getDocumentElement());
}, function() {
// Failed to load the translation file or the theme.
deferred.reject();
});
return deferred.promise();
};
//
// Fix XWiki custom links in print preview.
//
var originalPrintPreviewAddGraphFragment = mxPrintPreview.prototype.addGraphFragment;
mxPrintPreview.prototype.addGraphFragment = function(dx, dy, scale, pageNumber, div, clip) {
var result = originalPrintPreviewAddGraphFragment.apply(this, arguments);
// Convert XWiki custom links to absolute URLs.
$(div).find('a').each(function() {
// We have to update both SVG links and HTML links (within foreign objects).
['xlink:href', 'href'].forEach(function(name) {
var value = $(this).attr(name);
if (diagramLinkHandler.isXWikiCustomLink(value)) {
var url = diagramLinkHandler.getURLFromCustomLink(value);
var absoluteURL = $('<a/>').attr('href', url).prop('href');
$(this).attr(name, absoluteURL);
}
}, this);
});
return result;
};
return {
getDiagramXMLFromURL: getDiagramXMLFromURL,
loadTranslationAndTheme: loadTranslationAndTheme
};
});</code>
</property>
<property>
<name>Code used in both view and edit modes</name>
</property>
<property>
<parse>0</parse>
</property>
<property>
<use>onDemand</use>
</property>
</object>
<object>
<name>Diagram.DiagramSheet</name>
<number>0</number>
<className>XWiki.StyleSheetExtension</className>
<guid>b73d218d-1ebd-484b-91e1-d9a9cac2ea56</guid>
<class>
<name>XWiki.StyleSheetExtension</name>
<customClass/>
<customMapping/>
<defaultViewSheet/>
<defaultEditSheet/>
<defaultWeb/>
<nameField/>
<validationScript/>
<cache>
<cache>0</cache>
<disabled>0</disabled>
<displayType>select</displayType>
<multiSelect>0</multiSelect>
<name>cache</name>
<number>5</number>
<prettyName>Caching policy</prettyName>
<relationalStorage>0</relationalStorage>
<separator> </separator>
<separators>|, </separators>
<size>1</size>
<unmodifiable>0</unmodifiable>
<values>long|short|default|forbid</values>
<classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>
</cache>
<code>
<contenttype>PureText</contenttype>
<disabled>0</disabled>
<editor>PureText</editor>
<name>code</name>
<number>2</number>
<prettyName>Code</prettyName>
<rows>20</rows>
<size>50</size>
<unmodifiable>0</unmodifiable>
<classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>
</code>
<contentType>
<cache>0</cache>
<disabled>0</disabled>
<displayType>select</displayType>
<multiSelect>0</multiSelect>
<name>contentType</name>
<number>6</number>
<prettyName>Content Type</prettyName>
<relationalStorage>0</relationalStorage>
<separator> </separator>
<separators>|, </separators>
<size>1</size>
<unmodifiable>0</unmodifiable>
<values>CSS|LESS</values>
<classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>
</contentType>
<name>
<disabled>0</disabled>
<name>name</name>
<number>1</number>
<prettyName>Name</prettyName>
<size>30</size>
<unmodifiable>0</unmodifiable>
<classType>com.xpn.xwiki.objects.classes.StringClass</classType>
</name>
<parse>
<disabled>0</disabled>
<displayFormType>select</displayFormType>
<displayType>yesno</displayType>
<name>parse</name>
<number>4</number>
<prettyName>Parse content</prettyName>
<unmodifiable>0</unmodifiable>
<classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>
</parse>
<use>
<cache>0</cache>
<disabled>0</disabled>
<displayType>select</displayType>
<multiSelect>0</multiSelect>
<name>use</name>
<number>3</number>
<prettyName>Use this extension</prettyName>
<relationalStorage>0</relationalStorage>
<separator> </separator>
<separators>|, </separators>
<size>1</size>
<unmodifiable>0</unmodifiable>
<values>currentPage|onDemand|always</values>
<classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>
</use>
</class>
<property>
<cache>long</cache>
</property>
<property>
<code>/* The diagram styles should be loaded after the skin and before our overwrites. */
@import url("$services.webjars.url('org.xwiki.contrib:draw.io', 'styles/grapheditor.css')");
/**
* Diagram Editor and Dialogs
*/
.diagram-editor {
height: 600px;
min-height: 20px;
position: relative;
}
.diagram-editor input[type="checkbox"], .diagram-editor input[type="radio"],
.mxPopupMenu input[type="checkbox"], .mxPopupMenu input[type="radio"],
.mxWindow input[type="checkbox"], .mxWindow input[type="radio"],
.geDialog input[type="checkbox"], .geDialog input[type="radio"] {
vertical-align: text-bottom;
}
.fullScreenWrapper .buttons > .buttonwrapper:first-child {
/* Hide the "Exit Full Screen" button. We have a tool bar entry for this. */
display: none !important;
}
/**
* Overwrite XWiki skin styles
*/
.diagram-editor *,
.mxPopupMenu *,
.mxWindow *,
.geDialog,
.geDialog * {
box-sizing: content-box;
}
.mxPopupMenu,
.mxWindow,
.geDialog {
/* We need the same font size as on draw.io because the dialog height is hard-coded. */
font-size: 10pt;
}
.diagram-editor button, .diagram-editor select,
.mxPopupMenu button, .mxPopupMenu select,
.mxWindow button, .mxWindow select,
.geDialog button, .geDialog select {
box-sizing: border-box;
}
.diagram-editor input[type="text"],
.mxPopupMenu input[type="text"],
.mxWindow input[type="text"],
.geDialog input[type="text"] {
font-size: inherit;
height: auto;
padding: 1px;
}
.diagram-editor img,
.mxPopupMenu img,
.mxWindow img,
.geDialog img {
vertical-align: baseline;
}
.diagram-editor hr,
.mxPopupMenu hr,
.mxWindow hr,
.geDialog hr {
margin: 0;
}
.mxPopupMenu table,
.mxWindow table,
.geDialog table {
margin-bottom: 0;
width: auto;
}
.diagram-editor table > tbody > tr > td,
.mxPopupMenu table > tbody > tr > td,
.mxWindow table > tbody > tr > td,
.geDialog table > tbody > tr > td {
border-top: 0 none;
}
.geDialog table > tbody > tr > td {
padding: 0;
vertical-align: baseline;
}
.geDialog h3 {
font-size: 1.17em;
font-weight: bold;
}
.geDialog input[type='checkbox'] {
vertical-align: baseline;
}
.geDialog label {
display: inline;
}