From ea733f8fc8a61bb65ff251c57ca15849328d4d38 Mon Sep 17 00:00:00 2001 From: Depickere Sven Date: Sat, 15 Jan 2022 17:50:59 +0100 Subject: [PATCH] feat(#1251): Add file selector to demo application This PR should fix the request to add a file selector to the demo application see issue #1251 . --- demo/components/FileInput.tsx | 56 +++++++++++++++++++++++++++++++++++ demo/index.tsx | 16 ++++++++-- 2 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 demo/components/FileInput.tsx diff --git a/demo/components/FileInput.tsx b/demo/components/FileInput.tsx new file mode 100644 index 00000000..2f06cd8d --- /dev/null +++ b/demo/components/FileInput.tsx @@ -0,0 +1,56 @@ +import * as yaml from 'js-yaml'; +import * as React from 'react'; +import { RefObject, useRef } from 'react'; +import styled from '../../src/styled-components'; + +const Button = styled.button` + background-color: #fff; + color: #333; + padding: 2px 10px; + touch-action: manipulation; + cursor: pointer; + user-select: none; + border: 1px solid #ccc; + font-size: 16px; + height: 28px; + box-sizing: border-box; + vertical-align: middle; + line-height: 1; + outline: none; + white-space: nowrap; + @media (max-width: 699px) { + display: none; + } +`; + +function GetUseRef(): RefObject { + return useRef(null); +} + +const FileInput = props => { + const hiddenFileInput: RefObject = GetUseRef(); + + function handleClick() { + if (hiddenFileInput && hiddenFileInput.current) { + hiddenFileInput.current.click(); + } + } + + function uploadFile(event) { + const file = event.target.files[0]; + const reader = new FileReader(); + reader.onload = () => { + props.onUpload(yaml.load(reader.result)); + }; + reader.readAsText(file); + } + + return ( + + + + + ); +}; + +export default FileInput; diff --git a/demo/index.tsx b/demo/index.tsx index a92b940a..62c5323b 100644 --- a/demo/index.tsx +++ b/demo/index.tsx @@ -4,6 +4,7 @@ import styled from 'styled-components'; import { resolve as urlResolve } from 'url'; import { RedocStandalone } from '../src'; import ComboBox from './ComboBox'; +import FileInput from './components/FileInput'; const DEFAULT_SPEC = 'openapi.yaml'; const NEW_VERSION_SPEC = 'openapi-3-1.yaml'; @@ -22,7 +23,7 @@ const demos = [ class DemoApp extends React.Component< {}, - { specUrl: string; dropdownOpen: boolean; cors: boolean } + { spec: object | undefined; specUrl: string; dropdownOpen: boolean; cors: boolean } > { constructor(props) { super(props); @@ -40,15 +41,24 @@ class DemoApp extends React.Component< } this.state = { + spec: undefined, specUrl: url, dropdownOpen: false, cors, }; } + handleUploadFile = (spec: object) => { + this.setState({ + spec, + specUrl: '', + }); + }; + handleChange = (url: string) => { if (url === NEW_VERSION_SPEC) { - this.setState({ cors: false }) + this.setState({ cors: false }); + 0; } this.setState({ specUrl: url, @@ -90,6 +100,7 @@ class DemoApp extends React.Component< /> +