SelectableTextArea.js 2.89 KB
Ext.define('extensions.SelectableTextArea', {
    extend:'Ext.form.field.TextArea',
    alias: 'widget.selectableTextArea',

    constructor: function(){
    	this.callParent(arguments);
    },
		
    getSelection : function() {
//		var domElement = this.getEl().dom;
    	var domElement = this.inputEl.dom;
		
		if (Ext.isIE) {
		    //Works only if no other form field has been focused after this field
		    domElement.focus();
            var range = document.selection.createRange();
            var selectedTxt = range.text;/// selected text OK
            var bookmark = range.getBookmark();
            var selection = domElement.createTextRange();
            selection.moveToBookmark(bookmark);
            var before = domElement.createTextRange();
            before.collapse(true);//set start of selection to beginning
            before.setEndPoint("EndToStart", selection);
            
            var after = domElement.createTextRange();
            after.setEndPoint("StartToEnd", selection);
            return {
                selectionStart: before.text.length,
                selectionEnd: before.text.length + selectedTxt.length,
                beforeText: before.text,
                text: selection.text,
                afterText: after.text
            };
            
		} else { // not IE
			if (domElement.selectionEnd!=null && domElement.selectionStart!=null) {
				if (domElement.selectionEnd >= domElement.selectionStart){ 
					return {
						selectionStart     : domElement.selectionStart,
						selectionEnd    : domElement.selectionEnd,
						beforeText         : domElement.value.substr(0, domElement.selectionStart),
						text             : domElement.value.substr(domElement.selectionStart, domElement.selectionEnd - domElement.selectionStart),
						afterText         : domElement.value.substr(domElement.selectionEnd)
					};
				} 
			}
		}
		return null;
    },

	getSelectedText : function() {
		var selection = this.getSelection();
		return selection==null?null:selection.text;
	},

//Ext.form.TextField.prototype.getCaretPosition = function(ctrl) {
//	var CaretPos = 0;	
//	var domElement = this.getEl().dom;
//	// IE Support
//	if (document.selection) {
//		domElement.focus ();
//		var Sel = document.selection.createRange ();
//		Sel.moveStart ('character', -domElement.value.length);
//		CaretPos = Sel.text.length;
//	}
//	//	Firefox support
//	else if (domElement.selectionStart || domElement.selectionStart === '0') {
//		CaretPos = domElement.selectionStart;
//	}
//	return (CaretPos);
//}

	setCaretPosition : function(pos){

        var domElement = this.inputEl.dom;
	    
		if(domElement.setSelectionRange)
		{
			domElement.focus();
			domElement.setSelectionRange(pos,pos);
		}
		else if (domElement.createTextRange) {
			var range = domElement.createTextRange();
			range.collapse(true);
			range.moveEnd('character', pos);
			range.moveStart('character', pos);
			range.select();
		}
	}
	
});