Difference between revisions of "User:Eighty5cacao/common.js"

From Pin Eight
Jump to: navigation, search
m (max sepia - tweak a bit)
m (forgot this)
Line 67: Line 67:
 
// TODO: support disabling the effect via a CSS class or JS variable
 
// TODO: support disabling the effect via a CSS class or JS variable
 
if ( sepiaStrength > 1/128 ) {
 
if ( sepiaStrength > 1/128 ) {
var brght = 1 - 0.1 * sepiaStrength;
+
var brght = 1 - sepiaStrength / 8;
 
mw.util.addCSS(
 
mw.util.addCSS(
 
'#content, #p-tb { filter:brightness(' +
 
'#content, #p-tb { filter:brightness(' +

Revision as of 14:08, 30 November 2017

function jsfnPortletLink( container, myFunc, dispName, liId, myArg ) {
  var typ = typeof myFunc;
  if ( typ !== 'function' ) {
    var errStr = 'myFunc was a(n) ' + typ + ', but we needed a function';
    mw.util.jsMessage( '<strong class="error">[jsfnPortletLink] ' + errStr + '</strong>' );
    throw new TypeError( errStr );
  } //...let addPortletLink do its own error handling for the rest

  var plnk = mw.util.addPortletLink(
                          container,    '#', dispName, liId
  );
  $( plnk ).click( function ( e ) {
    e.preventDefault( );

    //TODO: expand to handle multiple args
    myFunc.call( this, myArg );
  });
}

var zzAction = mw.config.get( 'wgAction' );
var zzNamespaceNumber = mw.config.get( 'wgNamespaceNumber' );
var zzPageName = mw.config.get( 'wgPageName' );

function fakeEditNoticeForDotClockRates( ) {
  if ( ( zzAction === 'edit' || zzAction === 'submit' ) && zzPageName === 'Dot_clock_rates' ) {
    mw.notify( $(
        '<strong class="error">' +
        'STOP! Do NOT edit this article every time a GitHub commit affects screen raw params. ' +
        'Put it in userspace and wait a day or two.' +
        '</strong>'
      ), { autoHide: false }
    );
  }
}

mw.loader.using( [ 'mediawiki.util' ], function ( ) {
	var invState = Math.floor( Math.random( ) * 3 );
	var hue1 = Math.floor( Math.random( ) * 360 );
	var hue2 = Math.floor( Math.random( ) * 360 );
	var sat1 = Math.floor( Math.random( ) * 100 ) + Math.ceil( Math.random( ) * 100 );
	var sat2 = Math.floor( Math.random( ) * 100 ) + Math.ceil( Math.random( ) * 100 );
	mw.util.addCSS(       '#p-logo { filter:' + ( invState == 1 ? 'invert(100%) ' : '' ) + 'hue-rotate(' + hue1 + 'deg) saturate(' + sat1 + '%); }' );
	mw.util.addCSS( '#p-logo:hover { filter:' + ( invState == 2 ? 'invert(100%) ' : '' ) + 'hue-rotate(' + hue2 + 'deg) saturate(' + sat2 + '%); }' );

	var dt  = new Date( );
	var dtH = dt.getHours( );
	var dtM = dt.getMinutes( );
	var todFrac = ( dtH * 60 + dtM ) / ( 24 * 60 );
	// we want max effect at midnight and none at noon
	var sepiaStrength = Math.cos( todFrac * Math.PI ); sepiaStrength *= sepiaStrength;
	// Weaken the effect to max 50%, with intentional re-squaring to make a cos^4 dependence,
	// if we are on a file page or a special page that deals with files
	// or if we are editing.
	if (
		zzNamespaceNumber === 6 ||
		( zzNamespaceNumber === -1 && zzPageName.indexOf( 'File' ) !== -1 ) ||
		zzAction === 'edit' || zzAction === 'submit'
	) {
		sepiaStrength *= ( sepiaStrength / 2 );
	}
	else {
		var maxSepiaStr = 5 / 6;
		var capped = Math.min( sepiaStrength, maxSepiaStr );
		var scaled = sepiaStrength * maxSepiaStr;
		sepiaStrength = ( capped + scaled ) / 2;
	}
	// TODO: support disabling the effect via a CSS class or JS variable
	if ( sepiaStrength > 1/128 ) {
		var brght = 1 - sepiaStrength / 8;
		mw.util.addCSS(
			'#content, #p-tb { filter:brightness(' +
			brght +
			') sepia(' +
			sepiaStrength +
			'); }'
		);
	}
});

// XXX: maybe not needed anymore; should at least make this conditional
importScript( 'User:Eighty5cacao/secure.js' );

function printSHStatus( ) {
  mw.util.jsMessage( '<samp>TOut: ' + syntaxHighlighterConfig.timeout        + 'ms<br />'
                         + 'Best: ' + window.syntaxHlBestTime                + 'ms<br />'
                         + 'Wrst: ' + window.syntaxHlWorstTime               + 'ms<br />'
                         + 'UpLf: ' + window.syntaxHlTimeoutUpdatesLeft      + '<br />'
                         + 'SpTl: ' + syntaxHighlighterConfig.spikeTolerance + 'ms<br />'
                         + 'NumS: ' + window.syntaxHlNumSpikesTolerated      + '<br />'
                         + 'Abrt: ' + window.syntaxHlAborted                 + '</samp>' );
}
syntaxHighlighterConfig = {
  adaptiveTiming: true,
  timeoutCallback: function( thresh, actual ) {
    mw.util.jsMessage( 'syntax highlighter abort ' + actual + 'ms&gt;' + thresh + 'ms<br />'
                     + '<samp>Best: '   + window.syntaxHlBestTime               + 'ms<br />'
                           + 'Wrst: '   + window.syntaxHlWorstTime              + 'ms<br />'
                           + 'UpLf: '  + window.syntaxHlTimeoutUpdatesLeft      + '<br />'
                           + 'SpTl: '  + syntaxHighlighterConfig.spikeTolerance + 'ms<br />'
                           + 'NumS: ' + window.syntaxHlNumSpikesTolerated      + '<br />'
                           + 'Abrt: ' + window.syntaxHlAborted                 + '</samp>' );
  }
}
if ( Math.random( ) < 0.6 ) {
  syntaxHighlighterConfig.timeoutMsg = '';
}
else {
  syntaxHighlighterConfig.languageOverride = 'es';
}

if ( zzAction == 'edit' || zzAction == 'submit' ) {
  if ( typeof wgPageContentModel != 'string' )
  {
      if ( !((zzNamespaceNumber == 2 || zzNamespaceNumber == 8) && /\.(?:css|js)$/.test(wgTitle)) )
        wgPageContentModel = 'wikitext';
      else
        wgPageContentModel = 'xyzzy';
  }
  importScript('User:Eighty5cacao/enterInSummaryPreviews.js');
  window.BetterCancelAddSectionAnchor = true;
  importScript('User:Eighty5cacao/cancelRedirectNo.js');

  if ( wgPageContentModel == 'wikitext' ) {
    importScript('User:Eighty5cacao/syntax highlighter experimental.js');
    if ( syntaxHighlighterConfig.adaptiveTiming )
      jsfnPortletLink( 'p-cactions', printSHStatus, 'synHs', 'ca-syntaxhighlightdbg' );
    importScript('User:Eighty5cacao/cleanArrows.js');
  }

  window.aBBWarnInitially = ( wgPageContentModel !== 'wikitext' || /[:\/]sandbox/i.test( zzPageName ) || ( zzAction == 'submit' && (zzNamespaceNumber % 2) == 0 ) );
  importScript('User:Eighty5cacao/antiBracketBot.js');
} else {
  window.BAWarnAsJsMessage = true; importScript('User:Eighty5cacao/badAnchorWarning.js');
  if ( zzNamespaceNumber >= 0 && !document.getElementById('toc') ) importScript('User:Eighty5cacao/copySectionLink.js');
}

window.mbLocalContribsName = ['Contributions', 'Contribs', 'Block', 'DeletedContributions', 'EmailUser', 'Emailuser', 'ListFiles'];
window.mbLoadingOpacity = 0.25;
window.mbTempStyle = 'opacity:0.63; font-style:normal; text-decoration:line-through';
window.mbIndefStyle = 'font-style:italic; text-decoration:line-through; text-shadow:#F50800 0px 0px 2px';
window.mbShowRegDateRel = true;
window.mbShowYears = true;
window.mbRemoveWaitingCSSOnError = false;
window.mbReplaceUserRedLinksWithContribs = true;
//?
window.mbNoAutoStart = !(
  ( mw.config.get( 'wgNamespaceNumber' ) == -1 && mw.config.get( 'wgPageName' ) != 'Special:Contributions/Eighty5cacao' ) ||
  ( ( mw.config.get( 'wgAction' ) == 'history' || mw.config.get( 'wgNamespaceNumber' ) % 2 == 1 ) && Math.random( ) < .37 )
);
window.mbOnDemandLinkText = 'Userlink info';
window.mbOnDemandLinkLoc = 'p-tb';
importScript('User:Eighty5cacao/markBlockedPlus.js');

function isEditReasonableForBLR( ) {
  var editbox = $( '#wpTextbox1' );
  if ( !editbox || editbox.length == 0 ) return false;
  var editboxtext = editbox.val( );
  if ( typeof editboxtext != 'string' ) return false;

  if ( wgPageContentModel == 'wikitext' ) {
    if ( /\{\| *class="/.test( editboxtext ) )                     return false;
    if ( /(<font .*color="|style=".*color:)/.test( editboxtext ) ) return false;
    if ( editboxtext.indexOf( '<syntaxh' + 'ighlight ' ) != -1 )   return false;
    // fall through to length test
  }
  else { return false; }

  return ( editboxtext.length >= 768 && editboxtext.length < 15000 );
}
window.beelineReaderAutoColor = ( zzAction == 'edit' || zzAction == 'submit' ) && isEditReasonableForBLR( );
importScript('User:Eighty5cacao/beelineReader.js');

function doNothing( ) { }
if ( typeof createCollapseButtons           != 'function' ) { createCollapseButtons           = doNothing }
if ( typeof createNavigationBarToggleButton != 'function' ) { createNavigationBarToggleButton = doNothing }
if ( typeof collapsibleDivs                 != 'function' ) { collapsibleDivs                 = doNothing }
if ( typeof collapsibleTables               != 'function' ) { collapsibleTables               = doNothing }
function checkBadPipeTrick( ) {
  var edsumbox = $( '#wpSummary' );
  if ( !edsumbox || edsumbox.length == 0 ) return;
  var edsumboxtext = edsumbox.val( );
  if ( typeof edsumboxtext != 'string' ) return;
  if ( /\[\[.+\|\]\]/.test( edsumboxtext ) ) {
    mw.util.addCSS( '.mw-summary-preview{color:red;}' )
    mw.util.addCSS( '.mw-summary-preview a{text-decoration:line-through;}' )
    mw.util.addCSS( '.mw-summary-preview a:not(.new){color:red;}' )
    mw.util.jsMessage( '<span class="badpipewarn">Attempted pipe trick in edit summary &mdash; does NOT work</span>' );
  }
  else if ( /^Undo revision \d+ by \[\[Special:Contributions\/Eighty5cacao\|Eighty5cacao\]\] \(\[\[User talk:Eighty5cacao\|talk\]\]\)$/.test( edsumboxtext ) ) {
    //DIRTY HACK - move this elsewhere
    if ( mw.config.get( 'wgAction' ) == 'edit' ) { //that is, not 'submit'
      edsumbox.val( edsumboxtext.replace( 'Eighty5cacao]] ([[User talk:Eighty5cacao|talk]])', 'self]]: ' ).replace( 'Undo ', 'Undid ' ) );
    }
  }

  var editbox = $( '#wpTextbox1' );
  if ( !editbox || editbox.length == 0 ) return;
  var editboxtext = editbox.val( );
  if ( typeof editboxtext != 'string' ) return;
  if ( /<ref( name="[^<>]+")?>[^<>]*\[\[[^<>]+\|\]\][^<>]*<\/ref>/.test( editboxtext ) )
    mw.util.jsMessage( '<span class="badpipewarn">Attempted pipe trick in footnote &mdash; does NOT work</span>' );

  //XXX: maybe shoehorn this into antiBracketBot.js instead?
  //XXX: string is broken up to avoid warning when editing common.js itself.
  //     better to check wgPageContentModel?
  if ( /\]\] ?\[\[/.test( editboxtext ) ) {
    mw.notify( ']]' + '[[ = :-(' );
  }

  if ( zzNamespaceNumber == 0 && /\[https?:\/\/(forums|wiki)\.nesdev\.com\//.test( editboxtext ) ) {
    mw.util.jsMessage( '<strong class="error">There are absolute links to NESdev; please consider making them protocol-relative</strong>' );
  }
}
window.ajaxPreviewExec = function( previewArea ) {
  if ( typeof alwayssecurelinks == 'function' ) alwayssecurelinks( );

  if ( window.syntaxHlAborted === true ) {
      mw.util.jsMessage( 'WARNING: Syntax highlighter underperformed and gave up. You <b>must</b> do a <b>non-ajax</b> preview to resume highlighting.' );
  }

  if ( typeof checkEditBrackets == 'function' ) checkEditBrackets( );

  checkBadPipeTrick( );

  if ( wgPageContentModel == 'wikitext' && isEditReasonableForBLR( ) ) { //don't auto override css/js syntax highlight
    setTimeout( beelineReaderColoring, 700 ); //don't expand boxes
  }
  else if ( !document.getElementById( 'ca-beelinereader' ) ) {
    jsfnPortletLink( 'p-tb', beelineReaderColoringWrapper, 'BeeLine Reader', 'ca-beelinereader' );
  }

  fakeEditNoticeForDotClockRates( );
}
if ( /it$/.test(zzAction) ) {
  importScript( 'User:Eighty5cacao/ajaxPreview.js' );
  if ( zzAction == 'submit' || document.URL.indexOf( 'undo' ) != -1 ) checkBadPipeTrick( );
}
var ajaxPreviewPos = 'bottom';
window.ajaxPreviewMsg = {
 emptydiff: 'No changes',
 difftip:   '<span id="ajax-preview-tipmsg">SHIFT-click the button to show changes compared to this old version</span>',
 diff2old:  '<span id="ajax-preview-tipmsg">Comparison to old version</span>',
 viewtip:   '<span id="ajax-preview-tipmsg">SHIFT-click the button to update categories as well</span>'
};

$( function ( ) {
    var node = document.getElementById( 'wikiPreview' );
    if ( !node ) { node = document.getElementById( 'mw-content-text' ); }
    if ( node ) {
        var alist = node.getElementsByTagName( 'A' );
        if ( alist.length === 0 ) { return; }

        Array.prototype.forEach.call( alist, function ( a ) {
            var $a = $( a );
            var myURL = $a.attr( 'href' );
            if ( !myURL ) { return; }

            var anchorStart = myURL.indexOf( '#' );
            if ( anchorStart != -1 ) {
                var myAnchor = myURL.substr( anchorStart );
                var myTtip = $a.attr( 'title' );

                // XXX: unencode anchors...
                if ( myTtip ) {
                    $a.attr( 'title', myTtip + myAnchor );
                }
                else {
                    $a.attr( 'title', myAnchor );
                }
            }

            // XXX: Just to be safe, add a configuration setting to disable this
            if (
                    myURL.indexOf( 'title=' ) != -1 &&
                    myURL.indexOf( 'curid=' ) != -1 &&
                    !( $a.hasClass( 'external' ) )  &&
                    !( $a.hasClass( 'extiw' ) )
            ) {
                var fixURL = myURL.replace( /&curid=\d+/, '' );
                if ( fixURL !== myURL ) {
                    $a.addClass( 'curid-stripped' );
                    $a.attr( 'href', fixURL );
                }
            }
        });
    }

    fakeEditNoticeForDotClockRates( );
});