MediaWiki:Gadget-copyUnsigned.js

From Terraria Wiki
Jump to navigation Jump to search

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.
/* Adds a (copy unsigned) button on diff pages */
$(function() {
	const padTime = function(time){
		return (time + "").padStart(2, "0");
	};

	const l10n_text = {
		en: "copy unsigned",
		de: "„unsigned“ kopieren",
		fr: "copier le « unsigned »",
		zh: "复制未签名模板"
	};
	const l10n_notification = {
		en: "Copied template to clipboard",
		de: "Vorlage in Zwischenablage kopiert",
		fr: "Modèle copié vers le presse-papiers",
		zh: "模板代码已复制到剪贴板"
	};
	const l10n_timestamp = {
		en: function(date){
			return padTime(date.getUTCHours())
			+ ":"
			+ padTime(date.getUTCMinutes())
			+ ", "
			+ date.getUTCDate()
			+ " "
			+ date.toLocaleDateString("en-us", { month: "long", timeZone: "UTC" })
			+ " "
			+ date.getUTCFullYear();
		},
		de: function(date){
			return date.getUTCDate()
			+ ". "
			+ date.toLocaleDateString("de-de", { month: "long", timeZone: "UTC" })
			+ " "
			+ date.getUTCFullYear()
			+ ", "
			+ padTime(date.getUTCHours())
			+ ":"
			+ padTime(date.getUTCMinutes())
			+ " Uhr";
		},
		fr: function(date){
			return date.getUTCDate()
			+ " "
			+ date.toLocaleDateString("fr-fr", { month: "long", timeZone: "UTC" })
			+ " "
			+ date.getUTCFullYear()
			+ " à "
			+ padTime(date.getUTCHours())
			+ ":"
			+ padTime(date.getUTCMinutes());
		},
	};

	const currentRevisionId = mw.config.get("wgDiffNewId");

	if (!currentRevisionId)
		return;

	new mw.Api().get({
		action: "query",
		prop: "revisions",
		revids: currentRevisionId,
		rvprop: "user|timestamp",
		formatversion: 2
	}).done(function(data) {
		const page = data.query.pages[0];
		const revision = page.revisions[0];

		const user = revision.user;
		const date = new Date(revision.timestamp);

		const timestamp = (l10n_timestamp[mw.config.get("wgContentLanguage")] || l10n_timestamp["en"])(date);
			
		const textToCopy = "{{unsigned|" + user + "|UTC=" + timestamp + "}}";

        $(".diff .diff-ntitle strong").append(' <span id="copy-unsigned">(<a href="javascript:void(0);">' + (l10n_text[mw.config.get("wgUserLanguage")] || l10n_text["en"]) + '</a>)</span>');
        $("#copy-unsigned a").click(function() {
            navigator.clipboard.writeText(textToCopy).then(function() {
                mw.notify(l10n_notification[mw.config.get("wgUserLanguage")] || l10n_text["en"])
            });
        });
	});
});