Filter Builder
Conditions and nested groups joined by $and or $or, read from and written to a ledger query. Drawn as rows in a popover or as chips above a table.
A filter builder for ledger queries. A group joins its children with one $and or one $or; a child is a condition (a field, an operator, a value) or another group. So the builder holds what the data table's flat filters cannot: an $or of $ands, such as "payments not reverted, or refunds past transaction 100".
One tree, two layouts. Both take the same TFilterGroup and write the same ledger query, so they can edit one value side by side:
FilterBuilderdraws the tree as rows, for a popover or a panel: a data table's Filters popover.FilterBardraws it inline as chips, for a form or a page where the filter stays on screen.
In both layouts, Add filter is the one way to add to a group. It opens the fields, and a condition starts on the field picked. While maxDepth allows, Group is the last item: a group of the other join, with one condition in it.
The field of a condition is a searchable list: type to find a field by its label or its id. A new field starts a new condition.
FilterBuilder#
Each group is drawn the way the data table's filters are drawn today: "Where" on the first row, the group's join on the second, and the same join on each row after it. A nested group is a framed block in its parent's row, with its own join. Rows reorder by drag inside their group.
FilterBar#
- A condition is one chip of segments: the field, the operator, the value, and remove.
- A group is a framed run of chips. Its own + opens the same menu as Add filter. Its handle drags it to another place among its siblings.
- The join sits between each two children of a group: an outlined pill with a swap icon, so it reads as a control. A group has one join, so a click on any of them switches the whole group between
andandor. - A group that loses its last chip is removed with it.
Installation#
npx shadcn@latest add @formance/filter-builderInstall the Calendar, Dropdown Menu and Sortable components first:
npx shadcn@latest add @formance/calendar @formance/dropdown-menu @formance/sortableCopy the files of registry/default/ui-fragments/filter-builder/ into
components/ui-fragments/filter-builder/.
Update the import paths to match your project setup.
Usage#
import { FilterBar } from '@/components/ui-fragments/filter-builder/filter-bar';import { FilterBuilder } from '@/components/ui-fragments/filter-builder/filter-builder';import { filterOfQuery, queryOfFilter,} from '@/components/ui-fragments/filter-builder/filter-query';// An absent query is an empty group. `null`: the builder cannot hold the// stored query exactly, so keep the query and show it in the raw editor.const [filter, setFilter] = useState(() => filterOfQuery(storedQuery, fields));
// The ledger query to send: the builder's (`null` when nothing is written),// else the stored query as it is.const query = filter ? queryOfFilter(filter, fields) : storedQuery;
return filter ? ( // Or a `FilterBar`, with the same props, inline above a table. <FilterBuilder fields={fields} value={filter} onChange={setFilter} />) : ( // Your raw editor: a JSON `CodeEditor` of the stored query. <RawQueryEditor value={storedQuery} onChange={setStoredQuery} />);Both layouts take fields, value, onChange, maxDepth and className. maxDepth={1} removes Group from Add filter: a flat list with one join. The bar also takes actions, the other controls of its row, drawn after Reset: Inspect query.
Both layouts also take:
suggestions: what a value or key input offers while it has focus. It gets the condition, the input (keyorvalue), the text typed and apickthat writes a value. Return aFilterSuggestionListof{ value, label?, count? }, ornullto offer nothing. It is mounted only while the input has focus, so a read made in it (a ledger's facets) is made only then.activeGroupIdandonActiveGroupChange: for a surface that writes into one group of the tree, such as a filter panel. A press inside a group makes the innermost group the target, and the target's frame is drawn solid. With them, the root is drawn as a frame too, so the root can be the target.findFilterGroupandupdateFilterGroupread and replace the target.unavailableFields: the fields the reader cannot add now, by field id, each{ label, reason }. Add filter lists them after the other fields, disabled, and shows the reason on hover. Use it for a field the backend cannot answer, such as a ledger field with no index. A field already infieldsis not listed twice.timeZone: the IANA zone a picked day is read in,'UTC'by default. A day's first and last instants, the calendar's selected day and the shown instants are all in this zone, and the browser's zone is never read. So two readers in two zones who pick the same day write the same bounds. Pass the zone that your product shows instants in.
The parts#
filter-parts.tsx holds the parts both layouts draw a condition with, for a surface that draws conditions its own way:
FilterConditionSelects: the field picker, then the operator.FilterOperatorSelect: the operator alone, for a surface that fixes the field, such as a filter panel's section. A new operator keeps the value where its shape still fits.FilterValueInput: the value the operator takes: a text, a choice, a list, a key and a value, or a range of days.FilterAddMenuandFilterSuggestionList: Add filter's menu, and the values an input offers.
The model#
filter-query.ts is pure: no React. It is the part a consumer keeps when it draws its own surface.
| Export | What it does |
|---|---|
TFilterFields | The vocabulary: each field with its label, its variant and, optionally, its operators. |
TFilterField.key, TFilterField.keyTypes | On the metadata variant: key fixes the field on one key (metadata[<key>]), so no key is asked. keyTypes gives each key's operators and value format (TFilterKeyType). |
filterKeyType(field, key) | What the consumer knows of one key, or null: a field fixed on a key reads its own key. |
filterConditionOperators(condition, fields) | The operators a condition offers: its key type's for a condition the reader is making, else its field's. An operator the condition holds stays offered, so a query is drawn as written. |
filterConditionLabel(condition, fields) | The name a condition's field reads as: its label, and on the metadata field with no key, Metadata · <key> once the key is set. |
withFilterValue(condition, value, fields) | A condition with a value the reader changed, on an operator its key takes and in its key's format (a JSON bool, or an unsigned bound as a decimal string). |
withFilterKeyTypes(group, fields) | The tree with each condition the reader is making moved onto its key's type, for a type that arrived after the key was typed. A condition read from a query is not changed. |
filterDayStart(day, timeZone), filterDayEnd(day, timeZone) | The first and the last instant of a calendar day { year, month, day } in a zone. The end is the next day's start less 1 ms, so a 23 h or 25 h day is right. |
filterDayOf(instant, timeZone) | The calendar day of an instant in a zone. |
filterDayRange(from, to, timeZone), filterDayMicros(day, operator, timeZone) | A range of picked days as two instants, and one day's bound as Unix microseconds (the start, or the day's last microsecond for gt and lte). |
queryOfFilter(node, fields) | The ledger query. Each condition is the document a flat filter writes for it. A group of one child is that child. A condition that is not complete is left out. |
filterOfQuery(query, fields) | The filter a stored query is drawn as, or null when the builder cannot hold it exactly: the result is written back and compared with the query. |
filterMatches(node, fields, read) | Whether one row passes, for a table filtered in the browser. |
createFilterGroup(), createFilterCondition() | New nodes. |
createFilterSubgroup(fields, parentJoin) | A new group to open under a group: the other join, with one condition. |
countFilterConditions(node) | The conditions at any depth, for a trigger's badge. |
findFilterGroup(node, id) | The group of this id at any depth, the root included, or null: the target, or its loss when it was removed. |
updateFilterGroup(root, id, update) | The tree with the group of this id replaced by update(group). |
A null from filterOfQuery is the caller's cue to open the raw editor: a query is never flattened or dropped by the screen that shows it. A condition's value has the same four shapes as the console's clause value (text, list, keyed, instants), so a condition maps onto one console clause. On a metadata key, Is set is written as {"$exists": {"metadata": "<key>"}} and Is not set as that condition under $not, the shape the ledger decodes.
Examples#
In a data table, with a popover#
The toolbar of a Console table, opened on reverted = false and a group: reference refund-17 or fee-3. Filters opens the builder in a popover, and its badge counts the conditions while it is closed. Inspect query edits the same filter as the JSON the ledger reads: Apply writes it back when the builder can hold it. The rows are filtered in the browser with filterMatches.
In a data table#
The same filter as chips: the FilterBar keeps it on screen above the rows, and Inspect query shows the query as the JSON the ledger reads.
Bar#
The FilterBar on the stored query of the preview at the top of the page: payments not reverted, or refunds past transaction 100.
Flat#
maxDepth={1} removes Group from Add filter: one list of conditions with one join.
Target group and value offers#
A press in a group makes it the target, drawn solid, and the button writes into it. A metadata key or value input offers what a ledger counts, with the counts, while it has focus.
Rows on a fixed field#
A filter panel's section: the field is fixed, so each condition is drawn with FilterOperatorSelect and FilterValueInput only, and Add condition starts a new one on the field.
From a stored query#
Type a query in the editor above the builder. The builder draws it when it can hold it exactly, and a change in the builder writes the query back. A shape it cannot hold, such as a field outside the vocabulary or an $and of one member, opens in the raw editor instead.