Certainly! Below is the complete code for both the Home.js component and the newly created Sidebar.js component, along with the necessary CSS files.
1. Home.js
import React, { useState, useEffect } from 'react';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import Sidebar from '../components/Sidebar'; // Import the Sidebar component
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 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.2.5: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.');
}
};
// Form Submit for Search
const handleSubmit = async (event) => {
event.preventDefault();
if (!searchTerm.trim()) {
setError('Please enter a search term.');
return;
}
setIsLoading(true);
setError(null);
try {
const response = await fetch(
`http://192.168.2.5: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);
} 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.2.5:3006/files/${encodeURIComponent(relativePath)}#page=${page}`;
window.open(pdfUrl, '_blank');
};
return (
<div className="app-container">
<Navbar />
<div className="main-layout">
<Sidebar /> {/* Add the Sidebar here */}
<main>
{/* Search Form */}
<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>}
{/* Search Results */}
<div className="results-container">
{isLoading ? (
<p className="loading">Loading results...</p>
) : searchResults.length > 0 ? (
<div className="scrollable-container">
<p className="total-matches">Total documents: {searchResults.length}</p>
{searchResults.map((result, index) => (
<ResultCard
key={index}
result={result}
handleSnippetClick={handleSnippetClick}
onAddToLibrary={handleAddToLibrary}
searchTerm={searchTerm}
cardNumber={index + 1}
/>
))}
</div>
) : (
<p>No results found</p>
)}
</div>
</main>
</div>
<Footer />
</div>
);
};
const ResultCard = ({ result, handleSnippetClick, onAddToLibrary, searchTerm, cardNumber }) => {
const [isExpanded, setIsExpanded] = useState(false);
return (
<div className="result-card">
<div className="result-header">
<h3 className="filename">
<span className="card-number">{cardNumber}</span> {/* Display card number */}
<a
href={`http://192.168.2.5:3006/files/${result.relativePath}`}
target="_blank"
rel="noopener noreferrer"
>
{result.Filename.split('\\').pop()}
</a>
</h3>
<button
className="add-to-library-button"
onClick={() => onAddToLibrary(result)} // Call add to library function
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>Keyword Matches:</h4>
{result.matches.slice(0, 1).map((match, index) => ( // Show one snippet initially
<div key={index} className="match-snippet">
<strong>{match.keyword} (Page {match.page}):</strong>{' '}
<span
className="snippet-text"
dangerouslySetInnerHTML={{
__html: match.snippet.replace(
new RegExp(`(${match.keyword})`, 'gi'),
'<b>$1</b>' // Bold matching keyword
),
}}
onClick={() => handleSnippetClick(result.relativePath, match.page)} // Clickable snippet
/>
</div>
))}
{isExpanded ? (
result.matches.slice(1).map((match, index) => ( // Show additional snippets if expanded
<div key={index} className="match-snippet">
<strong>{match.keyword} (Page {match.page }):</strong>{' '}
<span
className="snippet-text"
dangerouslySetInnerHTML={{
__html: match.snippet.replace(
new RegExp(`(${match.keyword})`, 'gi'),
'<b>$1</b>' // Bold matching keyword
),
}}
onClick={() => handleSnippetClick(result.relativePath, match.page)} // Clickable snippet
/>
</div>
))
) : null}
{result.matches.length > 1 && (
<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;
2. Sidebar.js
Create a new file named Sidebar.js in the components directory:
import React from 'react';
import './Sidebar.css'; // Create a separate CSS file for sidebar styles
const Sidebar = () => {
return (
<div className="sidebar">
<div className="logo-container">
<img src="path_to_your_logo" alt="Logo" className="logo" /> {/* Replace with actual logo path */}
</div>
<h3>Search Options</h3>
<div className="search-dropdown">
<select>
<option value="">Select search option</option>
<option value="keyword">Keyword Search</option>
<option value="phrase">Phrase Search</option>
<option value="boolean">Boolean Search</option>
<option value="exclude">Exclude Keyword</option>
</select>
</div>
</div>
);
};
export default Sidebar;
3. Home.css
Here’s the CSS for the Home.js layout. Create or update Home.css as follows:
.app-container {
display: flex;
flex-direction: column;
min-height: 100vh; /* Ensure the container takes full height */
}
.main-layout {
display: flex; /* Use flexbox for layout */
margin-top: 100px; /* Adjust based on your Navbar height */
}
main {
margin-left: 250px; /* Adjust for sidebar width */
padding: 20px; /* Padding around the main content */
flex-grow: 1; /* Allow main content to fill space */
}
/* Add remaining styles based on your existing Home.css */
4. Sidebar.css
Create a new file named Sidebar.css in the components directory for the sidebar styles:
.sidebar {
width: 250px; /* Width of the sidebar */
background-color: #f1f1f1; /* Background color of sidebar */
padding: 20px; /* Padding inside sidebar */
position: fixed; /* Fix the sidebar on the left */
height: 100%; /* Full height */
overflow: auto; /* Enable scrolling if necessary */
}
.logo-container {
margin-bottom: 20px; /* Space below the logo */
}
.logo {
max-width: 100%; /* Make logo responsive */
height: auto;
}
.search-dropdown {
margin-top: 20px; /* Margin above dropdown */
}
Summary
You now have the complete code for:
- Home.js: The main component where users can search documents.
- Sidebar.js: A sidebar component that provides search options and a logo.
- Home.css: Styles for the main layout of the application.
- Sidebar.css: Styles specifically for the sidebar.
Make sure to replace "path_to_your_logo" in Sidebar.js with the actual path to your logo image. Additionally, ensure all components are correctly imported and organized in your project structure. If you have further questions or need more modifications, feel free to ask!