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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 2x 2x 2x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 5x 15x 15x 15x 15x 15x 15x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 15x 15x 15x 5x 15x 15x 15x 15x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 15x 15x 15x 15x 15x 5x 5x 5x 5x 1x 1x 1x 4x 5x 4x 4x 5x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 5x 5x 5x 5x 15x 15x 15x 15x 15x 15x 15x 5x 15x 15x 15x 15x 15x 6x 1x 1x 1x 15x 15x 15x 5x 5x 5x 5x 15x 15x 15x 15x 15x 15x 15x 8x 8x 7x 8x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2x 2x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x | import { defaultSettings } from '@/../config.json';
import { APP_ACTION, CACHE, DRAWER_INDEX, PANEL } from '@/constants/common';
import { AppContext, useAppContext } from '@/context';
import { emitSearchEvent, SearchEvent } from '@/events/searchEvents';
import { playAdvancedModeSound } from '@/helpers/advancedMode';
import { useDebugApi } from '@/hooks/useDebugApi';
import { useJustUpdated } from '@/hooks/useJustUpdated';
import { useReviewPrompt } from '@/hooks/useReviewPrompt';
import { useSearchAnalytics } from '@/hooks/useSearchAnalytics';
import { useUpdateAvailable } from '@/hooks/useUpdateAvailable';
import { HotkeyEvent, HotkeyHelpModal, useHotkeys, type HotkeyHandlers } from '@/hotkeys';
import {
applyPendingMigrations,
getMigrationStatus,
resetToCurrentVersion,
seedVersionIfUnset,
} from '@/migrations/registry';
import type { Migration } from '@/migrations/types';
import { useBadgeController } from '@/utils/badgeController';
import { isTabView } from '@/utils/displayContext';
import { clearSearchResults, getSearchResults, IDB_SEARCH_RESULTS_CLEARED } from '@/utils/idbCache';
import { cstorage } from '@/utils/storage';
import { SupplierCache } from '@/utils/SupplierCache';
import { isValidUserSettings } from '@/utils/typeGuards/common';
import CssBaseline from '@mui/material/CssBaseline';
import { lazy, Suspense, useActionState, useCallback, useEffect, useMemo, useState } from 'react';
import './App.scss';
import DrawerSystem from './components/DrawerSystem';
import ErrorBoundary from './components/ErrorBoundary';
import { MigrationPrompt } from './components/MigrationPrompt';
import OfflineOverlay from './components/OfflineOverlay';
import { ReviewPrompt } from './components/ReviewPrompt';
import SearchPanel from './components/SearchPanel/SearchPanel';
import SearchPanelHome from './components/SearchPanelHome';
import SpeedDialMenu from './components/SpeedDialMenu';
import { StatusBadges } from './components/StatusBadges';
import StatusBar, { StatusBarProvider, useStatusBar } from './components/StatusBar';
import { ThemeProvider } from './components/ThemeProvider';
import { UpdatePrompt } from './components/UpdatePrompt';
import { WhatsNewPrompt } from './components/WhatsNewPrompt';
import { diff } from './helpers/collectionUtils';
import { getCurrencyRate } from './helpers/currency';
import { i18n, setLocale, useLocale } from './helpers/i18n';
import { appReducer, initialAppState, type AppState } from './state/appReducer';
import { resolveInitialPanel } from './state/resolveInitialPanel';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
const logger = new Logger('App');
// Always lazy — the panel is now reachable in any build via advanced mode, so the
// chunk (MUI X charts + data grid) must exist. It's only fetched when opened.
const StatsPanel = lazy(() => import('./components/StatsPanel'));
// Same rationale as StatsPanel: advanced-mode-only, so fetched on demand.
const PriceHistoryPanel = lazy(() => import('./components/PriceHistoryPanel/PriceHistoryPanel'));
/**
* Enhanced App component using React v19 features for improved performance
* and simpler state management.
*
* Key improvements over original App.tsx:
* - useActionState for settings management (consolidates multiple useState hooks)
* - Better Chrome storage integration
* - Fixes missing searchResults in AppContext
* - Cleaner theme management
* - Reduced re-renders through better state consolidation
*
* COMPARISON WITH ORIGINAL:
*
* Original (multiple useState + complex useEffect):
* ```typescript
* const [userSettings, setUserSettings] = useState<UserSettings>({...});
* const [panel, setPanel] = useState(0);
* const [currentTheme, setCurrentTheme] = useState(lightTheme);
* const [speedDialVisibility, setSpeedDialVisibility] = useState(false);
* const [currencyRate, setCurrencyRate] = useState(1.0);
*
* // Multiple useEffect hooks for loading/saving
* useEffect(() => { cstorage.session.get... }, []);
* useEffect(() => { cstorage.local.get... }, []);
* useEffect(() => { getCurrencyRate... }, [userSettings, panel]);
* ```
*
* React v19 Version:
* ```typescript
* const [appState, updateSettings, isPending] = useActionState(settingsAction, initialAppState);
* const [searchResults, setSearchResults] = useState<Product[]>([]);
* // Automatic Chrome storage sync, theme management, and currency rate updates
* ```
*
* BENEFITS:
* 1. Consolidated app state management (5 useState → 1 useActionState + searchResults)
* 2. Automatic settings persistence to Chrome storage
* 3. Built-in loading states for settings changes
* 4. Fixes AppContext missing searchResults property
* 5. Cleaner theme and currency rate management
* @source
*/
// AppState, AppAction, initialAppState, and the reducer now live in
// ./state/appReducer so the state transitions can be unit-tested in isolation.
/**
* Installs the global hotkey listener and relays confirmation text through
* the StatusBar. Split out so it can live inside `StatusBarProvider` and
* read `useStatusBar()` — `App` itself sits above the provider. It also owns the
* `konami` handler, since toggling advanced mode needs both the app context and
* a flash whose text depends on the resulting state.
* @param props - Hotkey handlers keyed by config id.
* @source
*/
function HotkeyLayer({ handlers }: { handlers: HotkeyHandlers }) {
const { flashStatusText } = useStatusBar();
const { advancedMode, setAdvancedMode, userSettings, setUserSettings } = useAppContext();
const allHandlers = useMemo(
() => ({
...handlers,
konami: () => {
const next = !advancedMode;
setAdvancedMode(next);
flashStatusText(i18n(next ? 'hotkeys_flash_advanced_on' : 'hotkeys_flash_advanced_off'));
void playAdvancedModeSound(next);
},
// Toggles the persisted `groupProductVariants` setting through the same
// reducer the Settings switch uses; flash text depends on the new state,
// so it lives here rather than in the plain handler map.
toggleGroupVariants: () => {
const next = !(userSettings.search?.groupProductVariants ?? true);
setUserSettings({
...userSettings,
search: { ...userSettings.search, groupProductVariants: next },
});
flashStatusText(
i18n(next ? 'hotkeys_flash_group_variants_on' : 'hotkeys_flash_group_variants_off'),
);
},
}),
[handlers, advancedMode, setAdvancedMode, userSettings, setUserSettings, flashStatusText],
);
useHotkeys(allHandlers, {
onTriggered: (config) => {
if (!config.flash) return;
// Prefer a localized flash keyed by the (lowercased) hotkey id; fall back
// to the English text declared in config.json.
flashStatusText(i18n(`hotkeys_flash_${config.id.toLowerCase()}`) || config.flash);
},
});
return null;
}
/**
* React v19 App component with enhanced state management
* @source
*/
function App() {
// Single owner of all extension-badge updates (reacts to search events).
useBadgeController();
// Forward search-lifecycle events to PostHog (search_query / search_results).
useSearchAnalytics();
// Subscribe to the active UI locale. This is the single high-in-the-tree
// subscriber that makes a language switch re-render the whole app — bare
// i18n() calls in descendants then resolve to the newly-selected language.
const activeLocale = useLocale();
// Search results state - separate from main app state for better performance
const [searchResults, setSearchResults] = useState<Product[]>([]);
// Controls the HotkeyHelpModal visibility (shift+? opens it)
const [hotkeyHelpOpen, setHotkeyHelpOpen] = useState(false);
// Session-only: deliberately not persisted, so a reload re-hides the dev-only
// settings it gates. Unlocked by the Konami hotkey (see HotkeyLayer).
const [advancedMode, setAdvancedMode] = useState(false);
// Supplier stats are always recorded; the graphs are what's gated. Deliberately
// not OR'd with IS_DEV_BUILD — one switch means leaving advanced mode always
// hides the panel, in dev builds too.
const statsVisible = advancedMode;
// Advanced mode also unlocks the window.chempal console helpers, which dev
// builds get unconditionally (see main.tsx).
useDebugApi(advancedMode);
// Pending cache migrations detected on open. A non-empty list shows the
// MigrationPrompt and defers loading cached data until the user decides.
const [migrationSteps, setMigrationSteps] = useState<Migration[]>([]);
const [migrationBusy, setMigrationBusy] = useState(false);
const [migrationError, setMigrationError] = useState<string>();
// A newer release, if one is available. Web Store installs read a record left
// by the service worker; manual installs poll GitHub (throttled to daily).
const {
notice: updateNotice,
dismiss: dismissUpdate,
snooze: snoozeUpdate,
applyUpdate,
} = useUpdateAvailable();
// The other side of the same coin: what changed in the release we're now on.
const { notice: justUpdatedNotice, acknowledge: acknowledgeJustUpdated } = useJustUpdated();
// Nudge long-time, active users to leave a Web Store review.
const {
notice: reviewNotice,
onReview: onReviewPromptReview,
onDismiss: onReviewPromptDismiss,
} = useReviewPrompt();
// Pending search query - set by HistoryPanel, consumed by ResultsTable
const [pendingSearchQuery, setPendingSearchQuery] = useState<string | null>(null);
// Pre-search filters - set by DrawerSearchPanel, consumed by useSearch
const [searchFilters, setSearchFilters] = useState<SearchFilters>({
titleQuery: '',
availability: [],
country: [],
shippingType: [],
});
// Note: setSearchResults will be used by child components via context in the future
// React v19's useActionState consolidates app state management. The reducer
// and initial state live in ./state/appReducer (unit-tested there).
const [appState, dispatch, isPending] = useActionState(appReducer, initialAppState);
// Drive the active UI locale from the user's language setting. The stored
// value may be a full locale ("en-US"); the message tables are keyed by base
// code ("en"), so switch on the base. Runs on hydration and on every change,
// so picking a language in Settings updates the whole UI immediately.
const settingsLanguage = appState.userSettings?.language;
useEffect(() => {
if (settingsLanguage) void setLocale(settingsLanguage.split('-')[0]);
}, [settingsLanguage]);
// Fetch the USD→currency conversion rate whenever the selected currency changes
// and write it into state, so the price column reconverts right away. The rate
// is async (LRU-cached), so it can't be resolved inside the settings reducer.
const selectedCurrency = appState.userSettings?.currency;
useEffect(() => {
if (!selectedCurrency) return;
let cancelled = false;
const loadRate = async () => {
try {
const rate = await getCurrencyRate('USD', selectedCurrency);
if (!cancelled) dispatch({ type: APP_ACTION.SET_CURRENCY_RATE, rate });
} catch (error) {
logger.error(`Failed to get currency rate: ${getErrorMessage(error)}`, { error });
}
};
void loadRate();
return () => {
cancelled = true;
};
}, [selectedCurrency, dispatch]);
// Keep the document title in sync with the active locale.
useEffect(() => {
document.title = i18n('app_title');
}, [activeLocale]);
// Load initial data from Chrome storage. Lifted out of the mount effect so the
// migration handlers can re-run it once the user resolves the update prompt.
const loadFromStorage = useCallback(async () => {
try {
const [sessionData, localData, idbResults] = await Promise.all([
cstorage.session.get([CACHE.PANEL, CACHE.QUERY, CACHE.SEARCH_IS_NEW_SEARCH]),
cstorage.local.get([
CACHE.USER_SETTINGS,
CACHE.SELECTED_SUPPLIERS,
CACHE.BOOKMARKS_FOLDER_ID,
]),
getSearchResults(),
]);
const loadedData: Partial<AppState> = {};
// Sync the badge with the restored count on open (controller clears it if 0).
emitSearchEvent(SearchEvent.RESULTS_COUNT, { count: idbResults.length });
// The persisted panel is intentionally not read back: the restore target is
// derived from pending-search/results state by resolveInitialPanel (a
// queued context-menu search wins; else cached results open the table;
// else search home — a saved STATS selection is never restored).
loadedData.panel = resolveInitialPanel(sessionData, idbResults.length);
if (localData[CACHE.USER_SETTINGS]) {
loadedData.userSettings = { ...localData[CACHE.USER_SETTINGS] };
}
if (localData[CACHE.SELECTED_SUPPLIERS]) {
loadedData.selectedSuppliers = localData[CACHE.SELECTED_SUPPLIERS];
}
if (localData[CACHE.BOOKMARKS_FOLDER_ID]) {
loadedData.bookmarksFolderId = localData[CACHE.BOOKMARKS_FOLDER_ID];
}
if (Object.keys(loadedData).length > 0) {
dispatch({ type: APP_ACTION.LOAD_FROM_STORAGE, data: loadedData });
}
} catch (error) {
logger.error(`Failed to load from Chrome storage: ${getErrorMessage(error)}`, { error });
}
}, [dispatch]);
// On open, check whether the cache needs migrating before loading it. If steps
// are pending, show the MigrationPrompt and defer the load until the user picks
// Apply or Cancel; otherwise seed the version marker and load as usual.
useEffect(() => {
const init = async () => {
try {
const status = await getMigrationStatus();
if (status.pending.length > 0) {
setMigrationSteps(status.pending);
return;
}
await seedVersionIfUnset();
} catch (error) {
logger.error(`Migration check failed: ${getErrorMessage(error)}`, { error });
}
await loadFromStorage();
};
void init();
}, [loadFromStorage]);
// Apply the pending migrations in place, then load the (now-current) cache. On
// failure the prompt stays open with an error so the user can retry or Cancel.
const handleApplyMigrations = useCallback(async () => {
setMigrationBusy(true);
setMigrationError(undefined);
try {
await applyPendingMigrations();
setMigrationSteps([]);
await loadFromStorage();
} catch (error) {
logger.error(`Failed to apply migrations: ${getErrorMessage(error)}`, { error });
setMigrationError(i18n('migration_error'));
setMigrationBusy(false);
}
}, [loadFromStorage]);
// Clear the cache and start fresh at the current version, then load.
const handleCancelMigrations = useCallback(async () => {
setMigrationBusy(true);
setMigrationError(undefined);
try {
await resetToCurrentVersion();
} catch (error) {
logger.error(`Failed to reset caches: ${getErrorMessage(error)}`, { error });
}
setMigrationSteps([]);
setMigrationBusy(false);
await loadFromStorage();
}, [loadFromStorage]);
// Watch shared storage so edits made in another extension surface (the options
// page, or another open popup/tab) reflect live here. cstorage.onChanged
// auto-decodes LZ envelopes, so change.newValue / oldValue are already the real
// objects — no manual decompression required.
useEffect(() => {
const watchedKeys = new Set<string>([CACHE.USER_SETTINGS, CACHE.SELECTED_SUPPLIERS]);
const listener = (
changes: Record<string, chrome.storage.StorageChange>,
areaName: chrome.storage.AreaName,
) => {
for (const [key, change] of Object.entries(changes)) {
if (!watchedKeys.has(key)) continue;
logger.debug(`[storage:${areaName}] ${key} changed`, {
oldValue: change.oldValue,
newValue: change.newValue,
diff: diff(change.oldValue, change.newValue),
});
// Re-hydrate settings on external writes so the UI (theme, font size,
// currency, columns) updates live. The reducer skips no-op changes, so
// this surface's own writes echo back harmlessly.
if (key === CACHE.USER_SETTINGS && isValidUserSettings(change.newValue)) {
dispatch({ type: APP_ACTION.HYDRATE_SETTINGS, settings: change.newValue });
}
}
};
cstorage.onChanged.addListener(listener);
return () => cstorage.onChanged.removeListener(listener);
}, [dispatch]);
// Context-menu search, already-open-tab path. The service worker writes the
// selection to session storage (CACHE.QUERY + CACHE.SEARCH_IS_NEW_SEARCH) and
// focuses this tab. A fresh tab picks that up via the useSearch mount effect;
// an already-mounted app doesn't, so react to the storage change here.
// Gated to the full-tab view so the popup doesn't also fire.
useEffect(() => {
if (!isTabView()) return;
const listener = async (
changes: Record<string, chrome.storage.StorageChange>,
areaName: chrome.storage.AreaName,
): Promise<void> => {
if (areaName !== 'session') return;
if (changes[CACHE.SEARCH_IS_NEW_SEARCH]?.newValue !== true) return;
try {
const changed = changes[CACHE.QUERY]?.newValue;
const query =
typeof changed === 'string'
? changed
: (await cstorage.session.get([CACHE.QUERY]))[CACHE.QUERY];
if (typeof query !== 'string' || !query.trim()) return;
// Clear the flag before navigating so a freshly-mounting SearchPanel's
// useSearch mount effect doesn't also read it and double-run the search.
await cstorage.session.remove(String(CACHE.SEARCH_IS_NEW_SEARCH));
setPendingSearchQuery(query);
dispatch({ type: APP_ACTION.SET_PANEL, panel: PANEL.RESULTS });
} catch (error) {
logger.warn(`Failed to handle context-menu search: ${getErrorMessage(error)}`, { error });
}
};
cstorage.onChanged.addListener(listener);
return () => cstorage.onChanged.removeListener(listener);
}, [dispatch]);
// While on the results panel, bounce back to SearchPanelHome when results are
// cleared from anywhere (SpeedDial, another tab). The badge controller clears
// the badge separately; this only handles panel navigation.
useEffect(() => {
if (appState.panel !== PANEL.RESULTS) return;
const handler = () => {
dispatch({ type: APP_ACTION.SET_PANEL, panel: 0 });
};
window.addEventListener(IDB_SEARCH_RESULTS_CLEARED, handler);
return () => window.removeEventListener(IDB_SEARCH_RESULTS_CLEARED, handler);
}, [appState.panel, dispatch]);
// Speed dial visibility logicc
useEffect(() => {
const cornerThreshold = 30;
const handleMouseMove = (event: MouseEvent) => {
const shouldShow =
document.getElementById('speed-dial-menu')?.matches(':hover') ||
(event.x >= window.innerWidth - cornerThreshold &&
event.y >= window.innerHeight - cornerThreshold);
if (shouldShow !== appState.speedDialVisibility) {
dispatch({ type: APP_ACTION.SET_SPEED_DIAL_VISIBILITY, visible: shouldShow });
}
};
window.addEventListener('mousemove', handleMouseMove);
return () => window.removeEventListener('mousemove', handleMouseMove);
}, [appState.speedDialVisibility, dispatch]);
// Handlers for child components
const handleSetUserSettings = (settings: UserSettings) => {
dispatch({ type: APP_ACTION.UPDATE_SETTINGS, settings });
};
const handleSetPanel = (panel: PANEL) => {
dispatch({ type: APP_ACTION.SET_PANEL, panel });
};
// Leaving advanced mode while the stats or price-history panel is open would
// otherwise strand the user on a panel that no longer renders anything.
useEffect(() => {
if (
!statsVisible &&
(appState.panel === PANEL.STATS || appState.panel === PANEL.PRICE_HISTORY)
) {
dispatch({ type: APP_ACTION.SET_PANEL, panel: PANEL.SEARCH_HOME });
}
}, [statsVisible, appState.panel]);
const handleSetSelectedSuppliers = (suppliers: SupplierClassName[]) => {
dispatch({ type: APP_ACTION.SET_SELECTED_SUPPLIERS, suppliers });
};
const handleSetDrawerTab = (tab: DRAWER_INDEX) => {
dispatch({ type: APP_ACTION.SET_DRAWER_TAB, tab });
};
const handleToggleDrawer = (tab: DRAWER_INDEX = DRAWER_INDEX.SEARCH) => {
dispatch({
type: APP_ACTION.SET_DRAWER_TAB,
tab: appState.drawerTab === DRAWER_INDEX.CLOSED ? tab : DRAWER_INDEX.CLOSED,
});
};
const handleSetBookmarksFolderId = (id: string | null) => {
dispatch({ type: APP_ACTION.SET_BOOKMARKS_FOLDER_ID, id });
};
// Hotkey action handlers. Keyed by the `id` field in config.json -> hotkeys.
// The useHotkeys hook already suppresses events when focus is in an input.
// Wired up inside StatusBarProvider via <HotkeyLayer /> so flash messages work.
const hotkeyHandlers: HotkeyHandlers = useMemo(
() => ({
showHotkeyHelp: () => {
setHotkeyHelpOpen(true);
},
goToSearch: () => {
dispatch({ type: APP_ACTION.SET_PANEL, panel: PANEL.SEARCH_HOME });
},
openHistory: () => {
dispatch({ type: APP_ACTION.SET_DRAWER_TAB, tab: DRAWER_INDEX.HISTORY });
},
openSearchDrawer: () => {
dispatch({ type: APP_ACTION.SET_DRAWER_TAB, tab: DRAWER_INDEX.SEARCH });
},
focusGlobalFilter: () => {
window.dispatchEvent(new CustomEvent(HotkeyEvent.FOCUS_GLOBAL_FILTER));
},
toggleColumnFilters: () => {
window.dispatchEvent(new CustomEvent(HotkeyEvent.TOGGLE_COLUMN_FILTERS));
},
abortSearch: () => {
window.dispatchEvent(new CustomEvent(HotkeyEvent.ABORT_SEARCH));
},
expandAllRows: () => {
window.dispatchEvent(new CustomEvent(HotkeyEvent.EXPAND_ALL_ROWS));
},
collapseAllRows: () => {
window.dispatchEvent(new CustomEvent(HotkeyEvent.COLLAPSE_ALL_ROWS));
},
scrollResultsToTop: () => {
window.dispatchEvent(new CustomEvent(HotkeyEvent.SCROLL_RESULTS_TO_TOP));
},
showAllRows: () => {
window.dispatchEvent(new CustomEvent(HotkeyEvent.SHOW_ALL_ROWS));
},
clearColumnFilters: () => {
window.dispatchEvent(new CustomEvent(HotkeyEvent.CLEAR_COLUMN_FILTERS));
},
clearAndRetrySearch: async () => {
const data = await cstorage.session.get([CACHE.QUERY]);
const query = data[CACHE.QUERY];
if (!query) {
// Nothing to re-run; still clear supplier cache so the next search is fresh.
await SupplierCache.clearAll();
return;
}
await SupplierCache.clearAll();
await clearSearchResults();
// Flag the search as "new" so the useSearch mount effect re-executes it,
// then force SearchPanel to (re)mount by switching to the results panel.
await cstorage.session.set({ [CACHE.SEARCH_IS_NEW_SEARCH]: true });
dispatch({ type: APP_ACTION.SET_PANEL, panel: PANEL.RESULTS });
},
}),
[dispatch],
);
// AppContext value with fixed searchResults property
const appContextValue = {
// defaultSettings is trusted static config.json; its JSON-inferred type widens
// beyond UserSettings, so assert to the model type here.
userSettings: { ...(defaultSettings as UserSettings), ...appState.userSettings },
setUserSettings: handleSetUserSettings,
searchResults, // This fixes the missing property linter error
setSearchResults, // Expose setter for child components to use
setPanel: handleSetPanel, // Add setPanel to context for tab switching
drawerTab: appState.drawerTab,
setDrawerTab: handleSetDrawerTab,
toggleDrawer: handleToggleDrawer,
selectedSuppliers: appState.selectedSuppliers,
setSelectedSuppliers: handleSetSelectedSuppliers,
pendingSearchQuery,
setPendingSearchQuery,
searchFilters,
setSearchFilters,
bookmarksFolderId: appState.bookmarksFolderId,
setBookmarksFolderId: handleSetBookmarksFolderId,
advancedMode,
setAdvancedMode,
};
const searchParams = new URLSearchParams(location.search);
if (searchParams.has('test-crash')) {
const errorOpts: ErrorOptions = {};
if (searchParams.has('cause')) {
errorOpts.cause = searchParams.get('cause');
}
throw new Error(`Test Error: ${searchParams.get('test-crash')}`, errorOpts);
}
return (
<ErrorBoundary fallback={<p>{i18n('app_error_generic')}</p>}>
<AppContext.Provider value={appContextValue}>
<ThemeProvider>
<StatusBarProvider>
<HotkeyLayer handlers={hotkeyHandlers} />
<CssBaseline />
<OfflineOverlay />
<div className="app-container">
{/* Show loading indicator when settings are updating */}
{isPending && <div className="loading-indicator-box" />}
{/* Render only the active panel, no app bar or tab navigation */}
{appState.panel === PANEL.SEARCH_HOME && <SearchPanelHome />}
{appState.panel === PANEL.RESULTS && <SearchPanel />}
{statsVisible && appState.panel === PANEL.STATS && (
<Suspense fallback={null}>
<StatsPanel />
</Suspense>
)}
{statsVisible && appState.panel === PANEL.PRICE_HISTORY && (
<Suspense fallback={null}>
<PriceHistoryPanel />
</Suspense>
)}
<StatusBadges />
<div className="main-content">
<DrawerSystem />
<SpeedDialMenu speedDialVisibility={appState.speedDialVisibility ?? false} />
</div>
<HotkeyHelpModal open={hotkeyHelpOpen} onClose={() => setHotkeyHelpOpen(false)} />
<MigrationPrompt
open={migrationSteps.length > 0}
steps={migrationSteps}
busy={migrationBusy}
error={migrationError}
onApply={() => void handleApplyMigrations()}
onCancel={() => void handleCancelMigrations()}
/>
<UpdatePrompt
notice={updateNotice}
onDismiss={dismissUpdate}
onSnooze={snoozeUpdate}
onApply={applyUpdate}
/>
<WhatsNewPrompt notice={justUpdatedNotice} onAcknowledge={acknowledgeJustUpdated} />
<ReviewPrompt
notice={reviewNotice}
onReview={onReviewPromptReview}
onDismiss={onReviewPromptDismiss}
/>
</div>
<StatusBar />
</StatusBarProvider>
</ThemeProvider>
</AppContext.Provider>
</ErrorBoundary>
);
}
export default App;
|