hii
- User
hii
- Assistant
Hello! How can I assist you today?
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
hii
Hello! How can I assist you today?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import React, { useState, useEffect } from 'react'; import Navbar from '../components/Navbar'; import Footer from '../components/Footer'; import { useNavigate } from 'react-router-dom'; import './Home.css';
const Home = () => { const [searchTerm, setSearchTerm] = useState(''); const [excludeWords, setExcludeWords] = useState(''); const [searchResults, setSearchResults] = useState([]); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false);
const [totalMatches, setTotalMatches] = useState(0);
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem('token');
if (!token) {
console.log("User is not logged in");
}
}, []);
// Handle search term input
const handleSearchTermChange = (event) => {
setSearchTerm(event.target.value);
};
// Handle exclude-word input
const handleExcludeWordsChange = (event) => {
setExcludeWords(event.target.value);
};
// Add to Library Action
const handleAddToLibrary = async (pdf) => {
const token = localStorage.getItem('token');
if (!token) {
navigate('/login', {
state: {
message: 'Please log in to add documents to your library',
redirectAfterLogin: '/home',
},
});
return;
}
try {
const response = await fetch('http://192.168.7.206:3006/api/lib/library/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
filename: pdf.relativePath,
originalFilePath: pdf.Filename,
}),
});
if (response.ok) {
alert('Document added to library');
} else {
const errorData = await response.json();
alert(errorData.message || 'Failed to add document to library');
}
} catch (error) {
console.error('Error adding to library:', error);
alert('Network error. Please try again.');
}
};
const handleSubmit = async (event) => {
event.preventDefault();
if (!searchTerm.trim()) {
setError('Please enter a search term.');
return;
}
setIsLoading(true);
setError(null);
setSearchResults([]); // Clear previous results
setTotalMatches(0); // Reset total matches
try {
const response = await fetch(
`http://192.168.7.206:3006/search?keyword=${encodeURIComponent(searchTerm)}&exclude=${encodeURIComponent(
excludeWords || ''
)}`
);
if (!response.ok) {
throw new Error('Failed to fetch search results');
}
const data = await response.json();
setSearchResults(data);
setTotalMatches(data.length);
} catch (error) {
console.error(error);
setError('Error fetching search results.');
} finally {
setIsLoading(false);
}
};
// Handle Snippet Page Redirection
const handleSnippetClick = (relativePath, page) => {
const pdfUrl = `http://192.168.7.206:3006/files/${encodeURIComponent(relativePath)}#page=${page + 1}`;
window.open(pdfUrl, '_blank');
};
return (
<div className="app-container">
<Navbar />
<main>
<form onSubmit={handleSubmit} className="search-form">
<input
type="text"
placeholder="Enter search term"
value={searchTerm}
onChange={handleSearchTermChange}
className="search-input"
/>
<input
type="text"
placeholder="Exclude words (optional)"
value={excludeWords}
onChange={handleExcludeWordsChange}
className="exclude-input"
/>
<button
type="submit"
className="search-button"
disabled={isLoading}
>
{isLoading ? 'Searching...' : 'Search'}
</button>
</form>
{/* Error Message */}
{error && <p className="error-message">{error}</p>}
{/* Loading or Total Matches */}
{isLoading && !error && (
<p className="loading">
There are <strong>{totalMatches || '...'}</strong> matches for your search. Please wait...
</p>
)}
{/* Search Results */}
<div className="results-container">
{!isLoading && totalMatches > 0 && (
<p className="total-matches">
Total Documents Found: <strong>{totalMatches}</strong>
</p>
)}
{!isLoading && searchResults.length > 0 ? (
<div className="scrollable-container">
{searchResults.map((result, index) => (
<ResultCard
key={index}
index={index + 1} // Add index to card
result={result}
handleSnippetClick={handleSnippetClick}
onAddToLibrary={handleAddToLibrary}
searchTerm={searchTerm}
/>
))}
</div>
) : !isLoading && <p>No results found</p>}
</div>
</main>
<Footer />
</div>
);
};
const ResultCard = ({ result, index, handleSnippetClick, onAddToLibrary, searchTerm }) => { const [isExpanded, setIsExpanded] = useState(false);
return (
<div className="result-card">
<div className="result-header">
<h3 className="filename">
<span className="index">{index}.</span>{' '}
<a
href={`http://192.168.7.206:3006/files/${result.relativePath}`}
target="_blank"
rel="noopener noreferrer"
>
{result.Filename.split('\\').pop()}
</a>
</h3>
<button
className="add-to-library-button"
onClick={() => onAddToLibrary(result)}
title="Add to Library"
>
Add
</button>
</div>
<p className="relative-path">
<strong>Location:</strong> {result.relativePath}
</p>
{result.matches.length > 0 ? (
<div className="matches">
<h4>Matches:</h4>
<div
className="match-snippet"
onClick={() =>
handleSnippetClick(result.relativePath, result.matches[0].page)
}
>
<strong>Page {result.matches[0].page + 1}:</strong>{' '}
<span
className="snippet-text"
dangerouslySetInnerHTML={{
__html: result.matches[0].snippet.replace(
new RegExp(`(${searchTerm})`, 'gi'),
'<b>$1</b>' // Bold matching keyword
),
}}
/>
</div>
{result.matches.length > 1 && (
<>
{isExpanded &&
result.matches.slice(1).map((match, matchIndex) => (
<div
key={matchIndex}
className="match-snippet"
onClick={() =>
handleSnippetClick(result.relativePath, match.page)
}
>
<strong>Page {match.page + 1}:</strong>{' '}
<span
className="snippet-text"
dangerouslySetInnerHTML={{
__html: match.snippet.replace(
new RegExp(`(${searchTerm})`, 'gi'),
'<b>$1</b>' // Bold matching keyword
),
}}
/>
</div>
))}
<button
className="toggle-matches-btn"
onClick={() => setIsExpanded(!isExpanded)}
>
{isExpanded ? 'Show Less' : `Show More (${result.matches.length - 1})`}
</button>
</>
)}
</div>
) : (
<p className="no-matches">No matches found in this file.</p>
)}
</div>
);
};
export default Home; in this when i serach like profit + loss it is seraching but not highlight profit loss terms ....menas it only highlights phrse like if i serach profit of loss ....i want to highlight boolean results also..highlight boththe terms provde same resukts like pahes for them both also
To achieve the desired behavior of highlighting each term in a search query (including cases where you use boolean logic like "profit + loss"), you'll need to modify the regex used for highlighting the search terms in your ResultCard component.
Given the requirement, you can split the search term by any whitespace and boolean operators (like +, -, etc.) to create a list of terms to highlight. Then, you can construct a regex pattern that matches any of those terms.
Here’s how you can do that:
ResultCard Component:
Update the ResultCard to handle keyword splitting and regex construction for highlighting.Here’s the modified ResultCard component that includes the new highlighting behavior:
const ResultCard = ({ result, index, handleSnippetClick, onAddToLibrary, searchTerm }) => {
const [isExpanded, setIsExpanded] = useState(false);
// Function to create a regex pattern from search terms
const createHighlightRegex = (term) => {
const terms = term
.split(/\s*[\+\-]\s*|\s+/) // Split by spaces and boolean operators
.filter(Boolean); // Remove empty strings
// Create a regex that matches any of the terms, case insensitive
return new RegExp(`(${terms.join('|')})`, 'gi');
};
const highlightTerms = (text) => {
const highlightRegex = createHighlightRegex(searchTerm);
return text.replace(
highlightRegex,
'<b>$1</b>' // Bold matching keyword
);
};
return (
<div className="result-card">
<div className="result-header">
<h3 className="filename">
<span className="index">{index}.</span>{' '}
<a
href={`http://192.168.7.206:3006/files/${result.relativePath}`}
target="_blank"
rel="noopener noreferrer"
>
{result.Filename.split('\\').pop()}
</a>
</h3>
<button
className="add-to-library-button"
onClick={() => onAddToLibrary(result)}
title="Add to Library"
>
Add
</button>
</div>
<p className="relative-path">
<strong>Location:</strong> {result.relativePath}
</p>
{result.matches.length > 0 ? (
<div className="matches">
<h4>Matches:</h4>
<div
className="match-snippet"
onClick={() =>
handleSnippetClick(result.relativePath, result.matches[0].page)
}
>
<strong>Page {result.matches[0].page + 1}:</strong>{' '}
<span
className="snippet-text"
dangerouslySetInnerHTML={{
__html: highlightTerms(result.matches[0].snippet),
}}
/>
</div>
{result.matches.length > 1 && (
<>
{isExpanded &&
result.matches.slice(1).map((match, matchIndex) => (
<div
key={matchIndex}
className="match-snippet"
onClick={() =>
handleSnippetClick(result.relativePath, match.page)
}
>
<strong>Page {match.page + 1}:</strong>{' '}
<span
className="snippet-text"
dangerouslySetInnerHTML={{
__html: highlightTerms(match.snippet),
}}
/>
</div>
))}
<button
className="toggle-matches-btn"
onClick={() => setIsExpanded(!isExpanded)}
>
{isExpanded ? 'Show Less' : `Show More (${result.matches.length - 1})`}
</button>
</>
)}
</div>
) : (
<p className="no-matches">No matches found in this file.</p>
)}
</div>
);
};
createHighlightRegex: This function splits the search term by both spaces and Boolean operators (+, -) and generates a regex pattern to match them.
highlightTerms: This function applies the highlighting to a given snippet by using dangerouslySetInnerHTML. It calls the createHighlightRegex to get the correct regex.
dangerouslySetInnerHTML can expose your app to XSS (Cross-Site Scripting) vulnerabilities if the content is not sanitized. Ensure that the snippets you receive from the backend are safe before inserting them into the DOM.After adding these modifications, you should see both "profit" and "loss" being highlighted when you search for "profit + loss".