aboutsummaryrefslogtreecommitdiff
path: root/webAO/encoding.ts
blob: 10181442f935783b3413467fc8e97896ddb31f25 (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
/**
 * Escapes a string to AO1 escape codes.
 * @param {string} estring the string to be escaped
 */
export function escapeChat(estring: string): string {
  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: string): string {
  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 safeTags(unsafe: string): string {
  if (unsafe) {
    return unsafe
      .replace(/>/g, '&gt;')
      .replace(/</g, '&lt;');
  }
  return '';
}

/**
 * Encode text on client side.
 * @param {string} estring the string to be encoded
 */
export function encodeChat(estring: string): string {
  return estring;
}

/**
 * Decodes text on client side.
 * @param {string} estring the string to be decoded
 */
export function decodeChat(estring: string): string {
    // Source: https://stackoverflow.com/questions/7885096/how-do-i-decode-a-string-with-escaped-unicode
    return estring.replace(/\\u([\d\w]{1,})/gi, (match, group) => String.fromCharCode(parseInt(group, 16)));
}

/**
 * XXX: a nasty hack made by gameboyprinter.
 * @param {string} msg chat message to prepare for display
 */
export function prepChat(msg: string): string {
  // TODO: make this less awful
  return unescapeChat(decodeChat(msg));
}