User:CalendulaAsteraceae/sandbox.js

From Wikisource
Jump to navigation Jump to search
Note: After saving, changes may not occur immediately. Click here to learn how to bypass your browser's cache.
  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Cmd-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (Cmd-Shift-R on a Mac)
  • Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Clear the cache in Tools → Preferences

For details and instructions about other browsers, see Wikipedia:Bypass your cache.

// Immediately Invoked Function Expression (IIFE) to isolate the code
(function() {
	console.log('highlighting');
	// Wait for DOM to be fully loaded
	$.when(mw.loader.using('mediawiki.util'), $.ready).then(function () {
		console.log('loaded');
		
		const wikiEditor = document.getElementsByClassName('wikiEditor-ui');
		console.log('wikiEditor: ' + wikiEditor);
		console.log('wikiEditor 0' + wikiEditor.item(0))

		// Check if the wiki editor element exists
		if (!wikiEditor) {
			console.error('WikiEditor not found');
			return;
		}
		
		// Function to highlight specific character
		function highlightCharacter(doc, content, char, className) {
			console.log('highlightCharacter');
			let start = 0;
			let index;
			while ((index = content.indexOf(char, start)) !== -1) {
				doc.markText({line: 0, ch: index}, {line: 0, ch: index + char.length}, {className: className});
				start = index + 1;
			}
		}
		
		// Function to highlight text
		function highlightText(cm) {
			console.log('highlightText');
			// Clear existing marks
			cm.getAllMarks().forEach(function(mark) {
				mark.clear();
			});

			const doc = cm.getDoc();
			const content = doc.getValue();

			// Call function to highlight specific characters
			highlightCharacter(doc, content, '"', 'highlight-yellow');
			highlightCharacter(doc, content, "'", 'highlight-blue');
			// Add more characters as needed
		}

		// Function to set up highlighting
		function setupHighlighting(cm) {
			console.log('setupHighlighting');
			cm.on('change', function(instance) {
				highlightText(instance);
			});

			// Initial highlighting
			highlightText(cm);
		}

		// Wait for CodeMirror to be available
		const checkCodeMirror = setInterval(function() {
			console.log('checkCodeMirror');
			const cm = wikiEditor.CodeMirror;
			console.log('cm: ' + cm);
			if (cm) {
				clearInterval(checkCodeMirror);
				setupHighlighting(cm);
			}
		}, 100);
	});
})();