User:Zvpunry/WikibaseEcho.js

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.
// This is a fork of [[User:Lectrician1/WikibaseEcho.js]]

jQuery(() => {
	
	const api = new mw.Api();
	const denotations = new Map();
	const entityIdsToFetch = new Set();

	// Check for Entity Ids in notification messages
	setInterval(async () => {
		document.querySelectorAll('.mw-echo-ui-notificationItemWidget-content .mw-echo-ui-notificationItemWidget-content-message-header strong:not(.has_label)').forEach((strongNode) => {
			let innerTextClean = removeDirMarks( strongNode.innerText );
			if ( /^(Lexeme:L|Property:P|Q)\d+$/.test(innerTextClean) ) {
				const id = innerTextClean.match(/[QLP]\d+/)[0];
				if (denotations.has(id)) {
					const label = denotations.get(id);
					strongNode.innerText = `${label} (${id})`;
					strongNode.classList.add('has_label');
					return;
				}
				entityIdsToFetch.add(id);
			}
		},[]);
	}, 2000);

	async function updateDenotationsStore() {
		const missingIds = Array.from(entityIdsToFetch.values()).filter( id => !denotations.has(id) );
		entityIdsToFetch.clear();

		if (missingIds.length === 0) {
			return;
		}

		const d = await api.get({
			action: 'wbgetentities',
			ids: missingIds,
			format: 'json'
		}).promise();

		Object.values(d.entities).forEach((entity) => {
			if (entity.type === 'lexeme') {
				// take the first lemma
				denotations.set(entity.id, Object.values(entity.lemmas)[0].value);
			}
			if (entity.type === 'item' || entity.type === 'property') {
				denotations.set(entity.id, getLabelFromEntity(entity));
			}
		} );
	}
	setInterval(updateDenotationsStore, 2000);

	function removeDirMarks(text) {
		return text
			.replaceAll( '‎', '' )
			.replaceAll( '‏', '' )
			.replaceAll( '‪', '' )
			.replaceAll( '‬', '' )
			.replaceAll( '\u202a', '' )
			.replaceAll( '\u202c', '' );
	}

	function getLabelFromEntity(entity) {
		const userLanguages = OO.ui.getUserLanguages();
		for (let language of userLanguages) {
			if (entity.labels[language]) {
				return entity.labels[language].value;
			}
		}
		return ''; // no label 😢
	}
} );