1
Fork 0
holllo-org/source/ts/re-nav/share.ts

79 lines
2.1 KiB
TypeScript

import {Base64} from "js-base64";
const fragmentPrefix = "#json=";
const exampleRedirect: Redirect = {
matcherType: "hostname",
matcherValue: "example.com",
redirectType: "hostname",
redirectValue: "example.org",
};
function decodeBase64<T>(base64: string): T {
return JSON.parse(Base64.decode(base64)) as T;
}
function encodeBase64(source: any): string {
return Base64.encode(JSON.stringify(source), true);
}
window.addEventListener("DOMContentLoaded", () => {
window["Re-Nav"] = {
decodeBase64,
encodeBase64,
share,
};
console.log(
"Want to manually create a share link? Use the window['Re-Nav'].share",
"function, where redirect is an object with matcherType, matcherValue,",
"redirectType and redirectValue properties. Like this:",
);
console.log(JSON.stringify(exampleRedirect, undefined, 2));
console.log(window["Re-Nav"].share);
if (!location.hash.startsWith(fragmentPrefix)) {
return;
}
const decoded = decodeBase64<Redirect>(
location.hash.slice(fragmentPrefix.length),
);
for (const [key, value] of Object.entries(decoded)) {
insertText(key as keyof Redirect, value);
}
for (const element of document.querySelectorAll(".hidden-by-default")) {
element.classList.remove("hidden-by-default");
}
document.querySelector(".subtitle")!.textContent =
"Someone shared a redirect with you!";
});
function insertText(key: keyof Redirect, value: string): void {
const insert = (selector: string, text: string) => {
document.querySelector(selector)!.textContent = text;
};
// eslint-disable-next-line unicorn/prefer-switch
if (key === "matcherType") {
insert(".matcher-type", value);
} else if (key === "matcherValue") {
insert(".matcher-value", value);
} else if (key === "redirectType") {
insert(".redirect-type", value);
} else if (key === "redirectValue") {
insert(".redirect-value", value);
} else {
console.warn(`Unknown key: ${key as string}`);
}
}
function share(redirect: Redirect): string {
const encoded = encodeBase64(redirect);
const url = new URL(window.location.href);
url.hash = `${fragmentPrefix}${encoded}`;
return url.href;
}