50 lines
1.1 KiB
TypeScript
50 lines
1.1 KiB
TypeScript
import { Signal, useSignal, useSignalEffect } from "@preact/signals";
|
|
|
|
import Form from "@/islands/Form.tsx";
|
|
import { post_json } from "@/src/client.ts";
|
|
|
|
interface AskCodeProps {
|
|
page: Signal<string>;
|
|
}
|
|
|
|
export default function AskCode({ page }: AskCodeProps) {
|
|
const checking = useSignal(false);
|
|
|
|
const on_success = (data: { code: string }) => {
|
|
localStorage.setItem("code", data.code);
|
|
page.value = "keys";
|
|
};
|
|
|
|
useSignalEffect(() => {
|
|
const fn = async () => {
|
|
const code = localStorage.getItem("code");
|
|
if (!code) {
|
|
return;
|
|
}
|
|
|
|
checking.value = true;
|
|
const result = await post_json<{ code: string }>("/api/verify_code", { code });
|
|
checking.value = false;
|
|
|
|
if (result.ok) {
|
|
on_success(result.data);
|
|
} else if (result.status !== 0) {
|
|
// Network errors keep the code so it can be retried on the next load
|
|
localStorage.removeItem("code");
|
|
}
|
|
};
|
|
fn();
|
|
});
|
|
|
|
if (checking.value) {
|
|
return <p>Verifying code...</p>;
|
|
}
|
|
|
|
return (
|
|
<Form action="/api/verify_code" on_success={on_success}>
|
|
<input type="text" name="code" />
|
|
<button type="submit">Enter</button>
|
|
</Form>
|
|
);
|
|
}
|