Debian Codegraph @

dijit/_editor/plugins/ViewSource.js

raw symbols SCIP
1 define([
2 "dojo/_base/array", // array.forEach
3 "dojo/aspect", // Aspect commands for advice
4 "dojo/_base/declare", // declare
5 "dojo/dom-attr", // domAttr.set
6 "dojo/dom-construct", // domConstruct.create domConstruct.place
7 "dojo/dom-geometry", // domGeometry.setMarginBox domGeometry.position
8 "dojo/dom-style", // domStyle.set
9 "dojo/i18n", // i18n.getLocalization
10 "dojo/keys", // keys.F12
11 "dojo/_base/lang", // lang.hitch
12 "dojo/on", // on()
13 "dojo/sniff", // has("ie")
14 "dojo/window", // winUtils.getBox
15 "../../focus", // focus.focus()
16 "../_Plugin",
17 "../../form/ToggleButton",
18 "../..", // dijit._scopeName
19 "../../registry", // registry.getEnclosingWidget()
20 "dojo/i18n!../nls/commands"
21 ], function(array, aspect, declare, domAttr, domConstruct, domGeometry, domStyle, i18n, keys, lang, on, has, winUtils,
22 focus, _Plugin, ToggleButton, dijit, registry){
23
24 // module:
25 // dijit/_editor/plugins/ViewSource
26
27 var ViewSource = declare("dijit._editor.plugins.ViewSource", _Plugin, {
28 // summary:
29 // This plugin provides a simple view source capability. When view
30 // source mode is enabled, it disables all other buttons/plugins on the RTE.
31 // It also binds to the hotkey: CTRL-SHIFT-F11 for toggling ViewSource mode.
32
33 // stripScripts: [public] Boolean
34 // Boolean flag used to indicate if script tags should be stripped from the document.
35 // Defaults to true.
36 stripScripts: true,
37
38 // stripComments: [public] Boolean
39 // Boolean flag used to indicate if comment tags should be stripped from the document.
40 // Defaults to true.
41 stripComments: true,
42
43 // stripComments: [public] Boolean
44 // Boolean flag used to indicate if iframe tags should be stripped from the document.
45 // Defaults to true.
46 stripIFrames: true,
47
48 // stripEventHandlers: [public] Boolean
49 // Boolean flag used to indicate if event handler attributes like onload should be
50 // stripped from the document.
51 // Defaults to true.
52 stripEventHandlers: true,
53
54 // readOnly: [const] Boolean
55 // Boolean flag used to indicate if the source view should be readonly or not.
56 // Cannot be changed after initialization of the plugin.
57 // Defaults to false.
58 readOnly: false,
59
60 // _fsPlugin: [private] Object
61 // Reference to a registered fullscreen plugin so that viewSource knows
62 // how to scale.
63 _fsPlugin: null,
64
65 toggle: function(){
66 // summary:
67 // Function to allow programmatic toggling of the view.
68
69 // For Webkit, we have to focus a very particular way.
70 // when swapping views, otherwise focus doesn't shift right
71 // but can't focus this way all the time, only for VS changes.
72 // If we did it all the time, buttons like bold, italic, etc
73 // break.
74 if(has("webkit")){
75 this._vsFocused = true;
76 }
77 this.button.set("checked", !this.button.get("checked"));
78
79 },
80
81 _initButton: function(){
82 // summary:
83 // Over-ride for creation of the resize button.
84 var strings = i18n.getLocalization("dijit._editor", "commands"),
85 editor = this.editor;
86 this.button = new ToggleButton({
87 label: strings["viewSource"],
88 ownerDocument: editor.ownerDocument,
89 dir: editor.dir,
90 lang: editor.lang,
91 showLabel: false,
92 iconClass: this.iconClassPrefix + " " + this.iconClassPrefix + "ViewSource",
93 tabIndex: "-1",
94 onChange: lang.hitch(this, "_showSource")
95 });
96
97 // Make sure readonly mode doesn't make the wrong cursor appear over the button.
98 this.button.set("readOnly", false);
99 },
100
101
102 setEditor: function(/*dijit/Editor*/ editor){
103 // summary:
104 // Tell the plugin which Editor it is associated with.
105 // editor: Object
106 // The editor object to attach the print capability to.
107 this.editor = editor;
108 this._initButton();
109
110 // Filter the html content when it is set and retrieved in the editor.
111 this.removeValueFilterHandles();
112 this._setValueFilterHandle = aspect.before(this.editor, "setValue", lang.hitch(this, function (html) {
113 return [this._filter(html)];
114 }));
115 this._getValueFilterHandle = aspect.after(this.editor, "getValue", lang.hitch(this, function (html) {
116 return this._filter(html);
117 }));
118
119 this.editor.addKeyHandler(keys.F12, true, true, lang.hitch(this, function(e){
120 // Move the focus before switching
121 // It'll focus back. Hiding a focused
122 // node causes issues.
123 this.button.focus();
124 this.toggle();
125 e.stopPropagation();
126 e.preventDefault();
127
128 // Call the focus shift outside of the handler.
129 setTimeout(lang.hitch(this, function(){
130 // Focus the textarea... unless focus has moved outside of the editor completely during the timeout.
131 // Since we override focus, so we just need to call it.
132 if(this.editor.focused){
133 this.editor.focus();
134 }
135 }), 100);
136 }));
137 },
138
139 _showSource: function(source){
140 // summary:
141 // Function to toggle between the source and RTE views.
142 // source: boolean
143 // Boolean value indicating if it should be in source mode or not.
144 // tags:
145 // private
146 var ed = this.editor;
147 var edPlugins = ed._plugins;
148 var html;
149 this._sourceShown = source;
150 var self = this;
151 try{
152 if(!this.sourceArea){
153 this._createSourceView();
154 }
155 if(source){
156 // Update the QueryCommandEnabled function to disable everything but
157 // the source view mode. Have to over-ride a function, then kick all
158 // plugins to check their state.
159 ed._sourceQueryCommandEnabled = ed.queryCommandEnabled;
160 ed.queryCommandEnabled = function(cmd){
161 return cmd.toLowerCase() === "viewsource";
162 };
163 this.editor.onDisplayChanged();
164 array.forEach(edPlugins, function(p){
165 // Turn off any plugins not controlled by queryCommandenabled.
166 if(p && !(p instanceof ViewSource) && p.isInstanceOf(_Plugin)){
167 p.set("disabled", true)
168 }
169 });
170
171 // We actually do need to trap this plugin and adjust how we
172 // display the textarea.
173 if(this._fsPlugin){
174 this._fsPlugin._getAltViewNode = function(){
175 return self.sourceArea;
176 };
177 }
178
179 this.sourceArea.value = ed.get("value");
180
181 // Since neither iframe nor textarea have margin, border, or padding,
182 // just set sizes equal.
183 this.sourceArea.style.height = ed.iframe.style.height;
184 this.sourceArea.style.width = ed.iframe.style.width;
185
186 // Hide the iframe and show the HTML source <textarea>. But don't use display:none because
187 // that loses scroll position, and also causes weird problems on FF (see #18607).
188 ed.iframe.parentNode.style.position = "relative";
189 domStyle.set(ed.iframe, {
190 position: "absolute",
191 top: 0,
192 visibility: "hidden"
193 });
194 domStyle.set(this.sourceArea, {
195 display: "block"
196 });
197
198 var resizer = function(){
199 // function to handle resize events.
200 // Will check current VP and only resize if
201 // different.
202 var vp = winUtils.getBox(ed.ownerDocument);
203
204 if("_prevW" in this && "_prevH" in this){
205 // No actual size change, ignore.
206 if(vp.w === this._prevW && vp.h === this._prevH){
207 return;
208 }else{
209 this._prevW = vp.w;
210 this._prevH = vp.h;
211 }
212 }else{
213 this._prevW = vp.w;
214 this._prevH = vp.h;
215 }
216 if(this._resizer){
217 clearTimeout(this._resizer);
218 delete this._resizer;
219 }
220 // Timeout it to help avoid spamming resize on IE.
221 // Works for all browsers.
222 this._resizer = setTimeout(lang.hitch(this, function(){
223 delete this._resizer;
224 this._resize();
225 }), 10);
226 };
227 this._resizeHandle = on(window, "resize", lang.hitch(this, resizer));
228
229 //Call this on a delay once to deal with IE glitchiness on initial size.
230 setTimeout(lang.hitch(this, this._resize), 100);
231
232 //Trigger a check for command enablement/disablement.
233 this.editor.onNormalizedDisplayChanged();
234
235 this.editor.__oldGetValue = this.editor.getValue;
236 this.editor.getValue = lang.hitch(this, function(){
237 var txt = this.sourceArea.value;
238 txt = this._filter(txt);
239 return txt;
240 });
241
242 this._setListener = aspect.after(this.editor, "setValue", lang.hitch(this, function(htmlTxt){
243 htmlTxt = htmlTxt || "";
244 // htmlTxt was filtered in setValue before aspect.
245 this.sourceArea.value = htmlTxt;
246 }), true);
247 }else{
248 // First check that we were in source view before doing anything.
249 // corner case for being called with a value of false and we hadn't
250 // actually been in source display mode.
251 if(!ed._sourceQueryCommandEnabled){
252 return;
253 }
254
255 // Remove the set listener.
256 this._setListener.remove();
257 delete this._setListener;
258
259 this._resizeHandle.remove();
260 delete this._resizeHandle;
261
262 if(this.editor.__oldGetValue){
263 this.editor.getValue = this.editor.__oldGetValue;
264 delete this.editor.__oldGetValue;
265 }
266
267 // Restore all the plugin buttons state.
268 ed.queryCommandEnabled = ed._sourceQueryCommandEnabled;
269 if(!this._readOnly){
270 html = this.sourceArea.value;
271 ed.beginEditing();
272 // html will be filtered in setValue aspect.
273 ed.set("value", html);
274 ed.endEditing();
275 }
276
277 array.forEach(edPlugins, function(p){
278 // Turn back on any plugins we turned off.
279 if(p && p.isInstanceOf(_Plugin)){
280 p.set("disabled", false);
281 }
282 });
283
284 domStyle.set(this.sourceArea, "display", "none");
285 domStyle.set(ed.iframe, {
286 position: "relative",
287 visibility: "visible"
288 });
289 delete ed._sourceQueryCommandEnabled;
290
291 //Trigger a check for command enablement/disablement.
292 this.editor.onDisplayChanged();
293 }
294 // Call a delayed resize to wait for some things to display in header/footer.
295 setTimeout(lang.hitch(this, function(){
296 // Make resize calls.
297 var parent = ed.domNode.parentNode;
298 if(parent){
299 var container = registry.getEnclosingWidget(parent);
300 if(container && container.resize){
301 container.resize();
302 }
303 }
304 ed.resize();
305 }), 300);
306 }catch(e){
307 console.log(e);
308 }
309 },
310
311 updateState: function(){
312 // summary:
313 // Over-ride for button state control for disabled to work.
314 this.button.set("disabled", this.get("disabled"));
315 },
316
317 _resize: function(){
318 // summary:
319 // Internal function to resize the source view
320 // tags:
321 // private
322 var ed = this.editor;
323 var tbH = ed.getHeaderHeight();
324 var fH = ed.getFooterHeight();
325 var eb = domGeometry.position(ed.domNode);
326
327 // Styles are now applied to the internal source container, so we have
328 // to subtract them off.
329 var containerPadding = domGeometry.getPadBorderExtents(ed.iframe.parentNode);
330 var containerMargin = domGeometry.getMarginExtents(ed.iframe.parentNode);
331
332 var extents = domGeometry.getPadBorderExtents(ed.domNode);
333 var edb = {
334 w: eb.w - extents.w,
335 h: eb.h - (tbH + extents.h + fH)
336 };
337
338 // Fullscreen gets odd, so we need to check for the FS plugin and
339 // adapt.
340 if(this._fsPlugin && this._fsPlugin.isFullscreen){
341 // Okay, probably in FS, adjust.
342 var vp = winUtils.getBox(ed.ownerDocument);
343 edb.w = (vp.w - extents.w);
344 edb.h = (vp.h - (tbH + extents.h + fH));
345 }
346
347 domGeometry.setMarginBox(this.sourceArea, {
348 w: Math.round(edb.w - (containerPadding.w + containerMargin.w)),
349 h: Math.round(edb.h - (containerPadding.h + containerMargin.h))
350 });
351 },
352
353 _createSourceView: function(){
354 // summary:
355 // Internal function for creating the source view area.
356 // tags:
357 // private
358 var ed = this.editor;
359 var edPlugins = ed._plugins;
360 this.sourceArea = domConstruct.create("textarea");
361 if(this.readOnly){
362 domAttr.set(this.sourceArea, "readOnly", true);
363 this._readOnly = true;
364 }
365 domStyle.set(this.sourceArea, {
366 padding: "0px",
367 margin: "0px",
368 borderWidth: "0px",
369 borderStyle: "none"
370 });
371 domAttr.set(this.sourceArea, "aria-label", this.editor.id);
372
373 domConstruct.place(this.sourceArea, ed.iframe, "before");
374
375 if(has("ie") && ed.iframe.parentNode.lastChild !== ed.iframe){
376 // There's some weirdo div in IE used for focus control
377 // But is messed up scaling the textarea if we don't config
378 // it some so it doesn't have a varying height.
379 domStyle.set(ed.iframe.parentNode.lastChild, {
380 width: "0px",
381 height: "0px",
382 padding: "0px",
383 margin: "0px",
384 borderWidth: "0px",
385 borderStyle: "none"
386 });
387 }
388
389 // We also need to take over editor focus a bit here, so that focus calls to
390 // focus the editor will focus to the right node when VS is active.
391 ed._viewsource_oldFocus = ed.focus;
392 var self = this;
393 ed.focus = function(){
394 if(self._sourceShown){
395 self.setSourceAreaCaret();
396 }else{
397 try{
398 if(this._vsFocused){
399 delete this._vsFocused;
400 // Must focus edit node in this case (webkit only) or
401 // focus doesn't shift right, but in normal
402 // cases we focus with the regular function.
403 focus.focus(ed.editNode);
404 }else{
405 ed._viewsource_oldFocus();
406 }
407 }catch(e){
408 console.log("ViewSource focus code error: " + e);
409 }
410 }
411 };
412
413 var i, p;
414 for(i = 0; i < edPlugins.length; i++){
415 // We actually do need to trap this plugin and adjust how we
416 // display the textarea.
417 p = edPlugins[i];
418 if(p && (p.declaredClass === "dijit._editor.plugins.FullScreen" ||
419 p.declaredClass === (dijit._scopeName +
420 "._editor.plugins.FullScreen"))){
421 this._fsPlugin = p;
422 break;
423 }
424 }
425 if(this._fsPlugin){
426 // Found, we need to over-ride the alt-view node function
427 // on FullScreen with our own, chain up to parent call when appropriate.
428 this._fsPlugin._viewsource_getAltViewNode = this._fsPlugin._getAltViewNode;
429 this._fsPlugin._getAltViewNode = function(){
430 return self._sourceShown ? self.sourceArea : this._viewsource_getAltViewNode();
431 };
432 }
433
434 // Listen to the source area for key events as well, as we need to be able to hotkey toggle
435 // it from there too.
436 this.own(on(this.sourceArea, "keydown", lang.hitch(this, function(e){
437 if(this._sourceShown && e.keyCode == keys.F12 && e.ctrlKey && e.shiftKey){
438 this.button.focus();
439 this.button.set("checked", false);
440 setTimeout(lang.hitch(this, function(){
441 ed.focus();
442 }), 100);
443 e.stopPropagation();
444 e.preventDefault();
445 }
446 })));
447 },
448
449 _stripScripts: function(html){
450 // summary:
451 // Strips out script tags from the HTML used in editor.
452 // html: String
453 // The HTML to filter
454 // tags:
455 // private
456 if(html){
457 // Look for closed and unclosed (malformed) script attacks.
458 html = html.replace(/<\s*script[^>]*>((.|\s)*?)<\\?\/\s*script\s*>/ig, "");
459 html = html.replace(/<\s*script\b([^<>]|\s)*>?/ig, "");
460 html = html.replace(/<[^>]*=(\s|)*[("|')]javascript:[^$1][(\s|.)]*[$1][^>]*>/ig, "");
461 }
462 return html;
463 },
464
465 _stripComments: function(html){
466 // summary:
467 // Strips out comments from the HTML used in editor.
468 // html: String
469 // The HTML to filter
470 // tags:
471 // private
472 if(html){
473 html = html.replace(/<!--(.|\s){1,}?-->/g, "");
474 }
475 return html;
476 },
477
478 _stripIFrames: function(html){
479 // summary:
480 // Strips out iframe tags from the content, to avoid iframe script
481 // style injection attacks.
482 // html: String
483 // The HTML to filter
484 // tags:
485 // private
486 if(html){
487 html = html.replace(/<\s*iframe[^>]*>((.|\s)*?)<\\?\/\s*iframe\s*>/ig, "");
488 }
489 return html;
490 },
491
492 _stripEventHandlers: function (html) {
493 if(html){
494 // Find all tags that contain an event handler attribute (an on* attribute).
495 var matches = html.match(/<[a-z]+?\b(.*?on.*?(['"]).*?\2.*?)+>/gim);
496 if(matches){
497 for(var i = 0, l = matches.length; i < l; i++){
498 // For each tag, remove only the event handler attributes.
499 var match = matches[i];
500 var replacement = match.replace(/\s+on[a-z]*\s*=\s*(['"])(.*?)\1/igm, "");
501 html = html.replace(match, replacement);
502 }
503 }
504 }
505 return html;
506 },
507
508 _filter: function(html){
509 // summary:
510 // Internal function to perform some filtering on the HTML.
511 // html: String
512 // The HTML to filter
513 // tags:
514 // private
515 if(html){
516 if(this.stripScripts){
517 html = this._stripScripts(html);
518 }
519 if(this.stripComments){
520 html = this._stripComments(html);
521 }
522 if(this.stripIFrames){
523 html = this._stripIFrames(html);
524 }
525 if(this.stripEventHandlers){
526 html = this._stripEventHandlers(html);
527 }
528 }
529 return html;
530 },
531
532 removeValueFilterHandles: function () {
533 if (this._setValueFilterHandle) {
534 this._setValueFilterHandle.remove();
535 delete this._setValueFilterHandle;
536 }
537 if (this._getValueFilterHandle) {
538 this._getValueFilterHandle.remove();
539 delete this._getValueFilterHandle;
540 }
541 },
542
543 setSourceAreaCaret: function(){
544 // summary:
545 // Internal function to set the caret in the sourceArea
546 // to 0x0
547 var elem = this.sourceArea;
548 focus.focus(elem);
549 if(this._sourceShown && !this.readOnly){
550 if(elem.setSelectionRange){
551 elem.setSelectionRange(0, 0);
552 }else if(this.sourceArea.createTextRange){
553 // IE
554 var range = elem.createTextRange();
555 range.collapse(true);
556 range.moveStart("character", -99999); // move to 0
557 range.moveStart("character", 0); // delta from 0 is the correct position
558 range.moveEnd("character", 0);
559 range.select();
560 }
561 }
562 },
563
564 destroy: function(){
565 if(this._resizer){
566 clearTimeout(this._resizer);
567 delete this._resizer;
568 }
569 if(this._resizeHandle){
570 this._resizeHandle.remove();
571 delete this._resizeHandle;
572 }
573 if(this._setListener){
574 this._setListener.remove();
575 delete this._setListener;
576 }
577 this.removeValueFilterHandles();
578 this.inherited(arguments);
579 }
580 });
581
582 // Register this plugin.
583 // For back-compat accept "viewsource" (all lowercase) too, remove in 2.0
584 _Plugin.registry["viewSource"] = _Plugin.registry["viewsource"] = function(args){
585 return new ViewSource({
586 readOnly: ("readOnly" in args) ? args.readOnly : false,
587 stripComments: ("stripComments" in args) ? args.stripComments : true,
588 stripScripts: ("stripScripts" in args) ? args.stripScripts : true,
589 stripIFrames: ("stripIFrames" in args) ? args.stripIFrames : true,
590 stripEventHandlers: ("stripEventHandlers" in args) ? args.stripEventHandlers : true
591 });
592 };
593
594 return ViewSource;
595 });