From 38e6a79b385cafb151e418d5bf64fddbebde55df Mon Sep 17 00:00:00 2001 From: Connor Fogarty <40175891+connorff@users.noreply.github.com> Date: Mon, 5 Aug 2024 09:49:02 -0500 Subject: [PATCH] feat: add ability to change preview URL (#26) --- .../bolt/app/components/workbench/Preview.tsx | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/bolt/app/components/workbench/Preview.tsx b/packages/bolt/app/components/workbench/Preview.tsx index 840dfe2..9fde25e 100644 --- a/packages/bolt/app/components/workbench/Preview.tsx +++ b/packages/bolt/app/components/workbench/Preview.tsx @@ -1,10 +1,11 @@ import { useStore } from '@nanostores/react'; -import { memo, useEffect, useRef, useState } from 'react'; +import { memo, useCallback, useEffect, useRef, useState } from 'react'; import { IconButton } from '~/components/ui/IconButton'; import { workbenchStore } from '~/lib/stores/workbench'; export const Preview = memo(() => { const iframeRef = useRef(null); + const inputRef = useRef(null); const [activePreviewIndex] = useState(0); const previews = useStore(workbenchStore.previews); const activePreview = previews[activePreviewIndex]; @@ -28,6 +29,25 @@ export const Preview = memo(() => { } }, [activePreview, iframeUrl]); + const validateUrl = useCallback( + (value: string) => { + if (!activePreview) { + return false; + } + + const { baseUrl } = activePreview; + + if (value === baseUrl) { + return true; + } else if (value.startsWith(baseUrl)) { + return ['/', '?', '#'].includes(value.charAt(baseUrl.length)); + } + + return false; + }, + [activePreview], + ); + const reloadPreview = () => { if (iframeRef.current) { iframeRef.current.src = iframeRef.current.src; @@ -43,12 +63,22 @@ export const Preview = memo(() => {
{ setUrl(event.target.value); }} + onKeyDown={(event) => { + if (event.key === 'Enter' && validateUrl(url)) { + setIframeUrl(url); + + if (inputRef.current) { + inputRef.current.blur(); + } + } + }} />