mic_none

User:REAL MOUSE IRL/pings-tool.js Source: en.wikipedia.org/wiki/User:REAL_MOUSE_IRL/pings-tool.js

$(document).ready(function () {
	const makeNode = html => {
		let t = document.createElement("template");
		t.innerHTML = html;
		return t.content.firstElementChild;
	};

	const linkStyle = `
	font-size: 0.6em;
	font-family: sans-serif;
	font-weight: bold;
	margin-left: 0.75rem;
	color: red;
	`;

	//Talk, Wikipedia, and Wikipedia_talk: namespaces
	if ([1, 3, 4].includes(mw.config.get("wgNamespaceNumber"))) {
		const pageId = mw.config.get("wgArticleId");
		// We only need heading2s, but section number is based on all headings
		let headings = document.getElementsByClassName("mw-heading");
		//Filter to h2s, get section indices
		let h2s = Object.values(headings).flatMap((h, i) =>
			h.className.includes("mw-heading2") ? [{ index: i + 1, heading: h }] : []
		);
		h2s.forEach(h => {
			let e = makeNode(`<a style="${linkStyle}">[@]</a>`);
			e.onclick = e => {
				console.log(`Pings tool: Grabbing wikitext for page ${pageId}, section ${h.index}`);
				new mw.Api()
					.get({
						action: "query",
						pageids: pageId,
						rvsection: h.index,
						prop: ["revisions", "info"],
						rvprop: "content",
						indexpageids: 1,
						rawcontinue: ""
					})
					.then(a => {
						// Get only paragraphs that end with a timestamp
						let sigParas = a.query.pages[pageId].revisions[0]["*"]
							.split("\n")
							.filter(l => l.match(/\d{1,2}:\d{2}, \d{1,2} [a-zA-Z]+? \d{4} \(UTC\)/));
						console.log(`Pings tool: Found ${sigParas.length} paragraphs with signatures`);
						// Get last User: link in paragraph
						let users = sigParas
							.map(l =>
								l
									.match(/User:(.+?)\|/g)
									?.at(-1)
									?.replace("|", "")
							)
							.filter((u, i, a) => !!u && a.indexOf(u) === i) // dedupe
							.sort((a, b) => a.localeCompare(b)) // sort alphabetically
							.map(u => `@[[${u}|]]`) // map to ping list, using the pipe trick!
							.join(", ");
						console.log("Pings tool: Copied pings to clipboard:\n" + users);
						navigator.clipboard.writeText(users).then(() => (e.target.style.color = "blue")); // write to clipboard
					});
			};
			h.heading.appendChild(e);
		});
	}
});