Fix #7586 - more events for editor
[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                 cls : 'roo-html-editor-btn-' + id,
94                 cmd : cmd, // why id || cmd
95                 enableToggle: toggle !== false,
96                 html : html || '',
97                 pressed : toggle ? false : null,
98                 listeners : {}
99             };
100             a.listeners[toggle ? 'toggle' : 'click'] = function() {
101                 handler ? handler.call(_this,this) :_this.onBtnClick.call(_this, cmd ||  id);
102             };
103             children.push(a);
104             return a;
105        }
106        
107     //    var cb_box = function...
108         
109         var style = {
110                 xtype: 'Button',
111                 size : 'sm',
112                 xns: Roo.bootstrap,
113                 fa : 'font',
114                 cls : 'roo-html-editor-font-chooser',
115                 //html : 'submit'
116                 menu : {
117                     xtype: 'Menu',
118                     xns: Roo.bootstrap,
119                     items:  []
120                 }
121         };
122         Roo.each(this.formats, function(f) {
123             style.menu.items.push({
124                 xtype :'MenuItem',
125                 xns: Roo.bootstrap,
126                 html : '<'+ f+' style="margin:2px">'+f +'</'+ f+'>',
127                 tagname : f,
128                 listeners : {
129                     click : function()
130                     {
131                         editorcore.insertTag(this.tagname);
132                         editor.focus();
133                     }
134                 }
135                 
136             });
137         });
138         children.push(style);   
139         
140         btn('bold',         'bold',true);
141         btn('italic',       'italic',true);
142         btn('underline',     'underline',true);
143         btn('align-left',   'justifyleft',true);
144         btn('align-center', 'justifycenter',true);
145         btn('align-right' , 'justifyright',true);
146         btn('link', false, true, this.onLinkClick);
147         
148         
149         btn('image', false, true, this.onImageClick);
150         btn('list','insertunorderedlist',true);
151         btn('list-ol','insertorderedlist',true);
152
153         btn('pencil', false,true, function(btn){
154                 Roo.log(this);
155                 this.toggleSourceEdit(btn.pressed);
156         });
157         
158         if (this.editor.btns.length > 0) {
159             for (var i = 0; i<this.editor.btns.length; i++) {
160                 children.push(this.editor.btns[i]);
161             }
162         }
163         
164         
165          
166         this.xtype = 'NavSimplebar'; // why?
167         
168         for(var i=0;i< children.length;i++) {
169             
170             this.buttons.add(this.addxtypeChild(children[i]));
171             
172         }
173         this.buildToolbarDelete();
174
175         editor.on('editorevent', this.updateToolbar, this);
176     },
177     
178     buildToolbarDelete : function()
179     {
180         
181        /* this.addxtypeChild({
182             xtype : 'Element',
183             xns : Roo.bootstrap,
184             cls : 'roo-htmleditor-fill'
185         });
186         */
187         this.deleteBtn = this.addxtypeChild({
188             size : 'sm',
189             xtype: 'Button',
190             xns: Roo.bootstrap,
191             fa: 'trash',
192             listeners : {
193                 click : this.onDelete.createDelegate(this)
194             }
195         });
196         this.deleteBtn.hide();     
197         
198     },
199     
200     onImageClick : function()
201     {
202         if (this.input) {
203             this.input.un('change', this.onFileSelected, this);
204         }
205         this.input = Roo.get(document.body).createChild({ 
206           tag: 'input', 
207           type : 'file', 
208           style : 'display:none', 
209           multiple: 'multiple'
210        });
211         this.input.on('change', this.onFileSelected, this);
212         this.input.dom.click();
213     },
214     
215     onFileSelected : function(e)
216     {
217          e.preventDefault();
218         
219         if(typeof(this.input.dom.files) == 'undefined' || !this.input.dom.files.length){
220             return;
221         }
222     
223          
224         this.addFiles(Array.prototype.slice.call(this.input.dom.files), false);
225     },
226     
227     addFiles : function(far, fire_add) {
228
229          
230         var editor =  this.editorcore;
231   
232         if (!far.length) {
233             if (fire_add) {
234                 editor.owner.fireEvent('editorevent', editor.owner, false);
235                 editor.owner.fireEvent('imageadd', editor.owner, false);
236             }
237             return;
238         }
239         
240         var f = far.pop();
241         
242         if (!f.type.match(/^image/)) {
243             this.addFiles(far, fire_add);
244             return;
245         }
246          
247         var sn = this.selectedNode;
248         
249         var bl = sn  && this.editorcore.enableBlocks ? Roo.htmleditor.Block.factory(sn) : false;
250         
251         
252         var reader = new FileReader();
253         reader.addEventListener('load', (function() {
254             if (bl) {
255                 bl.image_src = reader.result;
256                 //bl.caption = f.name;
257                 bl.updateElement(sn);
258                 editor.owner.fireEvent('editorevent', editor.owner, false);
259                 editor.owner.fireEvent('imageupdate', editor.owner, sn);
260                 // we only do the first file!! and replace.
261                 return;
262             }
263             if (this.editorcore.enableBlocks) {
264                 var fig = new Roo.htmleditor.BlockFigure({
265                     image_src :  reader.result,
266                     caption : '',
267                     caption_display : 'none'  //default to hide captions..
268                  });
269                 editor.insertAtCursor(fig.toHTML());
270                 this.addFiles(far, true);
271                 return;
272             }
273             // just a standard img..
274             if (sn && sn.tagName.toUpperCase() == 'IMG') {
275                 sn.src = reader.result;
276                 editor.owner.fireEvent('editorevent', editor.owner, false);
277                 editor.owner.fireEvent('imageupdate', editor.owner, sn);
278                 return;
279             }
280             editor.insertAtCursor('<img src="' + reader.result +'">');
281             this.addFiles(far, true);
282             
283         }).createDelegate(this));
284         reader.readAsDataURL(f);
285         
286     
287      },
288     
289     
290     onBtnClick : function(id)
291     {
292        this.editorcore.relayCmd(id);
293        this.editorcore.focus();
294     },
295     
296     onLinkClick : function(btn) {
297         var url = this.selectedNode && this.selectedNode.tagName.toUpperCase() == 'A' ?
298                 this.selectedNode.getAttribute('href') : '';
299             
300         Roo.bootstrap.MessageBox.show({
301             title : "Add / Edit Link URL",
302             msg : "Enter the URL for the link",
303             buttons: Roo.bootstrap.MessageBox.OKCANCEL,
304             minWidth: 250,
305             scope : this,
306             prompt:true,
307             multiline: false,
308             modal : true,
309             value : url,
310             fn:  function(pressed, newurl) {
311                 if (pressed != 'ok') {
312                     this.editorcore.focus();
313                     return;
314                 }
315                 if (url != '') {
316                     this.selectedNode.setAttribute('href', newurl);
317                     return;
318                 }
319                 if(newurl && newurl .match(/http(s):\/\/.+/)) {
320                     this.editorcore.relayCmd('createlink', newurl);
321                 }
322                 this.editorcore.focus();
323             }
324         });
325     },
326     /**
327      * Protected method that will not generally be called directly. It triggers
328      * a toolbar update by reading the markup state of the current selection in the editor.
329      */
330     updateToolbar: function(editor ,ev, sel){
331
332         if(!this.editorcore.activated){
333             this.editor.onFirstFocus(); // is this neeed?
334             return;
335         }
336
337         var btns = this.buttons; 
338         var doc = this.editorcore.doc;
339         var hasToggle  = false;
340         btns.each(function(e) {
341             if (e.enableToggle && e.cmd) {
342                 hasToggle = hasToggle  || (['align-left', 'align-right', 'align-center', 'image' , 'link', 'underline'].indexOf(e.btnid) < 0 && doc.queryCommandState(e.cmd));
343                 e.setActive(doc.queryCommandState(e.cmd));
344             }
345         }, this);
346         
347         
348         if (ev &&
349             (ev.type == 'mouseup' || ev.type == 'click' ) &&
350             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
351             // they have click on an image...
352             // let's see if we can change the selection...
353             sel = ev.target;
354             
355         }
356         
357         var ans = this.editorcore.getAllAncestors();
358         if (!sel) { 
359             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
360             sel = sel ? sel : this.editorcore.doc.body;
361             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
362             
363         }
364         
365         var lastSel = this.selectedNode;
366         this.selectedNode = sel;
367          
368         // ok see if we are editing a block?
369         
370         var db = false;
371         // you are not actually selecting the block.
372         if (sel && sel.hasAttribute('data-block')) {
373             db = sel;
374         } else if (sel && sel.closest('[data-block]')) {
375             db = sel.closest('[data-block]');
376         }
377         
378         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
379             e.classList.remove('roo-ed-selection');
380         });
381         
382         var block = false;
383         if (db && this.editorcore.enableBlocks) {
384             block = Roo.htmleditor.Block.factory(db);
385             
386             if (block) {
387                 db.className =  (db.classList.length > 0  ? db.className + ' ' : '') +
388                     ' roo-ed-selection';
389                 sel = this.selectedNode = db;
390             }
391         }
392         
393         // highlight the 'a'..
394         var tn = sel && sel.tagName.toUpperCase() || '';
395         if (!block && sel && tn != 'A') {
396             var asel = sel.closest('A');
397             if (asel) {
398                 sel = asel;
399             }
400         }
401        
402         btns.get('link').setActive(tn == 'A' && this.selectedNode.hasAttribute('href'));
403         btns.get('image').setActive(tn == 'IMG' || this.editorcore.enableBlocks && tn == 'FIGURE');
404         btns.get('underline').setActive(tn == 'U' || sel.closest('u') ? true : false);
405         
406         Roo.bootstrap.menu.Manager.hideAll();
407          
408         
409         
410         
411         
412         // handle delete button..
413         if (hasToggle || (tn.length && tn == 'BODY')) {
414             this.deleteBtn.hide();
415             return;
416             
417         }
418         this.deleteBtn.show();
419         
420         
421         
422         //this.editorsyncValue();
423     },
424     onFirstFocus: function() {
425         this.buttons.each(function(item){
426            item.enable();
427         });
428     },
429     
430     onDelete : function()
431     {
432         var range = this.editorcore.createRange();
433         var selection = this.editorcore.getSelection();
434         var sn = this.selectedNode;
435         range.setStart(sn,0);
436         range.setEnd(sn,0); 
437         
438         
439         if (sn.hasAttribute('data-block')) {
440             var block = Roo.htmleditor.Block.factory(this.selectedNode);
441             if (block) {
442                 sn = block.removeNode();
443                 sn.parentNode.removeChild(sn);
444                 selection.removeAllRanges();
445                 selection.addRange(range);
446                 this.updateToolbar(null, null, null);
447                 if (sn.tagName.toUpperCase() == 'FIGURE') {
448                     this.editor.fireEvent('imagedelete', this.editor, sn);
449                 }
450                 
451                 this.selectedNode = false;
452                 this.editorcore.fireEditorEvent(false);
453                 return;
454             }   
455              
456         }
457         if (!sn) {
458             return; // should not really happen..
459         }
460         if (sn && sn.tagName == 'BODY') {
461             return;
462         }
463         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
464         
465         // remove and keep parents.
466         a = new Roo.htmleditor.FilterKeepChildren({tag : false});
467         a.replaceTag(sn);
468         
469         selection.removeAllRanges();
470         selection.addRange(range);
471         if (sn.tagName.toUpperCase() == 'IMG"') {
472             this.editor.fireEvent('imagedelete', this.editor, sn);
473         }
474         
475         this.selectedNode = false;
476         this.editorcore.fireEditorEvent(false);
477         
478         
479     },
480     
481     
482     toggleSourceEdit : function(sourceEditMode){
483         
484           
485         if(sourceEditMode){
486             Roo.log("disabling buttons");
487            this.buttons.each( function(item){
488                 if(item.cmd != 'pencil'){
489                     item.disable();
490                 }
491             });
492           
493         }else{
494             Roo.log("enabling buttons");
495             if(this.editorcore.initialized){
496                 this.buttons.each( function(item){
497                     item.enable();
498                 });
499             }
500             
501         }
502         Roo.log("calling toggole on editor");
503         // tell the editor that it's been pressed..
504         this.editor.toggleSourceEdit(sourceEditMode);
505        
506     }
507 });
508
509
510
511