import { useState, useMemo } from "react"; import { Copy, Check, Plus, X } from "lucide-react"; import { parseEncodeCommand, encodeToNostr, type ParsedEncodeCommand, } from "@/lib/encode-parser"; import { useCopy } from "../hooks/useCopy"; import { Button } from "./ui/button"; import { Input } from "./ui/input"; import { normalizeRelayURL } from "@/lib/relay-url"; interface EncodeViewerProps { args: string[]; } export default function EncodeViewer({ args }: EncodeViewerProps) { const { copy, copied } = useCopy(); const [relays, setRelays] = useState([]); const [newRelay, setNewRelay] = useState(""); const [error, setError] = useState(null); // Parse command const parsed = useMemo(() => { try { const result = parseEncodeCommand(args); setRelays(result.relays || []); setError(null); return result; } catch (err) { setError(err instanceof Error ? err.message : "Parse error"); return null; } }, [args]); // Generate bech32 with current relays const encoded = useMemo(() => { if (!parsed) return null; try { return encodeToNostr({ ...parsed, relays: relays.length > 0 ? relays : undefined, }); } catch { return null; } }, [parsed, relays]); const copyToClipboard = () => { if (encoded) { copy(encoded); } }; const addRelay = () => { if (!newRelay.trim()) return; // Auto-add wss:// if no protocol let relayUrl = newRelay.trim(); if (!relayUrl.startsWith("ws://") && !relayUrl.startsWith("wss://")) { relayUrl = `wss://${relayUrl}`; } try { const url = new URL(relayUrl); if (!url.protocol.startsWith("ws")) { setError("Relay must be a WebSocket URL (ws:// or wss://)"); return; } setRelays([...relays, normalizeRelayURL(relayUrl)]); setNewRelay(""); setError(null); } catch { setError("Invalid relay URL"); } }; const removeRelay = (index: number) => { setRelays(relays.filter((_, i) => i !== index)); }; if (error) { return (
{error}
); } if (!parsed) { return (
Loading...
); } const supportsRelays = ["nprofile", "nevent", "naddr"].includes(parsed.type); return (
{/* Header */}

ENCODE {parsed.type.toUpperCase()}

{/* Content */}
{/* Input Information */}
Input
{parsed.value}
{parsed.author && (
Author
{parsed.author}
)}
{/* Relay Editor */} {supportsRelays && (
Relays ({relays.length})
{relays.map((relay, index) => (
{relay}
))}
setNewRelay(e.target.value)} onKeyDown={(e) => e.key === "Enter" && addRelay()} className="font-mono text-xs" />
)} {/* Encoded Result */}
Result
{encoded}
); }