fix(data-table): handle ToolbarSearch filtering in DataTable (#2037)

This commit is contained in:
Eric Liu 2024-11-10 09:27:27 -08:00 committed by GitHub
commit 3192824322
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 36 additions and 24 deletions

View file

@ -147,6 +147,10 @@
const dispatch = createEventDispatcher();
const batchSelectedIds = writable(false);
const tableRows = writable(rows);
// Store a copy of the original rows for filter restoration.
$: originalRows = [...rows];
$: thKeys = headers.reduce((a, c) => ({ ...a, [c.key]: c.key }), {});
const resolvePath = (object, path) => {
if (path in object) return object[path];
@ -164,6 +168,36 @@
selectedRowIds = [];
if (refSelectAll) refSelectAll.checked = false;
},
filterRows: (searchValue, customFilter) => {
const value = searchValue.trim().toLowerCase();
if (value.length === 0) {
// Reset to original rows.
tableRows.set(originalRows);
return originalRows.map((row) => row.id);
}
let filteredRows = [];
if (typeof customFilter === "function") {
// Apply custom filter if provided.
filteredRows = originalRows.filter((row) => customFilter(row, value));
} else {
// Default filter checks all non-id fields for a basic, case-insensitive match (non-fuzzy).
filteredRows = originalRows.filter((row) => {
return Object.entries(row)
.filter(([key]) => key !== "id")
.some(([key, _value]) => {
if (typeof _value === "string" || typeof _value === "number") {
return (_value + "")?.toLowerCase().includes(value);
}
});
});
}
tableRows.set(filteredRows);
return filteredRows.map((row) => row.id);
},
});
let expanded = false;

View file

@ -49,32 +49,10 @@
import { tick, getContext } from "svelte";
import Search from "../Search/Search.svelte";
const { tableRows } = getContext("DataTable") ?? {};
const ctx = getContext("DataTable") ?? {};
$: originalRows = tableRows ? [...$tableRows] : [];
$: if (shouldFilterRows) {
let rows = originalRows;
if (value.trim().length > 0) {
if (shouldFilterRows === true) {
rows = rows.filter((row) => {
return Object.entries(row)
.filter(([key]) => key !== "id")
.some(([key, _value]) => {
if (typeof _value === "string" || typeof _value === "number") {
return (_value + "")
?.toLowerCase()
.includes(value.trim().toLowerCase());
}
});
});
} else if (typeof shouldFilterRows === "function") {
rows = rows.filter((row) => shouldFilterRows(row, value) ?? false);
}
}
tableRows.set(rows);
filteredRowIds = rows.map((row) => row.id);
filteredRowIds = ctx?.filterRows(value, shouldFilterRows);
}
async function expandSearch() {