Fix #7581 - selection of blocks
[roojs1] / Roo / bootstrap / form / HtmlEditorToolbar / Standard.js
1   
2 /**
3  * @class Roo.bootstrap.form.HtmlEditorToolbar.Standard
4  * @parent Roo.bootstrap.form.HtmlEditor
5  * @extends Roo.bootstrap.nav.Simplebar
6  * Basic Toolbar
7  * 
8  * @example
9  * Usage:
10  *
11  new Roo.bootstrap.form.HtmlEditor({
12     ....
13     toolbars : [
14         new Roo.bootstrap.form.HtmlEditorToolbar.Standard({
15             disable : { fonts: 1 , format: 1, ..., ... , ...],
16             btns : [ .... ]
17         })
18     }
19      
20  * 
21  * @cfg {Object} disable List of elements to disable..
22  * @cfg {Array} btns List of additional buttons.
23  * 
24  * 
25  * NEEDS Extra CSS? 
26  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
27  */
28  
29 Roo.bootstrap.form.HtmlEditorToolbar.Standard = function(config)
30 {
31     
32     Roo.apply(this, config);
33     
34     // default disabled, based on 'good practice'..
35     this.disable = this.disable || {};
36     Roo.applyIf(this.disable, {
37         fontSize : true,
38         colors : true,
39         specialElements : true
40     });
41     Roo.bootstrap.form.HtmlEditorToolbar.Standard.superclass.constructor.call(this, config);
42     
43     this.editor = config.editor;
44     this.editorcore = config.editor.editorcore;
45     
46     this.buttons   = new Roo.util.MixedCollection(false, function(o) { return o.btnid; });
47     
48     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
49     // dont call parent... till later.
50 }
51 Roo.extend(Roo.bootstrap.form.HtmlEditorToolbar.Standard, Roo.bootstrap.nav.Simplebar,  {
52      
53     bar : true,
54     
55     editor : false,
56     editorcore : false,
57     
58     
59     formats : [
60         "p" ,  
61         "h1","h2","h3","h4","h5","h6", 
62         "pre", "code", 
63         "abbr", "acronym", "address", "cite", "samp", "var",
64         'div','span'
65     ],
66     
67     
68     deleteBtn: false,
69     
70     onRender : function(ct, position)
71     {
72        // Roo.log("Call onRender: " + this.xtype);
73         
74        Roo.bootstrap.form.HtmlEditorToolbar.Standard.superclass.onRender.call(this, ct, position);
75        Roo.log(this.el);
76        this.el.dom.style.marginBottom = '0';
77        var _this = this;
78        var editorcore = this.editorcore;
79        var editor= this.editor;
80        
81        var children = [];
82        var btn = function(id, cmd , toggle, handler, html){
83        
84             var  event = toggle ? 'toggle' : 'click';
85        
86             var a = {
87                 size : 'sm',
88                 xtype: 'Button',
89                 xns: Roo.bootstrap,
90                 //glyphicon : id,
91                 btnid : id,
92                 fa: id,
93                 cmd : cmd, // why id || cmd
94                 enableToggle: toggle !== false,
95                 html : html || '',
96                 pressed : toggle ? false : null,
97                 listeners : {}
98             };
99             a.listeners[toggle ? 'toggle' : 'click'] = function() {
100                 handler ? handler.call(_this,this) :_this.onBtnClick.call(_this, cmd ||  id);
101             };
102             children.push(a);
103             return a;
104        }
105        
106     //    var cb_box = function...
107         
108         var style = {
109                 xtype: 'Button',
110                 size : 'sm',
111                 xns: Roo.bootstrap,
112                 fa : 'font',
113                 //html : 'submit'
114                 menu : {
115                     xtype: 'Menu',
116                     xns: Roo.bootstrap,
117                     items:  []
118                 }
119         };
120         Roo.each(this.formats, function(f) {
121             style.menu.items.push({
122                 xtype :'MenuItem',
123                 xns: Roo.bootstrap,
124                 html : '<'+ f+' style="margin:2px">'+f +'</'+ f+'>',
125                 tagname : f,
126                 listeners : {
127                     click : function()
128                     {
129                         editorcore.insertTag(this.tagname);
130                         editor.focus();
131                     }
132                 }
133                 
134             });
135         });
136         children.push(style);   
137         
138         btn('bold',         false,true);
139         btn('italic',       false,true);
140         btn('align-left',   'justifyleft',true);
141         btn('align-center', 'justifycenter',true);
142         btn('align-right' , 'justifyright',true);
143         btn('link', false, true, this.onLinkClick);
144         
145         
146         btn('image', false, true, this.onImageClick);
147         btn('list','insertunorderedlist',true);
148         btn('list-ol','insertorderedlist',true);
149
150         btn('pencil', false,true, function(btn){
151                 Roo.log(this);
152                 this.toggleSourceEdit(btn.pressed);
153         });
154         
155         if (this.editor.btns.length > 0) {
156             for (var i = 0; i<this.editor.btns.length; i++) {
157                 children.push(this.editor.btns[i]);
158             }
159         }
160         
161         
162          
163         this.xtype = 'NavSimplebar'; // why?
164         
165         for(var i=0;i< children.length;i++) {
166             
167             this.buttons.add(this.addxtypeChild(children[i]));
168             
169         }
170         this.buildToolbarDelete();
171
172         editor.on('editorevent', this.updateToolbar, this);
173     },
174     
175     buildToolbarDelete : function()
176     {
177         
178        /* this.addxtypeChild({
179             xtype : 'Element',
180             xns : Roo.bootstrap,
181             cls : 'roo-htmleditor-fill'
182         });
183         */
184         this.deleteBtn = this.addxtypeChild({
185             size : 'sm',
186             xtype: 'Button',
187             xns: Roo.bootstrap,
188             fa: 'trash',
189             listeners : {
190                 click : this.onDelete.createDelegate(this)
191             }
192         });
193         this.deleteBtn.hide();     
194         
195     },
196     
197     onImageClick : function()
198     {
199         if (this.input) {
200             this.input.un('change', this.onFileSelected, this);
201         }
202         this.input = Roo.get(document.body).createChild({ 
203           tag: 'input', 
204           type : 'file', 
205           style : 'display:none', 
206           multiple: 'multiple'
207        });
208         this.input.on('change', this.onFileSelected, this);
209         this.input.dom.click();
210     },
211     
212     onFileSelected : function(e)
213     {
214          e.preventDefault();
215         
216         if(typeof(this.input.dom.files) == 'undefined' || !this.input.dom.files.length){
217             return;
218         }
219     
220          
221         this.addFiles(Array.prototype.slice.call(this.input.dom.files));
222     },
223     
224     addFiles : function(far) {
225
226         if (!far.length) {
227             return;
228         }
229         
230         var f = far.pop();
231         
232         if (!f.type.match(/^image/)) {
233             this.addFiles(far);
234             return;
235         }
236          
237         var sn = this.selectedNode;
238         
239         var bl = sn  && this.editorcore.enableBlocks ? Roo.htmleditor.Block.factory(sn) : false;
240         
241         var editor =  this.editorcore;
242         
243         var reader = new FileReader();
244         reader.addEventListener('load', (function() {
245             if (bl) {
246                 bl.image_src = reader.result;
247                 //bl.caption = f.name;
248                 bl.updateElement(sn);
249                 editor.owner.fireEvent('editorevent', editor, false);
250                 // we only do the first file!! and replace.
251                 return;
252             }
253             if (this.editorcore.enableBlocks) {
254                 var fig = new Roo.htmleditor.BlockFigure({
255                     image_src :  reader.result,
256                     caption : '',
257                     caption_display : 'none'  //default to hide captions..
258                  });
259                 editor.insertAtCursor(fig.toHTML());
260                 editor.owner.fireEvent('editorevent', editor, false);
261                 return;
262             }
263             // just a standard img..
264             if (sn && sn.tagName.toUpperCase() == 'IMG') {
265                 sn.src = reader.result;
266                 editor.owner.fireEvent('editorevent', editor, false);
267                 return;
268             }
269             editor.insertAtCursor('<img src="' + reader.result +'">');
270             editor.owner.fireEvent('editorevent', editor, false);
271             
272         }).createDelegate(this));
273         reader.readAsDataURL(f);
274         
275     
276      },
277     
278     
279     onBtnClick : function(id)
280     {
281        this.editorcore.relayCmd(id);
282        this.editorcore.focus();
283     },
284     
285     onLinkClick : function(btn) {
286         var url = this.selectedNode && this.selectedNode.tagName.toUpperCase() == 'A' ?
287                 this.selectedNode.getAttribute('href') : '';
288             
289         Roo.bootstrap.MessageBox.show({
290             title : "Add / Edit Link URL",
291             msg : "Enter the URL for the link",
292             buttons: Roo.bootstrap.MessageBox.OKCANCEL,
293             minWidth: 250,
294             scope : this,
295             prompt:true,
296             multiline: false,
297             modal : true,
298             value : url,
299             fn:  function(pressed, newurl) {
300                 if (pressed != 'ok') {
301                     this.editorcore.focus();
302                     return;
303                 }
304                 if (url != '') {
305                     this.selectedNode.setAttribute('href', newurl);
306                     return;
307                 }
308                 if(newurl && newurl .match(/http(s):\/\/.+/)) {
309                     this.editorcore.relayCmd('createlink', newurl);
310                 }
311                 this.editorcore.focus();
312             }
313         });
314     },
315     /**
316      * Protected method that will not generally be called directly. It triggers
317      * a toolbar update by reading the markup state of the current selection in the editor.
318      */
319     updateToolbar: function(editor ,ev, sel){
320
321         if(!this.editorcore.activated){
322             this.editor.onFirstFocus(); // is this neeed?
323             return;
324         }
325
326         var btns = this.buttons; 
327         var doc = this.editorcore.doc;
328         var hasToggle  = false;
329         btns.each(function(e) {
330             if (e.enableToggle && e.cmd) {
331                 hasToggle = hasToggle  || (['align-left', 'align-right', 'align-center'].indexOf(e.btnid) < 0 && doc.queryCommandState(e.cmd));
332                 e.setActive(doc.queryCommandState(e.cmd));
333             }
334         }, this);
335         
336         
337         if (ev &&
338             (ev.type == 'mouseup' || ev.type == 'click' ) &&
339             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
340             // they have click on an image...
341             // let's see if we can change the selection...
342             sel = ev.target;
343             
344         }
345         
346         var ans = this.editorcore.getAllAncestors();
347         if (!sel) { 
348             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
349             sel = sel ? sel : this.editorcore.doc.body;
350             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
351             
352         }
353         
354         var lastSel = this.selectedNode;
355         this.selectedNode = sel;
356          
357         // ok see if we are editing a block?
358         
359         var db = false;
360         // you are not actually selecting the block.
361         if (sel && sel.hasAttribute('data-block')) {
362             db = sel;
363         } else if (sel && sel.closest('[data-block]')) {
364             db = sel.closest('[data-block]');
365         }
366         
367         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
368             e.classList.remove('roo-ed-selection');
369         });
370         
371         var block = false;
372         if (db && this.editorcore.enableBlocks) {
373             block = Roo.htmleditor.Block.factory(db);
374             
375             if (block) {
376                 db.className =  (db.classList.length > 0  ? db.className + ' ' : '') +
377                     ' roo-ed-selection';
378                 sel = this.selectedNode = db;
379             }
380         }
381         
382         // highlight the 'a'..
383         var tn = sel && sel.tagName.toUpperCase() || '';
384         if (!block && sel && tn != 'A') {
385             var asel = sel.closest('A');
386             if (asel) {
387                 sel = asel;
388             }
389         }
390        
391         btns.get('link').setActive(tn == 'A' && this.selectedNode.hasAttribute('href'));
392         
393         Roo.bootstrap.menu.Manager.hideAll();
394          
395         
396         
397         
398         
399         // handle delete button..
400         if (hasToggle || (tn.length && tn == 'BODY')) {
401             this.deleteBtn.hide();
402             return;
403             
404         }
405         this.deleteBtn.show();
406         
407         
408         
409         //this.editorsyncValue();
410     },
411     onFirstFocus: function() {
412         this.buttons.each(function(item){
413            item.enable();
414         });
415     },
416     
417     onDelete : function()
418     {
419         var range = this.editorcore.createRange();
420         var selection = this.editorcore.getSelection();
421         var sn = this.selectedNode;
422         range.setStart(sn,0);
423         range.setEnd(sn,0); 
424         
425         
426         if (sn.hasAttribute('data-block')) {
427             var block = Roo.htmleditor.Block.factory(this.selectedNode);
428             if (block) {
429                 sn = block.removeNode();
430                 sn.parentNode.removeChild(sn);
431                 selection.removeAllRanges();
432                 selection.addRange(range);
433                 this.updateToolbar(null, null, null);
434                 this.editorcore.fireEditorEvent(false);
435                 return;
436             }   
437              
438         }
439         if (!sn) {
440             return; // should not really happen..
441         }
442         if (sn && sn.tagName == 'BODY') {
443             return;
444         }
445         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
446         
447         // remove and keep parents.
448         a = new Roo.htmleditor.FilterKeepChildren({tag : false});
449         a.replaceTag(sn);
450         
451         selection.removeAllRanges();
452         selection.addRange(range);
453         this.editorcore.fireEditorEvent(false);
454         
455         
456     },
457     
458     
459     toggleSourceEdit : function(sourceEditMode){
460         
461           
462         if(sourceEditMode){
463             Roo.log("disabling buttons");
464            this.buttons.each( function(item){
465                 if(item.cmd != 'pencil'){
466                     item.disable();
467                 }
468             });
469           
470         }else{
471             Roo.log("enabling buttons");
472             if(this.editorcore.initialized){
473                 this.buttons.each( function(item){
474                     item.enable();
475                 });
476             }
477             
478         }
479         Roo.log("calling toggole on editor");
480         // tell the editor that it's been pressed..
481         this.editor.toggleSourceEdit(sourceEditMode);
482        
483     }
484 });
485
486
487
488