gristlabs_grist-core/app/common/RowFilterFunc.ts
Alex Hall bc54a6646e (core) Filter rows based on linked widgets when exporting view
Summary:
Fixes a problem reported here: https://community.getgrist.com/t/exporting-the-records-in-a-linked-view/2556/4

The download CSV/Excel link now contains an additional `linkingFilter` URL parameter containing JSON-encoded `filters` and `operations`. This object is originally created in the frontend in `LinkingState`, and previously it was only used internally in the frontend. It would make its way via `QuerySetManager` to `QuerySet.getFilterFunc` where the actual filtering logic happened. Now most of that logic has been moved to a similar function in `common`. The new function works with a new interface `ColumnGettersByColId` which abstract over the different ways data is accessed in the client and server in this context. There's no significant new logic in the diff, just refactoring and wiring.

Test Plan: Expanded two `nbrowser/SelectBy*.ts` test suites to also check the contents of a downloaded CSV in different linking scenarios.

Reviewers: paulfitz

Reviewed By: paulfitz

Differential Revision: https://phab.getgrist.com/D3961
2023-07-26 21:49:52 +02:00

50 lines
1.8 KiB
TypeScript

import {CellValue} from "app/common/DocActions";
import {ColumnFilterFunc} from "app/common/ColumnFilterFunc";
import {FilterColValues} from 'app/common/ActiveDocAPI';
import {isList} from 'app/common/gristTypes';
import {decodeObject} from 'app/plugin/objtypes';
import {ColumnGettersByColId} from 'app/common/ColumnGetters';
export type RowFilterFunc<T> = (row: T) => boolean;
// Builds RowFilter for a single column
export function buildRowFilter<T>(
getter: RowValueFunc<T> | null,
filterFunc: ColumnFilterFunc | null): RowFilterFunc<T> {
if (!getter || !filterFunc) {
return () => true;
}
return (rowId: T) => filterFunc(getter(rowId));
}
export type RowValueFunc<T> = (rowId: T) => CellValue;
// Filter rows for the purpose of linked widgets
export function getLinkingFilterFunc(
columnGetters: ColumnGettersByColId, {filters, operations}: FilterColValues
): RowFilterFunc<number> {
const colFuncs = Object.keys(filters).sort().map(
(colId) => {
const getter = columnGetters.getColGetterByColId(colId);
if (!getter) { return () => true; }
const values = new Set(filters[colId]);
switch (operations[colId]) {
case "intersects":
return (rowId: number) => {
const value = getter(rowId) as CellValue;
return isList(value) &&
(decodeObject(value) as unknown[]).some(v => values.has(v));
};
case "empty":
return (rowId: number) => {
const value = getter(rowId);
// `isList(value) && value.length === 1` means `value == ['L']` i.e. an empty list
return !value || isList(value) && value.length === 1;
};
case "in":
return (rowId: number) => values.has(getter(rowId));
}
});
return (rowId: number) => colFuncs.every(f => f(rowId));
}