Filters and selections: Design filtering for a Data App: one selection group, applying pending selections, filter objects that narrow each other, selections on semantic layer items, mirrored groups, clicks that open a detail, and reading selections reliably. # Filters and selections > Design filtering for a Data App: one selection group, applying pending selections, filter objects that narrow each other, selections on semantic layer items, mirrored groups, clicks that open a detail, and reading selections reliably. This page belongs to [Data App developer guide](https://docs.astrato.io/_llms-txt/data-app-developer-guide.txt). How selection groups, pending and applied selections work is in the [Interactivity guide](https://docs.astrato.io/_llms-txt/interactivity-guide.txt); read it first. This page covers the decisions a whole dashboard needs on top of it. This is a developer reference for app code. To add a filter in App Builder without writing code, see [Add a filter to a chart](https://docs.astrato.io/_llms-txt/add-a-filter-to-a-chart.txt). ## Use one selection group Use the same selection group for charts, tables and filter objects that should filter each other. Queries your app sends directly do not join a group: translate its applied selections into query filters as described below. Use separate groups when objects need independent selections, such as two copies of a chart in a comparison. Also use separate groups when objects do not share the selected field’s values. A selection becomes a filter on every connected object in the group. If one view holds national and regional rows, a region selection filters the national series to no rows. Group the objects that share a dimension, such as every regional chart with the region filter, and keep other objects in their own groups. A selection bar should then list the selections of every group it represents. A filter object’s value list applies selections on other connected fields and excludes selections on its own field. Use a shared group so connected filters update together without custom synchronization. Separate groups require synchronization that handles feedback loops, accidental clears and empty selection events while filters open. ## Field metadata for connected selections Cross-object filtering uses field metadata to check connections in the semantic layer’s join graph. The runtime can load that metadata from the client’s engine or data services before mounting and merge it with `dataBinding.fieldMetadata`. If your client has no metadata service, supply the snapshot yourself. Failed metadata requests are logged; a client with neither a metadata service nor supplied metadata cannot provide the connectivity information. See [Prerequisite: load field metadata first](https://docs.astrato.io/_llms-txt/interactivity-guide.txt#prerequisite-load-field-metadata-first). ## Selections on semantic layer items Objects built on stored dimensions and measures follow selections in the same way as objects built on view columns. Before an object applies a selection from its group, it checks that the selected field is connected to its own fields; for a stored item, it checks the view column the item is defined on. Selections identify the field by its view-column key. A chart or filter object built on a stored dimension writes the key of the view column that dimension is defined on, such as `[Customers].[Country]`, rather than the dimension’s own key, such as `[dimension].[Country]`. Selections your code writes must do the same. A selection keyed by a stored item’s key is not applied: objects keep their current data, and the console logs `could not find fieldKey`. Find a stored dimension’s view column from `availableFields`: its `item.dimension` names the column’s `view` and `name`. ```ts import type { VisualizationAvailableField } from '@astrato-io/visualizations/definitions'; // The key that selections on this field carry. const selectionKeyOf = (field: VisualizationAvailableField, availableFields: VisualizationAvailableField[]) => { if (field.kind !== 'dimension') return field.fieldKey; const { view, name } = field.item.dimension; const column = availableFields.find((entry) => entry.kind === 'field' && entry.view === view && entry.name === name); if (!column) throw new Error(`No view column found for ${field.name}.`); return column.fieldKey; }; ``` ## Apply pending selections Clicking a chart value writes a **pending** selection in either selection mode. So does a filter object, unless its quick select setting is on. The selection mode only sets the default for `selectValues` calls that pass no `state`; see [Driving selections from your own UI](https://docs.astrato.io/_llms-txt/interactivity-guide.txt#driving-selections-from-your-own-ui). A pending selection highlights matching points but does not filter queries until applied. The visualization packages do not include an apply control. Applying costs one query per mounted object in the group. Choose one of these: * **Apply automatically**, after a short debounce, so a click filters and a run of clicks costs one query per object. See [Auto-apply variant](https://docs.astrato.io/_llms-txt/interactivity-guide.txt#auto-apply-variant). The bar below then needs only the chips and **Clear all**. * **Build an apply bar**, when readers should confirm a set of selections before anything re-queries. Call `setSelectionMode('manual', GROUP)` so selections your own code writes wait too. ### Always show a selection bar Every page that readers can filter or click shows a selection bar, whichever apply model it uses. Without one, a reader cannot tell that a figure is filtered, or which click filtered it. Every chart counts as something readers can click, whether or not you planned an interaction: a click writes a selection to the chart’s group and dims its other marks, and no operation turns that off. A line is the exception: clicking a point on a `line` chart, or on a `combo` chart’s line series, shows its tooltip and selects nothing. Where readers should click a period or a category to focus the page, draw it with bars, and do not tell readers to click a line. Where a line stays, say in its subtitle that its points select nothing. A chart in a group with no selection bar leaves the reader with dimmed marks and nothing to clear them, so keep a chart in the page’s group, or show a bar for its own group beside it. A drill that opens another page needs no bar for that click: its way back is the back link. * Place it in a thin row under the [header](https://docs.astrato.io/_llms-txt/header.txt) that sticks with the header, so it stays visible while the page scrolls. Reserve its height even when it is empty. * Show the selections of the group on screen: one chip per field, with the field name and what it selects, read from its `operator`: `between`, `notBetween` and `range` with two values are ranges, so show both bounds rather than a count; a comparison such as `gt` with one value says so, as in “greater than 100”; otherwise show the value, or a count when there are several, and say so when a `not` operator excludes them. [Date values](#periods-and-date-ranges) need formatting first. When tabs use separate groups, render it again on every tab switch. * Give a chip to every selection that filters, including those with no values: `notSet` (“is empty”), `set` (“is not empty”) and an `ASSOCIATIVE` selection. Otherwise the bar says nothing is selected while the page is still filtered. * Give each chip a remove control (`removeSelection(GROUP, selection)`), and show **Clear all** when anything is selected. * When nothing is selected, the bar can show nothing. Show a hint only where it tells readers something true of this page alone, such as a way to select that only this page has. * Say each change to screen readers: keep a polite status line (`role="status"`), visually hidden and outside the chips, and write what is selected now, or that the selections were cleared. Where a chip shows a count, say the values. When the line would read as before, such as six values that differ past the fifth, add what was added and removed. Leave it empty on the first render. * Keep focus on a control that is still there after a change. When a chip’s remove control or **Clear all** goes away under focus, move focus to the bar (`tabindex="-1"`), not to the page’s start. * Include selections written by chart clicks, not only those from filter objects. ```ts // Words for a one-value selection whose operator is not equality. const COMPARISON = { gt: 'greater than', gte: 'at least', lt: 'less than', lte: 'at most', contains: 'contains', notContains: 'does not contain', like: 'like', notLike: 'not like', }; // Whether a selection filters: one with values, "is empty", "is not empty", or an associative one. const isAssociative = (s) => s.kind === 'ASSOCIATIVE' || !!s.associativeListFilter; const filters = (s) => s.values?.length > 0 || s.operator === 'set' || s.operator === 'notSet' || isAssociative(s); // What a chip says. Only the field's type shows that a number is a date. const selectionText = (s, availableFields) => { if (isAssociative(s)) return 'associative filter'; if (s.operator === 'notSet') return 'is empty'; if (s.operator === 'set') return 'is not empty'; const column = availableFields.find((entry) => entry.fieldKey === s.field.fieldKey); const onDate = /^(date|timestamp)/u.test(column?.dataType ?? '') && !s.datePart; const [first, second] = s.values.map((value) => { const date = onDate && typeof value === 'number' ? new Date(value) : undefined; return date && !Number.isNaN(date.getTime()) ? date.toISOString().slice(0, 10) : String(value); }); const compare = COMPARISON[s.operator]; if (compare && s.values.length === 1) return `${compare} ${first}`; const not = s.operator?.startsWith('not') ? 'not ' : ''; if (s.values.length === 1) return `${not}${first}`; if (s.values.length === 2 && ['between', 'notBetween', 'range'].includes(s.operator)) return first === second ? `${not}${first}` : `${not}${first} to ${second}`; return `${s.values.length} ${not ? 'excluded' : 'selected'}`; }; // Each value in a chip's words, and a list of up to five words, then how many more. const valueWords = (s) => s.values.map((value) => selectionText({ ...s, values: [value] }, availableFields)); const listed = (words) => words.slice(0, 5).join(', ') + (words.length > 5 ? ` and ${words.length - 5} more` : ''); // What the status line says: the chip's words, or the values where the chip shows a count. const spokenText = (s) => { const text = selectionText(s, availableFields); return /^\d+ (selected|excluded)$/u.test(text) ? listed(valueWords(s)) : text; }; // What changed, field by field, such as "Region: added G; removed F.", for when the line reads as before. const selectionChanges = (before, after) => { const words = (list) => new Map(list.map((s) => [s.field.fieldKey, valueWords(s)])); const was = words(before); const now = words(after); return [...new Set([...was.keys(), ...now.keys()])] .flatMap((key) => { const added = (now.get(key) ?? []).filter((word) => !(was.get(key) ?? []).includes(word)); const removed = (was.get(key) ?? []).filter((word) => !(now.get(key) ?? []).includes(word)); const parts = [added.length ? `added ${listed(added)}` : '', removed.length ? `removed ${listed(removed)}` : '']; return added.length || removed.length ? [`${fieldLabel(key)}: ${parts.filter(Boolean).join('; ')}.`] : []; }) .join(' '); }; let said; // what was selected when the status line last spoke, and what it said; nothing on the first render const renderSelectionBar = () => { const { applied, pending } = selections.getSelection(GROUP); // One chip per field: a pending replacement wins over the applied selection it replaces. const byField = new Map(); for (const s of [...applied, ...pending]) byField.set(s.field.fieldKey, s); const list = [...byField.values()].filter(filters); // Rebuilding replaces every control. chip() and clearAll() give their button a data-key (the // field key, or 'clear-all'), so focus goes back to the same control, or to the bar if it went. const focused = bar.contains(document.activeElement) ? document.activeElement : undefined; bar.replaceChildren( ...list.map((s) => chip(s.field.fieldKey, fieldLabel(s.field.fieldKey), selectionText(s, availableFields), () => selections.removeSelection(GROUP, s), ), ), ...(list.length ? [clearAll(() => selections.clearAllSelections(GROUP))] : []), ); const key = focused?.dataset.key; if (focused) (bar.querySelector(key ? `[data-key="${CSS.escape(key)}"]` : null) ?? bar).focus(); // status is a visually hidden role="status" element next to the bar, not inside it. It speaks when // what is selected changes, value by value, even where the chips' words stay the same. const selected = JSON.stringify( list.map((s) => [s.field.fieldKey, s.kind, s.operator, s.datePart, s.values, s.associativeListFilter]), ); const text = list.length ? `Selections: ${list.map((s) => `${fieldLabel(s.field.fieldKey)} ${spokenText(s)}`).join('; ')}.` : 'Selections cleared.'; if (said !== undefined && selected !== said.selected) // Two selections can read alike: then say what changed, or, where even the values read alike, that it did. status.textContent = text === said.text ? `${text} ${selectionChanges(said.list, list) || 'Selections changed.'}` : text; said = { selected, text, list }; }; selections.onActiveSelectionChange(GROUP).subscribe(renderSelectionBar); ``` The apply bar below is this selection bar with **Discard** and **Apply** added. ### Build an apply bar Reserve a fixed height for the apply bar to prevent layout shifts. Include: * a chip per selection, written as in the selection bar; * **Clear all** beside the chips when anything is selected; * **Discard** and **Apply** at the end, shown only while selections are pending, so the bar indicates which changes still need confirmation. ```ts selections.onActiveSelectionChange(GROUP).subscribe(({ applied, pending }) => { renderChips(applied, pending); applyControls.hidden = pending.length === 0; }); applyButton.addEventListener('click', () => selections.applyPendingSelections(GROUP)); discardButton.addEventListener('click', () => selections.clearPendingSelections(GROUP)); clearAllButton.addEventListener('click', () => selections.clearAllSelections(GROUP)); ``` ### Write a scope from the applied selections A subtitle, caption or sentence that names what its figures cover describes the current selection. “Full range”, “all time” or “all regions” is true only while nothing is selected: once a reader picks a date range or clicks a country, the figures change and fixed words do not, so the caption becomes false. On a page readers can filter or click, write the scope from the **applied** selections, as the selection bar writes its chips, with your words for everything while nothing is applied, or use wording that stays true for any selection. Pending selections have not filtered anything yet. ```ts // "Order date: 2023-06-02 to 2023-06-30; Country: Germany", or `all` while nothing is applied. const scopeText = (applied, all) => { const list = applied.filter((s) => s.values?.length); return list.length ? list.map((s) => `${fieldLabel(s.field.fieldKey)}: ${selectionText(s, availableFields)}`).join('; ') : all; }; const renderScope = () => { scope.textContent = scopeText(selections.getSelection(GROUP).applied, 'All recorded orders'); }; selections.onActiveSelectionChange(GROUP).subscribe(renderScope); renderScope(); ``` ```html

USD · All recorded orders

``` * Name a scope in one place per object, such as the subtitle, rather than in every caption. * A figure whose query deliberately ignores the selections, such as a benchmark for the whole range, keeps its fixed words. Say so in the label: “All dates, whatever is selected”. ## Re-query your own objects only on applied changes Figure cards and other hand-built objects must follow the same filters as the charts. Re-query them when the **applied** selections change, not on every emission: pending state changes on every brush and filters nothing. Compare a signature of the applied list so repeated emissions of the same state do not re-query. An associative selection has no values: its kind and its `associativeListFilter` tell one from another, so include them: ```ts let lastApplied = ''; selections.onActiveSelectionChangeApplied(GROUP).subscribe(({ applied }) => { const signature = JSON.stringify( applied.map((s) => [ selectionFieldKey(s), s.kind ?? 'VALUE', s.operator, s.values, s.dateLevel, s.datePart, s.associativeListFilter, ]), ); if (signature === lastApplied) return; lastApplied = signature; refreshFigures(applied); }); ``` To filter a query you build yourself, translate the applied `VALUE` selections into its `filters`. A query filter takes typed values, so a selection of text values becomes: ```ts import type { AstratoSelection } from '@astrato-io/sdk'; const toQueryFilter = (selection: AstratoSelection) => ({ fieldKey: selectionFieldKey(selection), operator: selection.operator ?? 'inList', values: selection.values.map((value) => ({ dataType: 'string', valueString: String(value) })), }); ``` A number is `{ dataType: 'int', valueInt }` when `Number.isSafeInteger(value)` is true and `{ dataType: 'float', valueFloat }` otherwise, including a whole number too large for that test. The engine refuses any other type name, and the whole query fails. A boolean is `{ dataType: 'boolean', valueBoolean }`, and an empty value is `null`, never the text `"null"`. A `set` or `notSet` selection (“is not empty”, “is empty”) has no values but still filters: keep it. On a `date` column, or with a `dateLevel`, date ranges use `valueDate` bounds instead; see [Periods and date ranges](#periods-and-date-ranges). On a `timestamp` column, with no `dateLevel` and no `datePart`, a value or a range bound is a time: send `{ dataType: 'timestamp', valueDatetime }` with its time of day, such as `'2024-05-08T14:30:05.120'` from `new Date(value).toISOString().slice(0, -1)`. On a `timestamp_tz` column, send `{ dataType: 'timestamp_tz', valueDatetimeTZ }` with that text and `+00:00`. A selection from a chart on a grouped date also carries `dateLevel` or `datePart`: copy it onto the filter, so the value is compared at that grain. An applied `ASSOCIATIVE` selection is not a filter: send its `associativeListFilter` as the query’s own `associativeListFilter`. A query takes one, so use the first applied. In `refreshFigures`, ignore results from superseded requests so a slow earlier query cannot overwrite the figures for the current selections. ## Read selections defensively Write selections in the documented `AstratoSelection` shape. Selections written by charts carry more than that shape (see [Driving selections from your own UI](https://docs.astrato.io/_llms-txt/interactivity-guide.txt#driving-selections-from-your-own-ui)), and producers do not all put the field key in the same place. Read it from `field.fieldKey` and fall back to a key on the selection itself: ```ts const selectionFieldKey = (selection: { field?: { fieldKey?: string }; fieldKey?: string }) => selection.field?.fieldKey ?? selection.fieldKey; ``` Use this lookup consistently so hand-built figures receive selections from each producer. Compare the result with `selectionKeyOf` from [Selections on semantic layer items](#selections-on-semantic-layer-items), not with a stored dimension’s own `fieldKey`, which selections never carry. Compare full keys; do not parse names or key suffixes. ## Mirror a group onto another view When one attribute exists as a column on two views that are not connected for it — a shift’s day on the shifts view and the same day on a scenarios view joined only through units — a selection on the first view’s column does not narrow the second view. Give the second view’s objects their own group and keep it a mirror of the main group: on every applied change of `main`, make the mirror hold exactly the main selections, with the keys that exist only on the first view renamed to the second view’s columns, plus the mirror’s own fixed selections such as a chosen scenario. Skip the write when the mirror already matches, or the redundant write triggers an unnecessary query for each object in that separate mirror group. Clear pending selections written inside a mirror, or route them back to `main`, so a click in a mirrored tile behaves like a click anywhere else. ## Use a click to open a detail A click on a chart or table value writes a pending selection; nothing says it has to become a filter. To open an item’s detail instead, read the pending selection on that field in the group’s change subscription, remove it and open the panel for its value. Do the removal outside the subscriber, in a timeout, because writing back synchronously re-enters it. Every other field still applies as a filter, so one table can filter on its risk column and open a panel from its name column. Tell readers which column opens the panel in the tile’s subtitle. ```ts selections.onActiveSelectionChange(GROUP).subscribe(({ pending }) => { const pick = pending.find((s) => selectionFieldKey(s) === unitNameKey); if (!pick) return applyPendingSoon(); setTimeout(() => { selections.removeSelection(GROUP, pick); openUnitPanel(String(pick.values[0])); }, 0); }); ``` ## Periods and date ranges A dashboard period — this month, year to date, a custom range — is usually best expressed as an **applied selection** on the date field in the shared group, so every object follows it the same way as any other filter. Measures that take date parameters need those values as well; send them as [parameters](https://docs.astrato.io/_llms-txt/querying-the-engine.txt#parameters) on the queries you build. * A date range selection holds its bounds as UTC epoch milliseconds, as numbers, inclusive at both ends. A mounted `date-picker` and a chart on a date field write this shape, and the picker reads it back, so send the same one from your own period buttons: ```ts selections.selectValues(GROUP, { field: { fieldKey }, fieldKey, operator: 'between', values: [Date.parse('2019-01-01T00:00:00.000Z'), Date.parse('2019-12-31T23:59:59.999Z')], }); ``` Send numbers only. With `yyyy-mm-dd` strings, charts still filter but a `date-picker` in the group shows `NaN`. Numeric strings are not compared as dates in the query. * To show a selection’s range, convert its bounds: a range picked from 1 to 8 May 2024 has `values: [1714521600000, 1715212799999]`. Check first that the field’s `dataType` in `availableFields` is a date and that the selection has no `datePart`, whose values are plain numbers; a number range on a number field looks the same. * In a query you build, the same range on a `date` column is a filter with typed bounds: `{ fieldKey, operator: 'between', values: [{ dataType: 'date', valueDate: '2019-01-01' }, { dataType: 'date', valueDate: '2019-12-31' }] }`. Convert a selection’s bound with `new Date(bound).toISOString().slice(0, 10)`. On a `timestamp` column, send the bounds as times, as in [Re-query your own objects only on applied changes](#re-query-your-own-objects-only-on-applied-changes). * For a chart-local fixed date filter, follow the native [`setStaticFilterGroup` date values](https://docs.astrato.io/_llms-txt/interactivity-guide.txt#filters-how-selections-reach-the-query). * Anchor relative periods on the latest date in the data, not today, when the data stops before today: on a historical extract every period counted back from today is empty. ### Keep comparison periods in scope A comparison calculated across answer rows, such as an inter-record change, needs the current and baseline periods in its input. Filtering that input to one period removes the preceding row; a shared date selection can do this. Check the governed question’s time scope before applying that selection to comparison objects. When detail views show only the selected period, synchronize comparison queries with the picker’s applied state while retaining their baseline. A separate selection group can isolate the page’s date selection, but does not choose the comparison’s current period. Keep relevant non-date filters aligned between the detail and comparison views. For measures that declare current and comparison date parameters, update both ranges from the applied period and omit the date selection from that query’s filters. Follow the [period picker’s parameter workflow](https://docs.astrato.io/_llms-txt/period-picker.txt#apply-the-period). For the [inter-record KPI pattern](https://docs.astrato.io/_llms-txt/governed-objects.txt#period-change-on-a-kpi-card), bound the input through the selected period while retaining the required baseline rows and preserving the question’s period grain. Without that cutoff, its descending query with a one-row limit shows the latest available period. Confirm the returned current period matches the selection; report missing period data rather than presenting an earlier period as the selected one. Keep the calculation in a stored question or measure, and label the compared periods and any scope that differs from the detail views. Verify both periods and the comparison result after changing the date filter, including a historical period and a custom range when supported by the question and picker. See [Period axes and comparisons](https://docs.astrato.io/_llms-txt/period-axes-and-comparisons.txt) for engine time-intelligence calculations. ## Limitations to design around * Selections live in memory and are lost on reload. Persist a period or filter state yourself if the dashboard needs it. * Objects that summarize selections render blank standalone. Show selection state in your own bar. See [Limitations](https://docs.astrato.io/_llms-txt/interactivity-guide.txt#limitations) for the full list.