Jump to content

User:Yair rand/CommentHelper.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
if (
  // user is currently editing the page
  [ 'edit', 'submit' ].indexOf( mw.config.get( 'wgAction' ) ) !== -1 &&
  (
    mw.config.get( 'wgNamespaceNumber' ) & 1 || // is a talk namespace or...
    // is other namespace that uses signatures sometimes (eg project)
    mw.config.get( 'wgExtraSignatureNamespaces' ).indexOf( mw.config.get( 'wgNamespaceNumber' ) ) !== -1
  )
) {
  $( function () {
    $( '#wpTextbox1' ).on( 'keydown', function ( e ) {
      // Check if key pressed was enter key.
      if ( e.which === 13 ) {
        var s = this.selectionStart,
          caretIsAtEndOfLine = this.value[ s ] === '\n' || s === this.value.length,
          isAfterSig = caretIsAtEndOfLine && this.value.substr( s - 6, 6 ) === ' (UTC)', // TODO: Actually check things reliably.
          startPriorLine = this.value.lastIndexOf( '\n', s - 1 ) + 1,
          priorComment = this.value.substr( startPriorLine, s - startPriorLine ),
          startIndent = priorComment.match( /^[:*]*/ )[ 0 ],
          noHighlight = s === this.selectionEnd;
        
        if ( noHighlight && ( isAfterSig || startIndent ) ) {
          var preToInsert = '\n' + startIndent + ( isAfterSig ? ': ' : ' ' ),
            highlightedText = isAfterSig ? 'Add your comment here' : '',
            afterText = isAfterSig ? ' --~~' + '~~' : '';
          this.value = this.value.substr( 0, s ) + preToInsert + highlightedText + afterText + this.value.substr( s );
          this.selectionStart = s + preToInsert.length;
          this.selectionEnd = this.selectionStart + highlightedText.length;
          e.preventDefault();
          return false;
        }
      }
    } );
  } );
}