refactor with uhtml, dynamically swap out page template whenever hash changes in URL

This commit is contained in:
2024-02-01 21:33:11 -05:00
parent d2d91e6ab3
commit 01d817a206
8 changed files with 409 additions and 210 deletions

83
src/utils/keyManager.ts Normal file
View File

@@ -0,0 +1,83 @@
import { html } from "uhtml";
import {
exportKeys,
importAndSaveKeys,
retrieveOrGenerateKeyPair,
} from "./crypto";
import { reactive } from "uhtml/reactive";
import { effect, signal } from "uhtml/preactive";
const render = reactive(effect);
const ecdhPublicKey = signal(localStorage.getItem("ecdhPublic"));
const ecdhPrivateKey = signal(localStorage.getItem("ecdhPrivate"));
const MODAL_ID = "keyManagerModal";
const template = html` <dialog class="key-manager" .id=${MODAL_ID}>
<article>
<header>Key Manager</header>
<p>
If you'd like to manage your keys, you can do so here. You can export your keys to transfer to a different
device, or import keys exported from a different device.
</p>
<p>
Public Key:
<pre>${ecdhPublicKey}</pre>
</p>
<p>
Private Key:
<pre>${ecdhPrivateKey}</pre>
</p>
<p>
<button @click=${exportKeys}>Export Keys</button>
<button @click=${importKeys}>Import Keys</button>
<input type="file" accept=".json" style="display: none" id="keypairImportEl" @change=${handleKeypairImport} />
<button @click=${close}>Close</button>
</p>
</article>
</dialog>`;
function importKeys(): void {
const el = document.querySelector("#keypairImportEl");
if (!el) {
throw new Error("No file input found");
}
(el as HTMLElement).click();
}
function handleKeypairImport(event: Event): void {
const fileInput = event.target as HTMLInputElement;
const file = fileInput.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async (event) => {
const keys = JSON.parse(event.target?.result as string);
await importAndSaveKeys(keys);
alert("Successfully imported keypair");
};
reader.readAsText(file);
}
function close(event: Event): void {
const dialog = (event.target as HTMLElement).closest(`#${MODAL_ID}`);
dialog?.removeAttribute("open");
}
export const initKeyManager = (target: HTMLElement | null) => {
const openKeyManagerEl = document.querySelector("#openKeyManager");
if (!target || !openKeyManagerEl) {
throw new Error("No target element found");
}
retrieveOrGenerateKeyPair();
openKeyManagerEl.addEventListener("click", (event: Event) => {
event.preventDefault();
ecdhPrivateKey.value = localStorage.getItem("ecdhPrivate");
ecdhPublicKey.value = localStorage.getItem("ecdhPublic");
document.querySelector(`#${MODAL_ID}`)?.setAttribute("open", "");
});
render(target, template);
};