[pbs-devel] [PATCH widget-toolkit v3 06/14] utils: add base64 conversion helper

Lukas Wagner l.wagner at proxmox.com
Fri Nov 8 15:41:16 CET 2024


From: Gabriel Goller <g.goller at proxmox.com>

Add helper functions to convert from a utf8 string to a base64 string
and vice-versa. Using the TextEncoder/TextDecoder we can support unicode
such as emojis as well [0].

[0]: https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem

Signed-off-by: Gabriel Goller <g.goller at proxmox.com>
Reviewed-by: Thomas Lamprecht <t.lamprecht at proxmox.com>
---
 src/Utils.js | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/src/Utils.js b/src/Utils.js
index b68c0f4..4ff95af 100644
--- a/src/Utils.js
+++ b/src/Utils.js
@@ -1356,6 +1356,24 @@ utilities: {
 	);
     },
 
+    // Convert utf-8 string to base64.
+    // This also escapes unicode characters such as emojis.
+    utf8ToBase64: function(string) {
+	let bytes = new TextEncoder().encode(string);
+	const escapedString = Array.from(bytes, (byte) =>
+	    String.fromCodePoint(byte),
+	).join("");
+	return btoa(escapedString);
+    },
+
+    // Converts a base64 string into a utf8 string.
+    // Decodes escaped unicode characters correctly.
+    base64ToUtf8: function(b64_string) {
+	let string = atob(b64_string);
+	let bytes = Uint8Array.from(string, (m) => m.codePointAt(0));
+	return new TextDecoder().decode(bytes);
+    },
+
     stringToRGB: function(string) {
 	let hash = 0;
 	if (!string) {
-- 
2.39.5





More information about the pbs-devel mailing list