User:Ritenerek/js/fav.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
This user script seems to have a documentation page at User:Ritenerek/js/fav. |
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);