forked from UNC-Libraries/jquery.xmleditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.xmleditor.js
2908 lines (2559 loc) · 89.5 KB
/
jquery.xmleditor.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
;(function($){
/*
Copyright 2008 The University of North Carolina at Chapel Hill
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* jQuery xml Editor
*
* Dependencies:
* jquery 1.7+
* jquery.ui 1.7+
* ajax ace editor
* jquery.autosize.js (optional)
* vkbeautify.js (optional)
*
* @author Ben Pennell
*/
var menuContainerClass = "xml_menu_container";
var menuHeaderClass = "menu_header";
var menuColumnClass = "xml_menu_column";
var menuContentClass = 'menu_content';
var menuExpandDuration = 180;
var xmlElementClass = 'xml_element';
var topLevelContainerClass = 'top_level_element_group';
var elementRootPrefix = "root_element_";
var elementPrefix = "xml_element_";
var childrenContainerSelector = " > .xml_children";
var childrenContainerClass = "xml_children";
var attributeContainerClass = "attribute_container";
var attributesContainerSelector = " > .xml_attrs";
var attributesContainerClass = "xml_attrs";
var xmlMenuHeaderPrefix = "xml_header_item_";
var xmlEditorContainerClass = "xml_editor_container";
var xmlWorkAreaContainerClass = "xml_work_area";
var addTopMenuClass = "add_top_menu";
var addAttrMenuClass = "add_attribute_menu";
var addElementMenuClass = "add_element_menu";
var xmlMenuBarClass = "xml_menu_bar";
var submitButtonClass = "send_xml";
var submissionStatusClass = "xml_submit_status";
var xmlContentClass = "xml_content";
var editorTabAreaClass = "xml_tab_area";
var problemsPanelClass = "xml_problems_panel";
var guiContentClass = "gui_content";
var textContentClass = "text_content";
var editorHeaderClass = "xml_editor_header";
var localName = function(node) {
var localName = node.localName;
if (localName) return localName;
var index = node.nodeName.indexOf(':');
if (index == -1) return node.nodeName;
return node.nodeName.substring(index + 1);
};
$.widget( "xml.xmlEditor", {
options: {
// Schema object to be used
schema: null,
// Whether or not to attempt to load the schema in a worker thread, if available
loadSchemaAsychronously: true,
// Path to directory containing cycle.js, needed for loadSchemaAsychronously
libPath: null,
// Document retrieval and upload parameters
ajaxOptions : {
xmlUploadPath: null,
xmlRetrievalPath: null,
xmlRetrievalParams : null
},
// Function triggered after uploading XML document, to interpret if the response was successful or not. If upload failed, an error message should be returned.
submitResponseHandler : null,
// Selector to the XML to be used as the starting document, if it is embedded in the current page
localXMLContentSelector: this.element,
// Event function trigger after an xml element is update via the gui
elementUpdated : undefined,
// Title for the document, displayed in the header
documentTitle : null,
addTopMenuHeaderText : 'Add Top Element',
addAttrMenuHeaderText : 'Add Attribute',
addElementMenuHeaderText : 'Add Subelement',
confirmExitWhenUnsubmitted : true,
enableGUIKeybindings : true,
floatingMenu : true,
// Requires jquery.autosize, defaults to false if plugin isn't detected
expandingTextAreas: true,
// Pretty formatting of XML output. Requires vkbeauty.js, defaults to false is not available
prettyXML : true,
// Number of history states held for the undo feature
undoHistorySize: 20,
// Object containing additional entries to add to the header menu
menuEntries: undefined,
targetNS: null
},
_create: function() {
var self = this;
this.instanceNumber = $("xml-xmlEditor").length;
// Tree of xml element types
this.xmlTree = null;
// State of the XML document
this.xmlState = null;
// Container for the entire editor
this.xmlEditorContainer = null;
// Container for the subeditors
this.xmlWorkAreaContainer = null;
// Tabbed container for differentiating between specific subeditors
this.xmlTabContainer = null;
// Header container for the menu and top level info
this.editorHeader = null;
// Panel for displaying errors
this.problemsPanel = null;
// GUI Editor object
this.guiEditor = null;
// Text Editor object
this.textEditor = null;
// Currently active editor
this.activeEditor = null;
// History manager for undo/redo
this.undoHistory = null;
// Top level menu bar object
this.menuBar = null;
// Element modification object
this.modifyMenu = null;
var url = document.location.href;
var index = url.lastIndexOf("/");
if (index != -1)
this.baseUrl = url.substring(0, index + 1);
// Detect optional features
if (!$.isFunction($.fn.autosize))
this.options.expandingTextAreas = false;
if (!vkbeautify)
this.options.prettyXML = false;
if (typeof(this.options.schema) != 'function') {
// Turn relative paths into absolute paths for the sake of web workers
if (this.options.libPath) {
if (this.options.libPath.indexOf('http') != 0)
this.libPath = this.baseUrl + this.options.libPath;
else this.libPath = this.options.libPath;
} else this.libPath = this.baseUrl + "lib/";
if ((typeof this.options.schema == 'string' || typeof this.options.schema instanceof String)
&& this.options.schema.indexOf('http') != 0)
this.options.schema = this.baseUrl + this.options.schema;
}
this.loadSchema(this.options.schema);
},
_init: function() {
if (this.options.submitResponseHandler == null)
this.options.submitResponseHandler = this.swordSubmitResponseHandler;
// Retrieve the local xml content before we start populating the editor.
var localXMLContent = null;
if ($(this.options.localXMLContentSelector).is("textarea")) {
localXMLContent = $(this.options.localXMLContentSelector).val();
} else {
localXMLContent = this.element.html();
}
this.element.empty();
this.xmlState = null;
this.xmlEditorContainer = $("<div/>").attr('class', xmlEditorContainerClass).appendTo(this.element);
this.xmlWorkAreaContainer = null;
this.xmlTabContainer = null;
this.editorHeader = null;
this.problemsPanel = null;
this.guiEditor = new GUIEditor(this);
this.textEditor = new TextEditor(this);
this.activeEditor = this.guiEditor;
var self = this;
this.undoHistory = new UndoHistory(this);
this.undoHistory.setStateChangeEvent(function() {
self.refreshDisplay();
});
this.menuBar = new MenuBar(this);
this.menuBar.updateFunctions.push(this.refreshMenuUndo);
this.menuBar.updateFunctions.push(this.refreshMenuSelected);
if (this.options.menuEntries) {
$.each(this.options.menuEntries, function() {
self.menuBar.addEntry(this);
});
}
this.modifyMenu = new ModifyMenuPanel(this);
if (this.options.enableGUIKeybindings)
$(window).keydown(function(e){
self.keydownCallback(e);
});
if (this.options.confirmExitWhenUnsubmitted) {
$(window).bind('beforeunload', function(e) {
if (self.xmlState != null && self.xmlState.isChanged()) {
return "The document contains unsaved changes.";
}
});
}
this.loadDocument(this.options.ajaxOptions, localXMLContent);
},
loadSchema: function(schema) {
var self = this;
// If the schema is a function, execute it to get the schema from it.
if (jQuery.isFunction(schema)) {
this.schema = schema.apply();
self._schemaReady();
} else {
// Load schema in separate thread for browsers tha support it. IE10 blocked to avoid security error
if (this.options.loadSchemaAsychronously && !window.MSBlobBuilder
&& typeof(window.URL) !== "undefined" && typeof(Worker) !== "undefined" && typeof(Blob) !== "undefined") {
var blob = new Blob([
"self.onmessage = function(e) {" +
"importScripts(e.data.libPath + 'cycle.js');" +
"var schema;" +
"if (typeof e.data.schema == 'string' || typeof e.data.schema instanceof String) {" +
" var xmlhttp = new XMLHttpRequest();" +
" xmlhttp.onreadystatechange = function() {" +
" if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {" +
" schema = eval('(' + xmlhttp.responseText + ')');" +
" self.postMessage(JSON.retrocycle(schema));" +
" }" +
" };" +
" xmlhttp.open('GET', e.data.schema, true);" +
" xmlhttp.send();" +
"} else {" +
" schema = JSON.retrocycle(e.data.schema);" +
" self.postMessage(schema);" +
"}" +
"}"
], { type: "text/javascript" });
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
self.schema = e.data;
self._schemaReady();
worker.terminate();
};
worker.onerror = function(e) {
self.schema = JSON.retrocycle(schema);
self._schemaReady();
};
worker.postMessage({'schema' : schema, 'libPath' : this.libPath});
} else {
if (typeof schema == 'string' || typeof schema instanceof String) {
$.ajax({
url : schema,
async : self.options.loadSchemaAsynchronously,
dataType : 'json',
success : function(data) {
self.schema = JSON.retrocycle(data);
self._schemaReady();
}
});
} else {
self.schema = JSON.retrocycle(schema);
self._schemaReady();
}
}
}
},
loadDocument: function(ajaxOptions, localXMLContent) {
if (ajaxOptions != null && ajaxOptions.xmlRetrievalPath != null) {
var self = this;
$.ajax({
type : "GET",
url : ajaxOptions.xmlRetrievalPath,
data : (ajaxOptions.xmlRetrievalParams),
dataType : "text",
success : function(data) {
self._documentReady(data);
}
});
} else {
this._documentReady(localXMLContent);
}
},
_documentReady : function(xmlString) {
this.xmlState = new DocumentState(xmlString, this);
this.xmlState.extractNamespacePrefixes();
this._documentAndSchemaReady();
},
_schemaReady : function() {
if (!this.options.targetNS) {
this.targetNS = this.schema.namespace;
}
this.xmlTree = new SchemaTree(this.schema);
this.xmlTree.build();
this._documentAndSchemaReady();
},
_documentAndSchemaReady : function() {
// Join back up asynchronous loading of document and schema
if (!this.xmlTree || !this.xmlState)
return;
this.xmlState.namespaces.namespaceURIs = $.extend({}, this.xmlTree.namespaces.namespaceURIs, this.xmlState.namespaces.namespaceURIs);
this.xmlState.namespaces.namespaceToPrefix = $.extend({}, this.xmlTree.namespaces.namespaceToPrefix, this.xmlState.namespaces.namespaceToPrefix);
this.targetPrefix = this.xmlState.namespaces.getNamespacePrefix(this.options.targetNS);
this.constructEditor();
this.refreshDisplay();
// Capture baseline undo state
this.undoHistory.captureSnapshot();
},
constructEditor: function() {
// Work Area
this.xmlWorkAreaContainer = $("<div/>").attr('class', xmlWorkAreaContainerClass).appendTo(this.xmlEditorContainer);
// Menu bar
this.editorHeader = $("<div/>").attr('class', editorHeaderClass).appendTo(this.xmlWorkAreaContainer);
if (this.options.documentTitle != null)
$("<h2/>").html("Editing Description: " + this.options.documentTitle).appendTo(this.editorHeader);
this.menuBar.render(this.editorHeader);
this.xmlTabContainer = $("<div/>").attr("class", editorTabAreaClass).css("padding-top", this.editorHeader.height() + "px").appendTo(this.xmlWorkAreaContainer);
this.problemsPanel = $("<pre/>").attr('class', problemsPanelClass).hide().appendTo(this.xmlTabContainer);
this.guiEditor.initialize(this.xmlTabContainer);
this.modeChange(0);
var self = this;
$(window).resize(function() {
self.xmlTabContainer.width(self.xmlEditorContainer.outerWidth() - self.modifyMenu.menuColumn.outerWidth());
if (self.activeEditor != null){
self.activeEditor.resize();
}
self.editorHeader.width(self.xmlTabContainer.width());
if (self.options.floatingMenu) {
self.modifyMenu.setMenuPosition();
}
});
this.modifyMenu.initialize(this.xmlEditorContainer);
this.modifyMenu.addMenu(addElementMenuClass, this.options.addElementMenuHeaderText,
true, false, true);
this.modifyMenu.addAttributeMenu(addAttrMenuClass, this.options.addAttrMenuHeaderText,
true, false, true);
this.addTopLevelMenu = this.modifyMenu.addMenu(addTopMenuClass, this.options.addTopMenuHeaderText,
true, true).populate(this.guiEditor.rootElement);
if (this.options.floatingMenu) {
$(window).bind('scroll', $.proxy(this.modifyMenu.setMenuPosition, this.modifyMenu));
}
$("." + submitButtonClass).click(function() {
self.saveXML();
});
//$(window).resize();
//this.refreshDisplay();
},
addChildElementCallback: function (instigator) {
var xmlElement = $(instigator).data("xml").target;
var objectType = $(instigator).data("xml").objectType;
if (this.textEditor.active) {
// Refresh xml state
if (this.xmlState.changesNotSynced()) {
try {
this.setXMLFromEditor();
} catch (e) {
this.addProblem("Unable to add element, please fix existing XML syntax first.", e);
return;
}
}
}
this.xmlState.addNamespace(objectType);
var newElement = xmlElement.addElement(objectType);
this.activeEditor.addElementEvent(xmlElement, newElement);
},
addAttributeButtonCallback: function(instigator) {
if ($(instigator).hasClass("disabled"))
return;
if (this.xmlState.changesNotSynced()) {
try {
this.setXMLFromEditor();
} catch (e) {
alert(e.message);
return;
}
}
var data = $(instigator).data('xml');
this.xmlState.addNamespace(data.objectType);
data.target.addAttribute(data.objectType);
this.activeEditor.addAttributeEvent(data.target, data.objectType, $(instigator));
},
modeChange: function(mode) {
// Can't change mode to current mode
if ((mode == 0 && this.guiEditor.active) || (mode == 1 && this.textEditor.active))
return this;
if (mode == 0) {
if (this.textEditor.isInitialized() && this.xmlState.isChanged()) {
// Try to reconstruct the xml object before changing tabs. Cancel change if parse error to avoid losing changes.
try {
this.setXMLFromEditor();
} catch (e) {
this.addProblem("Invalid xml", e);
return false;
}
this.undoHistory.captureSnapshot();
}
}
$(".active_mode_tab").removeClass("active_mode_tab");
this.modifyMenu.clearContextualMenus();
if (this.activeEditor != null) {
this.activeEditor.deactivate();
}
if (mode == 0) {
this.activeEditor = this.guiEditor;
$("#" + xmlMenuHeaderPrefix + "XML").addClass("active_mode_tab");
} else {
this.activeEditor = this.textEditor;
$("#" + xmlMenuHeaderPrefix + "Text").addClass("active_mode_tab");
}
this.activeEditor.activate();
return this;
},
refreshDisplay: function() {
if (this.activeEditor == null)
return;
this.activeEditor.refreshDisplay();
if (this.options.floatingMenu) {
this.modifyMenu.setMenuPosition();
}
this.xmlWorkAreaContainer.width(this.xmlEditorContainer.outerWidth() - this.modifyMenu.menuColumn.outerWidth());
},
setXMLFromEditor: function() {
var xmlString = this.textEditor.aceEditor.getValue();
this.xmlState.setXMLFromString(xmlString);
this.guiEditor.setRootElement(this.xmlState.xml.children()[0]);
this.addTopLevelMenu.populate(this.guiEditor.rootElement)
},
saveXML: function() {
if (this.options.ajaxOptions.xmlUploadPath != null) {
this.submitXML();
} else {
// Implement later when there is more browser support for html5 File API
this.exportXML();
}
},
exportXML: function() {
if (typeof(Blob) === "undefined") {
this.addProblem("Browser does not support saving files via this editor. To save, copy and paste the document from the Text view.");
return false;
}
var exportDialog = $("<form><input type='text' class='xml_export_filename' placeholder='file.xml'/><input type='submit' value='Export'/></form>")
.dialog({modal: true, dialogClass: 'xml_dialog', resizable : false, title: 'Enter file name', height: 80});
var self = this;
exportDialog.submit(function(){
if (self.textEditor.active) {
try {
self.setXMLFromEditor();
} catch (e) {
self.xmlState.setDocumentHasChanged(true);
$("." + submissionStatusClass).html("Failed to save<br/>See errors at top").css("background-color", "#ffbbbb").animate({backgroundColor: "#ffffff"}, 1000);
self.addProblem("Cannot save due to invalid xml", e);
return false;
}
}
var xmlString = self.xml2Str(self.xmlState.xml);
var blob = new Blob([xmlString], { type: "text/xml" });
var url = URL.createObjectURL(blob);
exportDialog.dialog('option', 'title', '');
var fileName = exportDialog.find('input[type="text"]').val();
if (!fileName)
fileName = "file.xml";
var download = $('<a>Download ' + fileName + '</a>').attr("href", url);
download.attr("download", fileName);
exportDialog.empty().append(download);
return false;
});
},
submitXML: function() {
if (this.textEditor.active) {
try {
this.setXMLFromEditor();
} catch (e) {
this.xmlState.setDocumentHasChanged(true);
$("." + submissionStatusClass).html("Failed to submit<br/>See errors at top").css("background-color", "#ffbbbb").animate({backgroundColor: "#ffffff"}, 1000);
this.addProblem("Cannot submit due to invalid xml", e);
return false;
}
}
// convert XML DOM to string
var xmlString = this.xml2Str(this.xmlState.xml);
$("." + submissionStatusClass).html("Submitting...");
var self = this;
$.ajax({
'url' : this.options.ajaxOptions.xmlUploadPath,
'contentType' : "application/xml",
'type' : "POST",
'data' : xmlString,
success : function(response) {
var outcome = self.options.submitResponseHandler(response);
if (!outcome) {
self.xmlState.changesCommittedEvent();
self.clearProblemPanel();
} else {
self.xmlState.syncedChangeEvent();
$("." + submissionStatusClass).html("Failed to submit<br/>See errors at top").css("background-color", "#ffbbbb").animate({backgroundColor: "#ffffff"}, 1000);
self.addProblem("Failed to submit xml document", outcome);
}
},
error : function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
},
swordSubmitResponseHandler: function(response) {
var responseObject = $(response);
if (responseObject.length > 0 && localName(responseObject[responseObject.length - 1]) == "sword:error") {
return responseObject.find("atom\\:summary").html();
}
return false;
},
// convert xml DOM to string
xml2Str: function(xmlNodeObject) {
if (xmlNodeObject == null)
return;
var xmlNode = (xmlNodeObject instanceof jQuery? xmlNodeObject[0]: xmlNodeObject);
var xmlStr = "";
try {
// Gecko-based browsers, Safari, Opera.
xmlStr = (new XMLSerializer()).serializeToString(xmlNode);
} catch (e) {
try {
// Internet Explorer.
xmlStr = xmlNode.xml;
} catch (e) {
this.addProblem('Xmlserializer not supported', e);
return false;
}
}
if (this.options.prettyXML)
xmlStr = vkbeautify.xml(xmlStr);
return xmlStr;
},
getParentObject: function(object, suffix) {
var objectId = $(object).attr('id');
var parentId = objectId.substring(0, objectId.indexOf(suffix));
var parentObject = $("#" + parentId);
if (parentObject.length == 0)
return;
return parentObject;
},
addProblem: function(message, problem) {
this.problemsPanel.html(message + "<br/>");
if (problem !== undefined) {
if (problem.substring) {
this.problemsPanel.append(problem.replace(/</g, "<").replace(/>/g, ">"));
} else {
this.problemsPanel.append(problem.message.replace(/</g, "<").replace(/>/g, ">"));
}
}
this.refreshProblemPanel();
},
clearProblemPanel: function() {
this.problemsPanel.hide();
},
refreshProblemPanel: function() {
if (this.problemsPanel.html() == "") {
this.problemsPanel.hide("fast");
} else {
this.problemsPanel.show("fast");
}
},
nsEquals: function(node, element, elementNS) {
if (element.substring)
return element == localName(node) && elementNS == node.namespaceURI;
return localName(element) == localName(node) && node.namespaceURI == element.namespace;
},
getXPath: function(element) {
var xpath = '';
for ( ; element && element.nodeType == 1; element = element.parentNode ) {
var id = $(element.parentNode).children(element.tagName.replace(":", "\\:")).index(element) + 1;
id = ('[' + id + ']');
if (element.tagName.indexOf("xml:") == -1)
xpath = '/xml:' + element.tagName + id + xpath;
else xpath = '/' + element.tagName + id + xpath;
}
return xpath;
},
keydownCallback: function(e) {
if (this.guiEditor.active) {
var focused = $("input:focus, textarea:focus, select:focus");
// Escape key, blur the currently selected input or deselect selected element
if (e.keyCode == 27) {
if (focused.length > 0)
focused.blur();
else this.guiEditor.selectElement(null);
return false;
}
// Enter, focus the first visible input
if (e.keyCode == 13 && focused.length == 0) {
e.preventDefault();
this.guiEditor.focusSelectedText();
return false;
}
// Tab, select the next input
if (e.keyCode == 9) {
e.preventDefault();
this.guiEditor.focusInput(e.shiftKey);
return false;
}
// Delete key press while item selected but nothing is focused.
if (e.keyCode == 46 && focused.length == 0) {
this.guiEditor.deleteSelected();
return false;
}
if (e.keyCode > 36 && e.keyCode < 41 && focused.length == 0){
e.preventDefault();
if (e.altKey) {
// Alt + up or down move the element up and down in the document
this.guiEditor.moveSelected(e.keyCode == 38);
} else if (e.shiftKey) {
// If holding shift while pressing up or down, then jump to the next/prev sibling
if (e.keyCode == 40 || e.keyCode == 38) {
this.guiEditor.selectSibling(e.keyCode == 38);
} else if (e.keyCode == 37 || e.keyCode == 39) {
this.guiEditor.selectParent(e.keyCode == 39);
}
} else {
// If not holding shift while hitting up or down, go to the next/prev element
if (e.keyCode == 40 || e.keyCode == 38){
this.guiEditor.selectNext(e.keyCode == 38);
} else if (e.keyCode == 37 || e.keyCode == 39) {
this.guiEditor.selectAttribute(e.keyCode == 37);
}
}
return false;
}
if ((e.metaKey || e.ctrlKey) && focused.length == 0 && e.keyCode == 'Z'.charCodeAt(0)) {
// Undo
this.undoHistory.changeHead(e.shiftKey? 1: -1);
return false;
} else if ((e.metaKey || e.ctrlKey) && focused.length == 0 && e.keyCode == 'Y'.charCodeAt(0)){
// Redo
this.undoHistory.changeHead(1);
return false;
}
}
// Save, on either tab.
if (e.altKey && e.shiftKey && e.keyCode == 'S'.charCodeAt(0)) {
$("." + submitButtonClass).click();
return false;
}
if (e.altKey && e.shiftKey && e.keyCode == 'E'.charCodeAt(0)) {
this.exportXML();
return false;
}
if (e.altKey && e.shiftKey && e.keyCode == 'X'.charCodeAt(0)) {
this.modeChange(0);
return false;
}
if (e.altKey && e.shiftKey && e.keyCode == 'T'.charCodeAt(0)) {
this.modeChange(1);
return false;
}
return true;
},
/**
* Menu Update functions
*/
refreshMenuUndo: function(self) {
if (self.undoHistory.headIndex > 0) {
$("#" + xmlMenuHeaderPrefix + "Undo").removeClass("disabled").data("menuItemData").enabled = true;
} else {
$("#" + xmlMenuHeaderPrefix + "Undo").addClass("disabled").data("menuItemData").enabled = false;
}
if (self.undoHistory.headIndex < self.undoHistory.states.length - 1) {
$("#" + xmlMenuHeaderPrefix + "Redo").removeClass("disabled").data("menuItemData").enabled = true;
} else {
$("#" + xmlMenuHeaderPrefix + "Redo").addClass("disabled").data("menuItemData").enabled = false;
}
},
refreshMenuSelected: function(self) {
var suffixes = ['Deselect', 'Next_Element', 'Previous_Element', 'Parent', 'First_Child', 'Next_Sibling',
'Previous_Sibling', 'Next_Attribute', 'Previous_Attribute', 'Delete', 'Move_Element_Up',
'Move_Element_Down'];
var hasSelected = self.guiEditor.selectedElement != null && self.guiEditor.active;
$.each(suffixes, function(){
if (hasSelected)
$("#" + xmlMenuHeaderPrefix + this.toString()).removeClass("disabled").data("menuItemData").enabled = true;
else $("#" + xmlMenuHeaderPrefix + this.toString()).addClass("disabled").data("menuItemData").enabled = false;
});
}
});
function AbstractXMLObject(editor, objectType) {
this.editor = editor;
this.guiEditor = this.editor.guiEditor;
this.objectType = objectType;
}
AbstractXMLObject.prototype.createElementInput = function (inputID, startingValue, appendTarget){
var input = null;
var $input = null;
if (this.objectType.values.length > 0){
var selectionValues = this.objectType.values;
input = document.createElement('select');
input.id = inputID;
input.className = 'xml_select';
appendTarget.appendChild(input);
for (var index in selectionValues) {
var selectionValue = selectionValues[index];
var option = new Option(selectionValue.toString(), selectionValue);
input.options[index] = option;
if (startingValue == selectionValue) {
input.options[index].selected = true;
}
}
$input = $(input);
} else if ((this.objectType.element && (this.objectType.type == 'string' || this.objectType.type == 'mixed'))
|| this.objectType.attribute){
input = document.createElement('textarea');
input.id = inputID;
input.className = 'xml_textarea';
input.value = startingValue;
appendTarget.appendChild(input);
$input = $(input);
var self = this;
$input.one('focus', function() {
if (!self.objectType.attribute && self.editor.options.expandingTextAreas)
$input.autosize();
if (this.value == " ")
this.value = "";
});
} else if (this.objectType.type){
input = document.createElement('input');
input.type = 'text';
input.id = inputID;
input.className = 'xml_input';
input.value = startingValue;
appendTarget.appendChild(input);
$input = $(input);
$input.one('focus', function() {
if (this.value == " ")
this.value = "";
});
}
return $input;
};
AbstractXMLObject.prototype.focus = function() {
if (this.getDomElement() != null)
this.guiEditor.focusObject(this.getDomElement());
};
AbstractXMLObject.prototype.getDomElement = function () {
return null;
};
function AttributeMenu(menuID, label, expanded, enabled, owner) {
ModifyElementMenu.call(this, menuID, label, expanded, enabled, owner);
}
AttributeMenu.prototype.constructor = AttributeMenu;
AttributeMenu.prototype = Object.create( ModifyElementMenu.prototype );
AttributeMenu.prototype.initEventHandlers = function() {
var self = this;
this.menuContent.on('click', 'li', function(event){
self.owner.editor.addAttributeButtonCallback(this);
});
};
AttributeMenu.prototype.populate = function (xmlElement) {
if (xmlElement == null || (this.target != null && xmlElement.guiElement != null
&& this.target[0] === xmlElement.guiElement[0]))
return;
if (this.expanded)
this.menuContent.css("height", "auto");
var startingHeight = this.menuContent.outerHeight();
this.menuContent.empty();
this.target = xmlElement;
var attributesArray = this.target.objectType.attributes;
var attributesPresent = {};
$(this.target.xmlNode[0].attributes).each(function() {
var targetAttribute = this;
$.each(attributesArray, function(){
if (this.name == targetAttribute.nodeName) {
attributesPresent[this.name] = $("#" + xmlElement.guiElementID + "_" + targetAttribute.nodeName.replace(':', '-'));
}
});
});
var self = this;
$.each(this.target.objectType.attributes, function(){
var attribute = this;
var addButton = $("<li/>").attr({
title : 'Add ' + attribute.name,
'id' : xmlElement.guiElementID + "_" + attribute.nameEsc + "_add"
}).html(attribute.name)
.data('xml', {
"objectType": attribute,
"target": xmlElement
}).appendTo(self.menuContent);
if (attribute.name in attributesPresent) {
addButton.addClass("disabled");
if (attributesPresent[attribute.name].length > 0)
attributesPresent[attribute.name].data('xmlAttribute').addButton = addButton;
}
});
if (this.expanded) {
var endingHeight = this.menuContent.outerHeight();
if (endingHeight == 0)
endingHeight = 1;
this.menuContent.css({height: startingHeight + "px"}).stop().animate({height: endingHeight + "px"}, menuExpandDuration).show();
}
if (this.menuContent.children().length == 0) {
this.menuHeader.addClass("disabled");
this.enabled = false;
} else {
this.menuHeader.removeClass("disabled");
this.enabled = true;
}
return this;
};
/**
* Manages and tracks the state of the underlying document being edited.
*/
function DocumentState(baseXML, editor) {
this.baseXML = baseXML;
this.xml = null;
this.changeState = 0;
this.editor = editor;
this.domParser = null;
if (window.DOMParser)
this.domParser = new DOMParser();
this.setXMLFromString(this.baseXML);
this.namespaces = new NamespaceList();
}
DocumentState.prototype.isChanged = function() {
return this.changeState > 1;
};
DocumentState.prototype.isBaseDocument = function() {
return this.changeState == 0;
};
DocumentState.prototype.changesSaved = function() {
return this.changeState == 1;
};
DocumentState.prototype.changesSynced = function() {
return this.changeState == 2;
};
DocumentState.prototype.changesNotSynced = function() {
return this.changeState == 3;
};
DocumentState.prototype.documentChangedEvent = function() {
this.changeState = 2;
this.editor.undoHistory.captureSnapshot();
this.updateStateMessage();
};
DocumentState.prototype.changesCommittedEvent = function() {
this.changeState = 1;
this.updateStateMessage();
};
DocumentState.prototype.changeEvent = function() {
if (this.changeState < 2)
this.changeState = 2;
this.updateStateMessage();
};
DocumentState.prototype.syncedChangeEvent = function() {
this.changeState = 2;
this.updateStateMessage();
};
DocumentState.prototype.unsyncedChangeEvent = function() {
this.changeState = 3;
this.updateStateMessage();
};
DocumentState.prototype.updateStateMessage = function () {
if (this.isChanged()) {
$("." + submissionStatusClass).html("Unsaved changes");
} else {
$("." + submissionStatusClass).html("All changes saved");
}
};
DocumentState.prototype.addNamespace = function(prefixOrType, namespace) {
if (this.xml[0].setAttributeNS)
var prefix;
if (arguments.length == 1) {
var prefix = prefixOrType.name.split(':');
if (prefix.length > 1)
prefix = prefix[0];
else prefix = '';
namespace = prefixOrType.namespace;
} else {
prefix = prefixOrType;
}
if (this.namespaces.containsURI(namespace))
return;
if (!prefix)
prefix = "ns";
var nsPrefix = prefix;
var i = 0;
while (nsPrefix in this.namespaces.namespaceURIs)