import React, { useState } from 'react'; import { useIntl, FormattedMessage, defineMessages } from 'react-intl'; import { createApp } from 'pl-fe/actions/apps'; import { obtainOAuthToken } from 'pl-fe/actions/oauth'; import Button from 'pl-fe/components/ui/button'; import Column from 'pl-fe/components/ui/column'; import Form from 'pl-fe/components/ui/form'; import FormActions from 'pl-fe/components/ui/form-actions'; import FormGroup from 'pl-fe/components/ui/form-group'; import Input from 'pl-fe/components/ui/input'; import Stack from 'pl-fe/components/ui/stack'; import Text from 'pl-fe/components/ui/text'; import Textarea from 'pl-fe/components/ui/textarea'; import { useAppDispatch } from 'pl-fe/hooks/useAppDispatch'; import { useOwnAccount } from 'pl-fe/hooks/useOwnAccount'; import { getBaseURL } from 'pl-fe/utils/accounts'; import type { Token } from 'pl-api'; const messages = defineMessages({ heading: { id: 'column.app_create', defaultMessage: 'Create app' }, namePlaceholder: { id: 'app_create.name_placeholder', defaultMessage: 'e.g. \'pl-fe\'' }, scopesPlaceholder: { id: 'app_create.scopes_placeholder', defaultMessage: 'e.g. \'read write follow\'' }, }); const BLANK_PARAMS = { client_name: '', redirect_uris: 'urn:ietf:wg:oauth:2.0:oob', scopes: '', website: '', }; type Params = typeof BLANK_PARAMS; const CreateApp: React.FC = () => { const intl = useIntl(); const dispatch = useAppDispatch(); const { account } = useOwnAccount(); const [app, setApp] = useState | null>(null); const [token, setToken] = useState(null); const [isLoading, setLoading] = useState(false); const [params, setParams] = useState(BLANK_PARAMS); const handleCreateApp = () => { const baseURL = getBaseURL(account!); return dispatch(createApp(params, baseURL)) .then(app => { setApp(app); return app; }); }; const handleCreateToken = (app: Record) => { const baseURL = getBaseURL(account!); const tokenParams = { client_id: app!.client_id, client_secret: app!.client_secret, redirect_uri: params.redirect_uris, grant_type: 'client_credentials', scope: params.scopes, }; return dispatch(obtainOAuthToken(tokenParams, baseURL)) .then(setToken); }; const handleSubmit = () => { setLoading(true); handleCreateApp() .then(handleCreateToken) .then(() => { scrollToTop(); setLoading(false); }).catch(error => { console.error(error); setLoading(false); }); }; const setParam = (key: string, value: string) => { setParams({ ...params, [key]: value }); }; const handleParamChange = (key: string): React.ChangeEventHandler => e => { setParam(key, e.target.value); }; const resetState = () => { setApp(null); setToken(null); setLoading(false); setParams(BLANK_PARAMS); }; const handleReset = () => { resetState(); scrollToTop(); }; const scrollToTop = (): void => { window.scrollTo({ top: 0, behavior: 'smooth' }); }; const renderResults = () => (
}>