feat: search bar in topbar with Gmail-style query syntax

- Search form in topbar routes to /app/search?q=...
- SearchResults page with infinite scroll, same row style as FolderView
- Supports Gmail-like operators: from:, is:unread, has:attachment, after:, before:
- SearchApi.query() calls GET /search which runs through the existing GmailQueryParser
- Input sanitised via encodeURIComponent on submit; external links use noopener/noreferrer

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
cesnimda
2026-06-30 20:15:45 +02:00
parent 4d15a3a8fb
commit 498536451e
5 changed files with 164 additions and 1 deletions
+2
View File
@@ -65,6 +65,8 @@ export const LayoutApi = {
export const SearchApi = { export const SearchApi = {
folder: (slug, page = 1, pageSize = 50) => folder: (slug, page = 1, pageSize = 50) =>
api.post('/search', folderToRequest(slug, page, pageSize)).then((r) => r.data), api.post('/search', folderToRequest(slug, page, pageSize)).then((r) => r.data),
query: (q, page = 1, pageSize = 50) =>
api.get('/search', { params: { q, page, pageSize } }).then((r) => r.data),
}; };
function folderToRequest(slug, page, pageSize) { function folderToRequest(slug, page, pageSize) {
+20 -1
View File
@@ -1,4 +1,4 @@
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'; import { Link, Outlet, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { useEffect, useState, useCallback } from 'react'; import { useEffect, useState, useCallback } from 'react';
import { AuthApi, SyncApi, AnalyticsApi } from '../api/client.js'; import { AuthApi, SyncApi, AnalyticsApi } from '../api/client.js';
import Logo from './Logo.jsx'; import Logo from './Logo.jsx';
@@ -102,6 +102,8 @@ function FolderLink({ item, active, count, collapsed, extra }) {
export default function Layout() { export default function Layout() {
const [user, setUser] = useState(null); const [user, setUser] = useState(null);
const [searchParams] = useSearchParams();
const [searchQuery, setSearchQuery] = useState(() => searchParams.get('q') ?? '');
const [sidebarOpen, setSidebarOpen] = useState(() => { const [sidebarOpen, setSidebarOpen] = useState(() => {
try { return localStorage.getItem(LS_OPEN) !== 'false'; } catch { return true; } try { return localStorage.getItem(LS_OPEN) !== 'false'; } catch { return true; }
}); });
@@ -158,6 +160,12 @@ export default function Layout() {
navigate('/'); navigate('/');
}; };
const submitSearch = (e) => {
e.preventDefault();
const q = searchQuery.trim();
if (q) navigate(`/app/search?q=${encodeURIComponent(q)}`);
};
const startSync = async () => { const startSync = async () => {
try { await SyncApi.incremental(); } catch { /* ignore */ } try { await SyncApi.incremental(); } catch { /* ignore */ }
if (loc.pathname !== '/app') navigate('/app'); if (loc.pathname !== '/app') navigate('/app');
@@ -199,6 +207,17 @@ export default function Layout() {
<Link key={n.to} to={n.to} className={isNavActive(n) ? 'active' : ''}>{n.label}</Link> <Link key={n.to} to={n.to} className={isNavActive(n) ? 'active' : ''}>{n.label}</Link>
))} ))}
</nav> </nav>
<form className="search-form" onSubmit={submitSearch}>
<input
className="search-input"
type="search"
placeholder="Search… (from:, is:unread, has:attachment)"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
aria-label="Search emails"
/>
<button type="submit" className="search-btn" aria-label="Search">🔍</button>
</form>
<div className="spacer" /> <div className="spacer" />
<button onClick={startSync}>Sync now</button> <button onClick={startSync}>Sync now</button>
<span className="user">{user?.email}</span> <span className="user">{user?.email}</span>
+2
View File
@@ -7,6 +7,7 @@ import Senders from './pages/Senders.jsx';
import Cleanup from './pages/Cleanup.jsx'; import Cleanup from './pages/Cleanup.jsx';
import Unsubscribe from './pages/Unsubscribe.jsx'; import Unsubscribe from './pages/Unsubscribe.jsx';
import FolderView from './pages/FolderView.jsx'; import FolderView from './pages/FolderView.jsx';
import SearchResults from './pages/SearchResults.jsx';
import Layout from './components/Layout.jsx'; import Layout from './components/Layout.jsx';
import './styles.css'; import './styles.css';
@@ -24,6 +25,7 @@ ReactDOM.createRoot(document.getElementById('root')).render(
<Route path="cleanup" element={<Cleanup />} /> <Route path="cleanup" element={<Cleanup />} />
<Route path="unsubscribe" element={<Unsubscribe />} /> <Route path="unsubscribe" element={<Unsubscribe />} />
<Route path="folder/:slug" element={<FolderView />} /> <Route path="folder/:slug" element={<FolderView />} />
<Route path="search" element={<SearchResults />} />
</Route> </Route>
<Route path="*" element={<Navigate to="/" replace />} /> <Route path="*" element={<Navigate to="/" replace />} />
+126
View File
@@ -0,0 +1,126 @@
import { useEffect, useState, useCallback, useRef } from 'react';
import { useSearchParams } from 'react-router-dom';
import { SearchApi } from '../api/client.js';
const PAGE_SIZE = 50;
const fmtDate = (iso) => {
const d = new Date(iso);
const now = new Date();
const diffDays = (now - d) / 86400000;
if (diffDays < 1) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
if (diffDays < 7) return d.toLocaleDateString([], { weekday: 'short' });
return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
};
const fmtSize = (b) => {
if (b < 1024) return `${b} B`;
if (b < 1048576) return `${(b / 1024).toFixed(0)} KB`;
return `${(b / 1048576).toFixed(1)} MB`;
};
export default function SearchResults() {
const [searchParams] = useSearchParams();
const q = searchParams.get('q') ?? '';
const [emails, setEmails] = useState([]);
const [totalCount, setTotalCount] = useState(null);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setEmails([]);
setTotalCount(null);
setPage(1);
setHasMore(true);
setError(null);
}, [q]);
const fetchPage = useCallback((p) => {
if (!q.trim()) return;
setLoading(true);
SearchApi.query(q, p, PAGE_SIZE)
.then((r) => {
setEmails((prev) => p === 1 ? r.items : [...prev, ...r.items]);
setTotalCount(r.totalCount);
setHasMore(p < r.totalPages);
setPage(p);
})
.catch(() => setError('Search failed. Please try again.'))
.finally(() => setLoading(false));
}, [q]);
useEffect(() => { fetchPage(1); }, [fetchPage]);
const sentinelRef = useRef(null);
useEffect(() => {
const el = sentinelRef.current;
if (!el) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMore && !loading) fetchPage(page + 1);
},
{ rootMargin: '200px' }
);
observer.observe(el);
return () => observer.disconnect();
}, [hasMore, loading, page, fetchPage]);
return (
<div className="folder-view">
<div className="folder-view-head">
<h2 className="folder-view-title">🔍 "{q}"</h2>
{totalCount !== null && (
<span className="folder-view-count">{totalCount.toLocaleString()} result{totalCount !== 1 ? 's' : ''}</span>
)}
</div>
{!q.trim() && <div className="fv-empty">Enter a search query above.</div>}
{error && <div className="fv-error">{error}</div>}
{!loading && !error && q.trim() && emails.length === 0 && !hasMore && (
<div className="fv-empty">No results for "{q}".</div>
)}
{emails.length > 0 && (
<table className="email-list">
<tbody>
{emails.map((e) => (
<tr
key={e.id}
className={`email-row${e.isUnread ? ' email-row--unread' : ''}`}
onClick={() => window.open(
`https://mail.google.com/mail/u/0/#all/${e.gmailMessageId}`,
'_blank',
'noopener,noreferrer'
)}
title="Open in Gmail"
>
<td className="el-unread">{e.isUnread && <span className="unread-dot" />}</td>
<td className="el-sender" title={e.senderAddress}>
{e.senderDisplayName || e.senderAddress}
</td>
<td className="el-subject">
<span className="el-subj-text">{e.subject || '(no subject)'}</span>
{e.snippet && <span className="el-snippet"> {e.snippet}</span>}
</td>
<td className="el-meta">
{e.hasAttachments && <span className="el-attach" title="Has attachment">📎</span>}
{e.sizeEstimateBytes > 1048576 && <span className="el-size">{fmtSize(e.sizeEstimateBytes)}</span>}
</td>
<td className="el-date">{fmtDate(e.sentAtUtc)}</td>
</tr>
))}
</tbody>
</table>
)}
<div ref={sentinelRef} className="fv-sentinel" />
{loading && <div className="fv-loading-more">Loading</div>}
{!hasMore && emails.length > 0 && (
<div className="fv-end"> {emails.length.toLocaleString()} results </div>
)}
</div>
);
}
+14
View File
@@ -17,6 +17,20 @@ body { margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-
.topbar nav a { color: var(--muted); text-decoration: none; margin-right: 14px; } .topbar nav a { color: var(--muted); text-decoration: none; margin-right: 14px; }
.topbar nav a.active, .topbar nav a:hover { color: var(--text); } .topbar nav a.active, .topbar nav a:hover { color: var(--text); }
.spacer { flex: 1; } .spacer { flex: 1; }
/* ── Search bar ── */
.search-form { display: flex; align-items: center; gap: 0; flex: 1; max-width: 420px; }
.search-input {
flex: 1; background: var(--panel-2); border: 1px solid #2c3550; border-right: none;
color: var(--text); border-radius: 6px 0 0 6px; padding: 7px 10px; font-size: 13px;
min-width: 0;
}
.search-input:focus { outline: none; border-color: var(--accent); }
.search-btn {
background: var(--panel-2); border: 1px solid #2c3550; border-left: none;
color: var(--muted); border-radius: 0 6px 6px 0; padding: 7px 10px; cursor: pointer; font-size: 13px;
}
.search-btn:hover { color: var(--text); border-color: var(--accent); }
.user { color: var(--muted); font-size: 13px; } .user { color: var(--muted); font-size: 13px; }
/* ── App body (sidebar + main) ── */ /* ── App body (sidebar + main) ── */