import React from "react"; import { Form, Button, Row, Col } from "react-bootstrap"; import axios from "axios"; import { debounce } from "lodash"; import "bootstrap/dist/css/bootstrap.min.css"; const UI_PARAMS_API_URL = "/params"; const TRANSLATE_API_URL = "/translate"; const EXAMPLE_API_URL = "/examples"; const DEBOUNCE_INPUT = 250; class App extends React.Component { constructor(props) { super(props); this.state = { output: "", input: "", buttonText: "Submit", description: "Description", showExampleForm: false, examples: {}, }; // Bind the event handlers this.handleInputChange = this.handleInputChange.bind(this); this.handleClick = this.handleClick.bind(this); } componentDidMount() { // Call API for the UI params axios .get(UI_PARAMS_API_URL) .then( ({ data: { placeholder, button_text, description, show_example_form }, }) => { this.setState({ input: placeholder, buttonText: button_text, description: description, showExampleForm: show_example_form, }); if (this.state.showExampleForm) { axios.get(EXAMPLE_API_URL).then(({ data: examples }) => { this.setState({ examples }); }); } } ); const load = document.getElementById("loading"); load.style.visibility = "visible"; } updateExample(id, body) { axios.put(`${EXAMPLE_API_URL}/${id}`, body); } debouncedUpdateExample = debounce(this.updateExample, DEBOUNCE_INPUT); handleExampleChange = (id, field) => (e) => { const text = e.target.value; let body = { [field]: text }; let examples = { ...this.state.examples }; examples[id][field] = text; this.setState({ examples }); this.debouncedUpdateExample(id, body); }; handleExampleDelete = (id) => (e) => { e.preventDefault(); axios.delete(`${EXAMPLE_API_URL}/${id}`).then(({ data: examples }) => { this.setState({ examples }); }); }; handleExampleAdd = (e) => { e.preventDefault(); axios.post(EXAMPLE_API_URL).then(({ data: examples }) => { this.setState({ examples }); }); }; handleInputChange(e) { this.setState({ input: e.target.value }); } handleClick(e) { e.preventDefault(); const load = document.getElementById("loading"); load.style.visibility = "visible"; let body = { prompt: this.state.input, }; axios.post(TRANSLATE_API_URL, body).then(({ data: { text } }) => { this.setState({ output: text }); load.style.visibility = "hidden"; }); } render() { const showExampleForm = this.state.showExampleForm; return (
{showExampleForm && (

Examples

{Object.values(this.state.examples).map((example) => ( Example Input Example Output ))}
)} {this.state.description}
Loading...
{this.state.output}
); } } export default App;