summaryrefslogtreecommitdiff
path: root/packages/taler-wallet-webextension/src/wallet/QrReader.tsx
blob: 9c9ab7ce4794fe4caeb7a3331cf9c06a8c19fde9 (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
/*
 This file is part of GNU Taler
 (C) 2022 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

import { classifyTalerUri, TalerUriType } from "@gnu-taler/taler-util";
import { styled } from "@linaria/react";
import { Fragment, h, VNode } from "preact";
import { Ref, useEffect, useRef, useState } from "preact/hooks";
import QrScanner from "qr-scanner";
import { Alert } from "../mui/Alert.js";
import { Button } from "../mui/Button.js";
import { TextField } from "../mui/TextField.js";

const QrVideo = styled.video`
  width: 80%;
  margin-left: auto;
  margin-right: auto;
  padding: 8px;
  background-color: black;
`;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  & > * {
    margin-bottom: 20px;
  }
`;

interface Props {
  onDetected: (url: string) => void;
}

export function QrReaderPage({ onDetected }: Props): VNode {
  const videoRef = useRef<HTMLVideoElement>(null);
  // const imageRef = useRef<HTMLImageElement>(null);
  const qrScanner = useRef<QrScanner | null>(null);
  const [value, onChange] = useState("");
  const [active, setActive] = useState(false);

  function start(): void {
    qrScanner.current!.start();
    onChange("");
    setActive(true);
  }
  function stop(): void {
    qrScanner.current!.stop();
    setActive(false);
  }

  function check(v: string) {
    return (
      v.startsWith("taler://") && classifyTalerUri(v) !== TalerUriType.Unknown
    );
  }

  useEffect(() => {
    if (!videoRef.current) {
      console.log("vide was not ready");
      return;
    }
    const elem = videoRef.current;
    setTimeout(() => {
      qrScanner.current = new QrScanner(
        elem,
        ({ data, cornerPoints }) => {
          if (check(data)) {
            onDetected(data);
            return;
          }
          onChange(data);
          stop();
        },
        {
          maxScansPerSecond: 5, //default 25
          highlightScanRegion: true,
        },
      );
      start();
    }, 1);
    return () => {
      qrScanner.current?.destroy();
    };
  }, []);

  const isValid = check(value);

  return (
    <Container>
      {/* <InputFile onChange={(f) => scanImage(imageRef, f)}>
        Read QR from file
      </InputFile>
      <div ref={imageRef} /> */}
      <QrVideo ref={videoRef} />
      <TextField
        label="Taler URI"
        variant="standard"
        fullWidth
        value={value}
        onChange={onChange}
      />
      {isValid && (
        <Button variant="contained" onClick={async () => onDetected(value)}>
          Open
        </Button>
      )}
      {!active && !isValid && (
        <Fragment>
          <Alert severity="error">
            URI is not valid. Taler URI should start with `taler://`
          </Alert>
          <Button variant="contained" onClick={async () => start()}>
            Try another
          </Button>
        </Fragment>
      )}
    </Container>
  );
}

async function scanImage(
  imageRef: Ref<HTMLImageElement>,
  image: string,
): Promise<void> {
  const imageEl = new Image();
  imageEl.src = image;
  imageEl.width = 200;
  imageRef.current!.appendChild(imageEl);
  QrScanner.scanImage(image, {
    alsoTryWithoutScanRegion: true,
  })
    .then((result) => console.log(result))
    .catch((error) => console.log(error || "No QR code found."));
}