Debian Codegraph @

dijit/_editor/plugins/EnterKeyHandling.js

raw symbols SCIP
1 define([
2 "dojo/_base/declare", // declare
3 "dojo/dom-construct", // domConstruct.destroy domConstruct.place
4 "dojo/keys", // keys.ENTER
5 "dojo/_base/lang",
6 "dojo/on",
7 "dojo/sniff", // has("ie") has("mozilla") has("webkit")
8 "dojo/_base/window", // win.withGlobal
9 "dojo/window", // winUtils.scrollIntoView
10 "../_Plugin",
11 "../RichText",
12 "../range"
13 ], function(declare, domConstruct, keys, lang, on, has, win, winUtils, _Plugin, RichText, rangeapi){
14
15 // module:
16 // dijit/_editor/plugins/EnterKeyHandling
17
18 return declare("dijit._editor.plugins.EnterKeyHandling", _Plugin, {
19 // summary:
20 // This plugin tries to make all browsers behave consistently with regard to
21 // how ENTER behaves in the editor window. It traps the ENTER key and alters
22 // the way DOM is constructed in certain cases to try to commonize the generated
23 // DOM and behaviors across browsers.
24 //
25 // description:
26 // This plugin has three modes:
27 //
28 // - blockNodeForEnter=BR
29 // - blockNodeForEnter=DIV
30 // - blockNodeForEnter=P
31 //
32 // In blockNodeForEnter=P, the ENTER key starts a new
33 // paragraph, and shift-ENTER starts a new line in the current paragraph.
34 // For example, the input:
35 //
36 // | first paragraph <shift-ENTER>
37 // | second line of first paragraph <ENTER>
38 // | second paragraph
39 //
40 // will generate:
41 //
42 // | <p>
43 // | first paragraph
44 // | <br/>
45 // | second line of first paragraph
46 // | </p>
47 // | <p>
48 // | second paragraph
49 // | </p>
50 //
51 // In BR and DIV mode, the ENTER key conceptually goes to a new line in the
52 // current paragraph, and users conceptually create a new paragraph by pressing ENTER twice.
53 // For example, if the user enters text into an editor like this:
54 //
55 // | one <ENTER>
56 // | two <ENTER>
57 // | three <ENTER>
58 // | <ENTER>
59 // | four <ENTER>
60 // | five <ENTER>
61 // | six <ENTER>
62 //
63 // It will appear on the screen as two 'paragraphs' of three lines each. Markupwise, this generates:
64 //
65 // BR:
66 // | one<br/>
67 // | two<br/>
68 // | three<br/>
69 // | <br/>
70 // | four<br/>
71 // | five<br/>
72 // | six<br/>
73 //
74 // DIV:
75 // | <div>one</div>
76 // | <div>two</div>
77 // | <div>three</div>
78 // | <div>&nbsp;</div>
79 // | <div>four</div>
80 // | <div>five</div>
81 // | <div>six</div>
82
83 // blockNodeForEnter: String
84 // This property decides the behavior of Enter key. It can be either P,
85 // DIV, BR, or empty (which means disable this feature). Anything else
86 // will trigger errors. The default is 'BR'
87 //
88 // See class description for more details.
89 blockNodeForEnter: 'BR',
90
91 constructor: function(args){
92 if(args){
93 if("blockNodeForEnter" in args){
94 args.blockNodeForEnter = args.blockNodeForEnter.toUpperCase();
95 }
96 lang.mixin(this, args);
97 }
98 },
99
100 setEditor: function(editor){
101 // Overrides _Plugin.setEditor().
102 if(this.editor === editor){
103 return;
104 }
105 this.editor = editor;
106 if(this.blockNodeForEnter == 'BR'){
107 // While Moz has a mode tht mostly works, it's still a little different,
108 // So, try to just have a common mode and be consistent. Which means
109 // we need to enable customUndo, if not already enabled.
110 this.editor.customUndo = true;
111 editor.onLoadDeferred.then(lang.hitch(this, function(d){
112 this.own(on(editor.document, "keydown", lang.hitch(this, function(e){
113 if(e.keyCode == keys.ENTER){
114 // Just do it manually. The handleEnterKey has a shift mode that
115 // Always acts like <br>, so just use it.
116 var ne = lang.mixin({}, e);
117 ne.shiftKey = true;
118 if(!this.handleEnterKey(ne)){
119 e.stopPropagation();
120 e.preventDefault();
121 }
122 }
123 })));
124 if(has("ie") >= 9 && has("ie") <= 10){
125 this.own(on(editor.document, "paste", lang.hitch(this, function(e){
126 setTimeout(lang.hitch(this, function(){
127 // Use the old range/selection code to kick IE 9 into updating
128 // its range by moving it back, then forward, one 'character'.
129 var r = this.editor.document.selection.createRange();
130 r.move('character', -1);
131 r.select();
132 r.move('character', 1);
133 r.select();
134 }), 0);
135 })));
136 }
137 return d;
138 }));
139 }else if(this.blockNodeForEnter){
140 // add enter key handler
141 var h = lang.hitch(this, "handleEnterKey");
142 editor.addKeyHandler(13, 0, 0, h); //enter
143 editor.addKeyHandler(13, 0, 1, h); //shift+enter
144 this.own(this.editor.on('KeyPressed', lang.hitch(this, 'onKeyPressed')));
145 }
146 },
147 onKeyPressed: function(){
148 // summary:
149 // Handler for after the user has pressed a key, and the display has been updated.
150 // Connected to RichText's onKeyPressed() method.
151 // tags:
152 // private
153 if(this._checkListLater){
154 if(this.editor.selection.isCollapsed()){
155 var liparent = this.editor.selection.getAncestorElement('LI');
156 if(!liparent){
157 // circulate the undo detection code by calling RichText::execCommand directly
158 RichText.prototype.execCommand.call(this.editor, 'formatblock', this.blockNodeForEnter);
159 // set the innerHTML of the new block node
160 var block = this.editor.selection.getAncestorElement(this.blockNodeForEnter);
161 if(block){
162 block.innerHTML = this.bogusHtmlContent;
163 if(has("ie") <= 9){
164 // move to the start by moving backwards one char
165 var r = this.editor.document.selection.createRange();
166 r.move('character', -1);
167 r.select();
168 }
169 }else{
170 console.error('onKeyPressed: Cannot find the new block node'); // FIXME
171 }
172 }else{
173 if(has("mozilla")){
174 if(liparent.parentNode.parentNode.nodeName == 'LI'){
175 liparent = liparent.parentNode.parentNode;
176 }
177 }
178 var fc = liparent.firstChild;
179 if(fc && fc.nodeType == 1 && (fc.nodeName == 'UL' || fc.nodeName == 'OL')){
180 liparent.insertBefore(fc.ownerDocument.createTextNode('\xA0'), fc);
181 var newrange = rangeapi.create(this.editor.window);
182 newrange.setStart(liparent.firstChild, 0);
183 var selection = rangeapi.getSelection(this.editor.window, true);
184 selection.removeAllRanges();
185 selection.addRange(newrange);
186 }
187 }
188 }
189 this._checkListLater = false;
190 }
191 if(this._pressedEnterInBlock){
192 // the new created is the original current P, so we have previousSibling below
193 if(this._pressedEnterInBlock.previousSibling){
194 this.removeTrailingBr(this._pressedEnterInBlock.previousSibling);
195 }
196 delete this._pressedEnterInBlock;
197 }
198 },
199
200 // bogusHtmlContent: [private] String
201 // HTML to stick into a new empty block
202 bogusHtmlContent: '&#160;', // &nbsp;
203
204 // blockNodes: [private] Regex
205 // Regex for testing if a given tag is a block level (display:block) tag
206 blockNodes: /^(?:P|H1|H2|H3|H4|H5|H6|LI)$/,
207
208 handleEnterKey: function(e){
209 // summary:
210 // Handler for enter key events when blockNodeForEnter is DIV or P.
211 // description:
212 // Manually handle enter key event to make the behavior consistent across
213 // all supported browsers. See class description for details.
214 // tags:
215 // private
216
217 var selection, range, newrange, startNode, endNode, brNode, doc = this.editor.document, br, rs, txt;
218 if(e.shiftKey){ // shift+enter always generates <br>
219 var parent = this.editor.selection.getParentElement();
220 var header = rangeapi.getAncestor(parent, this.blockNodes);
221 if(header){
222 if(header.tagName == 'LI'){
223 return true; // let browser handle
224 }
225 selection = rangeapi.getSelection(this.editor.window);
226 range = selection.getRangeAt(0);
227 if(!range.collapsed){
228 range.deleteContents();
229 selection = rangeapi.getSelection(this.editor.window);
230 range = selection.getRangeAt(0);
231 }
232 if(rangeapi.atBeginningOfContainer(header, range.startContainer, range.startOffset)){
233 br = doc.createElement('br');
234 newrange = rangeapi.create(this.editor.window);
235 header.insertBefore(br, header.firstChild);
236 newrange.setStartAfter(br);
237 selection.removeAllRanges();
238 selection.addRange(newrange);
239 }else if(rangeapi.atEndOfContainer(header, range.startContainer, range.startOffset)){
240 newrange = rangeapi.create(this.editor.window);
241 br = doc.createElement('br');
242 header.appendChild(br);
243 header.appendChild(doc.createTextNode('\xA0'));
244 newrange.setStart(header.lastChild, 0);
245 selection.removeAllRanges();
246 selection.addRange(newrange);
247 }else{
248 rs = range.startContainer;
249 if(rs && rs.nodeType == 3){
250 // Text node, we have to split it.
251 txt = rs.nodeValue;
252 startNode = doc.createTextNode(txt.substring(0, range.startOffset));
253 endNode = doc.createTextNode(txt.substring(range.startOffset));
254 brNode = doc.createElement("br");
255
256 if(endNode.nodeValue == "" && has("webkit")){
257 endNode = doc.createTextNode('\xA0')
258 }
259 domConstruct.place(startNode, rs, "after");
260 domConstruct.place(brNode, startNode, "after");
261 domConstruct.place(endNode, brNode, "after");
262 domConstruct.destroy(rs);
263 newrange = rangeapi.create(this.editor.window);
264 newrange.setStart(endNode, 0);
265 selection.removeAllRanges();
266 selection.addRange(newrange);
267 return false;
268 }
269 return true; // let browser handle
270 }
271 }else{
272 selection = rangeapi.getSelection(this.editor.window);
273 if(selection.rangeCount){
274 range = selection.getRangeAt(0);
275 if(range && range.startContainer){
276 if(!range.collapsed){
277 range.deleteContents();
278 selection = rangeapi.getSelection(this.editor.window);
279 range = selection.getRangeAt(0);
280 }
281 rs = range.startContainer;
282 if(rs && rs.nodeType == 3){
283 // Text node, we have to split it.
284
285 var offset = range.startOffset;
286 if(rs.length < offset){
287 //We are not splitting the right node, try to locate the correct one
288 ret = this._adjustNodeAndOffset(rs, offset);
289 rs = ret.node;
290 offset = ret.offset;
291 }
292 txt = rs.nodeValue;
293
294 startNode = doc.createTextNode(txt.substring(0, offset));
295 endNode = doc.createTextNode(txt.substring(offset));
296 brNode = doc.createElement("br");
297
298 if(!endNode.length){
299 // Create dummy text with a &nbsp to go after the BR, to prevent IE crash.
300 // See https://bugs.dojotoolkit.org/ticket/12008 for details.
301 endNode = doc.createTextNode('\xA0');
302 }
303
304 if(startNode.length){
305 domConstruct.place(startNode, rs, "after");
306 }else{
307 startNode = rs;
308 }
309 domConstruct.place(brNode, startNode, "after");
310 domConstruct.place(endNode, brNode, "after");
311 domConstruct.destroy(rs);
312 newrange = rangeapi.create(this.editor.window);
313 newrange.setStart(endNode, 0);
314 newrange.setEnd(endNode, endNode.length);
315 selection.removeAllRanges();
316 selection.addRange(newrange);
317 this.editor.selection.collapse(true);
318 }else{
319 var targetNode;
320 if(range.startOffset >= 0){
321 targetNode = rs.childNodes[range.startOffset];
322 }
323 var brNode = doc.createElement("br");
324 var endNode = doc.createTextNode('\xA0');
325 if(!targetNode){
326 rs.appendChild(brNode);
327 rs.appendChild(endNode);
328 }else{
329 domConstruct.place(brNode, targetNode, "before");
330 domConstruct.place(endNode, brNode, "after");
331 }
332 newrange = rangeapi.create(this.editor.window);
333 newrange.setStart(endNode, 0);
334 newrange.setEnd(endNode, endNode.length);
335 selection.removeAllRanges();
336 selection.addRange(newrange);
337 this.editor.selection.collapse(true);
338 }
339 // \xA0 dummy text node remains, but is stripped before get("value")
340 // by RichText._stripTrailingEmptyNodes(). Still, could we just use a plain
341 // space (" ") instead?
342 }
343 }else{
344 // don't change this: do not call this.execCommand, as that may have other logic in subclass
345 RichText.prototype.execCommand.call(this.editor, 'inserthtml', '<br>');
346 }
347 }
348 return false;
349 }
350 var _letBrowserHandle = true;
351
352 // first remove selection
353 selection = rangeapi.getSelection(this.editor.window);
354 range = selection.getRangeAt(0);
355 if(!range.collapsed){
356 range.deleteContents();
357 selection = rangeapi.getSelection(this.editor.window);
358 range = selection.getRangeAt(0);
359 }
360
361 var block = rangeapi.getBlockAncestor(range.endContainer, null, this.editor.editNode);
362 var blockNode = block.blockNode;
363
364 // if this is under a LI or the parent of the blockNode is LI, just let browser to handle it
365 if((this._checkListLater = (blockNode && (blockNode.nodeName == 'LI' || blockNode.parentNode.nodeName == 'LI')))){
366 if(has("mozilla")){
367 // press enter in middle of P may leave a trailing <br/>, let's remove it later
368 this._pressedEnterInBlock = blockNode;
369 }
370 // if this li only contains spaces, set the content to empty so the browser will outdent this item
371 if(/^(\s|&nbsp;|&#160;|\xA0|<span\b[^>]*\bclass=['"]Apple-style-span['"][^>]*>(\s|&nbsp;|&#160;|\xA0)<\/span>)?(<br>)?$/.test(blockNode.innerHTML)){
372 // empty LI node
373 blockNode.innerHTML = '';
374 if(has("webkit")){ // WebKit tosses the range when innerHTML is reset
375 newrange = rangeapi.create(this.editor.window);
376 newrange.setStart(blockNode, 0);
377 selection.removeAllRanges();
378 selection.addRange(newrange);
379 }
380 this._checkListLater = false; // nothing to check since the browser handles outdent
381 }
382 return true;
383 }
384
385 // text node directly under body, let's wrap them in a node
386 if(!block.blockNode || block.blockNode === this.editor.editNode){
387 try{
388 RichText.prototype.execCommand.call(this.editor, 'formatblock', this.blockNodeForEnter);
389 }catch(e2){ /*squelch FF3 exception bug when editor content is a single BR*/
390 }
391 // get the newly created block node
392 // FIXME
393 block = {blockNode: this.editor.selection.getAncestorElement(this.blockNodeForEnter),
394 blockContainer: this.editor.editNode};
395 if(block.blockNode){
396 if(block.blockNode != this.editor.editNode &&
397 (!(block.blockNode.textContent || block.blockNode.innerHTML).replace(/^\s+|\s+$/g, "").length)){
398 this.removeTrailingBr(block.blockNode);
399 return false;
400 }
401 }else{ // we shouldn't be here if formatblock worked
402 block.blockNode = this.editor.editNode;
403 }
404 selection = rangeapi.getSelection(this.editor.window);
405 range = selection.getRangeAt(0);
406 }
407
408 var newblock = doc.createElement(this.blockNodeForEnter);
409 newblock.innerHTML = this.bogusHtmlContent;
410 this.removeTrailingBr(block.blockNode);
411 var endOffset = range.endOffset;
412 var node = range.endContainer;
413 if(node.length < endOffset){
414 //We are not checking the right node, try to locate the correct one
415 var ret = this._adjustNodeAndOffset(node, endOffset);
416 node = ret.node;
417 endOffset = ret.offset;
418 }
419 if(rangeapi.atEndOfContainer(block.blockNode, node, endOffset)){
420 if(block.blockNode === block.blockContainer){
421 block.blockNode.appendChild(newblock);
422 }else{
423 domConstruct.place(newblock, block.blockNode, "after");
424 }
425 _letBrowserHandle = false;
426 // lets move caret to the newly created block
427 newrange = rangeapi.create(this.editor.window);
428 newrange.setStart(newblock, 0);
429 selection.removeAllRanges();
430 selection.addRange(newrange);
431 if(this.editor.height){
432 winUtils.scrollIntoView(newblock);
433 }
434 }else if(rangeapi.atBeginningOfContainer(block.blockNode,
435 range.startContainer, range.startOffset)){
436 domConstruct.place(newblock, block.blockNode, block.blockNode === block.blockContainer ? "first" : "before");
437 if(newblock.nextSibling && this.editor.height){
438 // position input caret - mostly WebKit needs this
439 newrange = rangeapi.create(this.editor.window);
440 newrange.setStart(newblock.nextSibling, 0);
441 selection.removeAllRanges();
442 selection.addRange(newrange);
443 // browser does not scroll the caret position into view, do it manually
444 winUtils.scrollIntoView(newblock.nextSibling);
445 }
446 _letBrowserHandle = false;
447 }else{ //press enter in the middle of P/DIV/Whatever/
448 if(block.blockNode === block.blockContainer){
449 block.blockNode.appendChild(newblock);
450 }else{
451 domConstruct.place(newblock, block.blockNode, "after");
452 }
453 _letBrowserHandle = false;
454
455 // Clone any block level styles.
456 if(block.blockNode.style){
457 if(newblock.style){
458 if(block.blockNode.style.cssText){
459 newblock.style.cssText = block.blockNode.style.cssText;
460 }
461 }
462 }
463
464 // Okay, we probably have to split.
465 rs = range.startContainer;
466 var firstNodeMoved;
467 if(rs && rs.nodeType == 3){
468 // Text node, we have to split it.
469 var nodeToMove, tNode;
470 endOffset = range.endOffset;
471 if(rs.length < endOffset){
472 //We are not splitting the right node, try to locate the correct one
473 ret = this._adjustNodeAndOffset(rs, endOffset);
474 rs = ret.node;
475 endOffset = ret.offset;
476 }
477
478 txt = rs.nodeValue;
479 startNode = doc.createTextNode(txt.substring(0, endOffset));
480 endNode = doc.createTextNode(txt.substring(endOffset, txt.length));
481
482 // Place the split, then remove original nodes.
483 domConstruct.place(startNode, rs, "before");
484 domConstruct.place(endNode, rs, "after");
485 domConstruct.destroy(rs);
486
487 // Okay, we split the text. Now we need to see if we're
488 // parented to the block element we're splitting and if
489 // not, we have to split all the way up. Ugh.
490 var parentC = startNode.parentNode;
491 while(parentC !== block.blockNode){
492 var tg = parentC.tagName;
493 var newTg = doc.createElement(tg);
494 // Clone over any 'style' data.
495 if(parentC.style){
496 if(newTg.style){
497 if(parentC.style.cssText){
498 newTg.style.cssText = parentC.style.cssText;
499 }
500 }
501 }
502 // If font also need to clone over any font data.
503 if(parentC.tagName === "FONT"){
504 if(parentC.color){
505 newTg.color = parentC.color;
506 }
507 if(parentC.face){
508 newTg.face = parentC.face;
509 }
510 if(parentC.size){ // this check was necessary on IE
511 newTg.size = parentC.size;
512 }
513 }
514
515 nodeToMove = endNode;
516 while(nodeToMove){
517 tNode = nodeToMove.nextSibling;
518 newTg.appendChild(nodeToMove);
519 nodeToMove = tNode;
520 }
521 domConstruct.place(newTg, parentC, "after");
522 startNode = parentC;
523 endNode = newTg;
524 parentC = parentC.parentNode;
525 }
526
527 // Lastly, move the split out tags to the new block.
528 // as they should now be split properly.
529 nodeToMove = endNode;
530 if(nodeToMove.nodeType == 1 || (nodeToMove.nodeType == 3 && nodeToMove.nodeValue)){
531 // Non-blank text and non-text nodes need to clear out that blank space
532 // before moving the contents.
533 newblock.innerHTML = "";
534 }
535 firstNodeMoved = nodeToMove;
536 while(nodeToMove){
537 tNode = nodeToMove.nextSibling;
538 newblock.appendChild(nodeToMove);
539 nodeToMove = tNode;
540 }
541 }
542
543 //lets move caret to the newly created block
544 newrange = rangeapi.create(this.editor.window);
545 var nodeForCursor;
546 var innerMostFirstNodeMoved = firstNodeMoved;
547 if(this.blockNodeForEnter !== 'BR'){
548 while(innerMostFirstNodeMoved){
549 nodeForCursor = innerMostFirstNodeMoved;
550 tNode = innerMostFirstNodeMoved.firstChild;
551 innerMostFirstNodeMoved = tNode;
552 }
553 if(nodeForCursor && nodeForCursor.parentNode){
554 newblock = nodeForCursor.parentNode;
555 newrange.setStart(newblock, 0);
556 selection.removeAllRanges();
557 selection.addRange(newrange);
558 if(this.editor.height){
559 winUtils.scrollIntoView(newblock);
560 }
561 if(has("mozilla")){
562 // press enter in middle of P may leave a trailing <br/>, let's remove it later
563 this._pressedEnterInBlock = block.blockNode;
564 }
565 }else{
566 _letBrowserHandle = true;
567 }
568 }else{
569 newrange.setStart(newblock, 0);
570 selection.removeAllRanges();
571 selection.addRange(newrange);
572 if(this.editor.height){
573 winUtils.scrollIntoView(newblock);
574 }
575 if(has("mozilla")){
576 // press enter in middle of P may leave a trailing <br/>, let's remove it later
577 this._pressedEnterInBlock = block.blockNode;
578 }
579 }
580 }
581 return _letBrowserHandle;
582 },
583
584 _adjustNodeAndOffset: function(/*DomNode*/node, /*Int*/offset){
585 // summary:
586 // In the case there are multiple text nodes in a row the offset may not be within the node. If the offset is larger than the node length, it will attempt to find
587 // the next text sibling until it locates the text node in which the offset refers to
588 // node:
589 // The node to check.
590 // offset:
591 // The position to find within the text node
592 // tags:
593 // private.
594 while(node.length < offset && node.nextSibling && node.nextSibling.nodeType == 3){
595 //Adjust the offset and node in the case of multiple text nodes in a row
596 offset = offset - node.length;
597 node = node.nextSibling;
598 }
599 return {"node": node, "offset": offset};
600 },
601
602 removeTrailingBr: function(container){
603 // summary:
604 // If last child of container is a `<br>`, then remove it.
605 // tags:
606 // private
607 var para = /P|DIV|LI/i.test(container.tagName) ?
608 container : this.editor.selection.getParentOfType(container, ['P', 'DIV', 'LI']);
609
610 if(!para){
611 return;
612 }
613 if(para.lastChild){
614 if((para.childNodes.length > 1 && para.lastChild.nodeType == 3 && /^[\s\xAD]*$/.test(para.lastChild.nodeValue)) ||
615 para.lastChild.tagName == 'BR'){
616
617 domConstruct.destroy(para.lastChild);
618 }
619 }
620 if(!para.childNodes.length){
621 para.innerHTML = this.bogusHtmlContent;
622 }
623 }
624 });
625
626 });