dcea277dd73ca66a8cc8c84a8d45467067088c72
[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                 this.editor.syncValue();
235                 editor.owner.fireEvent('editorevent', editor.owner, false);
236                 editor.owner.fireEvent('imageadd', editor.owner, false);
237             }
238             return;
239         }
240         
241         var f = far.pop();
242         
243         if (!f.type.match(/^image/)) {
244             this.addFiles(far, fire_add);
245             return;
246         }
247          
248         var sn = this.selectedNode;
249         
250         var bl = sn  && this.editorcore.enableBlocks ? Roo.htmleditor.Block.factory(sn) : false;
251         
252         
253         var reader = new FileReader();
254         reader.addEventListener('load', (function() {
255             if (bl) {
256                 var oldSrc = bl.image_src;
257                 bl.image_src = reader.result;
258                 //bl.caption = f.name;
259                 bl.updateElement(sn);
260                 this.editor.syncValue();
261                 editor.owner.fireEvent('editorevent', editor.owner, false);
262                 editor.owner.fireEvent('imageupdate', editor.owner, sn, oldSrc);
263                 // we only do the first file!! and replace.
264                 return;
265             }
266             if (this.editorcore.enableBlocks) {
267                 var fig = new Roo.htmleditor.BlockFigure({
268                     image_src :  reader.result,
269                     caption : '',
270                     caption_display : 'none'  //default to hide captions..
271                  });
272                 editor.insertAtCursor(fig.toHTML());
273                 this.addFiles(far, true);
274                 return;
275             }
276             // just a standard img..
277             if (sn && sn.tagName.toUpperCase() == 'IMG') {
278                 var oldSrc = sn.src;
279                 sn.src = reader.result;
280                 this.editor.syncValue();
281                 editor.owner.fireEvent('editorevent', editor.owner, false);
282                 editor.owner.fireEvent('imageupdate', editor.owner, sn, oldSrc);
283                 return;
284             }
285             editor.insertAtCursor('<img src="' + reader.result +'">');
286             this.addFiles(far, true);
287             
288         }).createDelegate(this));
289         reader.readAsDataURL(f);
290         
291     
292      },
293     
294     
295     onBtnClick : function(id)
296     {
297        this.editorcore.relayCmd(id);
298        this.editorcore.focus();
299     },
300     
301     onLinkClick : function(btn) {
302         var url = this.selectedNode && this.selectedNode.tagName.toUpperCase() == 'A' ?
303                 this.selectedNode.getAttribute('href') : '';
304             
305         Roo.bootstrap.MessageBox.show({
306             title : "Add / Edit Link URL",
307             msg : "Enter the URL for the link",
308             buttons: Roo.bootstrap.MessageBox.OKCANCEL,
309             minWidth: 250,
310             scope : this,
311             prompt:true,
312             multiline: false,
313             modal : true,
314             value : url,
315             fn:  function(pressed, newurl) {
316                 if (pressed != 'ok') {
317                     this.editorcore.focus();
318                     return;
319                 }
320                 if (url != '') {
321                     this.selectedNode.setAttribute('href', newurl);
322                     return;
323                 }
324                 if(newurl && newurl .match(/http(s):\/\/.+/)) {
325                     this.editorcore.relayCmd('createlink', newurl);
326                 }
327                 this.editorcore.focus();
328             }
329         });
330     },
331     /**
332      * Protected method that will not generally be called directly. It triggers
333      * a toolbar update by reading the markup state of the current selection in the editor.
334      */
335     updateToolbar: function(editor ,ev, sel){
336
337         if(!this.editorcore.activated){
338             this.editor.onFirstFocus(); // is this neeed?
339             return;
340         }
341
342         var btns = this.buttons; 
343         var doc = this.editorcore.doc;
344         var hasToggle  = false;
345         btns.each(function(e) {
346             if (e.enableToggle && e.cmd) {
347                 hasToggle = hasToggle  || (['align-left', 'align-right', 'align-center', 'image' , 'link', 'underline'].indexOf(e.btnid) < 0 && doc.queryCommandState(e.cmd));
348                 e.setActive(doc.queryCommandState(e.cmd));
349             }
350         }, this);
351         
352         
353         if (ev &&
354             (ev.type == 'mouseup' || ev.type == 'click' ) &&
355             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
356             // they have click on an image...
357             // let's see if we can change the selection...
358             sel = ev.target;
359             
360         }
361         
362         var ans = this.editorcore.getAllAncestors();
363         if (!sel) { 
364             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
365             sel = sel ? sel : this.editorcore.doc.body;
366             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
367             
368         }
369         
370         var lastSel = this.selectedNode;
371         this.selectedNode = sel;
372          
373         // ok see if we are editing a block?
374         
375         var db = false;
376         // you are not actually selecting the block.
377         if (sel && sel.hasAttribute('data-block')) {
378             db = sel;
379         } else if (sel && sel.closest('[data-block]')) {
380             db = sel.closest('[data-block]');
381         }
382         
383         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
384             e.classList.remove('roo-ed-selection');
385         });
386         
387         var block = false;
388         if (db && this.editorcore.enableBlocks) {
389             block = Roo.htmleditor.Block.factory(db);
390             
391             if (block) {
392                 db.className =  (db.classList.length > 0  ? db.className + ' ' : '') +
393                     ' roo-ed-selection';
394                 sel = this.selectedNode = db;
395             }
396         }
397         
398         // highlight the 'a'..
399         var tn = sel && sel.tagName.toUpperCase() || '';
400         if (!block && sel && tn != 'A') {
401             var asel = sel.closest('A');
402             if (asel) {
403                 sel = asel;
404             }
405         }
406        
407         btns.get('link').setActive(tn == 'A' && this.selectedNode.hasAttribute('href'));
408         btns.get('image').setActive(tn == 'IMG' || this.editorcore.enableBlocks && tn == 'FIGURE');
409         btns.get('underline').setActive(tn == 'U' || sel.closest('u') ? true : false);
410         
411         Roo.bootstrap.menu.Manager.hideAll();
412          
413         
414         
415         
416         
417         // handle delete button..
418         if (hasToggle || (tn.length && tn == 'BODY')) {
419             this.deleteBtn.hide();
420             return;
421             
422         }
423         this.deleteBtn.show();
424         
425         
426         
427         //this.editorsyncValue();
428     },
429     onFirstFocus: function() {
430         this.buttons.each(function(item){
431            item.enable();
432         });
433     },
434     
435     onDelete : function()
436     {
437         var range = this.editorcore.createRange();
438         var selection = this.editorcore.getSelection();
439         var sn = this.selectedNode;
440         range.setStart(sn,0);
441         range.setEnd(sn,0); 
442         
443         
444         if (sn.hasAttribute('data-block')) {
445             var block = Roo.htmleditor.Block.factory(this.selectedNode);
446             if (block) {
447                 sn = block.removeNode();
448                 sn.parentNode.removeChild(sn);
449                 selection.removeAllRanges();
450                 selection.addRange(range);
451                 this.updateToolbar(null, null, null);
452                 if (sn.tagName.toUpperCase() == 'FIGURE') {
453                     this.editor.syncValue();
454                     this.editor.fireEvent('imagedelete', this.editor, sn);
455                 }
456                 
457                 this.selectedNode = false;
458                 this.editorcore.fireEditorEvent(false);
459                 return;
460             }   
461              
462         }
463         if (!sn) {
464             return; // should not really happen..
465         }
466         if (sn && sn.tagName == 'BODY') {
467             return;
468         }
469         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
470         
471         // remove and keep parents.
472         a = new Roo.htmleditor.FilterKeepChildren({tag : false});
473         a.replaceTag(sn);
474         
475         selection.removeAllRanges();
476         selection.addRange(range);
477         if (sn.tagName.toUpperCase() == 'IMG"') {
478             this.editor.syncValue();
479             this.editor.fireEvent('imagedelete', this.editor, sn);
480         }
481         
482         this.selectedNode = false;
483         this.editorcore.fireEditorEvent(false);
484         
485         
486     },
487     
488     
489     toggleSourceEdit : function(sourceEditMode){
490         
491           
492         if(sourceEditMode){
493             Roo.log("disabling buttons");
494            this.buttons.each( function(item){
495                 if(item.cmd != 'pencil'){
496                     item.disable();
497                 }
498             });
499           
500         }else{
501             Roo.log("enabling buttons");
502             if(this.editorcore.initialized){
503                 this.buttons.each( function(item){
504                     item.enable();
505                 });
506             }
507             
508         }
509         Roo.log("calling toggole on editor");
510         // tell the editor that it's been pressed..
511         this.editor.toggleSourceEdit(sourceEditMode);
512        
513     }
514 });
515
516
517
518