import { canonicalizeBaseUrl, TalerConfigResponse, } from "@gnu-taler/taler-util"; import { Fragment, h } from "preact"; import { useEffect, useState } from "preact/hooks"; import { ErrorMessage } from "../components/ErrorMessage"; import { Button, ButtonPrimary, Input, LightText, WarningBox, } from "../components/styled"; import { useTranslationContext } from "../context/translation"; export interface Props { initialValue?: string; expectedCurrency?: string; onCancel: () => void; onVerify: (s: string) => Promise; onConfirm: (url: string) => Promise; withError?: string; } function useEndpointStatus( endpoint: string, onVerify: (e: string) => Promise, ): { loading: boolean; error?: string; endpoint: string; result: T | undefined; updateEndpoint: (s: string) => void; } { const [value, setValue] = useState(endpoint); const [dirty, setDirty] = useState(false); const [loading, setLoading] = useState(false); const [result, setResult] = useState(undefined); const [error, setError] = useState(undefined); const [handler, setHandler] = useState(undefined); useEffect(() => { if (!value) return; window.clearTimeout(handler); const h = window.setTimeout(async () => { setDirty(true); setLoading(true); try { const url = canonicalizeBaseUrl(value); const result = await onVerify(url); setResult(result); setError(undefined); setLoading(false); } catch (e) { const errorMessage = e instanceof Error ? e.message : `unknown error: ${e}`; setError(errorMessage); setLoading(false); setResult(undefined); } }, 500); setHandler(h); }, [value]); return { error: dirty ? error : undefined, loading: loading, result: result, endpoint: value, updateEndpoint: setValue, }; } export function ExchangeSetUrlPage({ initialValue, expectedCurrency, onCancel, onVerify, onConfirm, }: Props) { const { i18n } = useTranslationContext(); const { loading, result, endpoint, updateEndpoint, error } = useEndpointStatus(initialValue ?? "", onVerify); const [confirmationError, setConfirmationError] = useState< string | undefined >(undefined); return (
{!expectedCurrency ? (

Add new exchange

) : (

Add exchange for {expectedCurrency}

)} {!result && ( Enter the URL of an exchange you trust. )} {result && ( An exchange has been found! Review the information and click next )} {result && expectedCurrency && expectedCurrency !== result.currency && ( This exchange doesn't match the expected currency {expectedCurrency} )} {error && ( Unable to verify this exchange } description={error} /> )} {confirmationError && ( Unable to add this exchange} description={confirmationError} /> )}

updateEndpoint(e.currentTarget.value)} /> {loading && (

loading...
)} {result && !loading && ( )}

); }