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