1 //<script type="text/javascript">
5 * Copyright(c) 2006-2007, Ext JS, LLC.
8 * http://www.extjs.com/license
14 * Default CSS appears to render it as fixed text by default (should really be Sans-Serif)
15 * - IE ? - no idea how much works there.
23 * @class Ext.form.HtmlEditor
24 * @extends Ext.form.Field
25 * Provides a lightweight HTML Editor component.
26 * WARNING - THIS CURRENTlY ONLY WORKS ON FIREFOX - USE FCKeditor for a cross platform version
28 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
29 * supported by this editor.</b><br/><br/>
30 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
31 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
33 Roo.form.HtmlEditor = Roo.extend(Roo.form.Field, {
35 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
39 * @cfg {String} createLinkText The default text for the create link prompt
41 createLinkText : 'Please enter the URL for the link:',
43 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
45 defaultLinkValue : 'http:/'+'/',
52 validationEvent : false,
56 sourceEditMode : false,
57 onFocus : Roo.emptyFn,
62 style:"width:500px;height:300px;",
67 initComponent : function(){
71 * Fires when the editor is fully initialized (including the iframe)
72 * @param {HtmlEditor} this
77 * Fires when the editor is first receives the focus. Any insertion must wait
78 * until after this event.
79 * @param {HtmlEditor} this
84 * Fires before the textarea is updated with content from the editor iframe. Return false
86 * @param {HtmlEditor} this
87 * @param {String} html
92 * Fires before the iframe editor is updated with content from the textarea. Return false
94 * @param {HtmlEditor} this
95 * @param {String} html
100 * Fires when the textarea is updated with content from the editor iframe.
101 * @param {HtmlEditor} this
102 * @param {String} html
107 * Fires when the iframe editor is updated with content from the textarea.
108 * @param {HtmlEditor} this
109 * @param {String} html
113 * @event editmodechange
114 * Fires when the editor switches edit modes
115 * @param {HtmlEditor} this
116 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
118 editmodechange: true,
121 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
122 * @param {HtmlEditor} this
129 * Protected method that will not generally be called directly. It
130 * is called when the editor creates its toolbar. Override this method if you need to
131 * add custom toolbar buttons.
132 * @param {HtmlEditor} editor
134 createToolbar : function(editor){
135 if (!editor.toolbars || !editor.toolbars.length) {
136 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
139 for (var i =0 ; i < editor.toolbars.length;i++) {
140 editor.toolbars[i].init(editor);
147 * Protected method that will not generally be called directly. It
148 * is called when the editor initializes the iframe with HTML contents. Override this method if you
149 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
151 getDocMarkup : function(){
152 return '<html><head><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;}</style></head><body></body></html>';
156 onRender : function(ct, position){
157 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
158 this.el.dom.style.border = '0 none';
159 this.el.dom.setAttribute('tabIndex', -1);
160 this.el.addClass('x-hidden');
161 if(Roo.isIE){ // fix IE 1px bogus margin
162 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
164 this.wrap = this.el.wrap({
165 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
168 this.frameId = Roo.id();
169 this.createToolbar(this);
176 var iframe = this.wrap.createChild({
181 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
184 // console.log(iframe);
185 //this.wrap.dom.appendChild(iframe);
187 this.iframe = iframe.dom;
191 this.doc.designMode = 'on';
194 this.doc.write(this.getDocMarkup());
198 var task = { // must defer to wait for browser to be ready
200 //console.log("run task?" + this.doc.readyState);
202 if(this.doc.body || this.doc.readyState == 'complete'){
206 this.doc.designMode="on";
210 Roo.TaskMgr.stop(task);
211 this.initEditor.defer(10, this);
218 Roo.TaskMgr.start(task);
221 this.setSize(this.el.getSize());
226 onResize : function(w, h){
227 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
228 if(this.el && this.iframe){
229 if(typeof w == 'number'){
230 var aw = w - this.wrap.getFrameWidth('lr');
231 this.el.setWidth(this.adjustWidth('textarea', aw));
232 this.iframe.style.width = aw + 'px';
234 if(typeof h == 'number'){
236 for (var i =0; i < this.toolbars.length;i++) {
237 // fixme - ask toolbars for heights?
238 tbh += this.toolbars[i].tb.el.getHeight();
244 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
245 this.el.setHeight(this.adjustWidth('textarea', ah));
246 this.iframe.style.height = ah + 'px';
248 (this.doc.body || this.doc.documentElement).style.height = (ah - (this.iframePad*2)) + 'px';
255 * Toggles the editor between standard and source edit mode.
256 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
258 toggleSourceEdit : function(sourceEditMode){
260 this.sourceEditMode = sourceEditMode === true;
262 if(this.sourceEditMode){
265 this.iframe.className = 'x-hidden';
266 this.el.removeClass('x-hidden');
267 this.el.dom.removeAttribute('tabIndex');
272 this.iframe.className = '';
273 this.el.addClass('x-hidden');
274 this.el.dom.setAttribute('tabIndex', -1);
277 this.setSize(this.wrap.getSize());
278 this.fireEvent('editmodechange', this, this.sourceEditMode);
281 // private used internally
282 createLink : function(){
283 var url = prompt(this.createLinkText, this.defaultLinkValue);
284 if(url && url != 'http:/'+'/'){
285 this.relayCmd('createlink', url);
289 // private (for BoxComponent)
290 adjustSize : Roo.BoxComponent.prototype.adjustSize,
292 // private (for BoxComponent)
293 getResizeEl : function(){
297 // private (for BoxComponent)
298 getPositionEl : function(){
303 initEvents : function(){
304 this.originalValue = this.getValue();
308 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
311 markInvalid : Roo.emptyFn,
313 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
316 clearInvalid : Roo.emptyFn,
318 setValue : function(v){
319 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
324 * Protected method that will not generally be called directly. If you need/want
325 * custom HTML cleanup, this is the method you should override.
326 * @param {String} html The HTML to be cleaned
327 * return {String} The cleaned HTML
329 cleanHtml : function(html){
332 if(Roo.isSafari){ // strip safari nonsense
333 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
336 if(html == ' '){
343 * Protected method that will not generally be called directly. Syncs the contents
344 * of the editor iframe with the textarea.
346 syncValue : function(){
347 if(this.initialized){
348 var bd = (this.doc.body || this.doc.documentElement);
349 var html = bd.innerHTML;
351 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
352 var m = bs.match(/text-align:(.*?);/i);
354 html = '<div style="'+m[0]+'">' + html + '</div>';
357 html = this.cleanHtml(html);
358 if(this.fireEvent('beforesync', this, html) !== false){
359 this.el.dom.value = html;
360 this.fireEvent('sync', this, html);
366 * Protected method that will not generally be called directly. Pushes the value of the textarea
367 * into the iframe editor.
369 pushValue : function(){
370 if(this.initialized){
371 var v = this.el.dom.value;
375 if(this.fireEvent('beforepush', this, v) !== false){
376 (this.doc.body || this.doc.documentElement).innerHTML = v;
377 this.fireEvent('push', this, v);
383 deferFocus : function(){
384 this.focus.defer(10, this);
389 if(this.win && !this.sourceEditMode){
396 assignDocWin: function()
398 var iframe = this.iframe;
401 this.doc = iframe.contentWindow.document;
402 this.win = iframe.contentWindow;
404 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
405 this.win = Roo.get(this.frameId).dom.contentWindow;
410 initEditor : function(){
411 //console.log("INIT EDITOR");
416 this.doc.designMode="on";
418 this.doc.write(this.getDocMarkup());
421 var dbody = (this.doc.body || this.doc.documentElement);
422 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
423 // this copies styles from the containing element into thsi one..
424 // not sure why we need all of this..
425 var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
426 ss['background-attachment'] = 'fixed'; // w3c
427 dbody.bgProperties = 'fixed'; // ie
428 Roo.DomHelper.applyStyles(dbody, ss);
429 Roo.EventManager.on(this.doc, {
430 'mousedown': this.onEditorEvent,
431 'dblclick': this.onEditorEvent,
432 'click': this.onEditorEvent,
433 'keyup': this.onEditorEvent,
438 Roo.EventManager.on(this.doc, 'keypress', this.applyCommand, this);
440 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
441 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
443 this.initialized = true;
445 this.fireEvent('initialize', this);
450 onDestroy : function(){
456 for (var i =0; i < this.toolbars.length;i++) {
457 // fixme - ask toolbars for heights?
458 this.toolbars[i].onDestroy();
461 this.wrap.dom.innerHTML = '';
467 onFirstFocus : function(){
472 this.activated = true;
473 for (var i =0; i < this.toolbars.length;i++) {
474 this.toolbars[i].onFirstFocus();
477 if(Roo.isGecko){ // prevent silly gecko errors
479 var s = this.win.getSelection();
480 if(!s.focusNode || s.focusNode.nodeType != 3){
481 var r = s.getRangeAt(0);
482 r.selectNodeContents((this.doc.body || this.doc.documentElement));
487 this.execCmd('useCSS', true);
488 this.execCmd('styleWithCSS', false);
491 this.fireEvent('activate', this);
495 adjustFont: function(btn){
496 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
497 //if(Roo.isSafari){ // safari
500 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
501 if(Roo.isSafari){ // safari
502 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
503 v = (v < 10) ? 10 : v;
504 v = (v > 48) ? 48 : v;
505 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
510 v = Math.max(1, v+adjust);
512 this.execCmd('FontSize', v );
515 onEditorEvent : function(e){
516 this.fireEvent('editorevent', this, e);
517 // this.updateToolbar();
521 insertTag : function(tg)
523 // could be a bit smarter... -> wrap the current selected tRoo..
525 this.execCmd("formatblock", tg);
529 insertText : function(txt)
533 range = this.createRange();
534 range.deleteContents();
535 //alert(Sender.getAttribute('label'));
537 range.insertNode(this.doc.createTextNode(txt));
541 relayBtnCmd : function(btn){
542 this.relayCmd(btn.cmd);
546 * Executes a Midas editor command on the editor document and performs necessary focus and
547 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
548 * @param {String} cmd The Midas command
549 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
551 relayCmd : function(cmd, value){
553 this.execCmd(cmd, value);
554 this.fireEvent('editorevent', this);
555 //this.updateToolbar();
560 * Executes a Midas editor command directly on the editor document.
561 * For visual commands, you should use {@link #relayCmd} instead.
562 * <b>This should only be called after the editor is initialized.</b>
563 * @param {String} cmd The Midas command
564 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
566 execCmd : function(cmd, value){
567 this.doc.execCommand(cmd, false, value === undefined ? null : value);
572 applyCommand : function(e){
574 var c = e.getCharCode(), cmd;
576 c = String.fromCharCode(c);
599 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
601 * @param {String} text
603 insertAtCursor : function(text){
609 var r = this.doc.selection.createRange();
616 }else if(Roo.isGecko || Roo.isOpera){
618 this.execCmd('InsertHTML', text);
620 }else if(Roo.isSafari){
621 this.execCmd('InsertText', text);
627 fixKeys : function(){ // load time branching for fastest keydown performance
630 var k = e.getKey(), r;
633 r = this.doc.selection.createRange();
636 r.pasteHTML('    ');
639 }else if(k == e.ENTER){
640 r = this.doc.selection.createRange();
642 var target = r.parentElement();
643 if(!target || target.tagName.toLowerCase() != 'li'){
645 r.pasteHTML('<br />');
652 }else if(Roo.isOpera){
658 this.execCmd('InsertHTML','    ');
662 }else if(Roo.isSafari){
667 this.execCmd('InsertText','\t');
674 getAllAncestors: function()
676 var p = this.getSelectedNode();
679 a.push(p); // push blank onto stack..
680 p = this.getParentElement();
684 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
688 a.push(this.doc.body);
695 getSelection : function()
698 return Roo.isIE ? this.doc.selection : this.win.getSelection();
701 getSelectedNode: function()
703 // this may only work on Gecko!!!
705 // should we cache this!!!!
710 var range = this.createRange(this.getSelection());
713 var parent = range.parentElement();
715 var testRange = range.duplicate();
716 testRange.moveToElementText(parent);
717 if (testRange.inRange(range)) {
720 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
723 parent = parent.parentElement;
729 var ar = range.endContainer.childNodes;
731 ar = range.commonAncestorContainer.childNodes;
735 var other_nodes = [];
736 var has_other_nodes = false;
737 for (var i=0;i<ar.length;i++) {
738 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
741 // fullly contained node.
743 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
748 // probably selected..
749 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
750 other_nodes.push(ar[i]);
753 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
758 has_other_nodes = true;
760 if (!nodes.length && other_nodes.length) {
763 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
769 createRange: function(sel)
771 // this has strange effects when using with
772 // top toolbar - not sure if it's a great idea.
773 //this.editor.contentWindow.focus();
774 if (typeof sel != "undefined") {
776 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
778 return this.doc.createRange();
781 return this.doc.createRange();
784 getParentElement: function()
788 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
790 var range = this.createRange(sel);
793 var p = range.commonAncestorContainer;
794 while (p.nodeType == 3) { // text node
806 // BC Hacks - cause I cant work out what i was trying to do..
807 rangeIntersectsNode : function(range, node)
809 var nodeRange = node.ownerDocument.createRange();
811 nodeRange.selectNode(node);
814 nodeRange.selectNodeContents(node);
817 return range.compareBoundaryPoints(Range.END_TO_START, nodeRange) == -1 &&
818 range.compareBoundaryPoints(Range.START_TO_END, nodeRange) == 1;
820 rangeCompareNode : function(range, node) {
821 var nodeRange = node.ownerDocument.createRange();
823 nodeRange.selectNode(node);
825 nodeRange.selectNodeContents(node);
827 var nodeIsBefore = range.compareBoundaryPoints(Range.START_TO_START, nodeRange) == 1;
828 var nodeIsAfter = range.compareBoundaryPoints(Range.END_TO_END, nodeRange) == -1;
830 if (nodeIsBefore && !nodeIsAfter)
832 if (!nodeIsBefore && nodeIsAfter)
834 if (nodeIsBefore && nodeIsAfter)
842 // hide stuff that is not compatible
860 * @cfg {String} fieldClass @hide
863 * @cfg {String} focusClass @hide
866 * @cfg {String} autoCreate @hide
869 * @cfg {String} inputType @hide
872 * @cfg {String} invalidClass @hide
875 * @cfg {String} invalidText @hide
878 * @cfg {String} msgFx @hide
881 * @cfg {String} validateOnBlur @hide