import { useState } from 'react'; import { useForm } from 'react-hook-form'; import QRCode from 'react-qr-code'; import { generateUrl } from '../../../../common/api/session'; import { maybeAxiosError } from '../../../../common/api/utils'; import Button from '../../../../common/components/buttons/Button'; import Info from '../../../../common/components/info/Info'; import Select from '../../../../common/components/select/Select'; import Switch from '../../../../common/components/switch/Switch'; import copyToClipboard from '../../../../common/utils/copyToClipboard'; import { preventEscape } from '../../../../common/utils/keyEvent'; import { linkToOtherHost } from '../../../../common/utils/linkUtils'; import { currentHostName, isOntimeCloud, serverURL } from '../../../../externals'; import * as Panel from '../../panel-utils/PanelUtils'; import style from './GenerateLinkForm.module.scss'; interface GenerateLinkFormProps { hostOptions: { value: string; label: string }[]; pathOptions: { value: string; label: string }[]; isLockedToView?: boolean; } interface GenerateLinkFormOptions { baseUrl: string; path: string; lock: boolean; authenticate: boolean; } type GenerateLinkState = 'pending' | 'loading' | 'success' | 'error'; export default function GenerateLinkForm({ hostOptions, pathOptions, isLockedToView }: GenerateLinkFormProps) { const [formState, setFormState] = useState('pending'); const [url, setUrl] = useState(serverURL); const { handleSubmit, setError, watch, setValue, formState: { errors }, } = useForm({ mode: 'onChange', defaultValues: { baseUrl: currentHostName, path: isLockedToView ? pathOptions[0].value : 'timer', lock: false, authenticate: false, }, resetOptions: { keepDirtyValues: true, }, }); const onSubmit = async (options: GenerateLinkFormOptions) => { try { setFormState('loading'); const baseUrl = linkToOtherHost(options.baseUrl); const url = await generateUrl(baseUrl, options.path, options.lock, options.authenticate); await copyToClipboard(url); setUrl(url); setFormState('success'); setTimeout(() => { setFormState('pending'); }, 4000); } catch (error) { const message = maybeAxiosError(error); setError('root', { message }); setFormState('error'); } }; return ( preventEscape(event)}> {errors.root && {errors.root.message}} {!isLockedToView ? ( You can generate a link to share with your team or to use in automation (such as companion). ) : ( You can generate a link to share with your team )} ) : (