/ concept-collection / proofery-web
Sign in
concept-collection / proofery-web
proofery-web / src / utils / urlState.ts
38 lines · 990 BCodeBlameHistory
c1bee11initialJeremy Magland 1// URL state management using base64 encoding
3export const encodeToUrl = (content: string): string => {
4 try {
5 const base64 = btoa(unescape(encodeURIComponent(content)));
6 return base64;
7 } catch (error) {
8 console.error('Error encoding to base64:', error);
9 return '';
10 }
11};
13export const decodeFromUrl = (base64: string): string => {
14 try {
15 const decoded = decodeURIComponent(escape(atob(base64)));
16 return decoded;
17 } catch (error) {
18 console.error('Error decoding from base64:', error);
19 return '';
20 }
21};
23export const getContentFromUrl = (): string => {
24 const hash = window.location.hash.slice(1); // Remove the '#'
25 if (hash) {
26 return decodeFromUrl(hash);
27 }
28 return '';
29};
31export const updateUrlWithContent = (content: string): void => {
32 const encoded = encodeToUrl(content);
33 if (encoded) {
34 window.history.replaceState(null, '', `#${encoded}`);
35 } else {
36 window.history.replaceState(null, '', window.location.pathname);
37 }
38};
moveopenescclose