|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @flow |
| 8 | + */ |
| 9 | + |
| 10 | +import type {TimelineEvent} from '@elg/speedscope'; |
| 11 | +import type {ReactProfilerData} from './types'; |
| 12 | + |
| 13 | +import * as React from 'react'; |
| 14 | +import {useCallback, useContext, useRef} from 'react'; |
| 15 | + |
| 16 | +import Button from 'react-devtools-shared/src/devtools/views/Button'; |
| 17 | +import ButtonIcon from 'react-devtools-shared/src/devtools/views/ButtonIcon'; |
| 18 | +import {ModalDialogContext} from 'react-devtools-shared/src/devtools/views/ModalDialog'; |
| 19 | + |
| 20 | +import preprocessData from './utils/preprocessData'; |
| 21 | +import {readInputData} from './utils/readInputData'; |
| 22 | + |
| 23 | +import styles from './ImportButton.css'; |
| 24 | + |
| 25 | +type Props = {| |
| 26 | + onDataImported: (profilerData: ReactProfilerData) => void, |
| 27 | +|}; |
| 28 | + |
| 29 | +export default function ImportButton({onDataImported}: Props) { |
| 30 | + const inputRef = useRef<HTMLInputElement | null>(null); |
| 31 | + const {dispatch: modalDialogDispatch} = useContext(ModalDialogContext); |
| 32 | + |
| 33 | + const handleFiles = useCallback(async () => { |
| 34 | + const input = inputRef.current; |
| 35 | + if (input === null) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + if (input.files.length > 0) { |
| 40 | + try { |
| 41 | + const readFile = await readInputData(input.files[0]); |
| 42 | + const events: TimelineEvent[] = JSON.parse(readFile); |
| 43 | + if (events.length > 0) { |
| 44 | + onDataImported(preprocessData(events)); |
| 45 | + } |
| 46 | + } catch (error) { |
| 47 | + modalDialogDispatch({ |
| 48 | + type: 'SHOW', |
| 49 | + title: 'Import failed', |
| 50 | + content: ( |
| 51 | + <> |
| 52 | + <div>The profiling data you selected cannot be imported.</div> |
| 53 | + {error !== null && ( |
| 54 | + <div className={styles.ErrorMessage}>{error.message}</div> |
| 55 | + )} |
| 56 | + </> |
| 57 | + ), |
| 58 | + }); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + // Reset input element to allow the same file to be re-imported |
| 63 | + input.value = ''; |
| 64 | + }, [onDataImported, modalDialogDispatch]); |
| 65 | + |
| 66 | + const uploadData = useCallback(() => { |
| 67 | + if (inputRef.current !== null) { |
| 68 | + inputRef.current.click(); |
| 69 | + } |
| 70 | + }, []); |
| 71 | + |
| 72 | + return ( |
| 73 | + <> |
| 74 | + <input |
| 75 | + ref={inputRef} |
| 76 | + className={styles.Input} |
| 77 | + type="file" |
| 78 | + onChange={handleFiles} |
| 79 | + tabIndex={-1} |
| 80 | + /> |
| 81 | + <Button onClick={uploadData} title="Load profile..."> |
| 82 | + <ButtonIcon type="import" /> |
| 83 | + </Button> |
| 84 | + </> |
| 85 | + ); |
| 86 | +} |
0 commit comments