import { useState } from 'react' import { useIdeContext, ideTypeNameMap } from 'src/helpers/hooks/useIdeContext' import OutBound from 'src/components/OutBound/OutBound' import { prepareEncodedUrl, makeExternalUrl } from './helpers' import { copyTextToClipboard } from 'src/helpers/clipboard' import { useRender } from 'src/components/IdeWrapper/useRender' import { toast } from '@redwoodjs/web/toast' const ExternalScript = () => { const { state, thunkDispatch } = useIdeContext() const handleRender = useRender() const [rawUrl, setRawUrl] = useState('') const [script, setScript] = useState('') const [asyncState, setAsyncState] = useState<'INIT' | 'SUCCESS' | 'ERROR' | 'LOADING'>('INIT') const cadName = ideTypeNameMap[state.ideType] const onPaste: React.ClipboardEventHandler = async ({ clipboardData, }) => { const url = clipboardData.getData('Text') processUserUrl(url) } const onChange: React.ChangeEventHandler = async ({ target, }) => setRawUrl(target.value) const onKeyDown = async ({ key, target }) => key === 'Enter' && processUserUrl(target.value) async function processUserUrl(url: string) { setRawUrl(url) try { setAsyncState('LOADING') const response = await fetch(prepareEncodedUrl(url)) if (response.status === 404) throw new Error("couldn't find script") const script2 = await response.text() if (script2.startsWith('')) throw new Error('got html document, not a script') setScript(script2) setAsyncState('SUCCESS') } catch (e) { setAsyncState('ERROR') toast.error( "We had trouble with you're URL, are you sure it was correct?" ) } } const onCopyRender: React.MouseEventHandler = () => { copyTextToClipboard(makeExternalUrl(rawUrl)) thunkDispatch({ type: 'updateCode', payload: script }) setTimeout(handleRender) } return (

Paste an external url containing a {cadName} script to generate a new CadHub url for this resource.{' '} Learn more {' '} about this feature.

{['INIT', 'ERROR'].includes(asyncState) && ( <>

Paste url

)} {asyncState === 'ERROR' && (

That didn't work, try again.

)} {asyncState === 'LOADING' && (
)} {asyncState === 'SUCCESS' && ( <>
)}
) } export default ExternalScript