forked from stackblitz/bolt.new
-
Notifications
You must be signed in to change notification settings - Fork 10.1k
feat: web search feature #1703
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
migavel508
wants to merge
2
commits into
stackblitz-labs:main
Choose a base branch
from
migavel508:web-search-feature
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: web search feature #1703
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
import { useState } from 'react'; | ||
import { IconButton } from '~/components/ui/IconButton'; | ||
import { toast } from 'react-toastify'; | ||
|
||
interface WebSearchProps { | ||
onSearchResult: (result: string) => void; | ||
disabled?: boolean; | ||
} | ||
|
||
interface WebSearchResponse { | ||
success: boolean; | ||
data?: { | ||
title: string; | ||
description: string; | ||
mainContent: string; | ||
codeBlocks: string[]; | ||
relevantLinks: Array<{ | ||
url: string; | ||
text: string; | ||
}>; | ||
sourceUrl: string; | ||
}; | ||
error?: string; | ||
} | ||
|
||
export const WebSearch = ({ onSearchResult, disabled = false }: WebSearchProps) => { | ||
const [isSearching, setIsSearching] = useState(false); | ||
|
||
const formatSearchResult = (data: WebSearchResponse['data']) => { | ||
if (!data) { | ||
return ''; | ||
} | ||
|
||
let result = `# Web Search Results from ${data.sourceUrl}\n\n`; | ||
result += `## ${data.title}\n\n`; | ||
|
||
if (data.description) { | ||
result += `**Description:** ${data.description}\n\n`; | ||
} | ||
|
||
result += `**Main Content:**\n${data.mainContent}\n\n`; | ||
|
||
if (data.codeBlocks.length > 0) { | ||
result += `## Code Examples\n\n`; | ||
data.codeBlocks.forEach((block, _index) => { | ||
result += `\`\`\`\n${block}\n\`\`\`\n\n`; | ||
}); | ||
} | ||
|
||
if (data.relevantLinks.length > 0) { | ||
result += `## Relevant Links\n\n`; | ||
data.relevantLinks.forEach((link) => { | ||
result += `- [${link.text}](${link.url})\n`; | ||
}); | ||
} | ||
|
||
return result; | ||
}; | ||
|
||
const handleWebSearch = async () => { | ||
if (disabled) { | ||
return; | ||
} | ||
|
||
try { | ||
setIsSearching(true); | ||
|
||
const url = window.prompt('Enter URL to search:'); | ||
|
||
if (!url) { | ||
setIsSearching(false); | ||
return; | ||
} | ||
|
||
const formData = new FormData(); | ||
formData.append('url', url); | ||
|
||
const response = await fetch('/api-web-search', { | ||
method: 'POST', | ||
body: formData, | ||
}); | ||
|
||
const data = (await response.json()) as WebSearchResponse; | ||
|
||
if (!response.ok) { | ||
throw new Error(data.error || 'Failed to perform web search'); | ||
} | ||
|
||
if (!data.data) { | ||
throw new Error('No data received from web search'); | ||
} | ||
|
||
const formattedResult = formatSearchResult(data.data); | ||
onSearchResult(formattedResult); | ||
toast.success('Web search completed successfully'); | ||
} catch (error) { | ||
console.error('Web search error:', error); | ||
toast.error('Failed to perform web search: ' + (error instanceof Error ? error.message : 'Unknown error')); | ||
} finally { | ||
setIsSearching(false); | ||
} | ||
}; | ||
|
||
return ( | ||
<IconButton | ||
title="Web Search" | ||
disabled={disabled || isSearching} | ||
onClick={handleWebSearch} | ||
className="transition-all" | ||
> | ||
{isSearching ? ( | ||
<div className="i-svg-spinners:90-ring-with-bg text-bolt-elements-loader-progress text-xl animate-spin"></div> | ||
) : ( | ||
<div className="i-ph:globe text-xl"></div> | ||
)} | ||
</IconButton> | ||
); | ||
}; |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
import { json } from '@remix-run/node'; | ||
import type { ActionFunctionArgs } from '@remix-run/node'; | ||
|
||
export async function action({ request }: ActionFunctionArgs) { | ||
try { | ||
const formData = await request.formData(); | ||
const url = formData.get('url') as string; | ||
|
||
if (!url) { | ||
return json({ error: 'URL is required' }, { status: 400 }); | ||
} | ||
|
||
// Add proper headers to handle CORS and content type | ||
const response = await fetch(url, { | ||
headers: { | ||
'User-Agent': | ||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', | ||
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', | ||
'Accept-Language': 'en-US,en;q=0.5', | ||
}, | ||
}); | ||
|
||
if (!response.ok) { | ||
throw new Error(`Failed to fetch URL: ${response.status} ${response.statusText}`); | ||
} | ||
|
||
const contentType = response.headers.get('content-type'); | ||
|
||
if (!contentType?.includes('text/html')) { | ||
throw new Error('URL must point to an HTML page'); | ||
} | ||
|
||
const html = await response.text(); | ||
|
||
// Extract title | ||
const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i); | ||
const title = titleMatch ? titleMatch[1].trim() : 'No title found'; | ||
|
||
// Extract meta description | ||
const descriptionMatch = html.match(/<meta[^>]*name="description"[^>]*content="([^"]*)"[^>]*>/i); | ||
const description = descriptionMatch ? descriptionMatch[1].trim() : ''; | ||
|
||
// Extract main content | ||
const mainContent = html | ||
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '') | ||
.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '') | ||
.replace(/<[^>]+>/g, ' ') | ||
.replace(/\s+/g, ' ') | ||
.trim(); | ||
|
||
// Extract code blocks | ||
const codeBlocks = html.match(/<pre[^>]*>[\s\S]*?<\/pre>|<code[^>]*>[\s\S]*?<\/code>/gi) || []; | ||
const formattedCodeBlocks = codeBlocks.map((block) => { | ||
return block | ||
.replace(/<[^>]+>/g, '') | ||
.replace(/</g, '<') | ||
.replace(/>/g, '>') | ||
.replace(/&/g, '&') | ||
.trim(); | ||
}); | ||
|
||
// Extract links | ||
const links = html.match(/<a[^>]*href="([^"]*)"[^>]*>([^<]*)<\/a>/gi) || []; | ||
const formattedLinks = links.map((link) => { | ||
const hrefMatch = link.match(/href="([^"]*)"/i); | ||
const textMatch = link.match(/>([^<]*)</i); | ||
|
||
return { | ||
url: hrefMatch ? hrefMatch[1] : '', | ||
text: textMatch ? textMatch[1].trim() : '', | ||
}; | ||
}); | ||
|
||
// Structure the content for code generation | ||
const structuredContent = { | ||
title, | ||
description, | ||
mainContent: mainContent.slice(0, 1000) + '...', | ||
codeBlocks: formattedCodeBlocks, | ||
relevantLinks: formattedLinks.filter( | ||
(link) => link.url && !link.url.startsWith('#') && !link.url.startsWith('javascript:') && link.text.trim(), | ||
), | ||
sourceUrl: url, | ||
}; | ||
|
||
return json({ | ||
success: true, | ||
data: structuredContent, | ||
}); | ||
} catch (error) { | ||
console.error('Web search error:', error); | ||
return json({ error: error instanceof Error ? error.message : 'Unknown error occurred' }, { status: 500 }); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { json } from '@remix-run/node'; | ||
import type { ActionFunctionArgs } from '@remix-run/node'; | ||
|
||
export async function action({ request }: ActionFunctionArgs) { | ||
try { | ||
const formData = await request.formData(); | ||
const url = formData.get('url') as string; | ||
|
||
if (!url) { | ||
return json({ error: 'URL is required' }, { status: 400 }); | ||
} | ||
|
||
const response = await fetch(url); | ||
|
||
if (!response.ok) { | ||
throw new Error(`Failed to fetch URL: ${response.status} ${response.statusText}`); | ||
} | ||
|
||
const html = await response.text(); | ||
|
||
// Basic HTML parsing to extract title and content | ||
const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i); | ||
const title = titleMatch ? titleMatch[1].trim() : 'No title found'; | ||
|
||
// Extract content by removing script and style tags, then getting text content | ||
const content = | ||
html | ||
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '') | ||
.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '') | ||
.replace(/<[^>]+>/g, ' ') | ||
.replace(/\s+/g, ' ') | ||
.trim() | ||
.slice(0, 1000) + '...'; // Limit content length | ||
|
||
return json({ | ||
success: true, | ||
data: { | ||
title, | ||
content, | ||
url, | ||
}, | ||
}); | ||
} catch (error) { | ||
console.error('Web search error:', error); | ||
return json({ error: error instanceof Error ? error.message : 'Unknown error occurred' }, { status: 500 }); | ||
} | ||
} |
Empty file.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Both api-web-search.ts and web-search.ts are doing the same job fetching a list of search results (title, content, and URL).