d4229969deb68fd675882cf928198b1fc5247d02
[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            
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 != '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       
325         //var updateFooter = sel ? false : true; 
326         
327         
328         var ans = this.editorcore.getAllAncestors();
329         
330         // pick
331         var ty = Roo.form.HtmlEditor.ToolbarContext.types;
332         
333         if (!sel) { 
334             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
335             sel = sel ? sel : this.editorcore.doc.body;
336             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
337             
338         }
339         
340         var tn = sel.tagName.toUpperCase();
341         var lastSel = this.tb.selectedNode;
342         this.tb.selectedNode = sel;
343         var left_label = tn;
344         
345         // ok see if we are editing a block?
346         var sel_el = Roo.get(sel);
347         var db = false;
348         // you are not actually selecting the block.
349         if (sel && sel.hasAttribute('data-block')) {
350             db = sel;
351         } else if (sel && !sel.hasAttribute('contenteditable')) {
352             db = sel_el.findParent('[data-block]');
353             var cepar = sel_el.findParent('[contenteditable=true]');
354             if (db && cepar && cepar.tagName != 'BODY') {
355                db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
356             }   
357         }
358         
359         
360         var block = false;
361         //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
362         if (db) {
363             block = Roo.htmleditor.Block.factory(db);
364             if (block) {
365                 tn = 'BLOCK.' + db.getAttribute('data-block');
366                 
367                 //this.editorcore.selectNode(db);
368                 if (typeof(this.toolbars[tn]) == 'undefined') {
369                    this.toolbars[tn] = this.buildToolbar( false  ,tn ,block.friendly_name, block);
370                 }
371                 this.toolbars[tn].selectedNode = db;
372                 left_label = block.friendly_name;
373                 ans = this.editorcore.getAllAncestors();
374             }
375             
376                 
377             
378         }
379         
380         
381         if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
382             return; // no change?
383         }
384         
385         
386           
387         this.tb.el.hide();
388         ///console.log("show: " + tn);
389         this.tb =  typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
390         
391         this.tb.el.show();
392         // update name
393         this.tb.items.first().el.innerHTML = left_label + ':&nbsp;';
394         
395         
396         // update attributes
397         if (block) {
398              
399             this.tb.fields.each(function(e) {
400                 e.setValue(block[e.name]);
401             });
402             
403             
404         } else  if (this.tb.fields && this.tb.selectedNode) {
405             this.tb.fields.each( function(e) {
406                 if (e.stylename) {
407                     e.setValue(this.tb.selectedNode.style[e.stylename]);
408                     return;
409                 } 
410                 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
411             }, this);
412             this.updateToolbarStyles(this.tb.selectedNode);  
413         }
414         
415         
416        
417         Roo.menu.MenuMgr.hideAll();
418
419         
420         
421     
422         // update the footer
423         //
424         this.updateFooter(ans);
425              
426     },
427     
428     updateToolbarStyles : function(sel)
429     {
430         var hasStyles = false;
431         for(var i in this.styles) {
432             hasStyles = true;
433             break;
434         }
435         
436         // update styles
437         if (hasStyles && this.tb.hasStyles) { 
438             var st = this.tb.fields.item(0);
439             
440             st.store.removeAll();
441             var cn = sel.className.split(/\s+/);
442             
443             var avs = [];
444             if (this.styles['*']) {
445                 
446                 Roo.each(this.styles['*'], function(v) {
447                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
448                 });
449             }
450             if (this.styles[tn]) { 
451                 Roo.each(this.styles[tn], function(v) {
452                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
453                 });
454             }
455             
456             st.store.loadData(avs);
457             st.collapse();
458             st.setValue(cn);
459         }
460     },
461     
462      
463     updateFooter : function(ans)
464     {
465         var html = '';
466         if (ans === false) {
467             this.footDisp.dom.innerHTML = '';
468             return;
469         }
470         
471         this.footerEls = ans.reverse();
472         Roo.each(this.footerEls, function(a,i) {
473             if (!a) { return; }
474             html += html.length ? ' &gt; '  :  '';
475             
476             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
477             
478         });
479        
480         // 
481         var sz = this.footDisp.up('td').getSize();
482         this.footDisp.dom.style.width = (sz.width -10) + 'px';
483         this.footDisp.dom.style.marginLeft = '5px';
484         
485         this.footDisp.dom.style.overflow = 'hidden';
486         
487         this.footDisp.dom.innerHTML = html;
488             
489         
490     },
491    
492        
493     // private
494     onDestroy : function(){
495         if(this.rendered){
496             
497             this.tb.items.each(function(item){
498                 if(item.menu){
499                     item.menu.removeAll();
500                     if(item.menu.el){
501                         item.menu.el.destroy();
502                     }
503                 }
504                 item.destroy();
505             });
506              
507         }
508     },
509     onFirstFocus: function() {
510         // need to do this for all the toolbars..
511         this.tb.items.each(function(item){
512            item.enable();
513         });
514     },
515     buildToolbar: function(tlist, nm, friendly_name, block)
516     {
517         var editor = this.editor;
518         var editorcore = this.editorcore;
519          // create a new element.
520         var wdiv = editor.wrap.createChild({
521                 tag: 'div'
522             }, editor.wrap.dom.firstChild.nextSibling, true);
523         
524        
525         var tb = new Roo.Toolbar(wdiv);
526         this.tb = tb;
527         if (tlist === false && block) {
528             tlist = block.contextMenu(this);
529         }
530         
531         tb.hasStyles = false;
532         tb.name = nm;
533         
534         tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ":&nbsp;");
535         
536         var styles = Array.from(this.styles);
537         
538         
539         // styles...
540         if (styles && styles.length) {
541             tb.hasStyles = true;
542             // this needs a multi-select checkbox...
543             tb.addField( new Roo.form.ComboBox({
544                 store: new Roo.data.SimpleStore({
545                     id : 'val',
546                     fields: ['val', 'selected'],
547                     data : [] 
548                 }),
549                 name : '-roo-edit-className',
550                 attrname : 'className',
551                 displayField: 'val',
552                 typeAhead: false,
553                 mode: 'local',
554                 editable : false,
555                 triggerAction: 'all',
556                 emptyText:'Select Style',
557                 selectOnFocus:true,
558                 width: 130,
559                 listeners : {
560                     'select': function(c, r, i) {
561                         // initial support only for on class per el..
562                         tb.selectedNode.className =  r ? r.get('val') : '';
563                         editorcore.syncValue();
564                     }
565                 }
566     
567             }));
568         }
569         
570         var tbc = Roo.form.HtmlEditor.ToolbarContext;
571         
572         
573         for (var i = 0; i < tlist.length; i++) {
574             
575             // newer versions will use xtype cfg to create menus.
576             if (typeof(tlist[i].xtype) != 'undefined') {
577                 
578                 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
579                 
580                 
581                 continue;
582             }
583             
584             var item = tlist[i];
585             tb.add(item.title + ":&nbsp;");
586             
587             
588             //optname == used so you can configure the options available..
589             var opts = item.opts ? item.opts : false;
590             if (item.optname) { // use the b
591                 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
592            
593             }
594             
595             if (opts) {
596                 // opts == pulldown..
597                 tb.addField( new Roo.form.ComboBox({
598                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
599                         id : 'val',
600                         fields: ['val', 'display'],
601                         data : opts  
602                     }),
603                     name : '-roo-edit-' + tlist[i].name,
604                     
605                     attrname : tlist[i].name,
606                     stylename : item.style ? item.style : false,
607                     
608                     displayField: item.displayField ? item.displayField : 'val',
609                     valueField :  'val',
610                     typeAhead: false,
611                     mode: typeof(tbc.stores[tlist[i].name]) != 'undefined'  ? 'remote' : 'local',
612                     editable : false,
613                     triggerAction: 'all',
614                     emptyText:'Select',
615                     selectOnFocus:true,
616                     width: item.width ? item.width  : 130,
617                     listeners : {
618                         'select': function(c, r, i) {
619                             if (tb.selectedNode.hasAttribute('data-block')) {
620                                 var b = Roo.htmleditor.Block.factory(tb.selectedNode);
621                                 b[c.attrname] = r.get('val');
622                                 b.updateElement(tb.selectedNode);
623                                 editorcore.syncValue();
624                                 return;
625                             }
626                             
627                             if (c.stylename) {
628                                 tb.selectedNode.style[c.stylename] =  r.get('val');
629                                 editorcore.syncValue();
630                                 return;
631                             }
632                             if (r === false) {
633                                 tb.selectedNode.removeAttribute(c.attrname);
634                                 editorcore.syncValue();
635                                 return;
636                             }
637                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
638                             editorcore.syncValue();
639                         }
640                     }
641
642                 }));
643                 continue;
644                     
645                  
646                 /*
647                 tb.addField( new Roo.form.TextField({
648                     name: i,
649                     width: 100,
650                     //allowBlank:false,
651                     value: ''
652                 }));
653                 continue;
654                 */
655             }
656             tb.addField( new Roo.form.TextField({
657                 name: '-roo-edit-' + tlist[i].name,
658                 attrname : tlist[i].name,
659                 
660                 width: item.width,
661                 //allowBlank:true,
662                 value: '',
663                 listeners: {
664                     'change' : function(f, nv, ov) {
665                         
666                         if (tb.selectedNode.hasAttribute('data-block')) {
667                             var b = Roo.htmleditor.Block.factory(tb.selectedNode);
668                             b[f.attrname] = nv;
669                             b.updateElement(tb.selectedNode);
670                             editorcore.syncValue();
671                             return;
672                         }
673                         
674                         tb.selectedNode.setAttribute(f.attrname, nv);
675                         editorcore.syncValue();
676                     }
677                 }
678             }));
679              
680         }
681         
682         var _this = this;
683         
684         if(nm == 'BODY'){
685             tb.addSeparator();
686         
687             tb.addButton( {
688                 text: 'Stylesheets',
689
690                 listeners : {
691                     click : function ()
692                     {
693                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
694                     }
695                 }
696             });
697         }
698         
699         tb.addFill();
700         tb.addButton({
701             text: 'Remove Block or Formating', // remove the tag, and puts the children outside...
702     
703             listeners : {
704                 click : function ()
705                 {
706                     if (block) {
707                         sn = Roo.htmleditor.Block.factory(tb.selectedNode).removalNode();
708                         
709                     } else {
710                     
711                         // remove
712                         // undo does not work.
713                         var sn = tb.selectedNode;
714                     }
715                     if (!sn) {
716                         return;
717                     }
718                     var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
719                     if (sn.hasAttribute('data-block')) {
720                         stn =  sn.nextSibling || sn.previousSibling || sn.parentNode;
721                         sn.parentNode.removeChild(sn);
722                         
723                     } else if (sn && sn.tagName != 'BODY') {
724                         // remove and keep parents.
725                         a = new Roo.htmleditor.FilterKeepChildren({tag : false});
726                         a.removeTag(sn);
727                     }
728                     
729                     
730                     var range = editorcore.createRange();
731         
732                     range.setStart(stn,0);
733                     range.setEnd(stn,0); 
734                     var selection = editorcore.getSelection();
735                     selection.removeAllRanges();
736                     selection.addRange(range);
737                     
738                     
739                     //_this.updateToolbar(null, null, pn);
740                     _this.updateToolbar(null, null, null);
741                     _this.updateFooter(false);
742                     
743                 }
744             }
745             
746                     
747                 
748             
749         });
750         
751         
752         tb.el.on('click', function(e){
753             e.preventDefault(); // what does this do?
754         });
755         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
756         tb.el.hide();
757         
758         // dont need to disable them... as they will get hidden
759         return tb;
760          
761         
762     },
763     buildFooter : function()
764     {
765         
766         var fel = this.editor.wrap.createChild();
767         this.footer = new Roo.Toolbar(fel);
768         // toolbar has scrolly on left / right?
769         var footDisp= new Roo.Toolbar.Fill();
770         var _t = this;
771         this.footer.add(
772             {
773                 text : '&lt;',
774                 xtype: 'Button',
775                 handler : function() {
776                     _t.footDisp.scrollTo('left',0,true)
777                 }
778             }
779         );
780         this.footer.add( footDisp );
781         this.footer.add( 
782             {
783                 text : '&gt;',
784                 xtype: 'Button',
785                 handler : function() {
786                     // no animation..
787                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
788                 }
789             }
790         );
791         var fel = Roo.get(footDisp.el);
792         fel.addClass('x-editor-context');
793         this.footDispWrap = fel; 
794         this.footDispWrap.overflow  = 'hidden';
795         
796         this.footDisp = fel.createChild();
797         this.footDispWrap.on('click', this.onContextClick, this)
798         
799         
800     },
801     // when the footer contect changes
802     onContextClick : function (ev,dom)
803     {
804         ev.preventDefault();
805         var  cn = dom.className;
806         //Roo.log(cn);
807         if (!cn.match(/x-ed-loc-/)) {
808             return;
809         }
810         var n = cn.split('-').pop();
811         var ans = this.footerEls;
812         var sel = ans[n];
813         
814          // pick
815         var range = this.editorcore.createRange();
816         
817         range.selectNodeContents(sel);
818         //range.selectNode(sel);
819         
820         
821         var selection = this.editorcore.getSelection();
822         selection.removeAllRanges();
823         selection.addRange(range);
824         
825         
826         
827         this.updateToolbar(null, null, sel);
828         
829         
830     }
831     
832     
833     
834     
835     
836 });
837
838
839
840
841