aboutsummaryrefslogtreecommitdiff
path: root/webAO/encoding.js
blob: 76e0b6df1457b5346ce19b136efad2e004d6acbe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
 * Escapes a string to AO1 escape codes.
 * @param {string} estring the string to be escaped
 */
export function escapeChat(estring) {
	return estring
		.replace(/#/g, "<num>")
		.replace(/&/g, "<and>")
		.replace(/%/g, "<percent>")
		.replace(/\$/g, "<dollar>");
}

/**
 * Unescapes a string to AO1 escape codes.
 * @param {string} estring the string to be unescaped
 */
export function unescapeChat(estring) {
	return estring
		.replace(/<num>/g, "#")
		.replace(/<and>/g, "&")
		.replace(/<percent>/g, "%")
		.replace(/<dollar>/g, "$");
}

/**
 * Escapes a string to be HTML-safe.
 * 
 * XXX: This is unnecessary if we use `createTextNode` instead!
 * @param {string} unsafe an unsanitized string
 */
export function safe_tags(unsafe) {
	if (unsafe) {
		return unsafe
			.replace(/&/g, "&amp;")
			.replace(/</g, "&lt;");
		//.replace(/"/g, "&quot;")
		//.replace(/'/g, "&#039;");
	} else {
		return "";
	}
}

/**
 * Encode text on client side.
 * @param {string} estring the string to be encoded
 */
export function encodeChat(estring) {
	const selectedEncoding = document.getElementById("client_encoding").value;
	if (selectedEncoding === "unicode") {
		// This approach works by escaping all special characters to Unicode escape sequences.
		// Source: https://gist.github.com/mathiasbynens/1243213
		return estring.replace(/[^\0-~]/g, function (ch) {
			return "\\u" + ("000" + ch.charCodeAt().toString(16)).slice(-4);
		});
	} else if (selectedEncoding === "utf16") {
		// Source: https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
		const buffer = new ArrayBuffer(estring.length * 2);
		const result = new Uint16Array(buffer);
		for (let i = 0, strLen = estring.length; i < strLen; i++) {
			result[i] = estring.charCodeAt(i);
		}
		return String(result);
	} else {
		return estring;
	}
}

/**
 * Decodes text on client side.
 * @param {string} estring the string to be decoded
 */
export function decodeChat(estring) {
	const selectedDecoding = document.getElementById("client_decoding").value;
	if (selectedDecoding === "unicode") {
		// Source: https://stackoverflow.com/questions/7885096/how-do-i-decode-a-string-with-escaped-unicode
		return estring.replace(/\\u([\d\w]{1,})/gi, function (match, group) {
			return String.fromCharCode(parseInt(group, 16));
		});
	} else if (selectedDecoding === "utf16") {
		// Source: https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
		return String.fromCharCode.apply(null, new Uint16Array(estring.split(",")));
	} else {
		return estring;
	}
}