Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 10x 10x 10x 10x 10x 10x 10x 19x 19x 19x 19x 1x 1x 1x 1x 1x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 19x 11x 11x 11x 11x 11x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 6x 13x 19x 19x 19x 19x 19x 19x 19x 19x 11x 11x 11x 11x 11x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 2x 9x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x | import { DRAWER_INDEX, PANEL } from '@/constants/common';
import { useAppContext } from '@/context';
import { i18n } from '@/helpers/i18n';
import { formatTimestamp } from '@/helpers/utils';
import { clearSearchHistory, getSearchHistory } from '@/utils/idbCache';
import DeleteIcon from '@mui/icons-material/Delete';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import FilterListIcon from '@mui/icons-material/FilterList';
import {
Accordion,
Box,
IconButton,
Link,
List,
ListItem,
ListItemText,
Tooltip,
Typography,
} from '@mui/material';
import { FC, SyntheticEvent, useEffect, useState } from 'react';
import ExportsPanel from './ExportsPanel';
import styles from './HistoryPanel.module.scss';
import { StyledAccordionDetailsNoPadding, StyledAccordionSummary } from './StyledComponents';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
const logger = new Logger('HistoryPanel');
/**
* HistoryPanel component that displays past search queries,
* when they were executed, and how many results were returned.
* History is persisted in `chrome.storage.local` (same mechanism as user settings / cache).
* Clicking a query re-triggers the search via the app context's `pendingSearchQuery`.
*
* @example
* ```tsx
* // Rendered inside the drawer's tab panel:
* <HistoryPanel />
* // Displays:
* // 3 searches
* // acetone Mar 26, 2:15 PM — 12 results
* // sodium chloride Mar 25, 9:00 AM — 8 results
* // benzene Mar 24, 4:30 PM — 5 results
* ```
* @category Components
* @source
*/
const HistoryPanel: FC = () => {
const [history, setHistory] = useState<SearchHistoryEntry[]>([]);
const [expandedSection, setExpandedSection] = useState<'history' | 'exports' | false>('history');
const {
setPendingSearchQuery,
setDrawerTab,
setSearchFilters,
setSelectedSuppliers,
setPanel,
userSettings,
setUserSettings,
} = useAppContext();
/**
* Returns an MUI Accordion `onChange` handler that opens the given section and
* collapses the other (single-open accordion behavior).
* @param section - The section this handler controls.
* @returns The Accordion change handler.
* @source
*/
const handleSectionChange =
(section: 'history' | 'exports') => (_event: SyntheticEvent, isExpanded: boolean) => {
setExpandedSection(isExpanded ? section : false);
};
useEffect(() => {
const loadHistory = async () => {
try {
const entries = await getSearchHistory();
setHistory(entries);
} catch (error) {
logger.warn(`Failed to load search history: ${getErrorMessage(error)}`, { error });
}
};
loadHistory();
}, []);
/**
* Clears all search history entries from both local state and
* `chrome.storage.local`, resetting the panel to its empty state.
* @example
* ```ts
* handleClearHistory();
* // chrome.storage.local.search_history => []
* // UI shows "No search history yet."
* ```
* @source
*/
const handleClearHistory = async () => {
try {
await clearSearchHistory();
setHistory([]);
} catch (error) {
logger.warn(`Failed to clear search history: ${getErrorMessage(error)}`, { error });
}
};
/**
* Re-executes a previous search by setting the pending search query
* in the app context and closing the drawer.
* @param query - The search term to re-run (e.g. `"sodium chloride"`)
* @example
* ```ts
* handleReSearch("acetone");
* // Sets pendingSearchQuery to "acetone"
* // Sets drawerTab to -1 (closes drawer)
* ```
* @source
*/
const handleReSearch = (entry: SearchHistoryEntry) => {
// Restore filters that were active when this search was originally executed
if (entry.filters) {
setSearchFilters(entry.filters);
}
if (entry.selectedSuppliers) {
setSelectedSuppliers(entry.selectedSuppliers);
// Restore whether the list was an exclusion list; older entries predate the checkbox.
setUserSettings({
...userSettings,
search: {
...userSettings.search,
invertSuppliersSelection:
(entry.excludeSelectedSuppliers ?? false) && entry.selectedSuppliers.length > 0,
},
});
}
setPendingSearchQuery(entry.query);
setDrawerTab(DRAWER_INDEX.CLOSED); // Close the drawer
setPanel?.(PANEL.RESULTS); // Navigate to results panel
};
const getFilterSummary = (entry: SearchHistoryEntry): string | null => {
const parts: string[] = [];
if (entry.filters) {
if (entry.filters.availability.length > 0)
parts.push(i18n('history_filter_availability', [entry.filters.availability.join(', ')]));
if (entry.filters.country.length > 0)
parts.push(i18n('history_filter_country', [entry.filters.country.join(', ')]));
if (entry.filters.shippingType.length > 0)
parts.push(i18n('history_filter_shipping', [entry.filters.shippingType.join(', ')]));
}
if (entry.selectedSuppliers && entry.selectedSuppliers.length > 0) {
parts.push(
i18n(
entry.excludeSelectedSuppliers
? 'history_filter_suppliers_excluded'
: 'history_filter_suppliers',
[String(entry.selectedSuppliers.length)],
),
);
}
return parts.length > 0 ? parts.join('\n') : null;
};
return (
<>
<Accordion expanded={expandedSection === 'history'} onChange={handleSectionChange('history')}>
<StyledAccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography>{i18n('history_section_search')}</Typography>
</StyledAccordionSummary>
<StyledAccordionDetailsNoPadding>
<Box className={styles['history-panel']}>
<Box className={styles['history-panel__header']}>
<Typography variant="caption" color="text.secondary">
{history.length === 1
? i18n('history_count_single', [String(history.length)])
: i18n('history_count_plural', [String(history.length)])}
</Typography>
{history.length > 0 && (
<Tooltip title={i18n('history_clear')}>
<IconButton
size="small"
onClick={handleClearHistory}
className={styles['history-panel__clear-btn']}
>
<DeleteIcon className={styles['history-panel__clear-icon']} />
</IconButton>
</Tooltip>
)}
</Box>
{history.length === 0 ? (
<Typography
variant="caption"
color="text.secondary"
className={styles['history-panel__empty']}
>
{i18n('history_empty')}
</Typography>
) : (
<List dense disablePadding>
{history.map((entry, idx) => (
<ListItem
key={`${entry.timestamp}-${idx}`}
divider
className={styles['history-panel__list-item']}
>
<ListItemText
primary={
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<Link
component="button"
variant="body2"
onClick={() => handleReSearch(entry)}
sx={{ fontWeight: 'bold' }}
className={styles['history-panel__link']}
>
{entry.query}
</Link>
{getFilterSummary(entry) && (
<Tooltip
title={getFilterSummary(entry)!}
sx={{ whiteSpace: 'pre-line' }}
>
<FilterListIcon sx={{ fontSize: 14, color: 'text.secondary' }} />
</Tooltip>
)}
</Box>
}
secondary={`${formatTimestamp(entry.timestamp)} — ${
entry.resultCount === 1
? i18n('history_result_single', [String(entry.resultCount)])
: i18n('history_result_plural', [String(entry.resultCount)])
}`}
slotProps={{
secondary: {
variant: 'caption',
className: styles['history-panel__secondary-text'],
},
}}
className={styles['history-panel__list-item-text']}
/>
</ListItem>
))}
</List>
)}
</Box>
</StyledAccordionDetailsNoPadding>
</Accordion>
<Accordion expanded={expandedSection === 'exports'} onChange={handleSectionChange('exports')}>
<StyledAccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography>{i18n('history_section_exports')}</Typography>
</StyledAccordionSummary>
<StyledAccordionDetailsNoPadding>
<ExportsPanel />
</StyledAccordionDetailsNoPadding>
</Accordion>
</>
);
};
export default HistoryPanel;
|