| 1 |
const eCache = {}; |
| 2 |
const dCache = {}; |
| 3 |
|
| 4 |
/** |
| 5 |
* Encode URI component with `try {} catch` and caching. |
| 6 |
* |
| 7 |
* @param {string} str - decoded string. |
| 8 |
* @return {string} - new encoded string. |
| 9 |
*/ |
| 10 |
export function maybeEncode(str) { |
| 11 |
// return cached string. |
| 12 |
if (eCache[str]) { |
| 13 |
return eCache[str]; |
| 14 |
} |
| 15 |
|
| 16 |
let result = {}; |
| 17 |
|
| 18 |
// Object |
| 19 |
if (typeof str === 'object') { |
| 20 |
Object.keys(str).forEach((k) => { |
| 21 |
result[maybeEncode(k)] = maybeEncode(str[k]); |
| 22 |
}); |
| 23 |
|
| 24 |
return result; |
| 25 |
} |
| 26 |
|
| 27 |
// String |
| 28 |
result = str; |
| 29 |
|
| 30 |
if (typeof result === 'string') { |
| 31 |
try { |
| 32 |
// Because of these replacements, some attributes can't be exported to XML without being broken. So, we need to replace it manually with something safe. |
| 33 |
// https://github.com/WordPress/gutenberg/blob/88645e4b268acf5746e914159e3ce790dcb1665a/packages/blocks/src/api/serializer.js#L246-L271 |
| 34 |
result = result.replace(/--/gm, '_u002d__u002d_'); |
| 35 |
|
| 36 |
result = encodeURIComponent(result); |
| 37 |
} catch (e) { |
| 38 |
// eslint-disable-next-line no-console |
| 39 |
console.warn(e); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
// save to cache. |
| 44 |
eCache[str] = result; |
| 45 |
|
| 46 |
return result; |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Encode URI component with `try {} catch` and caching. |
| 51 |
* |
| 52 |
* @param {string} str - decoded string. |
| 53 |
* @return {string} - new encoded string. |
| 54 |
*/ |
| 55 |
export function maybeDecode(str) { |
| 56 |
// return cached string. |
| 57 |
if (dCache[str]) { |
| 58 |
return dCache[str]; |
| 59 |
} |
| 60 |
|
| 61 |
let result = {}; |
| 62 |
|
| 63 |
if (Array.isArray(str)) { |
| 64 |
result = []; |
| 65 |
} |
| 66 |
|
| 67 |
// Object |
| 68 |
if (typeof str === 'object') { |
| 69 |
Object.keys(str).forEach((k) => { |
| 70 |
result[maybeDecode(k)] = maybeDecode(str[k]); |
| 71 |
}); |
| 72 |
|
| 73 |
return result; |
| 74 |
} |
| 75 |
|
| 76 |
// String |
| 77 |
result = str; |
| 78 |
|
| 79 |
if (typeof result === 'string') { |
| 80 |
try { |
| 81 |
result = decodeURIComponent(result); |
| 82 |
|
| 83 |
// Because of these replacements, some attributes can't be exported to XML without being broken. So, we need to replace it manually with something safe. |
| 84 |
// https://github.com/WordPress/gutenberg/blob/88645e4b268acf5746e914159e3ce790dcb1665a/packages/blocks/src/api/serializer.js#L246-L271 |
| 85 |
result = result.replace(/_u002d__u002d_/gm, '--'); |
| 86 |
} catch (e) { |
| 87 |
// eslint-disable-next-line no-console |
| 88 |
console.warn(e); |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
// save to cache. |
| 93 |
dCache[str] = result; |
| 94 |
|
| 95 |
return result; |
| 96 |
} |
| 97 |
|