import { useState } from "react"; import { KeyRound, Plus, Trash2 } from "lucide-react"; import type { ApiToken, CreatedToken } from "../../shared/api-types.js"; import { api, useApi } from "../api.js"; import { Button } from "../components/ui/button.js"; import { Dialog, useConfirm } from "../components/ui/dialog.js"; import { Field, Input } from "../components/ui/form.js"; import { CopyButton } from "../components/ui/misc.js"; import { Alert, Card, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js"; import { useAction } from "../components/ui/toast.js"; function relative(date: string): string { const seconds = (new Date(date).getTime() - Date.now()) / 1000; const units: [Intl.RelativeTimeFormatUnit, number][] = [ ["year", 31536000], ["month", 2592000], ["day", 86400], ["hour", 3600], ["minute", 60], ]; const fmt = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" }); for (const [unit, size] of units) { if (Math.abs(seconds) >= size) return fmt.format(Math.round(seconds / size), unit); } return "just now"; } function CreateTokenDialog({ open, onClose, onCreated }: { open: boolean; onClose: () => void; onCreated: () => void }) { const [name, setName] = useState(""); const [created, setCreated] = useState(null); const { busy, run } = useAction(); const close = () => { setName(""); setCreated(null); onClose(); }; if (created) { return ( Done} > You won't be able to see this token again.
{created.token}
); } return ( void run(async () => { setCreated(await api("POST", "/tokens", { name })); onCreated(); }) } footer={ <> } > {(id) => setName(e.target.value)} />} ); } export function TokensScreen() { const tokens = useApi("/tokens"); const [creating, setCreating] = useState(false); const { run } = useAction(); const confirm = useConfirm(); const revoke = async (t: ApiToken) => { const ok = await confirm({ title: `Revoke "${t.name}"?`, description: "Scripts using this token stop working immediately.", confirmLabel: "Revoke", danger: true, }); if (ok) void run(async () => { await api("DELETE", `/tokens/${t.id}`); await tokens.reload(); }, "Token revoked"); }; const example = `curl -X POST ${location.origin}/~/api/pages \\ -H "Authorization: Bearer " \\ -H "Content-Type: application/json" \\ -d '{"kind":"redirect","dest":"https://example.com"}'`; const createButton = ( ); return ( <>
{!tokens.data ? (
) : tokens.data.length ? (
    {tokens.data.map((t) => (
  • {t.name}
    Created {relative(t.createdAt)} ยท {t.lastUsedAt ? `last used ${relative(t.lastUsedAt)}` : "never used"}
  • ))}
) : ( } title="No tokens yet" description="Tokens let scripts use the API on your behalf." action={createButton} /> )}
} />
{example}
setCreating(false)} onCreated={() => void tokens.reload()} /> ); }