User:Bkil/user-script/utf8mb4-to-entity.js

From OpenStreetMap 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.
// [[Category:User scripts]]
// <syntaxhighlight lang="javascript" line highlight="61-67">
// <pre>

// Replaces characters that would only fit within utf8mb4 with numerical HTML entity references.
// Ideal if your host has installed MySQL incorrectly, otherwise the wikipage will be chopped in half at the character position.

/*!
Copyright (c) 2022 bkil.hu
@author bkil.hu
@license MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// <nowiki>

(function() {
'use strict';

function init() {
	const save = document.getElementById('wpSave');
	if (save) {
		save.addEventListener('click', escapeTextInForm);
	}

	const preview = document.getElementById('wpPreview');
	if (preview) {
		preview.addEventListener('click', escapeTextInForm);
	}
}

function escapeTextInForm() {
	const text = document.querySelector('.wikiEditor-ui-text > textarea');
	if (text) {
		text.value = utf8mb4ToEntity(text.value);
	} else {
		console.log('failed to find text editor widget');
	}
	return true;
}

function utf8mb4ToEntity(rawText) {
	let result = '';
	for (const char of rawText) {
		const n = char.codePointAt(0);
		// https://en.wikipedia.org/wiki/UTF-8#Encoding
		if (n >= 0x10000) {
			result += '&#' + n + ';';
		} else {
			result += char;
		}
	}
	return result;
}

init();
})();
// </nowiki>
// </pre>
// </syntaxhighlight>