User:Mooeypoo/NotificationsTest.js
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Press Ctrl-F5.
/**
* This is a test gadget to update notification count without loading all of
* Echo's robust scripts. This can be adapted to be done periodically or used
* as a basis of another widget.
*/
$( function () {
var echoApi = null,
currentCount = 0,
unseenClass = 'mw-echo-unseen-notifications';
// Load using existing Echo message for the badge + Echo's API processors
mw.loader.using( [ 'mediawiki.api.messages', 'mediawiki.jqueryMsg', 'ext.echo.api', 'ext.echo.dm' ] )
.then( function() {
// This loads the required i18n message (see https://www.mediawiki.org/wiki/Manual:Messages_API)
return new mw.Api().loadMessagesIfMissing( [ 'echo-badge-count' ] );
} )
.then( function () {
var alertSeenTimeModel = new mw.echo.dm.SeenTimeModel( { types: [ 'alert' ] } ),
msgSeenTimeModel = new mw.echo.dm.SeenTimeModel( { types: [ 'message' ] } );
setInterval( updateCountForBadges, 10000 );
} );
function updateBadgeCount( type, count ) {
var $badge = $( '#pt-notifications-' + ( type === 'alert' ? 'alert' : 'notice' ) + ' a' );
label = mw.msg( 'echo-badge-count', mw.language.convertNumber( count ) );
if ( !$badge.length ) {
return;
}
$badge
.toggleClass( 'mw-echo-notifications-badge-all-read', !count )
.toggleClass( 'mw-echo-notifications-badge-long-label', label.length > 2 )
.attr( 'data-counter-num', count )
.attr( 'data-counter-text', label );
if ( currentCount !== count ) {
currentCount = count;
// Fire badge count change hook
mw.hook( 'ext.echo.badge.countChange' ).fire( type, currentCount, label );
}
}
function fetchCount( type ) {
// Use the EchoApi to fetch unread count for alert
echoApi.fetchUnreadCount( 'local', type )
.then( function ( notifCount ) {
// Update the badge
updateBadgeCount( type, notifCount );
// For debugging/testing purposes - output to the console
console.log( 'updated ' + type + ' badge', notifCount )
} )
.then( function () {
return echoApi.fetchNotifications( type, 'local', false, { unreadFirst: true, bundle: true } );
} )
.then( function ( result ) {
console.log( result );
} );
}
/**
* Call for a new count for both badges and update them
*/
function updateCountForBadges() {
echoApi = new mw.echo.api.EchoApi();
fetchCount( 'alert' );
fetchCount( 'message' );
}
} );