summaryrefslogtreecommitdiff
path: root/packages/taler-wallet-webextension/src/wallet/ExchangeSetUrl.tsx
blob: 755cf425f552a30895830696f295b0d16008f821 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import {
  canonicalizeBaseUrl,
  TalerConfigResponse,
} from "@gnu-taler/taler-util";
import { Fragment, h, VNode } from "preact";
import { useEffect, useState } from "preact/hooks";
import { ErrorMessage } from "../components/ErrorMessage.js";
import {
  Input,
  LightText,
  SubTitle,
  Title,
  WarningBox,
} from "../components/styled/index.js";
import { useTranslationContext } from "../context/translation.js";
import { Button } from "../mui/Button.js";

export interface Props {
  initialValue?: string;
  expectedCurrency?: string;
  onCancel: () => Promise<void>;
  onVerify: (s: string) => Promise<TalerConfigResponse | undefined>;
  onConfirm: (url: string) => Promise<string | undefined>;
  withError?: string;
}

function useEndpointStatus<T>(
  endpoint: string,
  onVerify: (e: string) => Promise<T>,
): {
  loading: boolean;
  error?: string;
  endpoint: string;
  result: T | undefined;
  updateEndpoint: (s: string) => void;
} {
  const [value, setValue] = useState<string>(endpoint);
  const [dirty, setDirty] = useState(false);
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<T | undefined>(undefined);
  const [error, setError] = useState<string | undefined>(undefined);

  const [handler, setHandler] = useState<number | undefined>(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, setHandler, onVerify]);

  return {
    error: dirty ? error : undefined,
    loading: loading,
    result: result,
    endpoint: value,
    updateEndpoint: setValue,
  };
}

export function ExchangeSetUrlPage({
  initialValue,
  expectedCurrency,
  onCancel,
  onVerify,
  onConfirm,
}: Props): VNode {
  const { i18n } = useTranslationContext();
  const { loading, result, endpoint, updateEndpoint, error } =
    useEndpointStatus(initialValue ?? "", onVerify);

  const [confirmationError, setConfirmationError] = useState<
    string | undefined
  >(undefined);

  return (
    <Fragment>
      <section>
        {!expectedCurrency ? (
          <Title>
            <i18n.Translate>Add new exchange</i18n.Translate>
          </Title>
        ) : (
          <SubTitle>
            <i18n.Translate>Add exchange for {expectedCurrency}</i18n.Translate>
          </SubTitle>
        )}
        {!result && (
          <LightText>
            <i18n.Translate>
              Enter the URL of an exchange you trust.
            </i18n.Translate>
          </LightText>
        )}
        {result && (
          <LightText>
            <i18n.Translate>
              An exchange has been found! Review the information and click next
            </i18n.Translate>
          </LightText>
        )}
        {result && expectedCurrency && expectedCurrency !== result.currency && (
          <WarningBox>
            <i18n.Translate>
              This exchange doesn&apos;t match the expected currency
              <b>{expectedCurrency}</b>
            </i18n.Translate>
          </WarningBox>
        )}
        {error && (
          <ErrorMessage
            title={
              <i18n.Translate>Unable to verify this exchange</i18n.Translate>
            }
            description={error}
          />
        )}
        {confirmationError && (
          <ErrorMessage
            title={<i18n.Translate>Unable to add this exchange</i18n.Translate>}
            description={confirmationError}
          />
        )}
        <p>
          <Input invalid={!!error}>
            <label>URL</label>
            <input
              type="text"
              placeholder="https://"
              value={endpoint}
              onInput={(e) => updateEndpoint(e.currentTarget.value)}
            />
          </Input>
          {loading && (
            <div>
              <i18n.Translate>loading</i18n.Translate>...
            </div>
          )}
          {result && !loading && (
            <Fragment>
              <Input>
                <label>
                  <i18n.Translate>Version</i18n.Translate>
                </label>
                <input type="text" disabled value={result.version} />
              </Input>
              <Input>
                <label>
                  <i18n.Translate>Currency</i18n.Translate>
                </label>
                <input type="text" disabled value={result.currency} />
              </Input>
            </Fragment>
          )}
        </p>
      </section>
      <footer>
        <Button variant="contained" color="secondary" onClick={onCancel}>
          <i18n.Translate>Cancel</i18n.Translate>
        </Button>
        <Button
          variant="contained"
          disabled={
            !result ||
            !!error ||
            (!!expectedCurrency && expectedCurrency !== result.currency)
          }
          onClick={() => {
            const url = canonicalizeBaseUrl(endpoint);
            return onConfirm(url).then((r) =>
              r ? setConfirmationError(r) : undefined,
            );
          }}
        >
          <i18n.Translate>Next</i18n.Translate>
        </Button>
      </footer>
    </Fragment>
  );
}