میڈیاویکی:Gadget-Favorites.js

آزاد دائرۃ المعارف، ویکیپیڈیا سے

تفصیل کے لیے کھولیں کے بٹن پر کلک کریں یاددہانی: محفوظ کرنے کے بعد تازہ ترین تبدیلیوں کو دیکھنے کے لیے آپ کو اپنے براؤزر کا کیش صاف کرنا ہوگا۔

  • فائرفاکس/ سفاری: جب Reload پر کلک کریں تو Shift دبا کر رکھیں، یا Ctrl-F5 یا Ctrl-R دبائیں (Mac پر R- )
  • گوگل کروم: Ctrl-Shift-R دبائیں (Mac پر Shift-R-⌘)
  • انٹرنیٹ ایکسپلورر: جب Refresh پر کلک کریں تو Ctrl یا Ctrl-F5 دبائیں
  • اوپیرا: Tools → Preferences میں جائیں اور کیش صاف کریں

/**
* User interface enhancement to star images and add them to a personal favorites gallery
* @author [[User:Dschwen]], 2013
* required modules: mediawiki.util, mediawiki.Title, mediawiki.user
*/
/* jshint laxcomma:true, smarttabs:true */
/* global mediaWiki, jQuery */
//https://commons.wikimedia.org/w/index.php?title=MediaWiki:Gadget-Favorites.js&oldid=368806766

(function ($, mw) {
"use strict";
//virtual indent

// only run on main namespace
if (mw.config.get('wgNamespaceNumber') !== 0 || !window.localStorage)
	return;

var user = mw.user.getName(),
	title = new mw.Title(mw.config.get('wgPageName')),
	file = title.getMain(),
	favesPage = 'User:' + user + '/پسندیدہ مضامین',
	ls = window.localStorage,
	favCache = JSON.parse(ls.getItem('favCache') || '{}'),
	isFaved = !!favCache[file],
	favLink = $(mw.util.addPortletLink($('#p-views').length ? 'p-views' : 'p-cactions', '#', '-', 'ca-fave', '-', '', 'ca-edit')),
	hasPersonalLink = false,
	editToken = mw.user.tokens.get('csrfToken');

// toggle link
function toggleLink() {
	var a = favLink.find('a');
	a.text(isFaved ? 'ناپسند' : 'پسند');
	a.prop('title', isFaved ? 'فہرست سے حذف کریں' : 'فہرست میں شامل کریں');
}

// add a link in the top right row next to the watchlist link (this might be too much clutter)
function addPersonalLink() {
	// do favCache.keys().length ? what about support
	for (var k in favCache) {
		if (favCache.hasOwnProperty(k)) {
			if (!hasPersonalLink) {
				mw.util.addPortletLink('p-personal', '/wiki/' + favesPage, 'پسندیدہ', 'pt-fave', 'آپ کے پسندیدہ مضامین', undefined, '#pt-watchlist');
				hasPersonalLink = true;
			}
			break;
		}
	}
}

// refresh fave status (on window focus)
function refreshFaveStatus() {
	favCache = JSON.parse(ls.getItem('favCache') || '{}');
	isFaved = !!favCache[file];
	toggleLink();
}

$(refreshFaveStatus);
// $(window).on('load', refreshFaveStatus);

// load /Favorites page
function loadFavorites(callback) {
	// normalize the gallery tag placement in the receved text
	function normalizeGalleryTags(text) {
		callback(text);
	}

	// fetch raw text
	$.get(mw.util.wikiScript('index'), {
		action: 'raw',
		title: favesPage
	}, undefined, 'text')
		.done(normalizeGalleryTags)
		.fail(function (xhr, a, b) {
			if (xhr.status === 404) {
				// The /Favorites page does not yet exist, initialize empty page
				normalizeGalleryTags('');
			} else if (xhr.status === 200 && xhr.responseText) {
				// sometimes jquery throws a parse error (even though we requested the dataType to be 'string'!)
				mw.notify("Come on Fabrice, this should not happen! (" + xhr.status + "," + a + "," + b + ")");
				normalizeGalleryTags(xhr.responseText);
			} else {
				mw.notify("فہرست کھل نہیں سکی۔ (" + xhr.status + "," + a + "," + b + ")");
				ls.removeItem('favLock');
			}
		});
}

// save picks function
function saveFavorites(text, callback) {
	// call API
	$.post(mw.util.wikiScript('api'), {
		format: 'json',
		action: 'edit',
		title: favesPage,
		summary: 'پسندیدہ مضامین کی فہرست میں اضافہ کیا گیا',
		text: text,
		token: editToken
	})
	.done(callback)
	.fail(function () {
		mw.notify("پسندیدہ مضامین کی فہرست میں اضافہ نہیں ہو سکا۔");
	})
	.always(function () {
		// remove the lock in either case
		ls.removeItem('favLock');
	});
}

function commitTransactions() {
	var lock = parseInt(ls.getItem('favLock') || "0", 10),
		now = new Date(),
		time = now.getTime();

	// check if lock is set and if so, was it set less than a minute ago?
	if (lock > 0 && (time - lock) < (60 * 1000)) {
		// already running, try again in 5 seconds
		setTimeout(commitTransactions, 5000);
	}
	ls.setItem('favLock', time);

	// load the /Favorites page
	loadFavorites(function (text) {
		// fetch transactions again (in case page loading took a long time)
		var trans = JSON.parse(ls.getItem('favTrans') || '{}'),
			applied = 0;

		// to be executed when all transactions are applied
		function transactionsApplied() {
			// fetch transactions again (in case page saving took a long time)
			var newTrans = JSON.parse(ls.getItem('favTrans') || '{}'),
				file;

			// now remove all transactions in newTrans that are identical to the transactions in trans that we just processed
			for (file in trans) {
				if (trans.hasOwnProperty(file) && file in newTrans && trans[file].action == newTrans[file].action) {
					delete newTrans[file];
				}
			}
			ls.setItem('favTrans', JSON.stringify(newTrans));
		}

		// process the page text and apply transactions
        var newText=text+'\n* [[' + file + ']]'
        // yes, save the new /Favorites page text
        saveFavorites(newText, transactionsApplied);
	});
}

// hook portlet link handler
favLink.on('click', function (e) {
	if (!e.target || !confirm(e.target.title + '؟'))
		return;
	// change faved flag
	isFaved = !isFaved;

	if (isFaved) {
		// now insert into favCache if it is a favorite
		favCache[file] = 1;
	} else {
		// or delete from cache if unfaved
		delete favCache[file];
	}

	// store in localStorage
	ls.setItem('favCache', JSON.stringify(favCache));

	// determine image author/uploader
	var author = $('.filehistory a.mw-userlink').first().clone().find('.adminMark').remove().end().eq(0).text();

	// add transaction (use localStorage to share data across tabs, if the servers are really slow and multiple images were faved before the edit to /Favorites is made)
	var trans = JSON.parse(ls.getItem('favTrans') || '{}');
	trans[file] = {
		action: isFaved ? "add" : "rem",
		author: author
	};
	ls.setItem('favTrans', JSON.stringify(trans));
	commitTransactions();

	// change link appearance and description to reflect new operation
	toggleLink();

	e.preventDefault();
});

// check if we have pending transactions from an aborted save
function checkPendingTasks() {
	var trans = JSON.parse(ls.getItem('favTrans') || '{}'),
		pending = 0,
		t;
	for (t in trans)
		if (trans.hasOwnProperty(t))
			pending++;
	if (pending > 0) {
		commitTransactions();
	} else {
		// check if we need to refresh the favorites cache (every 15mins)
		var cacheTime = parseInt(ls.getItem('favTimestamp') || "0", 10),
			now = new Date(),
			time = now.getTime();
		if (cacheTime === 0 || (time - cacheTime) > (15 * 60 * 1000)) {
			//loadFavorites(refreshFaveCache);
		} else {
			addPersonalLink();
		}
	}
}
$(checkPendingTasks);

}(jQuery, mediaWiki));