bad87793b2a4e376bedf6988f597cfd42d76848d
[roojs1] / Roo / form / HtmlEditor / ToolbarContext.js
1 // <script type="text/javascript">
2 /*
3  * Based on
4  * Ext JS Library 1.1.1
5  * Copyright(c) 2006-2007, Ext JS, LLC.
6  *  
7  
8  */
9
10  
11 /**
12  * @class Roo.form.HtmlEditor.ToolbarContext
13  * Context Toolbar
14  * 
15  * Usage:
16  *
17  new Roo.form.HtmlEditor({
18     ....
19     toolbars : [
20         { xtype: 'ToolbarStandard', styles : {} }
21         { xtype: 'ToolbarContext', disable : {} }
22     ]
23 })
24
25      
26  * 
27  * @config : {Object} disable List of elements to disable.. (not done yet.)
28  * @config : {Object} styles  Map of styles available.
29  * 
30  */
31
32 Roo.form.HtmlEditor.ToolbarContext = function(config)
33 {
34     
35     Roo.apply(this, config);
36     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
37     // dont call parent... till later.
38     this.styles = this.styles || {};
39 }
40
41  
42
43 Roo.form.HtmlEditor.ToolbarContext.types = {
44     'IMG' : [
45         {
46             name : 'width',
47             title: "Width",
48             width: 40
49         },
50         {
51             name : 'height',
52             title: "Height",
53             width: 40
54         },
55         {
56             name : 'align',
57             title: "Align",
58             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
59             width : 80
60             
61         },
62         {
63             name : 'border',
64             title: "Border",
65             width: 40
66         },
67         {
68             name : 'alt',
69             title: "Alt",
70             width: 120
71         },
72         {
73             name : 'src',
74             title: "Src",
75             width: 220
76         }
77         
78     ],
79     
80     'FIGURE' : [
81         {
82             name : 'align',
83             title: "Align",
84             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
85             width : 80  
86         }
87     ],
88     'A' : [
89         {
90             name : 'name',
91             title: "Name",
92             width: 50
93         },
94         {
95             name : 'target',
96             title: "Target",
97             width: 120
98         },
99         {
100             name : 'href',
101             title: "Href",
102             width: 220
103         } // border?
104         
105     ],
106     
107     'INPUT' : [
108         {
109             name : 'name',
110             title: "name",
111             width: 120
112         },
113         {
114             name : 'value',
115             title: "Value",
116             width: 120
117         },
118         {
119             name : 'width',
120             title: "Width",
121             width: 40
122         }
123     ],
124     'LABEL' : [
125          {
126             name : 'for',
127             title: "For",
128             width: 120
129         }
130     ],
131     'TEXTAREA' : [
132         {
133             name : 'name',
134             title: "name",
135             width: 120
136         },
137         {
138             name : 'rows',
139             title: "Rows",
140             width: 20
141         },
142         {
143             name : 'cols',
144             title: "Cols",
145             width: 20
146         }
147     ],
148     'SELECT' : [
149         {
150             name : 'name',
151             title: "name",
152             width: 120
153         },
154         {
155             name : 'selectoptions',
156             title: "Options",
157             width: 200
158         }
159     ],
160     
161     // should we really allow this??
162     // should this just be 
163     'BODY' : [
164         
165         {
166             name : 'title',
167             title: "Title",
168             width: 200,
169             disabled : true
170         }
171     ],
172  
173     '*' : [
174         // empty.
175     ]
176
177 };
178
179 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
180 Roo.form.HtmlEditor.ToolbarContext.stores = false;
181
182 Roo.form.HtmlEditor.ToolbarContext.options = {
183         'font-family'  : [ 
184                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
185                 [ 'Courier New', 'Courier New'],
186                 [ 'Tahoma', 'Tahoma'],
187                 [ 'Times New Roman,serif', 'Times'],
188                 [ 'Verdana','Verdana' ]
189         ]
190 };
191
192 // fixme - these need to be configurable..
193  
194
195 //Roo.form.HtmlEditor.ToolbarContext.types
196
197
198 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
199     
200     tb: false,
201     
202     rendered: false,
203     
204     editor : false,
205     editorcore : false,
206     /**
207      * @cfg {Object} disable  List of toolbar elements to disable
208          
209      */
210     disable : false,
211     /**
212      * @cfg {Object} styles List of styles 
213      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
214      *
215      * These must be defined in the page, so they get rendered correctly..
216      * .headline { }
217      * TD.underline { }
218      * 
219      */
220     styles : false,
221     
222     options: false,
223     
224     toolbars : false,
225     
226     init : function(editor)
227     {
228         this.editor = editor;
229         this.editorcore = editor.editorcore ? editor.editorcore : editor;
230         var editorcore = this.editorcore;
231         
232         var fid = editorcore.frameId;
233         var etb = this;
234         function btn(id, toggle, handler){
235             var xid = fid + '-'+ id ;
236             return {
237                 id : xid,
238                 cmd : id,
239                 cls : 'x-btn-icon x-edit-'+id,
240                 enableToggle:toggle !== false,
241                 scope: editorcore, // was editor...
242                 handler:handler||editorcore.relayBtnCmd,
243                 clickEvent:'mousedown',
244                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
245                 tabIndex:-1
246             };
247         }
248         // create a new element.
249         var wdiv = editor.wrap.createChild({
250                 tag: 'div'
251             }, editor.wrap.dom.firstChild.nextSibling, true);
252         
253         // can we do this more than once??
254         
255          // stop form submits
256       
257  
258         // disable everything...
259         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
260         this.toolbars = {};
261         // block toolbars are built in updateToolbar when needed.
262         for (var i in  ty) {
263             
264             this.toolbars[i] = this.buildToolbar(ty[i],i);
265         }
266         this.tb = this.toolbars.BODY;
267         this.tb.el.show();
268         this.buildFooter();
269         this.footer.show();
270         editor.on('hide', function( ) { this.footer.hide() }, this);
271         editor.on('show', function( ) { this.footer.show() }, this);
272         
273          
274         this.rendered = true;
275         
276         // the all the btns;
277         editor.on('editorevent', this.updateToolbar, this);
278         // other toolbars need to implement this..
279         //editor.on('editmodechange', this.updateToolbar, this);
280     },
281     
282     
283     
284     /**
285      * Protected method that will not generally be called directly. It triggers
286      * a toolbar update by reading the markup state of the current selection in the editor.
287      *
288      * Note you can force an update by calling on('editorevent', scope, false)
289      */
290     updateToolbar: function(editor ,ev, sel)
291     {
292         
293         if (ev) {
294             ev.stopEvent(); // se if we can stop this looping with mutiple events.
295         }
296         
297         //Roo.log(ev);
298         // capture mouse up - this is handy for selecting images..
299         // perhaps should go somewhere else...
300         if(!this.editorcore.activated){
301              this.editor.onFirstFocus();
302             return;
303         }
304         //Roo.log(ev ? ev.target : 'NOTARGET');
305         
306         
307         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
308         // selectNode - might want to handle IE?
309         
310         
311         
312         if (ev &&
313             (ev.type == 'mouseup' || ev.type == 'click' ) &&
314             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
315             // they have click on an image...
316             // let's see if we can change the selection...
317             sel = ev.target;
318             
319             // this triggers looping?
320             //this.editorcore.selectNode(sel);
321              
322         }
323         
324         // this forces an id..
325         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
326              e.classList.remove('roo-ed-selection');
327         });
328         //Roo.select('.roo-ed-selection', false, this.editorcore.doc).removeClass('roo-ed-selection');
329         //Roo.get(node).addClass('roo-ed-selection');
330       
331         //var updateFooter = sel ? false : true; 
332         
333         
334         var ans = this.editorcore.getAllAncestors();
335         
336         // pick
337         var ty = Roo.form.HtmlEditor.ToolbarContext.types;
338         
339         if (!sel) { 
340             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
341             sel = sel ? sel : this.editorcore.doc.body;
342             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
343             
344         }
345         
346         var tn = sel.tagName.toUpperCase();
347         var lastSel = this.tb.selectedNode;
348         this.tb.selectedNode = sel;
349         var left_label = tn;
350         
351         // ok see if we are editing a block?
352         
353         var db = false;
354         // you are not actually selecting the block.
355         if (sel && sel.hasAttribute('data-block')) {
356             db = sel;
357         } else if (sel && sel.closest('[data-block]')) {
358             
359             db = sel.closest('[data-block]');
360             //var cepar = sel.closest('[contenteditable=true]');
361             //if (db && cepar && cepar.tagName != 'BODY') {
362             //   db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
363             //}   
364         }
365         
366         
367         var block = false;
368         //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
369         if (db && this.editorcore.enableBlocks) {
370             block = Roo.htmleditor.Block.factory(db);
371             
372             
373             if (block) {
374                  db.className = (
375                         db.classList.length > 0  ? db.className + ' ' : ''
376                     )  + 'roo-ed-selection';
377                  
378                  // since we removed it earlier... its not there..
379                 tn = 'BLOCK.' + db.getAttribute('data-block');
380                 
381                 //this.editorcore.selectNode(db);
382                 if (typeof(this.toolbars[tn]) == 'undefined') {
383                    this.toolbars[tn] = this.buildToolbar( false  ,tn ,block.friendly_name, block);
384                 }
385                 this.toolbars[tn].selectedNode = db;
386                 left_label = block.friendly_name;
387                 ans = this.editorcore.getAllAncestors();
388             }
389             
390                 
391             
392         }
393         
394         
395         if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
396             return; // no change?
397         }
398         
399         
400           
401         this.tb.el.hide();
402         ///console.log("show: " + tn);
403         this.tb =  typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
404         
405         this.tb.el.show();
406         // update name
407         this.tb.items.first().el.innerHTML = left_label + ':&nbsp;';
408         
409         
410         // update attributes
411         if (block && this.tb.fields) {
412              
413             this.tb.fields.each(function(e) {
414                 e.setValue(block[e.name]);
415             });
416             
417             
418         } else  if (this.tb.fields && this.tb.selectedNode) {
419             this.tb.fields.each( function(e) {
420                 if (e.stylename) {
421                     e.setValue(this.tb.selectedNode.style[e.stylename]);
422                     return;
423                 } 
424                 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
425             }, this);
426             this.updateToolbarStyles(this.tb.selectedNode);  
427         }
428         
429         
430        
431         Roo.menu.MenuMgr.hideAll();
432
433         
434         
435     
436         // update the footer
437         //
438         this.updateFooter(ans);
439              
440     },
441     
442     updateToolbarStyles : function(sel)
443     {
444         var hasStyles = false;
445         for(var i in this.styles) {
446             hasStyles = true;
447             break;
448         }
449         
450         // update styles
451         if (hasStyles && this.tb.hasStyles) { 
452             var st = this.tb.fields.item(0);
453             
454             st.store.removeAll();
455             var cn = sel.className.split(/\s+/);
456             
457             var avs = [];
458             if (this.styles['*']) {
459                 
460                 Roo.each(this.styles['*'], function(v) {
461                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
462                 });
463             }
464             if (this.styles[tn]) { 
465                 Roo.each(this.styles[tn], function(v) {
466                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
467                 });
468             }
469             
470             st.store.loadData(avs);
471             st.collapse();
472             st.setValue(cn);
473         }
474     },
475     
476      
477     updateFooter : function(ans)
478     {
479         var html = '';
480         if (ans === false) {
481             this.footDisp.dom.innerHTML = '';
482             return;
483         }
484         
485         this.footerEls = ans.reverse();
486         Roo.each(this.footerEls, function(a,i) {
487             if (!a) { return; }
488             html += html.length ? ' &gt; '  :  '';
489             
490             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
491             
492         });
493        
494         // 
495         var sz = this.footDisp.up('td').getSize();
496         this.footDisp.dom.style.width = (sz.width -10) + 'px';
497         this.footDisp.dom.style.marginLeft = '5px';
498         
499         this.footDisp.dom.style.overflow = 'hidden';
500         
501         this.footDisp.dom.innerHTML = html;
502             
503         
504     },
505    
506        
507     // private
508     onDestroy : function(){
509         if(this.rendered){
510             
511             this.tb.items.each(function(item){
512                 if(item.menu){
513                     item.menu.removeAll();
514                     if(item.menu.el){
515                         item.menu.el.destroy();
516                     }
517                 }
518                 item.destroy();
519             });
520              
521         }
522     },
523     onFirstFocus: function() {
524         // need to do this for all the toolbars..
525         this.tb.items.each(function(item){
526            item.enable();
527         });
528     },
529     buildToolbar: function(tlist, nm, friendly_name, block)
530     {
531         var editor = this.editor;
532         var editorcore = this.editorcore;
533          // create a new element.
534         var wdiv = editor.wrap.createChild({
535                 tag: 'div'
536             }, editor.wrap.dom.firstChild.nextSibling, true);
537         
538        
539         var tb = new Roo.Toolbar(wdiv);
540         ///this.tb = tb; // << this sets the active toolbar..
541         if (tlist === false && block) {
542             tlist = block.contextMenu(this);
543         }
544         
545         tb.hasStyles = false;
546         tb.name = nm;
547         
548         tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ":&nbsp;");
549         
550         var styles = Array.from(this.styles);
551         
552         
553         // styles...
554         if (styles && styles.length) {
555             tb.hasStyles = true;
556             // this needs a multi-select checkbox...
557             tb.addField( new Roo.form.ComboBox({
558                 store: new Roo.data.SimpleStore({
559                     id : 'val',
560                     fields: ['val', 'selected'],
561                     data : [] 
562                 }),
563                 name : '-roo-edit-className',
564                 attrname : 'className',
565                 displayField: 'val',
566                 typeAhead: false,
567                 mode: 'local',
568                 editable : false,
569                 triggerAction: 'all',
570                 emptyText:'Select Style',
571                 selectOnFocus:true,
572                 width: 130,
573                 listeners : {
574                     'select': function(c, r, i) {
575                         // initial support only for on class per el..
576                         tb.selectedNode.className =  r ? r.get('val') : '';
577                         editorcore.syncValue();
578                     }
579                 }
580     
581             }));
582         }
583         
584         var tbc = Roo.form.HtmlEditor.ToolbarContext;
585         
586         
587         for (var i = 0; i < tlist.length; i++) {
588             
589             // newer versions will use xtype cfg to create menus.
590             if (typeof(tlist[i].xtype) != 'undefined') {
591                 
592                 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
593                 
594                 
595                 continue;
596             }
597             
598             var item = tlist[i];
599             tb.add(item.title + ":&nbsp;");
600             
601             
602             //optname == used so you can configure the options available..
603             var opts = item.opts ? item.opts : false;
604             if (item.optname) { // use the b
605                 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
606            
607             }
608             
609             if (opts) {
610                 // opts == pulldown..
611                 tb.addField( new Roo.form.ComboBox({
612                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
613                         id : 'val',
614                         fields: ['val', 'display'],
615                         data : opts  
616                     }),
617                     name : '-roo-edit-' + tlist[i].name,
618                     
619                     attrname : tlist[i].name,
620                     stylename : item.style ? item.style : false,
621                     
622                     displayField: item.displayField ? item.displayField : 'val',
623                     valueField :  'val',
624                     typeAhead: false,
625                     mode: typeof(tbc.stores[tlist[i].name]) != 'undefined'  ? 'remote' : 'local',
626                     editable : false,
627                     triggerAction: 'all',
628                     emptyText:'Select',
629                     selectOnFocus:true,
630                     width: item.width ? item.width  : 130,
631                     listeners : {
632                         'select': function(c, r, i) {
633                              
634                             
635                             if (c.stylename) {
636                                 tb.selectedNode.style[c.stylename] =  r.get('val');
637                                 editorcore.syncValue();
638                                 return;
639                             }
640                             if (r === false) {
641                                 tb.selectedNode.removeAttribute(c.attrname);
642                                 editorcore.syncValue();
643                                 return;
644                             }
645                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
646                             editorcore.syncValue();
647                         }
648                     }
649
650                 }));
651                 continue;
652                     
653                  
654                 /*
655                 tb.addField( new Roo.form.TextField({
656                     name: i,
657                     width: 100,
658                     //allowBlank:false,
659                     value: ''
660                 }));
661                 continue;
662                 */
663             }
664             tb.addField( new Roo.form.TextField({
665                 name: '-roo-edit-' + tlist[i].name,
666                 attrname : tlist[i].name,
667                 
668                 width: item.width,
669                 //allowBlank:true,
670                 value: '',
671                 listeners: {
672                     'change' : function(f, nv, ov) {
673                         
674                          
675                         tb.selectedNode.setAttribute(f.attrname, nv);
676                         editorcore.syncValue();
677                     }
678                 }
679             }));
680              
681         }
682         
683         var _this = this;
684         var show_delete = !block || block.deleteTitle !== false;
685         if(nm == 'BODY'){
686             show_delete = false;
687             tb.addSeparator();
688         
689             tb.addButton( {
690                 text: 'Stylesheets',
691
692                 listeners : {
693                     click : function ()
694                     {
695                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
696                     }
697                 }
698             });
699         }
700         
701         tb.addFill();
702         if (show_delete) {
703             tb.addButton({
704                 text: block && block.deleteTitle ? block.deleteTitle  : 'Remove Block or Formating', // remove the tag, and puts the children outside...
705         
706                 listeners : {
707                     click : function ()
708                     {
709                         var sn = tb.selectedNode;
710                         if (block) {
711                             sn = Roo.htmleditor.Block.factory(tb.selectedNode).removeNode();
712                             
713                         }
714                         if (!sn) {
715                             return;
716                         }
717                         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
718                         if (sn.hasAttribute('data-block')) {
719                             stn =  sn.nextSibling || sn.previousSibling || sn.parentNode;
720                             sn.parentNode.removeChild(sn);
721                             
722                         } else if (sn && sn.tagName != 'BODY') {
723                             // remove and keep parents.
724                             a = new Roo.htmleditor.FilterKeepChildren({tag : false});
725                             a.replaceTag(sn);
726                         }
727                         
728                         
729                         var range = editorcore.createRange();
730             
731                         range.setStart(stn,0);
732                         range.setEnd(stn,0); 
733                         var selection = editorcore.getSelection();
734                         selection.removeAllRanges();
735                         selection.addRange(range);
736                         
737                         
738                         //_this.updateToolbar(null, null, pn);
739                         _this.updateToolbar(null, null, null);
740                         _this.updateFooter(false);
741
742
743                         editorcore.syncValue();
744                     }
745                 }
746                 
747                         
748                     
749                 
750             });
751         }    
752         
753         tb.el.on('click', function(e){
754             e.preventDefault(); // what does this do?
755         });
756         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
757         tb.el.hide();
758         
759         // dont need to disable them... as they will get hidden
760         return tb;
761          
762         
763     },
764     buildFooter : function()
765     {
766         
767         var fel = this.editor.wrap.createChild();
768         this.footer = new Roo.Toolbar(fel);
769         // toolbar has scrolly on left / right?
770         var footDisp= new Roo.Toolbar.Fill();
771         var _t = this;
772         this.footer.add(
773             {
774                 text : '&lt;',
775                 xtype: 'Button',
776                 handler : function() {
777                     _t.footDisp.scrollTo('left',0,true)
778                 }
779             }
780         );
781         this.footer.add( footDisp );
782         this.footer.add( 
783             {
784                 text : '&gt;',
785                 xtype: 'Button',
786                 handler : function() {
787                     // no animation..
788                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
789                 }
790             }
791         );
792         var fel = Roo.get(footDisp.el);
793         fel.addClass('x-editor-context');
794         this.footDispWrap = fel; 
795         this.footDispWrap.overflow  = 'hidden';
796         
797         this.footDisp = fel.createChild();
798         this.footDispWrap.on('click', this.onContextClick, this)
799         
800         
801     },
802     // when the footer contect changes
803     onContextClick : function (ev,dom)
804     {
805         ev.preventDefault();
806         var  cn = dom.className;
807         //Roo.log(cn);
808         if (!cn.match(/x-ed-loc-/)) {
809             return;
810         }
811         var n = cn.split('-').pop();
812         var ans = this.footerEls;
813         var sel = ans[n];
814         
815         this.editorcore.selectNode(sel);
816         
817         
818         this.updateToolbar(null, null, sel);
819         
820         
821     }
822     
823     
824     
825     
826     
827 });
828
829
830
831
832