@microsoft/rayfin-semantic-model-pack 1.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG +4 -0
- package/README.md +16 -5
- package/kit/hooks/use-query-factory-target.spec.ts +191 -0
- package/kit/hooks/use-query-factory-target.ts +123 -0
- package/kit/hooks/use-semantic-model-query.spec.ts +51 -34
- package/kit/hooks/use-semantic-model-query.ts +30 -49
- package/kit/lib/query-factory.spec.ts +97 -0
- package/kit/lib/query-factory.ts +68 -0
- package/kit/lib/semantic-model-errors.spec.ts +131 -0
- package/kit/lib/semantic-model-errors.ts +110 -0
- package/kit/lib/to-data-table.spec.ts +444 -0
- package/kit/lib/to-data-table.ts +221 -0
- package/pack.json +122 -25
- package/package.json +1 -1
- package/skills/analytics/SKILL.md +126 -422
- package/skills/dax-authoring/SKILL.md +98 -31
- package/skills/query-design/SKILL.md +22 -29
- package/skills/query-design/references/anti-patterns.md +13 -11
- package/skills/query-design/references/format-strings.md +6 -12
- package/skills/query-design/references/multi-grain-patterns.md +121 -108
- package/skills/schema-discovery/SKILL.md +197 -368
- package/skills/schema-discovery/references/discovery-queries.md +6 -8
- package/skills/visual-interactivity/SKILL.md +68 -0
- package/skills/visual-interactivity/references/advanced-query-shapes.md +155 -0
- package/skills/visual-interactivity/references/filter-aware-grid-totals.md +101 -0
- package/skills/visual-interactivity/references/highlight-queries.md +88 -0
- package/skills/visual-interactivity/references/interaction-manager.md +127 -0
- package/skills/visual-interactivity/references/native-selections.md +20 -0
- package/skills/visual-interactivity/references/query-factories.md +169 -0
- package/kit/scripts/rayfin-connector.mjs +0 -265
- package/kit/scripts/rayfin-connector.test.mjs +0 -243
- package/kit/scripts/schema-sql-batch.test.mjs +0 -2097
- package/kit/scripts/schema-sql-cli.test.mjs +0 -488
- package/kit/scripts/schema-sql.mjs +0 -2650
- package/kit/scripts/schema-sql.test.mjs +0 -1387
- package/kit/scripts/schema.mjs +0 -166
- package/kit/scripts/schema.test.mjs +0 -271
- package/skills/query-design/references/filter-strategy.md +0 -68
- package/skills/query-design/references/highlight-queries.md +0 -122
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: visual-interactivity
|
|
3
|
+
description: >
|
|
4
|
+
Coordinates Power BI semantic-model-backed visuals, grids and slicers through
|
|
5
|
+
the Interaction Manager. Use for managed selections, cross-filtering,
|
|
6
|
+
cross-highlighting, filter-aware grid totals and runtime DAX query factories.
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Visual Interactivity
|
|
10
|
+
|
|
11
|
+
Use this skill for coordinated semantic-model interactions. Visual components
|
|
12
|
+
emit selections and render their supplied tables; the Interaction Manager owns
|
|
13
|
+
accepted selections and compiles them into DAX filters.
|
|
14
|
+
The consuming template owns execution caching, client/bootstrap wiring and UI sequencing.
|
|
15
|
+
|
|
16
|
+
## Managed semantic-model interactions
|
|
17
|
+
|
|
18
|
+
Semantic-model-backed components on a page interact by default. When a page has
|
|
19
|
+
more than one semantic-model-backed visual, grid or slicer, wire those components
|
|
20
|
+
through one Interaction Manager even when the user did not explicitly request
|
|
21
|
+
interactions. Preserve both source wiring and the appropriate cross-highlight
|
|
22
|
+
or cross-filter behavior.
|
|
23
|
+
|
|
24
|
+
Record-backed components do not participate in this default. On mixed pages,
|
|
25
|
+
do not wire unrelated record-backed visuals into semantic-model coordination.
|
|
26
|
+
|
|
27
|
+
Both `VegaVisual` and `DataGrid` expose selection props. Bind them to the
|
|
28
|
+
manager-owned source; do not mirror accepted selections into local state.
|
|
29
|
+
Register raw model identity fields through `selectableFields` and preserve every
|
|
30
|
+
complete compiled filter argument without extracting, splitting or dropping predicates.
|
|
31
|
+
|
|
32
|
+
## Implementation workflow
|
|
33
|
+
|
|
34
|
+
1. Identify the semantic model, selectable field identities, sources and targets.
|
|
35
|
+
For purely chart-local emphasis, use [native selections](references/native-selections.md).
|
|
36
|
+
2. Configure one manager per interaction boundary and wrap the coordinated
|
|
37
|
+
components in its provider. Follow [manager configuration](references/interaction-manager.md#configure-the-manager)
|
|
38
|
+
and choose each target's capabilities from [coordinated visuals](references/interaction-manager.md#coordinated-visuals).
|
|
39
|
+
3. Bind selectable sources with `useManagedInteractionSource` and load receiving
|
|
40
|
+
targets with `useQueryFactoryTarget`. Follow [source binding](references/interaction-manager.md#bind-sources)
|
|
41
|
+
and [query factories](references/query-factories.md). Target-only components use
|
|
42
|
+
`selectableFields: []` and do not receive source props; see
|
|
43
|
+
[target-only components](references/query-factories.md#target-only-components).
|
|
44
|
+
4. Configure [highlight alignment](references/highlight-queries.md) for supported
|
|
45
|
+
targets. Pass aligned tables and their highlight flag together, with the existing
|
|
46
|
+
spec unchanged. For Top N or other non-grouped queries, follow
|
|
47
|
+
[advanced query shapes](references/advanced-query-shapes.md).
|
|
48
|
+
5. Keep body rows and provided totals together using
|
|
49
|
+
[filter-aware grid totals](references/filter-aware-grid-totals.md).
|
|
50
|
+
On `refresh-error`, show the diagnostic and label retained data as stale.
|
|
51
|
+
With no previous data, explain that the visual could not load. Follow
|
|
52
|
+
[loading and failure guidance](references/query-factories.md#present-loading-and-failures).
|
|
53
|
+
6. Verify repeated selection, deselection, empty results and query failures in the implementation.
|
|
54
|
+
Preserve the consuming template's resolved theme and runtime conventions.
|
|
55
|
+
Interaction tests are an optional follow-up on user request.
|
|
56
|
+
|
|
57
|
+
## Reference materials
|
|
58
|
+
|
|
59
|
+
Read only the references needed for the page:
|
|
60
|
+
|
|
61
|
+
| Topic | Reference |
|
|
62
|
+
|---|---|
|
|
63
|
+
| API surface, manager configuration, source binding and target capabilities | [Interaction Manager](references/interaction-manager.md) |
|
|
64
|
+
| Runtime variants, complete DAX filters and target loading | [Query factories](references/query-factories.md) |
|
|
65
|
+
| Baseline/subset alignment and rendering | [Highlight queries](references/highlight-queries.md) |
|
|
66
|
+
| Measures-only, multiple-base, outer-context and Top N queries | [Advanced query shapes](references/advanced-query-shapes.md) |
|
|
67
|
+
| DataGrid local filters and provided totals | [Filter-aware grid totals](references/filter-aware-grid-totals.md) |
|
|
68
|
+
| Chart-local click and hover emphasis | [Native selections](references/native-selections.md) |
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Advanced Query Shapes
|
|
2
|
+
|
|
3
|
+
Read this after the grouped-query example in [query factories](query-factories.md)
|
|
4
|
+
when a target's query is not a single top-level `SUMMARIZECOLUMNS`.
|
|
5
|
+
|
|
6
|
+
## Where to insert filters
|
|
7
|
+
|
|
8
|
+
Apply the complete filter list wherever a base result is evaluated, before any
|
|
9
|
+
ranking or combining. The examples below show one filter for brevity.
|
|
10
|
+
|
|
11
|
+
### Measures-only and columns-only queries
|
|
12
|
+
|
|
13
|
+
Wrap a measures-only `ROW`, or a columns-only `VALUES`, `DISTINCT`, or
|
|
14
|
+
`SUMMARIZE`, in `CALCULATETABLE`. Filters follow the base expression here, so
|
|
15
|
+
each needs a leading comma instead of a trailing one:
|
|
16
|
+
|
|
17
|
+
```dax
|
|
18
|
+
EVALUATE
|
|
19
|
+
CALCULATETABLE(
|
|
20
|
+
ROW("Sales", [Total Sales], "Quantity", [Total Quantity]),
|
|
21
|
+
TREATAS({ "West" }, 'Geography'[Region])
|
|
22
|
+
)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```dax
|
|
26
|
+
EVALUATE
|
|
27
|
+
CALCULATETABLE(
|
|
28
|
+
VALUES('Product'[Name]),
|
|
29
|
+
TREATAS({ "West" }, 'Geography'[Region])
|
|
30
|
+
)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
With no filters, keep the original expression or a wrapper without a dangling
|
|
34
|
+
comma. Keep an existing `DISTINCT` or `SUMMARIZE` rather than switching to
|
|
35
|
+
`VALUES`, which can change BLANK or distinct results.
|
|
36
|
+
|
|
37
|
+
Author `CALCULATETABLE(ROW(...)/*__FILTER_ARGUMENTS__*/)` and call
|
|
38
|
+
`insertInteractionFilters(baseQuery, interactionFilters, marker, "afterTable")`.
|
|
39
|
+
The helper owns the leading commas; do not add a comma beside the marker.
|
|
40
|
+
|
|
41
|
+
### Multiple bases and nested operations
|
|
42
|
+
|
|
43
|
+
When a query combines several base results, apply the complete filter list to
|
|
44
|
+
each one. Filtering only the final result cannot recalculate the bases:
|
|
45
|
+
|
|
46
|
+
```dax
|
|
47
|
+
DEFINE
|
|
48
|
+
VAR _region = TREATAS({ "West" }, 'Geography'[Region])
|
|
49
|
+
VAR _internet =
|
|
50
|
+
SUMMARIZECOLUMNS(
|
|
51
|
+
'Product'[Name], _region, "Sales", [Internet Sales]
|
|
52
|
+
)
|
|
53
|
+
VAR _reseller =
|
|
54
|
+
SUMMARIZECOLUMNS(
|
|
55
|
+
'Product'[Name], _region, "Sales", [Reseller Sales]
|
|
56
|
+
)
|
|
57
|
+
EVALUATE
|
|
58
|
+
INTERSECT(
|
|
59
|
+
SUMMARIZE(_internet, 'Product'[Name]),
|
|
60
|
+
SUMMARIZE(_reseller, 'Product'[Name])
|
|
61
|
+
)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
If you use several insertion markers, give each a distinct name, check that
|
|
65
|
+
each occurs exactly once, and insert the complete list at every marker.
|
|
66
|
+
Call `insertInteractionFilters` once for each marker. Do not parse a completed
|
|
67
|
+
query to discover insertion points.
|
|
68
|
+
|
|
69
|
+
For `TOPN` or `FILTER`, keep the filters inside the base beneath the outer
|
|
70
|
+
operation. A columns-only base uses the `CALCULATETABLE` wrapper shown above.
|
|
71
|
+
|
|
72
|
+
```dax
|
|
73
|
+
EVALUATE
|
|
74
|
+
TOPN(
|
|
75
|
+
10,
|
|
76
|
+
SUMMARIZECOLUMNS(
|
|
77
|
+
'Product'[Name],
|
|
78
|
+
TREATAS({ "West" }, 'Geography'[Region]),
|
|
79
|
+
"Sales", [Total Sales]
|
|
80
|
+
),
|
|
81
|
+
[Sales], DESC
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Queries with an outer filter context
|
|
86
|
+
|
|
87
|
+
The examples above are top-level queries, so they need no `KEEPFILTERS`. If a
|
|
88
|
+
base expression is evaluated inside outer filters, such as a `CALCULATETABLE`
|
|
89
|
+
with its own filter arguments, an interaction filter replaces outer filters on
|
|
90
|
+
the columns it references. To intersect with them instead, wrap the whole
|
|
91
|
+
argument in `KEEPFILTERS(...)`. `SUMMARIZECOLUMNS` currently rejects a mix of
|
|
92
|
+
`KEEPFILTERS` and unwrapped filters on the same table, so wrap all of that
|
|
93
|
+
table's filters. Do not add `KEEPFILTERS` to top-level queries or to change a
|
|
94
|
+
measure's intended behavior.
|
|
95
|
+
|
|
96
|
+
## Top N highlight targets
|
|
97
|
+
|
|
98
|
+
Cross-filtering may change which groups make the Top N. Cross-highlighting must
|
|
99
|
+
keep the baseline's groups. Do not rerun `TOPN` under highlight filters: a
|
|
100
|
+
displayed group can drop out of that ranking even though it has a highlighted
|
|
101
|
+
value, and alignment cannot recover a row the query never returned.
|
|
102
|
+
|
|
103
|
+
Instead, load the baseline first. Serialize its target keys with
|
|
104
|
+
`createBaselineKeyFilter`, and pass that filter plus the complete highlight
|
|
105
|
+
scope to a separate, **unranked** factory. `useQueryFactoryTarget` runs one
|
|
106
|
+
factory for both queries, so write this loader for `useManagedInteractionTarget`:
|
|
107
|
+
|
|
108
|
+
```tsx
|
|
109
|
+
import { useCallback } from "react";
|
|
110
|
+
import { createBaselineKeyFilter, createHighlightData } from "@microsoft/fabric-interaction-manager";
|
|
111
|
+
import type { InteractionTargetData, InteractionTargetLoadContext } from "@microsoft/fabric-interaction-manager";
|
|
112
|
+
import { useManagedInteractionTarget } from "@microsoft/fabric-interaction-manager/react";
|
|
113
|
+
import { executeQueryFactory } from "@/lib/query-factory";
|
|
114
|
+
|
|
115
|
+
const loadData = useCallback(
|
|
116
|
+
async ({ isCrossHighlightActive, compiledFilters }: InteractionTargetLoadContext): Promise<InteractionTargetData> => {
|
|
117
|
+
const all: DataTable = await executeQueryFactory(topCategories({
|
|
118
|
+
interactionFilters: compiledFilters.getFilters("baseline"),
|
|
119
|
+
}));
|
|
120
|
+
if (isCrossHighlightActive && all.rows.length > 0) {
|
|
121
|
+
const baselineKeys: string = createBaselineKeyFilter(all, {
|
|
122
|
+
CategoryKey: { table: "Product", column: "CategoryKey", dataType: "number" },
|
|
123
|
+
});
|
|
124
|
+
const subset: DataTable = await executeQueryFactory(unrankedCategories({
|
|
125
|
+
interactionFilters: [...compiledFilters.getFilters("highlight"), baselineKeys],
|
|
126
|
+
}));
|
|
127
|
+
return createHighlightData(all, subset, ["CategoryKey"], { Value: 0 }, ["Value"]);
|
|
128
|
+
}
|
|
129
|
+
return { all, highlighted: all };
|
|
130
|
+
},
|
|
131
|
+
[],
|
|
132
|
+
);
|
|
133
|
+
const result = useManagedInteractionTarget("topCategories", loadData);
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Memoize the loader and list its app inputs as dependencies; each new loader
|
|
137
|
+
identity starts a new load. `executeQueryFactory` uses the same execution and errors
|
|
138
|
+
as `useQueryFactoryTarget`; do not call React query hooks from a loader.
|
|
139
|
+
|
|
140
|
+
The key mapping uses the target query's result aliases. Map every tuple key to its physical model column. Do not infer model identifiers
|
|
141
|
+
from aliases or hand-write literals. The resulting query has this shape:
|
|
142
|
+
|
|
143
|
+
```dax
|
|
144
|
+
EVALUATE
|
|
145
|
+
SUMMARIZECOLUMNS(
|
|
146
|
+
'Product'[Category],
|
|
147
|
+
TREATAS({ "Bikes", "Accessories" }, 'Product'[Category]),
|
|
148
|
+
TREATAS({ "West" }, 'Geography'[Region]),
|
|
149
|
+
"Sales", [Total Sales]
|
|
150
|
+
)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
For an empty baseline, `createBaselineKeyFilter` returns a filter that matches
|
|
154
|
+
nothing; the loader above skips the highlight query instead. The displayed
|
|
155
|
+
highlight flag still remains true for an active selection matching no baseline groups.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Filter-Aware DataGrid Totals
|
|
2
|
+
|
|
3
|
+
DataGrid filters locally by default but does not recompute provided totals. Re-query the total without removing body rows needed for local filtering.
|
|
4
|
+
|
|
5
|
+
## Query shape
|
|
6
|
+
|
|
7
|
+
Extend the [flagged rollup](../../query-design/references/multi-grain-patterns.md#datagrid-grand-total-query), retaining its metadata and payload limits. Return body rows and total in one query; put local filters in `ROLLUPADDISSUBTOTAL`'s optional `grandtotalFilter`:
|
|
8
|
+
|
|
9
|
+
```dax
|
|
10
|
+
DEFINE
|
|
11
|
+
VAR _GrandTotalFilter =
|
|
12
|
+
TREATAS({<selected-values>}, '<GridDimension>'[<GridColumn>])
|
|
13
|
+
|
|
14
|
+
EVALUATE
|
|
15
|
+
SUMMARIZECOLUMNS(
|
|
16
|
+
ROLLUPADDISSUBTOTAL(
|
|
17
|
+
_GrandTotalFilter,
|
|
18
|
+
ROLLUPGROUP(
|
|
19
|
+
'<Dimension1>'[<Column1>],
|
|
20
|
+
'<Dimension2>'[<Column2>]
|
|
21
|
+
),
|
|
22
|
+
"IsGrandTotal"
|
|
23
|
+
),
|
|
24
|
+
"<MetricAlias>", [<Measure>]
|
|
25
|
+
)
|
|
26
|
+
ORDER BY
|
|
27
|
+
'<Dimension1>'[<Column1>] ASC,
|
|
28
|
+
'<Dimension2>'[<Column2>] ASC
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
With no local filter, omit `_GrandTotalFilter` and its argument. For multiple filters, `CROSSJOIN` one `TREATAS` table per known filterable column.
|
|
32
|
+
|
|
33
|
+
## Factory safety
|
|
34
|
+
|
|
35
|
+
Use a typed [query factory](query-factories.md): map `GridColumnDef.id` through a closed DAX-column map, reject unknown IDs, and escape literals by type. Application/page filters affect body and totals; local grid filters go only in `grandtotalFilter`.
|
|
36
|
+
|
|
37
|
+
## Component wiring
|
|
38
|
+
|
|
39
|
+
```tsx
|
|
40
|
+
import { useState } from "react";
|
|
41
|
+
import type { CellValue } from "@microsoft/fabric-datagrid";
|
|
42
|
+
import { toRollupDataTables } from "@/lib/to-data-table";
|
|
43
|
+
|
|
44
|
+
const [gridFilters, setGridFilters] = useState<Record<string, CellValue[]>>({});
|
|
45
|
+
const config = revenueByRegion({ filters: gridFilters });
|
|
46
|
+
const result = useSemanticModelQuery({
|
|
47
|
+
connection: config.connection,
|
|
48
|
+
query: config.query,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
if (result.error) return <ErrorMessage message={result.error.message} />;
|
|
52
|
+
if (!result.data && result.isLoading) return <LoadingSpinner />;
|
|
53
|
+
if (result.data?.status === "error") {
|
|
54
|
+
return <ErrorMessage message={result.data.error.message} />;
|
|
55
|
+
}
|
|
56
|
+
if (result.data?.status !== "success") return null;
|
|
57
|
+
|
|
58
|
+
const { bodyTable, grandTotalTable } = toRollupDataTables(
|
|
59
|
+
result.data.table,
|
|
60
|
+
config.columnMetadata,
|
|
61
|
+
{ rollupFlagColumns: ["[IsGrandTotal]"] },
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
<DataGrid
|
|
65
|
+
data={bodyTable}
|
|
66
|
+
grandTotals={{ position: "bottom", data: grandTotalTable }}
|
|
67
|
+
onFilterChange={(columnId, selectedValues) =>
|
|
68
|
+
setGridFilters((current) => ({ ...current, [columnId]: selectedValues }))
|
|
69
|
+
}
|
|
70
|
+
theme={theme}
|
|
71
|
+
/>
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Changing `gridFilters` re-queries; the hook retains the previous result while loading. Keep rendering the body and replace the total only on success. Always pass `grandTotalTable` through `grandTotals.data`; omitting it selects client-computed totals.
|
|
75
|
+
|
|
76
|
+
## Managed targets
|
|
77
|
+
|
|
78
|
+
When the grid is an Interaction Manager target, load the same combined flagged query through `useQueryFactoryTarget`, then split the accepted table with `splitRollupDataTable` so the body and total come from one result. The hook has already applied the column metadata, so name flag and internal columns by their converted `name` aliases.
|
|
79
|
+
|
|
80
|
+
The factory also accepts `ManagedQueryFactoryParams` and inserts the interaction filters after `ROLLUPADDISSUBTOTAL(...)` and before the measures (`"beforeMeasures"`), so they constrain both body rows and the total. DataGrid's local column filters still constrain only the total through `grandtotalFilter`.
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
import { useQueryFactoryTarget } from "@/hooks/use-query-factory-target";
|
|
84
|
+
import { splitRollupDataTable } from "@/lib/to-data-table";
|
|
85
|
+
|
|
86
|
+
const result = useQueryFactoryTarget("revenueGrid", revenueByRegion, { filters: gridFilters });
|
|
87
|
+
|
|
88
|
+
if (result.status === "loading") return <LoadingSpinner />;
|
|
89
|
+
if (result.status === "error") return <ErrorMessage message={result.error.message} />;
|
|
90
|
+
|
|
91
|
+
const { bodyTable, grandTotalTable } = splitRollupDataTable(result.data, {
|
|
92
|
+
rollupFlagColumns: ["IsGrandTotal"],
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Render `DataGrid` with `bodyTable`, `grandTotals.data`, and `onFilterChange` as
|
|
97
|
+
above, adding the source props when the grid is also a source. During
|
|
98
|
+
`"refreshing"` or `"refresh-error"`, `result.data` keeps the previous body and
|
|
99
|
+
total together. On `"refresh-error"`, keep the grid visible and render
|
|
100
|
+
`result.error.message` in an alert alongside it. Label the retained tables as
|
|
101
|
+
stale. An `"error"` has no prior tables.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Highlight Queries
|
|
2
|
+
|
|
3
|
+
Cross-highlighting keeps the baseline visible and draws a re-aggregated subset
|
|
4
|
+
over it. Load both with `useQueryFactoryTarget` and a highlight alignment, then
|
|
5
|
+
pass them to `VegaVisual` with the target's existing spec. This extends the
|
|
6
|
+
filter-only target in [query factories](query-factories.md#load-the-target).
|
|
7
|
+
|
|
8
|
+
## Load and align
|
|
9
|
+
|
|
10
|
+
Pass the `createHighlightData` settings as the hook's fourth argument. During an
|
|
11
|
+
active cross-highlight, the hook runs the factory under the baseline and
|
|
12
|
+
highlight filters and aligns the subset with the baseline. Otherwise it runs
|
|
13
|
+
only the baseline and returns it as both datasets.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import type { HighlightAlignment } from "@/hooks/use-query-factory-target";
|
|
17
|
+
|
|
18
|
+
const categoryAlignment: HighlightAlignment = {
|
|
19
|
+
groupingFields: ["Category"],
|
|
20
|
+
missingMeasureReplacementValues: { Value: 0 },
|
|
21
|
+
plottedMeasureFields: ["Value"],
|
|
22
|
+
};
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
When writing the alignment:
|
|
26
|
+
|
|
27
|
+
- List every group and series key in `groupingFields`, including hidden
|
|
28
|
+
identifiers. Alignment uses raw key values; never substitute localized display
|
|
29
|
+
labels. A series field requires alignment by both category and series.
|
|
30
|
+
- Alignment throws on duplicate tuples and on subset tuples outside the baseline.
|
|
31
|
+
- In `missingMeasureReplacementValues`, give each measure the value for a baseline
|
|
32
|
+
group absent from the subset: `0` when absence means zero, as for sums and
|
|
33
|
+
counts, or `null` to keep BLANK, as for ratios.
|
|
34
|
+
- List the measures the chart draws in `plottedMeasureFields`.
|
|
35
|
+
|
|
36
|
+
For Top N, do not rerun the ranking under highlight filters; see
|
|
37
|
+
[Top N highlight targets](advanced-query-shapes.md#top-n-highlight-targets).
|
|
38
|
+
|
|
39
|
+
## Render the target
|
|
40
|
+
|
|
41
|
+
Pass the target's existing spec unchanged. Do not author overlay layers, sort
|
|
42
|
+
fields, or radius calculations. Bind the source and target beneath the same
|
|
43
|
+
provider and call all hooks before early returns:
|
|
44
|
+
|
|
45
|
+
```tsx
|
|
46
|
+
const source = useManagedInteractionSource("categoryChart");
|
|
47
|
+
const result = useQueryFactoryTarget("categoryChart", categoryChart, {}, categoryAlignment);
|
|
48
|
+
if (result.status === "loading") return <div>Loading...</div>;
|
|
49
|
+
if (result.status === "error") return <div role="alert">{result.error.message}</div>;
|
|
50
|
+
|
|
51
|
+
return <>
|
|
52
|
+
{source.error && <div role="alert">{source.error.message}</div>}
|
|
53
|
+
<VegaVisual
|
|
54
|
+
spec={vegaLiteSpec}
|
|
55
|
+
data={result.data}
|
|
56
|
+
isCrossHighlightActive={result.isCrossHighlightActive}
|
|
57
|
+
selections={source.selections}
|
|
58
|
+
selectableFields={source.selectableFields}
|
|
59
|
+
onInteraction={source.onInteraction}
|
|
60
|
+
theme={theme}
|
|
61
|
+
/>
|
|
62
|
+
{result.status === "refreshing" && <div role="status">Refreshing...</div>}
|
|
63
|
+
</>;
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Always pass `result.data` with `result.isCrossHighlightActive` from the same
|
|
67
|
+
result; while refreshing or after a refresh error, both still describe the
|
|
68
|
+
previous successful load. On `"refresh-error"`, keep the chart visible and show
|
|
69
|
+
the diagnostic alongside it, identifying retained tables as stale, using the
|
|
70
|
+
[loading and failure guidance](query-factories.md#present-loading-and-failures).
|
|
71
|
+
If a new baseline succeeds but its highlighted-subset query fails, the hook
|
|
72
|
+
retains the entire previous result, not a new baseline combined with an old
|
|
73
|
+
highlight. Never use the latest selection's highlight flag with retained data.
|
|
74
|
+
Use the resolved `theme` from the host template without replacing its theme or
|
|
75
|
+
auth bootstrap.
|
|
76
|
+
|
|
77
|
+
With an active highlight, `VegaVisual` dims the baseline and draws the
|
|
78
|
+
highlighted values on top; generated data labels stay on the baseline values.
|
|
79
|
+
If it reports a cross-highlight diagnostic and renders only the highlighted rows,
|
|
80
|
+
check the supported shapes in the README's
|
|
81
|
+
[Cross-highlight overlays](../../../../node_modules/@microsoft/fabric-interaction-manager/README.md#cross-highlight-overlays),
|
|
82
|
+
then simplify the spec to a supported shape or set `canHighlight: false`.
|
|
83
|
+
|
|
84
|
+
A spec that references named datasets receives `all` and `highlighted` and draws
|
|
85
|
+
its own layers instead. Use this only when a highlight target needs layers the
|
|
86
|
+
automatic overlay cannot draw, and verify that the layers keep the baseline
|
|
87
|
+
geometry. See the visuals skill's
|
|
88
|
+
[multi-data input](../../visuals/references/multi-data-input.md) for named data.
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# Managed Visual Interactivity
|
|
2
|
+
|
|
3
|
+
Use this reference to implement semantic-model-backed visual selections and coordinated behavior. Visual components emit selections and render the tables they receive. For report interactions, an `InteractionManager` from `@microsoft/fabric-interaction-manager` owns the selection state and compiles it into DAX filters for the other visuals' queries.
|
|
4
|
+
|
|
5
|
+
## Choose the implementation
|
|
6
|
+
|
|
7
|
+
This file covers manager configuration, source binding, and target capabilities. Read a reference only when the page needs it:
|
|
8
|
+
|
|
9
|
+
| Behavior | Read |
|
|
10
|
+
|---|---|
|
|
11
|
+
| Highlight or dim marks inside one chart | [Native selections](native-selections.md) |
|
|
12
|
+
| Coordinate the visuals, grids, and slicers on a page | [Interaction Manager](#interaction-manager) below, then [Query factories](query-factories.md) for every target's filter insertion and loading |
|
|
13
|
+
| Cross-highlight a bar, column, pie, or donut target | [Highlight queries](highlight-queries.md) |
|
|
14
|
+
| Filter a measures-only, columns-only, multiple-base, or Top N query, or one with an outer filter context | [Advanced query shapes](advanced-query-shapes.md) |
|
|
15
|
+
| Keep a provided DataGrid total aligned with local filters, including a managed grid | [Filter-aware grid totals](filter-aware-grid-totals.md) |
|
|
16
|
+
| Change DAX or a spec from other runtime state | [Query factories](query-factories.md#structural-variants) |
|
|
17
|
+
| Publish predicates from a custom control | The installed Interaction Manager package README: sets, ranges, BLANK, dates, text |
|
|
18
|
+
|
|
19
|
+
Prefer native Vega-Lite behavior for styling that is entirely local to one chart. Route selections that affect other visuals through the Interaction Manager.
|
|
20
|
+
|
|
21
|
+
The API surface below and the references' examples cover every export a template page needs, so do not search the package's `.d.ts` files.
|
|
22
|
+
|
|
23
|
+
## API surface
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// Root entry: no React dependency.
|
|
27
|
+
import {
|
|
28
|
+
InteractionManager, // new InteractionManager(configuration: InteractionConfiguration)
|
|
29
|
+
createHighlightData, // (all, highlightedSubset, groupingFields: readonly string[], missingMeasureReplacementValues: Record<string, number | null>, plottedMeasureFields: readonly string[]) => { all: DataTable; highlighted: DataTable }
|
|
30
|
+
} from "@microsoft/fabric-interaction-manager";
|
|
31
|
+
import type {
|
|
32
|
+
InteractionConfiguration, // { semanticModelId: string; fields: Record<string, InteractionField>; components: Record<string, InteractionComponent>; rules?: InteractionRule[] }
|
|
33
|
+
InteractionField, // { table: string; column: string; dataType: "string" | "number" | "boolean" | "date" | "datetime" }
|
|
34
|
+
InteractionComponent, // { kind?: "visual" | "grid" | "slicer" | "custom"; selectableFields?: string[]; sourceEffect?: "filter" | "auto"; canFilter?: boolean; canHighlight?: boolean; receivesInteractionsByDefault?: boolean }
|
|
35
|
+
InteractionRule, // { sourceId: string; targetId: string; targetEffect: "filter" | "highlight" | "none" }
|
|
36
|
+
ManagedQueryFactoryParams, // { interactionFilters?: readonly string[] }
|
|
37
|
+
InteractionTargetLoadContext,// { isCrossHighlightActive: boolean; compiledFilters: CompiledDaxFilters }
|
|
38
|
+
CompiledDaxFilters, // getFilters(mode: "baseline" | "highlight"): readonly string[]
|
|
39
|
+
InteractionTargetData, // DataTable | { all: DataTable; highlighted: DataTable }
|
|
40
|
+
ManagedTargetLoadState, // loading | ready | refreshing | refresh-error (retained data and error) | error (no data)
|
|
41
|
+
ManagedInteractionSource, // { selections; selectableFields; onInteraction; error?: Error }
|
|
42
|
+
} from "@microsoft/fabric-interaction-manager";
|
|
43
|
+
|
|
44
|
+
// React entry.
|
|
45
|
+
import {
|
|
46
|
+
InteractionManagerProvider, // <InteractionManagerProvider manager={manager}>
|
|
47
|
+
useManagedInteractionSource, // (sourceId: string) => ManagedInteractionSource
|
|
48
|
+
useManagedInteractionTarget, // (targetId: string, loader: (context: InteractionTargetLoadContext) => Promise<InteractionTargetData>) => ManagedTargetLoadState
|
|
49
|
+
useInteractionManager, // () => InteractionManager; call .clearAll() to reset every source
|
|
50
|
+
} from "@microsoft/fabric-interaction-manager/react";
|
|
51
|
+
|
|
52
|
+
// Template helpers.
|
|
53
|
+
import { useQueryFactoryTarget } from "@/hooks/use-query-factory-target";
|
|
54
|
+
// useQueryFactoryTarget(targetId, factory, params, highlightAlignment?: HighlightAlignment) => QueryFactoryTargetState
|
|
55
|
+
// data is DataTable, or { all, highlighted } with highlightAlignment: { groupingFields; missingMeasureReplacementValues; plottedMeasureFields }
|
|
56
|
+
import { executeQueryFactory, insertInteractionFilters } from "@/lib/query-factory";
|
|
57
|
+
// executeQueryFactory(factory: { connection, query, columnMetadata }): Promise<DataTable>; for custom loaders
|
|
58
|
+
// insertInteractionFilters(query, filters, marker, position: "beforeMeasures" | "afterTable"): string
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Selection types (`SemanticSelection`, `InteractionPredicate`, `InteractionValue`, `RangeBoundary`) and `isDataTable` come from `@microsoft/fabric-visuals-core`.
|
|
62
|
+
|
|
63
|
+
## Interaction Manager
|
|
64
|
+
|
|
65
|
+
### Configure the manager
|
|
66
|
+
|
|
67
|
+
Configure one `InteractionManager` per interaction boundary, at the nearest common host of the coordinated components, and wrap that part of the page in `InteractionManagerProvider`. Create it once with `useState(() => new InteractionManager(configuration))`; configuration is fixed for the manager's lifetime. The installed package README's Configure a manager section lists each component kind's defaults and pair overrides through `rules`; read it only when the page needs to change those defaults.
|
|
68
|
+
|
|
69
|
+
When writing the configuration for a template page:
|
|
70
|
+
|
|
71
|
+
- Set `semanticModelId` to the one semantic model whose fields this manager configures.
|
|
72
|
+
- Key `fields` by the bracket-free column aliases in query results, and map each to its model table, column, and data type.
|
|
73
|
+
- List each source's `selectableFields` explicitly; an omitted list means every configured field. Keep those columns, with their raw model values rather than formatted labels, in the source's data even when hidden.
|
|
74
|
+
- Use `kind: "visual"` for charts, `"grid"` for `DataGrid`, and `"slicer"` for slicers. Set `canHighlight` on each visual as described in [Coordinated visuals](#coordinated-visuals).
|
|
75
|
+
- For `kind: "custom"` components, including target-only KPIs, explicitly set `sourceEffect` (`"filter"` or `"auto"`), `canFilter`, and `canHighlight`; custom components have no defaults for these three properties.
|
|
76
|
+
|
|
77
|
+
### Bind sources
|
|
78
|
+
|
|
79
|
+
Bind each component that has selectable model-field identities as a source. Charts and grids that receive interactions are sources too; slicers and custom controls add sources rather than replacing them:
|
|
80
|
+
|
|
81
|
+
```tsx
|
|
82
|
+
const source = useManagedInteractionSource("salesChart");
|
|
83
|
+
|
|
84
|
+
<VegaVisual spec={vegaLiteSpec} data={result.data} theme={theme}
|
|
85
|
+
isCrossHighlightActive={result.isCrossHighlightActive}
|
|
86
|
+
selections={source.selections} selectableFields={source.selectableFields}
|
|
87
|
+
onInteraction={source.onInteraction} />
|
|
88
|
+
{source.error && <div role="alert">{source.error.message}</div>}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
- `DataGrid` takes the same source props. Controlled chart selection requires a Vega-Lite spec.
|
|
92
|
+
- Each click publishes the component's complete selection. When the manager rejects a selection, it sets `source.error` and keeps the previously accepted selection.
|
|
93
|
+
- The manager owns accepted selections. Do not mirror them into component state.
|
|
94
|
+
- Slicers only report selections: pass `source.onInteraction` and render `source.error`. Slicers that report interactions reject JavaScript `Date` values, so pass dates as the strings the model returns.
|
|
95
|
+
- Clear one source by passing `[{ action: "clear" }]` to its `onInteraction`, or every source with `useInteractionManager().clearAll()`. Controlled components update without raising selection events.
|
|
96
|
+
|
|
97
|
+
Load every component that receives interactions with `useQueryFactoryTarget`; see [Query factories](query-factories.md). A shared chart or grid wrapper binds both hooks and passes the source props; render target-only components through a separate path.
|
|
98
|
+
|
|
99
|
+
A component is target-only when its rows have no selectable identities, such as a measures-only grid, or when the user asks for it. Register it with `selectableFields: []`, load it as a target, and render it without source props as shown in [Query factories](query-factories.md#load-the-target).
|
|
100
|
+
|
|
101
|
+
## Coordinated visuals
|
|
102
|
+
|
|
103
|
+
- **Cross-filtering** re-evaluates the target under the manager's compiled DAX filters. Do not filter pre-aggregated results in the browser; it cannot recalculate distinct counts, ratios, totals, or selections on unprojected columns. See [Query factories](query-factories.md).
|
|
104
|
+
- **Cross-highlighting** keeps the full baseline visible, dimmed, and draws the selected subset bright on top. Re-aggregate the subset at the baseline's grouping, measures, and row set rather than filtering an already aggregated baseline table. See [Highlight queries](highlight-queries.md).
|
|
105
|
+
- **Local presentation filters**, such as a search box over loaded grid rows or a Vega-Lite filter inside one unmanaged visual, only restrict displayed rows and can run in the browser. Label any subtotal over locally filtered rows accordingly.
|
|
106
|
+
|
|
107
|
+
Choose each visual target's `canHighlight` from its mark type and measures:
|
|
108
|
+
|
|
109
|
+
| Visual | Target configuration |
|
|
110
|
+
|---|---|
|
|
111
|
+
| Bar and column, including stacked and clustered | Cross-highlight with a highlight alignment; pass the spec unchanged |
|
|
112
|
+
| Pie and donut | Cross-highlight when the measures are non-negative and additive; otherwise `canHighlight: false` |
|
|
113
|
+
| Line and scatter | `canHighlight: false`; they receive cross-filters |
|
|
114
|
+
| Other shapes and layered combinations | `canHighlight: false` unless the target draws its own layers from named data; see [Highlight queries](highlight-queries.md#render-the-target) |
|
|
115
|
+
|
|
116
|
+
Implement the manager configuration and highlight alignment together. `createHighlightData` falls back to showing the highlighted values as the main values when they cannot be drawn as a part of the baseline, so wire highlighting by visual type without checking each source's relationships or measure definitions.
|
|
117
|
+
|
|
118
|
+
## Implementation workflow
|
|
119
|
+
|
|
120
|
+
1. Identify the sources, targets, and each target's behavior from [Coordinated visuals](#coordinated-visuals).
|
|
121
|
+
2. Discover the model fields, then register fields and components in one `InteractionManager` at the nearest common host of the coordinated visuals.
|
|
122
|
+
3. Read [Query factories](query-factories.md). Accept `ManagedQueryFactoryParams` in each target's query factory and load it with `useQueryFactoryTarget`. Before loading a bar, column, pie, or donut target, read [Highlight queries](highlight-queries.md); for other query shapes, use the table in [Choose the implementation](#choose-the-implementation).
|
|
123
|
+
4. Bind every source with `useManagedInteractionSource` and pass its props to the rendered component.
|
|
124
|
+
5. Keep showing the previous result while a replacement query is loading.
|
|
125
|
+
A `refresh-error` preserves prior data and its highlight flag; show the error
|
|
126
|
+
and label the retained result as stale. An `error` has no successful data.
|
|
127
|
+
6. Verify repeated selection, deselection, empty results, and query failures.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Native Vega-Lite Selections
|
|
2
|
+
|
|
3
|
+
For chart-local click or hover emphasis, use a selection with conditional encoding. One `DataTable` is enough; no query or named datasets.
|
|
4
|
+
|
|
5
|
+
```json
|
|
6
|
+
{
|
|
7
|
+
"params": [{ "name": "sel", "select": { "type": "point", "fields": ["Category"] } }],
|
|
8
|
+
"mark": "bar",
|
|
9
|
+
"encoding": {
|
|
10
|
+
"x": { "field": "Category", "type": "nominal" },
|
|
11
|
+
"y": { "field": "Sales", "type": "quantitative" },
|
|
12
|
+
"opacity": {
|
|
13
|
+
"condition": { "param": "sel", "value": 1, "empty": false },
|
|
14
|
+
"value": 0.3
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
With `empty: false`, bars remain dimmed until selected. Leave native selection parameters out of specs bound to an Interaction Manager source. A managed source passes `selections`, `selectableFields`, and `onInteraction` to the visual, which dims its own unselected marks. Use a [query factory](query-factories.md) for recomputation.
|