User:Ritenerek/js/fav.js

Source: 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.
const nullPromise = () => {
	// Incredibly flimsy way to branch with promises
	return new Promise((res, rej) => {
		res(null);
	});
};

const favjs = '[[en:User:Ritenerek/js/fav|fav.js♥]]';

let main = () => {
	let api, fav_page;
	mw.loader.using(
		['mediawiki.Title', 'mediawiki.util', 'mediawiki.api']
	).then(() => {
		api = new mw.Api();
		fav_page = new mw.Title(`User:${mw.user.getName()}/Favourites`);
		// Check if favourites page exists
		return $.get(
			'/w/api.php',
			{action: 'query', titles: fav_page.toText(), format: 'json'}
		);
	}).then((data) => {
		if (data.query.pages[-1]) {
			// Page does not exist; create it
			return api.create(
				fav_page,
				{summary: `Automatically created by ${favjs}`},
				`This is the favourite list of {{U|${mw.config.get('wgUserName')}}}. ` +
				`<small>(Generated by ${favjs} on {\{subst:#time: j M Y, H:i e\}})</small>`
			);
		} else {
			return nullPromise();
		}
	}).then((res) => {
		if (res !== null) {
			alert('Created favourites page! (Check your Navigation menu)');
		}
		// Add favourites link to navigation portlet
		mw.util.addPortletLink(
			'p-navigation',
			fav_page.getUrl(),
			'My Favourites',
			'n-favourites',
			'My favourite pages'
		);
		// Add "♥ this page" button to navigation portlet
		let fav_button = mw.util.addPortletLink(
			'p-navigation',
			'#',
			'♥ this page',
			'n-favourites-button',
			'Add this page to my favourites'
		);
		fav_button.lastChild.attributes.removeNamedItem('href');
		$(fav_button).on('click', () => {
			// Check if page is already on list.
			let title = new mw.Title(mw.config.get('wgRelevantPageName'));
			$.get(
				'/w/index.php',
				{title: fav_page.toText(), action: 'raw'}
			).then(raw => {
				// This is a pretty awful
				if (raw.includes(title.toText())) {
					alert('This page is already on your favourite list!');
				} else {
					// Add page to favourites
					api.edit(fav_page, revision => {
						let addition = `* {{anl|${title.toText()}}}`;
						if (!revision.content.endsWith('\n')) {
							addition = '\n' + addition;
						}
						return {
							text: revision.content + addition,
							summary: `[[${title.toText()}]] added by ${favjs}`
						};
					}).then(() => {
						alert('Added to your favourites!');
					}).catch(console.error);
				}
			});
		});
	}).catch(console.error);
};
// Cross fingers and hope it works
$(main);