import { Map as ImmutableMap } from 'immutable'; import React, { useState } from 'react'; import { useIntl, FormattedMessage, defineMessages } from 'react-intl'; import { createApp } from 'soapbox/actions/apps'; import { obtainOAuthToken } from 'soapbox/actions/oauth'; import { Button, Form, FormActions, FormGroup, Input, Stack, Text, Textarea } from 'soapbox/components/ui'; import Column from 'soapbox/features/ui/components/column'; import { useAppDispatch, useOwnAccount } from 'soapbox/hooks'; import { getBaseURL } from 'soapbox/utils/accounts'; const messages = defineMessages({ heading: { id: 'column.app_create', defaultMessage: 'Create app' }, namePlaceholder: { id: 'app_create.name_placeholder', defaultMessage: 'e.g. \'Soapbox\'' }, scopesPlaceholder: { id: 'app_create.scopes_placeholder', defaultMessage: 'e.g. \'read write follow\'' }, }); 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(ImmutableMap({ client_name: '', redirect_uris: 'urn:ietf:wg:oauth:2.0:oob', scopes: '', website: '', })); const handleCreateApp = () => { const baseURL = getBaseURL(account!); return dispatch(createApp(params.toJS() as Record, 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.get('redirect_uri'), grant_type: 'client_credentials', scope: params.get('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) => { const newParams = params.set(key, value); setParams(newParams); }; const handleParamChange = (key: string): React.ChangeEventHandler => { return e => { setParam(key, e.target.value); }; }; const resetState = () => { setApp(null); setToken(null); setLoading(false); setParams(ImmutableMap({ client_name: '', redirect_uris: 'urn:ietf:wg:oauth:2.0:oob', scopes: '', website: '', })); }; const handleReset = () => { resetState(); scrollToTop(); }; const scrollToTop = (): void => { window.scrollTo({ top: 0, behavior: 'smooth' }); }; const renderResults = () => { return (
}>