User:Erutuon/scripts/sandbox.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

$(() => {
	$('.mh-transcription-list').get().forEach(t => {
		const name = 'mh-transcription-list-search';
		const $label = $('<label>')
			.attr('for', name)
			.text('Filter table rows:');
		const $input = $('<input>')
			.attr('type', 'search')
			.attr('id', name)
			.on('input', function() {
				const $rows = $(t).find('tr').filter((_, e) => {
					return $(e).find('th').length === 0;
				});
				const input = $(this).val();
				let filterer;
				// CGV# don't occur in any of the rows.
				const map = {
					'C': '[pmtnrlkŋ][ʲˠʷ]?',
					'G': '[jɰw]',
					'V': '[æɛei]',
					'#': '(?:^|\s|$)',
				};
				let isGeneric = (new RegExp('[' + Object.keys(map).join('') + ']')).test(input);
				if (isGeneric) {
					const regex = new RegExp(
						input.replace(/./g, char => map[char] ? map[char] + "\\.?" : char),
						'g'
					);
					filterer = ($row, templateInput, phonemic) => {
						return phonemic && regex.test(phonemic);
					};
				} else {
					const lowercaseInput = input.toLowerCase();
					filterer = ($row, templateInput) => {
						return $row.text().toLowerCase().includes(input)
						|| templateInput && templateInput.toLowerCase().includes(input);
					};
				}
				$rows.each((_, row) => {
					const $row = $(row);
					const firstCell = $row.find('td').first();
					const templateInput = firstCell.data('template-input');
					const phonemic = firstCell.data('phonemic');
					$row.css(
						'display',
						filterer($row, templateInput, phonemic) ? '' : 'none');
				});
			});
		$(t).before($('<p>').append($label, $input));
	});
	
	const addZwnjBeforeCedilla = function(elem) {
		for (const child of elem.childNodes) {
			if (child.processedCedilla)
				continue;
			switch (child.nodeType) {
				case Node.ELEMENT_NODE: {
					addZwnjBeforeCedilla(child); break;
				}
				case Node.TEXT_NODE: {
					child.nodeValue = child.nodeValue
						.normalize('NFD')
						.replace(/\u0327/g, '\u200C\u0327')
						.normalize('NFC');
				}
			}
			child.processedCedilla = true;
		}
	};
	
	$(":lang(mh)").get().forEach(addZwnjBeforeCedilla);
});