xref: /aosp_15_r20/external/pigweed/pw_web/webconsole/components/uploadDb.tsx (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1// Copyright 2022 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15import Button from '@mui/material/Button';
16import {Alert} from '@mui/material';
17import {useState, useRef} from 'react';
18
19interface Props {
20  onUpload: (db: string) => void
21}
22
23export default function BtnUploadDB({onUpload}: Props) {
24  const [uploaded, setUploaded] = useState(false);
25  const [error, setError] = useState("");
26  const uploadInputRef = useRef<HTMLInputElement>(null);
27
28  if (uploaded) return (<Alert severity="success">DB Loaded</Alert>)
29  return (
30    <>
31      <input
32        ref={uploadInputRef}
33        type="file"
34        accept="text/*"
35        style={{display: "none"}}
36        onChange={async e => {
37          const tokenCsv = await readFile(e.target.files![0]);
38          try {
39            onUpload(tokenCsv);
40            setUploaded(true);
41            setError("");
42          }
43          catch (e: any) {
44            if (e instanceof Error) setError(e.message);
45            else setError("Error loading token database.");
46          }
47        }}
48      />
49      <Button
50        onClick={() => uploadInputRef.current && uploadInputRef.current.click()}
51        variant="contained">
52        Upload token database
53      </Button>
54      {error && <Alert severity="error">{error}</Alert>}
55    </>
56  )
57}
58
59function readFile(file: Blob): Promise<string> {
60  return new Promise((resolve, reject) => {
61    if (!file) return resolve('');
62    const reader = new FileReader();
63    reader.onload = function (e) {
64      resolve(String(e.target!.result));
65    };
66    reader.readAsText(file);
67  });
68}
69