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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 5x 5x 7x 7x 12x 2x 2x 5x 5x 5x 5x 5x 1x 71x 71x 71x 71x 71x 71x 54x 54x 1x 1x 3x 3x 55x 41x 55x 19x 15x 15x 37x 51x 15x 15x 15x 50x 50x 37x 37x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 130x 130x 130x 1x 1x 28x 28x 28x 28x 76x 76x 76x 76x 76x 76x 76x 76x 76x 28x 28x 28x 1x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 27x 3x 10x 10x 10x 4x 4x 3x 3x 24x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 27x 27x 27x 27x 24x 24x 27x 27x 27x 27x 27x 39x 39x 39x 39x 39x 39x 39x 31x 1x 2x 2x 2x 2x 2x 2x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 23x 23x 23x 23x 23x 1x 1x 23x 23x 23x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 23x 23x 23x 7x 7x 23x 23x 23x 4x 4x 4x 23x 39x 39x 39x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 39x 39x 39x 39x 39x | import { describeTrend, resolveRowTrendPoints } from '@/helpers/priceHistory';
import { flattenProductVariants, resolveDisplayedVariants } from '@/helpers/product';
import {
matchPercentageSortingFn,
priceSortingFn,
puritySortingFn,
quantitySortingFn,
unitPriceSortingFn,
} from '@/helpers/sorting';
import {
getAllUniqueValues,
getFullRange,
getHeaderText,
getVisibleRange,
getVisibleUniqueValues,
setColumnVisibility,
} from '@/mixins/tanstack';
import { getAllPriceSeries } from '@/utils/idbCache';
import {
ColumnFiltersState,
filterFns,
getCoreRowModel,
getExpandedRowModel,
getFacetedMinMaxValues,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
OnChangeFn,
Row,
useReactTable,
type FilterFn,
type Table,
} from '@tanstack/react-table';
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
import { useEffect, useMemo, useState } from 'react';
import TableColumns from './TableColumns';
/**
* Custom filter function for multi-select columns.
* Implements OR logic - shows rows that match ANY of the selected filter values.
*
* @param row - The table row being filtered
* @param columnId - The ID of the column being filtered
* @param filterValue - Array of selected filter values
* @returns true if the row should be shown, false otherwise
* @source
*/
const multiSelectBase: FilterFn<Product> = (row, columnId, filterValue) => {
// If no filter values are selected, show all rows
if (!Array.isArray(filterValue) || filterValue.length === 0) {
return true;
}
const cellValue = row.getValue(columnId);
// If cell value is null/undefined, don't show the row
if (cellValue == null) {
return false;
}
// Convert cell value to string for comparison
const cellValueStr = String(cellValue);
// Show row if cell value matches ANY of the selected filter values (OR logic)
return filterValue.some((value) => value.toLowerCase() === cellValueStr.toLowerCase());
};
const includesTextBase: FilterFn<Product> = (row, columnId, filterValue) => {
const search = String(filterValue ?? '')
.toLowerCase()
.trim();
if (!search) return true;
const cellValue = row.getValue(columnId);
if (cellValue == null) return false;
return String(cellValue).toLowerCase().includes(search);
};
/**
* Higher-order filter that makes any base filter "hierarchy aware" across
* the parent/variant row tree:
*
* - If THIS row's cell passes the base filter, include it.
* - If ANY ANCESTOR passes the base filter, include this row too (so a
* matching parent pulls all its variants along).
* - If ANY DESCENDANT passes the base filter, include this row too (so a
* matching variant pulls its parent along — non-matching siblings stay
* hidden because they fail on all three checks).
*
* Used as a wrapper in `filterFns` so every column filter and the global
* filter behave consistently with respect to the parent ↔ variant
* relationship. Works with `filterFromLeafRows: false` (the default).
*/
function withHierarchy<T>(base: FilterFn<T>): FilterFn<T> {
const fn: FilterFn<T> = (row, columnId, filterValue, addMeta) => {
if (base(row, columnId, filterValue, addMeta)) return true;
let parent = row.getParentRow();
while (parent) {
if (base(parent, columnId, filterValue, addMeta)) return true;
parent = parent.getParentRow();
}
const anyDescendant = (r: Row<T>): boolean => {
for (const sub of r.subRows) {
if (base(sub, columnId, filterValue, addMeta)) return true;
if (anyDescendant(sub)) return true;
}
return false;
};
return anyDescendant(row);
};
// Preserve `resolveFilterValue` / `autoRemove` hooks that the base filter
// may define (e.g. the built-in `inNumberRange` relies on these to parse
// min/max values). Without this passthrough, `inNumberRangeHierarchy`
// would never receive a parsed tuple and would reject every row.
fn.resolveFilterValue = base.resolveFilterValue;
fn.autoRemove = base.autoRemove;
return fn;
}
const multiSelectFilter = withHierarchy(multiSelectBase);
const includeHierarchyTextFilter = withHierarchy(includesTextBase);
const inNumberRangeHierarchyFilter = withHierarchy(filterFns.inNumberRange);
/**
* Configuration options for the useResultsTable hook.
* @source
*/
interface UseResultsTableProps {
/** Array of product data to display in the table */
showSearchResults: Product[];
/** Tuple containing column filter state and setter function from useState */
columnFilterFns: [ColumnFiltersState, OnChangeFn<ColumnFiltersState>];
/** Tuple containing global filter state and setter function from useState */
globalFilterFns: [string, OnChangeFn<string>];
/** Function to determine if a row can be expanded to show sub-rows */
getRowCanExpand: (row: Row<Product>) => boolean;
/** User preferences and settings object containing display options */
userSettings: UserSettings;
}
/**
* Hook for managing the results table with TanStack Table configuration.
* Co-located with ResultsTable.tsx since it's primarily used by that component.
*
* This hook configures and initializes a TanStack Table instance with:
* - Column resizing capabilities
* - Filtering and sorting functionality
* - Pagination support
* - Row expansion for product variants
* - Custom column methods for filtering and data access
* - Debounced and throttled filter updates
*
* @param props - Configuration options for the table setup
* @returns Configured TanStack Table instance with all features enabled
*
* @example
* ```tsx
* const table = useResultsTable({
* showSearchResults: products,
* columnFilterFns: [filters, setFilters],
* getRowCanExpand: (row) => row.original.variants?.length > 0,
* userSettings: { currency: 'USD', ... }
* });
*
* // Use table instance for rendering
* table.getHeaderGroups().map(headerGroup => ...)
* ```
* @source
*/
/** Minimal row shape read when building stable, unique row ids (products + variants). */
interface RowIdentity {
supplier?: string;
cacheKey?: string;
url?: string;
variants?: RowIdentity[];
}
/**
* Builds the traversal-path key for a row used by {@link buildRowIds} and the
* table's `getRowId`. The index is always a plain integer at the end, so the
* `parentId`/index pair maps to the same key unambiguously. Top-level rows have
* no parent id.
* @param index - The row's index within its sibling array.
* @param parentId - The resolved id of the parent row, if any.
* @returns A stable string key identifying the row's position in the tree.
* @example
* ```ts
* rowPathKey(2); // " 2"
* rowPathKey(0, "ACME:1"); // "ACME:1 0"
* ```
* @source
*/
function rowPathKey(index: number, parentId?: string): string {
return parentId === undefined ? ` ${index}` : `${parentId} ${index}`;
}
/**
* Builds a per-row map of unique, mostly-stable TanStack row ids for a result
* set. Each row's id is its product identity `supplier:cacheKey` (matching the
* exclusion/cache key), with variant sub-rows namespaced under their parent's
* id. When the same identity appears more than once in a result set — a
* duplicate product, or a supplier that reuses a cacheKey — later occurrences
* get a `#n` suffix so no two sibling rows share a React key. First occurrences
* keep the bare identity, so expansion/selection still survive re-indexing.
* Keyed by traversal path (parent id + index) rather than object identity, so
* it disambiguates duplicates even when a result set repeats the same object
* reference at two positions.
* @param rows - The top-level product rows for the current result set.
* @returns A map from each row's traversal path to its unique id string.
* @example
* ```ts
* const ids = buildRowIds([{ supplier: "ACME", cacheKey: "1" }, { supplier: "ACME", cacheKey: "1" }]);
* ids.get(rowPathKey(0)); // "ACME:1"
* ids.get(rowPathKey(1)); // "ACME:1#1"
* ```
* @source
*/
function buildRowIds(rows: readonly RowIdentity[]): Map<string, string> {
const idByPath = new Map<string, string>();
const seen = new Map<string, number>();
const assign = (row: RowIdentity, index: number, parentId?: string): string => {
const raw = row.cacheKey ? `${row.supplier}:${row.cacheKey}` : (row.url ?? String(index));
const base = parentId ? `${parentId}>${raw}` : raw;
const count = seen.get(base) ?? 0;
seen.set(base, count + 1);
const id = count === 0 ? base : `${base}#${count}`;
idByPath.set(rowPathKey(index, parentId), id);
(row.variants ?? []).forEach((variant, variantIndex) => assign(variant, variantIndex, id));
return id;
};
rows.forEach((row, index) => assign(row, index));
return idByPath;
}
/**
* Hook for managing the results table with TanStack Table configuration.
* @param props - Configuration options for the table setup
* @returns Configured TanStack Table instance with all features enabled
* @example
* ```tsx
* const table = useResultsTable({
* showSearchResults: products,
* columnFilterFns: [filters, setFilters],
* getRowCanExpand: (row) => row.original.variants?.length > 0,
* userSettings: { currency: 'USD', ... }
* });
* ```
* @source
*/
export function useResultsTable({
showSearchResults,
columnFilterFns,
globalFilterFns,
getRowCanExpand,
userSettings,
}: UseResultsTableProps) {
// State to track custom sorting
const [customSort, setCustomSort] = useState<{ type: string; order: 'asc' | 'desc' } | null>(
null,
);
// Apply custom sorting to data if needed
const sortedData = useMemo(() => {
if (customSort?.type === 'matchPercentage') {
const sorted = [...showSearchResults].sort((a, b) => {
const aVal = a.matchPercentage ?? 0;
const bVal = b.matchPercentage ?? 0;
if (customSort.order === 'desc') return bVal - aVal;
return aVal - bVal;
});
return sorted;
}
return showSearchResults;
}, [showSearchResults, customSort]);
// When "group product variants" is off, flatten each product's variants into
// their own top-level rows so column sorting/filtering (price, quantity, unit
// price) applies across every variant rather than only the primary one. This is
// a display-time transform — the underlying product data is untouched. Toggling
// the setting recomputes this live, without needing a fresh search.
const groupProductVariants = userSettings.search?.groupProductVariants ?? true;
const tableData = useMemo(
() => (groupProductVariants ? sortedData : flattenProductVariants(sortedData)),
[sortedData, groupProductVariants],
);
// Preload recorded price history once (and refresh when the result set changes,
// picking up prices a fresh search just recorded) into a by-series-id map, so the
// opt-in trend column's synchronous cell renderers can look a row's series up from
// table meta rather than each firing its own IndexedDB read.
const [priceHistory, setPriceHistory] = useState<ReadonlyMap<string, PriceHistoryEntry>>(
new Map(),
);
useEffect(() => {
let cancelled = false;
const load = async () => {
const series = await getAllPriceSeries();
if (!cancelled) {
setPriceHistory(new Map(series.map((entry) => [entry.id, entry])));
}
};
void load();
return () => {
cancelled = true;
};
}, [sortedData]);
// Stamp each top-level row with its trend's signed percent change so the
// (sortable) price-trend column has an accessor value — TanStack can't sort a
// column without one, and the async price history isn't on the row itself.
// Absent for rows with no drawable trend, which `sortUndefined: 'last'` on the
// column then parks at the bottom. Only rebuilds when the data or history change.
const dataWithTrend = useMemo(() => {
if (priceHistory.size === 0) return tableData;
return tableData.map((row) => {
const points = resolveRowTrendPoints(
row,
resolveDisplayedVariants(row, row.variants ?? []),
priceHistory,
);
return points ? { ...row, priceTrendValue: describeTrend(points).pctChange } : row;
});
}, [tableData, priceHistory]);
// Precompute a unique id per row so duplicate product identities in a result
// set don't produce duplicate React keys (see buildRowIds). Recomputed only
// when the data changes, keeping ids stable across unrelated re-renders.
const rowIds = useMemo(() => buildRowIds(dataWithTrend), [dataWithTrend]);
const resultsTable = useReactTable({
data: dataWithTrend,
enableColumnResizing: true,
columnResizeDirection: 'ltr',
defaultColumn: {
// Removed minSize and maxSize for more flexibility
},
columnResizeMode: 'onChange',
columns: TableColumns(),
// Passed through TanStack's `meta` so hook-free cell renderers (see the
// price column in TableColumns.tsx) can read userSettings without
// calling useAppContext() themselves.
meta: { userSettings, priceHistory },
filterFns: {
multiSelect: multiSelectFilter,
includeHierarchy: includeHierarchyTextFilter,
inNumberRangeHierarchy: inNumberRangeHierarchyFilter,
},
sortingFns: {
matchPercentage: matchPercentageSortingFn,
priceSortingFn: priceSortingFn,
puritySortingFn: puritySortingFn,
quantitySortingFn: quantitySortingFn,
unitPriceSortingFn: unitPriceSortingFn,
},
state: {
columnFilters: columnFilterFns[0],
globalFilter: globalFilterFns[0],
},
globalFilterFn: includeHierarchyTextFilter,
// Columns that should start hidden — users can opt them in via the
// column-visibility menu. Overridden by any persisted visibility state
// in chrome.storage on mount.
initialState: {
columnVisibility: {
availability: false,
// Opt-in: the price-trend sparkline column starts hidden and users enable
// it from the column-visibility menu (see the priceTrend column).
priceTrend: false,
},
},
// Each row is filtered independently by our `withHierarchy` wrapper
// (self / ancestors / descendants). Setting `filterFromLeafRows: true`
// would short-circuit that — parents of matching leaves would always
// be kept regardless of whether we matched them, which breaks the
// "show only matching variants" requirement.
filterFromLeafRows: false,
onColumnFiltersChange: columnFilterFns[1],
onGlobalFilterChange: globalFilterFns[1],
// Variants are built Product-shaped by the suppliers but typed as Variant[];
// reinterpret them as the table's row type. This is a data-model alias of
// trusted internal data, not untrusted input, so no runtime guard applies.
getRowId: (row, index, parent) => {
// Track rows by product identity, not array index, so row expansion and
// selection survive re-indexing when a product is ignored/removed. Ids are
// precomputed by buildRowIds, which mirrors the exclusion key (supplier +
// cacheKey), namespaces variant sub-rows under their parent, and suffixes
// duplicate identities so sibling React keys stay unique. Fall back to the
// same scheme for any row not in the map (shouldn't happen in practice).
const precomputed = rowIds.get(rowPathKey(index, parent?.id));
if (precomputed !== undefined) return precomputed;
const base = row.cacheKey ? `${row.supplier}:${row.cacheKey}` : (row.url ?? String(index));
return parent ? `${parent.id}>${base}` : base;
},
// Grouped mode nests variants as sub-rows (surfaced in the detail panel).
// Ungrouped mode has already flattened variants into top-level rows, so return
// no sub-rows — the parent row keeps its `variants` only as inert data for the
// detail panel's variant list, never as nested table rows.
getSubRows: (row) => (groupProductVariants ? (row?.variants as Product[]) : undefined),
getRowCanExpand: (row: Row<Product>) => getRowCanExpand(row),
getCoreRowModel: getCoreRowModel(),
getExpandedRowModel: getExpandedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
getFacetedMinMaxValues: getFacetedMinMaxValues(),
getFacetedRowModel: getFacetedRowModel(),
paginateExpandedRows: false,
debugTable: false,
debugHeaders: false,
debugColumns: false,
_features: [
{
createTable: (table: Table<Product>) => {
window.resultsTable = table;
table.userSettings = userSettings;
/**
* Updates the user settings on the table instance.
* @param userSettings - New user settings to apply
* @source
*/
table.setUserSettings = (userSettings: UserSettings) => {
table.userSettings = userSettings;
};
/**
* Sorts the table rows by match percentage.
* @param order - Sort order: 'asc' for ascending, 'desc' for descending
* @source
*/
table.sortByMatchPercentage = (order: 'asc' | 'desc' = 'desc') => {
// Clear existing table sorting first
table.resetSorting();
// Set custom sort state which will trigger re-render via useMemo
setCustomSort({
type: 'matchPercentage',
order: order,
});
// Store state on table for API compatibility
table._customSort = {
type: 'matchPercentage',
order: order,
};
};
/**
* Checks if the table is currently sorted by match percentage.
* @returns boolean indicating if match percentage sorting is active
* @source
*/
table.isSortedByMatchPercentage = () => {
return table._customSort?.type === 'matchPercentage';
};
/**
* Gets the current match percentage sort order.
* @returns 'asc', 'desc', or null if not sorted by match percentage
* @source
*/
table.getMatchPercentageSortOrder = () => {
if (!table.isSortedByMatchPercentage?.()) return null;
return table._customSort?.order || null;
};
},
/**
* Custom feature that extends table and column instances with additional methods.
* Adds utility functions for filtering, data access, and user settings management.
*
* @param column - The column instance to extend
* @param table - The table instance to extend
* @source
*/
createColumn: (column, table) => {
// Just gets the header text of the column
column.getHeaderText = () => getHeaderText(column);
// Function to set the visibility of the column
column.setColumnVisibility = (visible: boolean) => setColumnVisibility(column, visible);
// Function to count the number of unique values in the visible rows of the column
column.getVisibleUniqueValues = () => getVisibleUniqueValues(column, table);
// Same as getVisibleUniqueValues, but for all rows
column.getAllUniqueValues = () => getAllUniqueValues(column, table);
// Get the minimum and maximum values from a column (for range filters)
column.getFullRange = () => getFullRange(column, table);
// Visible range of values in the column
column.getVisibleRange = () => getVisibleRange(column, table);
// Debounced filter value setter
column.setFilterValueDebounced = debounce(column.setFilterValue, 500);
// Throttled filter value setter
column.setFilterValueThrottled = throttle(column.setFilterValue, 500);
},
},
],
});
window.resultsTable = resultsTable;
return resultsTable;
}
|