* added textSelection plugin from usability
authorMichael Dale <dale@users.mediawiki.org>
Mon, 9 Nov 2009 04:20:53 +0000 (04:20 +0000)
committerMichael Dale <dale@users.mediawiki.org>
Mon, 9 Nov 2009 04:20:53 +0000 (04:20 +0000)
js2/editPage.js
js2/mwEmbed/example_usage/Add_Media_Wizard.html
js2/mwEmbed/jquery/jquery.ui/ui/ui.core.js
js2/mwEmbed/jquery/plugins/jquery.textSelection.js [new file with mode: 0644]
js2/mwEmbed/libAddMedia/remoteSearchDriver.js
js2/mwEmbed/libEmbedVideo/embedVideo.js
js2/mwEmbed/mv_embed.js
js2/remoteMwEmbed.js

index 8e41461..36d2dd5 100644 (file)
@@ -46,7 +46,7 @@ js2AddOnloadHook( function() {
                );
        }               
        //add to old toolbar if wikiEditor did not remove '#toolbar' from the page:    
-       setTimeout(function(){                                  
+       setTimeout(function(){                  
                if( $j('#btn-add-media-wiz').length == 0 && $j( '#toolbar' ).length != 0 ){
                        $j( '#toolbar' ).append( '<img style="cursor:pointer" id="btn-add-media-wiz" src="' +
                                mv_skin_img_path + 'Button_add_media.png">' );
index 898c786..6f72706 100644 (file)
                        border:medium none;
                }
        </style>
-       <script type="text/javascript" src="../mv_embed.js?debug=true"></script>                 
+       <!--  <script type="text/javascript" src="../mv_embed.js?debug=true"></script> -->       
+       <script type="text/javascript" src="../jsScriptLoader.php?class=window.jQuery,mv_embed,remoteSearchDriver,$j.ui,$j.ui.resizable,$j.ui.draggable,$j.ui.dialog,$j.ui.tabs,$j.ui.sortable,$j.cookie,baseRemoteSearch&urid=1257728132531&debug=true&uselang=en"></script>            
        <script type="text/javascript">
-       mwAddOnloadHook(function(){
+       js2AddOnloadHook(function(){            
                $j('#add_media_link').addMediaWiz( {
                        'profile':'html_edit',                  
                        'target_textbox': '#wpTextbox1',
index 6be9993..601d0a8 100644 (file)
@@ -516,4 +516,4 @@ $.ui.mouse.defaults = {
        delay: 0
 };
 
-})(jQuery);
+})(jQuery);
\ No newline at end of file
diff --git a/js2/mwEmbed/jquery/plugins/jquery.textSelection.js b/js2/mwEmbed/jquery/plugins/jquery.textSelection.js
new file mode 100644 (file)
index 0000000..4fedc9f
--- /dev/null
@@ -0,0 +1,323 @@
+/**
+ * These plugins provide extra functionality for interaction with textareas.
+ */
+( function( $ ) { $.fn.extend( {
+/**
+ * Get the currently selected text in this textarea. Will focus the textarea
+ * in some browsers (IE/Opera)
+ */
+textSelection: function() {
+       var e = this.jquery ? this[0] : this;
+       var retval = '';
+       if ( e.style.display == 'none' ) {
+               // Do nothing
+       } else if ( document.selection && document.selection.createRange ) {
+               e.focus();
+               var range = document.selection.createRange();
+               retval = range.text;
+       } else if ( e.selectionStart || e.selectionStart == '0' ) {
+               retval = e.value.substring( e.selectionStart, e.selectionEnd );
+       }
+       return retval;
+},
+/**
+ * Ported from skins/common/edit.js by Trevor Parscal
+ * (c) 2009 Wikimedia Foundation (GPLv2) - http://www.wikimedia.org
+ * 
+ * Inserts text at the begining and end of a text selection, optionally
+ * inserting text at the caret when selection is empty.
+ * 
+ * @param pre Text to insert before selection
+ * @param peri Text to insert at caret if selection is empty
+ * @param post Text to insert after selection
+ * @param ownline If true, put the inserted text is on its own line
+ * @param replace If true, replaces any selected text with peri; if false, peri is ignored and selected text is left alone
+ */
+encapsulateSelection: function( pre, peri, post, ownline, replace ) {
+       return this.each( function() {
+               /**
+                * Check if the selected text is the same as the insert text
+                */ 
+               function checkSelectedText() {
+                       if ( !selText ) {
+                               selText = peri;
+                               isSample = true;
+                       } else if ( replace ) {
+                               selText = peri;
+                       } else if ( selText.charAt( selText.length - 1 ) == ' ' ) {
+                               // Exclude ending space char
+                               selText = selText.substring(0, selText.length - 1);
+                               post += ' ';
+                       }
+               }
+               var selText = $(this).getSelection();
+               var isSample = false;
+               if ( this.style.display == 'none' ) {
+                       // Do nothing
+               } else if ( this.selectionStart || this.selectionStart == '0' ) {
+                       // Mozilla/Opera
+                       $(this).focus();
+                       var startPos = this.selectionStart;
+                       var endPos = this.selectionEnd;
+                       checkSelectedText();
+                       if ( ownline ) {
+                               if ( startPos != 0 && this.value.charAt( startPos - 1 ) != "\n" ) {
+                                       pre = "\n" + pre;
+                               }
+                               if ( this.value.charAt( endPos ) != "\n" ) {
+                                       post += "\n";
+                               }
+                       }
+                       this.value = this.value.substring( 0, startPos ) + pre + selText + post + this.value.substring( endPos, this.value.length );
+                       if ( window.opera ) {
+                               pre = pre.replace( /\r?\n/g, "\r\n" );
+                               selText = selText.replace( /\r?\n/g, "\r\n" );
+                               post = post.replace( /\r?\n/g, "\r\n" );
+                       }
+                       if ( isSample ) {
+                               this.selectionStart = startPos + pre.length;
+                               this.selectionEnd = startPos + pre.length + selText.length;
+                       } else {
+                               this.selectionStart = startPos + pre.length + selText.length + post.length;
+                               this.selectionEnd = this.selectionStart;
+                       }
+               } else if ( document.selection && document.selection.createRange ) {
+                       // IE
+                       $(this).focus();
+                       var range = document.selection.createRange();
+                       if ( ownline && range.moveStart ) {
+                               var range2 = document.selection.createRange();
+                               range2.collapse();
+                               range2.moveStart( 'character', -1 );
+                               // FIXME: Which check is correct?
+                               if ( range2.text != "\r" && range2.text != "\n" && range2.text != "" ) {
+                                       pre = "\n" + pre;
+                               }
+                               var range3 = document.selection.createRange();
+                               range3.collapse( false );
+                               range3.moveEnd( 'character', 1 );
+                               if ( range3.text != "\r" && range3.text != "\n" && range3.text != "" ) {
+                                       post += "\n";
+                               }
+                       }
+                       checkSelectedText();
+                       range.text = pre + selText + post;
+                       if ( isSample && range.moveStart ) {
+                               range.moveStart( 'character', - post.length - selText.length );
+                               range.moveEnd( 'character', - post.length );
+                       }
+                       range.select();
+               }
+               // Scroll the textarea to the inserted text
+               $(this).scrollToCaretPosition();
+               $(this).trigger( 'encapsulateSelection', [ pre, peri, post, ownline, replace ] );
+       });
+},
+/**
+ * Ported from Wikia's LinkSuggest extension
+ * https://svn.wikia-code.com/wikia/trunk/extensions/wikia/LinkSuggest
+ * Some code copied from
+ * http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/
+ *
+ * Get the position (in resolution of bytes not nessecarily characters)
+ * in a textarea 
+ */
+ getCaretPosition: function( startAndEnd ) {
+       function getCaret( e ) {
+               var caretPos = 0, endPos = 0;
+               if ( $.browser.msie ) {
+                       // IE Support
+                       var postFinished = false;
+                       var periFinished = false;
+                       var postFinished = false;
+                       var preText, rawPreText, periText;
+                       var rawPeriText, postText, rawPostText;
+                       // Create range containing text in the selection
+                       var periRange = document.selection.createRange().duplicate();
+                       // Create range containing text before the selection
+                       var preRange = document.body.createTextRange();
+                       // Select all the text
+                       preRange.moveToElementText(e);
+                       // Move the end where we need it
+                       preRange.setEndPoint("EndToStart", periRange);
+                       // Create range containing text after the selection
+                       var postRange = document.body.createTextRange();
+                       // Select all the text
+                       postRange.moveToElementText(e);
+                       // Move the start where we need it
+                       postRange.setEndPoint("StartToEnd", periRange);
+                       // Load the text values we need to compare
+                       preText = rawPreText = preRange.text;
+                       periText = rawPeriText = periRange.text;
+                       postText = rawPostText = postRange.text;
+                       /*
+                        * Check each range for trimmed newlines by shrinking the range by 1
+                        * character and seeing if the text property has changed. If it has
+                        * not changed then we know that IE has trimmed a \r\n from the end.
+                        */
+                       do {
+                               if ( !postFinished ) {
+                                       if ( preRange.compareEndPoints( "StartToEnd", preRange ) == 0 ) {
+                                               postFinished = true;
+                                       } else {
+                                               preRange.moveEnd( "character", -1 )
+                                               if ( preRange.text == preText ) {
+                                                       rawPreText += "\r\n";
+                                               } else {
+                                                       postFinished = true;
+                                               }
+                                       }
+                               }
+                               if ( !periFinished ) {
+                                       if ( periRange.compareEndPoints( "StartToEnd", periRange ) == 0 ) {
+                                               periFinished = true;
+                                       } else {
+                                               periRange.moveEnd( "character", -1 )
+                                               if ( periRange.text == periText ) {
+                                                       rawPeriText += "\r\n";
+                                               } else {
+                                                       periFinished = true;
+                                               }
+                                       }
+                               }
+                               if ( !postFinished ) {
+                                       if ( postRange.compareEndPoints("StartToEnd", postRange) == 0 ) {
+                                               postFinished = true;
+                                       } else {
+                                               postRange.moveEnd( "character", -1 )
+                                               if ( postRange.text == postText ) {
+                                                       rawPostText += "\r\n";
+                                               } else {
+                                                       postFinished = true;
+                                               }
+                                       }
+                               }
+                       } while ( ( !postFinished || !periFinished || !postFinished ) );
+                       caretPos = rawPreText.replace( /\r\n/g, "\n" ).length;
+                       endPos = caretPos + rawPeriText.replace( /\r\n/g, "\n" ).length;
+               } else if ( e.selectionStart || e.selectionStart == '0' ) {
+                       // Firefox support
+                       caretPos = e.selectionStart;
+                       endPos = e.selectionEnd;
+               }
+               return startAndEnd ? [ caretPos, endPos ] : caretPos;
+       }
+       return getCaret( this.get( 0 ) );
+},
+setSelection: function( start, end ) {
+       if ( typeof end == 'undefined' )
+               end = start;
+       return this.each( function() {
+               if ( this.selectionStart || this.selectionStart == '0' ) {
+                       // Opera 9.0 doesn't allow setting selectionStart past
+                       // selectionEnd; any attempts to do that will be ignored
+                       // Make sure to set them in the right order
+                       if ( start > this.selectionEnd ) {
+                               this.selectionEnd = end;
+                               this.selectionStart = start;
+                       } else {
+                               this.selectionStart = start;
+                               this.selectionEnd = end;
+                       }
+               } else if ( document.body.createTextRange ) {
+                       var selection = document.body.createTextRange();
+                       selection.moveToElementText( this );
+                       var length = selection.text.length;
+                       selection.moveStart( 'character', start );
+                       selection.moveEnd( 'character', -length + end );
+                       selection.select();
+               }
+       });
+},
+/**
+ * Ported from Wikia's LinkSuggest extension
+ * https://svn.wikia-code.com/wikia/trunk/extensions/wikia/LinkSuggest
+ * 
+ * Scroll a textarea to the current cursor position. You can set the cursor
+ * position with setSelection()
+ * @param force boolean Whether to force a scroll even if the caret position
+ *  is already visible. Defaults to false
+ */
+scrollToCaretPosition: function( force ) {
+       function getLineLength( e ) {
+               return Math.floor( e.scrollWidth / ( $.os.name == 'linux' ? 7 : 8 ) );
+       }
+       function getCaretScrollPosition( e ) {
+               // FIXME: This functions sucks and is off by a few lines most
+               // of the time. It should be replaced by something decent.
+               var text = e.value.replace( /\r/g, "" );
+               var caret = $( e ).getCaretPosition();
+               var lineLength = getLineLength( e );
+               var row = 0;
+               var charInLine = 0;
+               var lastSpaceInLine = 0;
+               for ( i = 0; i < caret; i++ ) {
+                       charInLine++;
+                       if ( text.charAt( i ) == " " ) {
+                               lastSpaceInLine = charInLine;
+                       } else if ( text.charAt( i ) == "\n" ) {
+                               lastSpaceInLine = 0;
+                               charInLine = 0;
+                               row++;
+                       }
+                       if ( charInLine > lineLength ) {
+                               if ( lastSpaceInLine > 0 ) {
+                                       charInLine = charInLine - lastSpaceInLine;
+                                       lastSpaceInLine = 0;
+                                       row++;
+                               }
+                       }
+               }
+               var nextSpace = 0;
+               for ( j = caret; j < caret + lineLength; j++ ) {
+                       if (
+                               text.charAt( j ) == " " ||
+                               text.charAt( j ) == "\n" ||
+                               caret == text.length
+                       ) {
+                               nextSpace = j;
+                               break;
+                       }
+               }
+               if ( nextSpace > lineLength && caret <= lineLength ) {
+                       charInLine = caret - lastSpaceInLine;
+                       row++;
+               }
+               return ( $.os.name == 'mac' ? 13 : ( $.os.name == 'linux' ? 15 : 16 ) ) * row;
+       }
+       return this.each(function() {
+               if ( this.selectionStart || this.selectionStart == '0' ) {
+                       // Mozilla
+                       var scroll = getCaretScrollPosition( this );
+                       if ( force || scroll < $(this).scrollTop() ||
+                                       scroll > $(this).scrollTop() + $(this).height() )
+                               $(this).scrollTop( scroll );
+               } else if ( document.selection && document.selection.createRange ) {
+                       // IE / Opera
+                       /*
+                        * IE automatically scrolls the selected text to the
+                        * bottom of the textarea at range.select() time, except
+                        * if it was already in view and the cursor position
+                        * wasn't changed, in which case it does nothing. To
+                        * cover that case, we'll force it to act by moving one
+                        * character back and forth.
+                        */
+                       var range = document.selection.createRange();
+                       var pos = $(this).getCaretPosition();
+                       var oldScrollTop = this.scrollTop;
+                       range.moveToElementText( this );
+                       range.collapse();
+                       range.move( 'character', pos + 1);
+                       range.select();
+                       if ( this.scrollTop != oldScrollTop )
+                               this.scrollTop += range.offsetTop;
+                       else if ( force ) {
+                               range.move( 'character', -1 );
+                               range.select();
+                       }
+               }
+               $(this).trigger( 'scrollToPosition' );
+       } );
+}
+
+} ); } )( jQuery );
\ No newline at end of file
index 4a6a10d..22c9167 100644 (file)
@@ -257,10 +257,6 @@ remoteSearchDriver.prototype = {
                //@@todo for cleaner config we should set _this.opt to the provided options) 
                $j.extend( _this, default_remote_search_options, options);                      
                
-               //update the base text:
-               if(_this.target_textbox)
-                  _this.getTexboxSelection();
-
                //modify the content provider config based on options:          
                for(var i in this.content_providers){           
                        if(     _this.enabled_cps == 'all' && !this.disp_item  ){       
@@ -460,6 +456,10 @@ remoteSearchDriver.prototype = {
        },
        doInitDisplay:function(){
                var _this = this;
+               
+               //try and get the text selection:       
+               _this.getTexboxSelection();
+               
                //setup the parent container:
                this.init_modal();
                //fill in the html:
@@ -479,54 +479,30 @@ remoteSearchDriver.prototype = {
                var _this = this;
                js_log("doReDisplay::");
                //update the base text:
-               if( _this.target_textbox )
-                       _this.getTexboxSelection();
+               _this.getTexboxSelection();
+               if( _this.default_query !=  $j('#rsd_q').val() ){
+                       $j('#rsd_q').val( _this.default_query );
+                       _this.runSearch();
+               }
                //$j(_this.target_container).dialog("open");
                $j(_this.target_container).parents('.ui-dialog').fadeIn('slow');
                //re-center the dialog:
                $j(_this.target_container).dialog('option', 'position','center');
        },
        //gets the in and out points for insert position or grabs the selected text for search
-       getTexboxSelection:function(){
-               //update the caretPos
-               this.getCaretPos();
-
-               //if we have highlighted text use that as the query: (would be fun to add context menu once we have rich editor in-place)
-               if( this.caret_pos.selection )
-                       this.default_query = this.caret_pos.selection
-
-       },
-       getCaretPos:function(){
-               this.caret_pos={};
-               var txtarea = $j(this.target_textbox).get(0);
-               var getTextCusorStartPos = function (o){
-                       if (o.createTextRange) {
-                                       var r = document.selection.createRange().duplicate()
-                                       r.moveEnd('character', o.value.length)
-                                       if (r.text == '') return o.value.length
-                                       return o.value.lastIndexOf(r.text)
-                               } else return o.selectionStart
-               }
-               var getTextCusorEndPos = function (o){
-                       if (o.createTextRange) {
-                               var r = document.selection.createRange().duplicate();
-                               r.moveStart('character', -o.value.length);
-                               return r.text.length;
-                       } else{
-                               return o.selectionEnd
+       getTexboxSelection:function(){          
+               if(this.target_textbox){
+                       //get the selection text:
+                       var ts = $j(this.target_textbox).textSelection();
+                       if(ts!=''){
+                               this.default_query = ts;
                        }
+                       //get the caretPos / value
+                       this.caret_pos={};
+                       this.caret_pos.text = $j(this.target_textbox).val();            
+                       this.caret_pos.s = $j(this.target_textbox).getCaretPosition();
                }
-               this.caret_pos.s = getTextCusorStartPos( txtarea );
-               this.caret_pos.e = getTextCusorEndPos( txtarea );
-               this.caret_pos.text = txtarea.value;
-               if(this.caret_pos.s && this.caret_pos.e &&
-                               (this.caret_pos.s != this.caret_pos.e))
-                       this.caret_pos.selection = this.caret_pos.text.substring(this.caret_pos.s, this.caret_pos.e).replace(/ /g, '\xa0') || '\xa0';
-
-               js_log('got caret_pos:' + this.caret_pos.s);
-               //restore text value: (creating textRanges sometimes screws with the text content)
-               $j(this.target_textbox).val( this.caret_pos.text );
-       },
+       },      
        init_modal:function(){
                js_log("init_modal");
                var _this = this;       
index e0e90d5..e649a4d 100644 (file)
@@ -1726,7 +1726,7 @@ embedVideo.prototype = {
                //@@todo support position config
                var loc = $j(this).position();                  
                if($j('#metaBox_'+this.id).length==0){
-                       var theight =  (parseInt( this.height ) < 200) ? 200 : this.height;
+                       var theight =  (parseInt( this.height ) < 200) ? 200 : parseInt( this.height );
                        $j(this).after('<div class="ui-widget ui-widget-content ui-corner-all" style="position:absolute;z-index:10;'+
                                                'top:' + (loc.top) + 'px;' +
                                                'left:' + (parseInt( loc.left ) + parseInt(this.width) + 10 ) + 'px;' +
index 7cffc26..7fc146d 100644 (file)
@@ -88,6 +88,7 @@ lcPaths({
        "$j.cookie"                     : "jquery/plugins/jquery.cookie.js",
        "$j.contextMenu"        : "jquery/plugins/jquery.contextMenu.js",
        "$j.fn.suggestions"     : "jquery/plugins/jquery.suggestions.js",
+       "$j.fn.textSelection"   : "jquery/plugins/jquery.textSelection.js",
 
        "$j.effects.blind"              : "jquery/jquery.ui/ui/effects.blind.js",
        "$j.effects.drop"               : "jquery/jquery.ui/ui/effects.drop.js",
@@ -1004,13 +1005,14 @@ var mvJsLoader = {
         * checks for jQuery and adds the $j noConflict var
         */
        jQueryCheck: function( callback ) {
-               js_log( 'jQueryCheck::' );
+               //js_log( 'jQueryCheck::' );
+               var _this = this;
                // Skip stuff if $j is already loaded:
                if( _global['$j'] && callback ){
                        callback();
-                       return ;
-               }
-               var _this = this;
+                       if( _this.jQuerySetupFlag )
+                               return ;
+               }               
                // Load jQuery
                _this.doLoad([
                        'window.jQuery'
@@ -1020,7 +1022,7 @@ var mvJsLoader = {
                                _global['$j'] = jQuery.noConflict();
                        }
                        if( _this.jQuerySetupFlag == false){
-                               js_log('setup mv_embed jQuery bindings');
+                               //js_log('setup mv_embed jQuery bindings');
                                //setup our global settings using the (jQuery helper)
 
                                // Set up the skin path
@@ -1104,8 +1106,10 @@ var mvJsLoader = {
        },
        runReadyEvents: function() {
                js_log( "runReadyEvents" );
-               while( this.onReadyEvents.length ) {
-                       this.onReadyEvents.shift()();
+               while( this.onReadyEvents.length ) {    
+                       var func = this.onReadyEvents.shift();
+                       //js_log('run onReady:: ' + func );
+                       func();
                }
        }
 }
@@ -1172,15 +1176,16 @@ function mwdomReady( force ) {
 
 //js2AddOnloadHook: ensure jQuery and the DOM are ready
 function js2AddOnloadHook( func ) {
-       //js_log('js2AddOnloadHook::' );        
-       // If we have already run the DOM-ready function, just run the function directly:
-       if( mvJsLoader.doneReadyEvents ) {      
-               func();
-       } else {
-               mvJsLoader.jQueryCheck( function() {
+       //js_log('js2AddOnloadHook:: jquery:' + typeof window.jQuery + ' $j: ' + typeof $j);    
+       //check for jQuery then add the load event (to run after video tag rewrites (if present) 
+       mvJsLoader.jQueryCheck( function() {
+               if( mvJsLoader.doneReadyEvents ) {
+                       //js_log('run queued event: ' + func);  
+                       func();
+               } else {                
                        mvJsLoader.addLoadEvent( func );
-               })
-       }
+               }
+       });
 }
 // Deprecated mwAddOnloadHook in favor of js2 naming (for clear separation of js2 code from old MW code
 var mwAddOnloadHook = js2AddOnloadHook;
@@ -1302,6 +1307,7 @@ function mv_jqueryBindings() {
                                mvJsLoader.doLoadDepMode([
                                        [       'remoteSearchDriver',
                                                '$j.cookie',
+                                               '$j.fn.textSelection',
                                                '$j.ui'
                                        ],[
                                                '$j.ui.resizable',
index a1fd0eb..83db985 100644 (file)
@@ -5,7 +5,7 @@
  
 var urlparts = getRemoteEmbedPath();
 var mwEmbedHostPath = urlparts[0];
-var mwRemoteVersion = '1.0';
+var mwRemoteVersion = '1.02';
 
 reqArguments = urlparts[1];