import {
canonicalizeBaseUrl,
i18n,
TalerConfigResponse,
Translate,
} 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";
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 { loading, result, endpoint, updateEndpoint, error } =
useEndpointStatus(initialValue ?? "", onVerify);
const [confirmationError, setConfirmationError] = useState<
string | undefined
>(undefined);
return (
Cancel
{
const url = canonicalizeBaseUrl(endpoint);
return onConfirm(url).then((r) =>
r ? setConfirmationError(r) : undefined,
);
}}
>
Next
);
}