diff --git a/skills/igniteui-blazor-components/SKILL.md b/skills/igniteui-blazor-components/SKILL.md index 5a3c451c..c7fc2896 100644 --- a/skills/igniteui-blazor-components/SKILL.md +++ b/skills/igniteui-blazor-components/SKILL.md @@ -50,6 +50,7 @@ All four use the `IgniteUI.Blazor.Controls` namespace and serve static assets fr - **`Name` is not an HTML name attribute.** On every Ignite UI component `Name` is the framework's element identity used for lookups. Do not use it to group radios or to name a form field. - **Forms.** There is no universal form-integration pattern; several components (`IgbCombo`, `IgbRadio`) do not participate in a plain HTML `
`. Bind explicitly with `@bind-Value` / `@bind-Checked` and check the component's doc before assuming form behavior. - **`*Script` parameters** take the *name* of a JavaScript function registered through `_content/IgniteUI.Blazor/api.js` (Lite) or the `igRegisterScript` window global (full product), not code. Use them for client-side templates (rendered per item in the browser, no server round trip). For events prefer the C# event; the script variant is for synchronous cancellation or purely client-side reactions. See [`client-scripts.md`](./references/client-scripts.md). +- **Event handlers and `StateHasChanged()`.** Ignite UI events are raised from JavaScript, outside Blazor's event batch. Most are `EventCallback` (`Select`, `Change`, `PagingDone`, `SortingDone`, …): like `@onclick`, the page re-renders when the handler reaches its first `await` (or returns) and again when its `Task` completes, so **do not call `StateHasChanged()` for the final state**. Each such call adds one more render, and before the first `await` it renders immediately, before the next line runs (in `@onclick` that part is batched). State set between two later `await`s is not rendered on its own, though: to show a "Saving…" message after a fetch, call `StateHasChanged()` right after setting it. Call it once, after the state change, where Blazor cannot see the change at all: a `[JSInvokable]` method called from a `*Script` handler, and the full product's `Action`-typed events: `IgbGrid` `CellEditDone` / `RowAdded` / `RowDeleted`; chart pointer-move events (`SeriesPointerMove` / `PlotAreaPointerMove`; `IgbDataChart` `SeriesMouseMove` / `SeriesCursorMouseMove`); `IgbDataChart` `PlotAreaMouseEnter` / `Leave` / `Over` and its `AxisLabelMouse*` / `AxisPanelMouse*` events; gauge `ValueChanged`, …. Other chart pointer events are `EventCallback`s: series Enter / Leave / Down / Up / Click, `IgbCategoryChart` `PlotAreaPointerEnter` / `Leave` / `Down` / `Up`, `IgbDataChart` `PlotAreaClicked` / `PlotAreaMouseLeftButtonDown` / `Up`, and `IgbPieChart` `SliceEnter` / `SliceHover` / `SliceLeave` / `SliceClick`. Check the parameter type with `get_api_reference`. An `Action` handler must return `void`. - **Dynamic `class` values** must be a single C# expression (`class="@ChipClass(item)"`). Mixing literal text with `@(...)` in one attribute raises **RZ9986**. ## MCP server (optional) diff --git a/skills/igniteui-blazor-components/references/charts.md b/skills/igniteui-blazor-components/references/charts.md index 2a348a66..fe0a3a76 100644 --- a/skills/igniteui-blazor-components/references/charts.md +++ b/skills/igniteui-blazor-components/references/charts.md @@ -108,6 +108,28 @@ The data source must expose `Open`, `High`, `Low`, `Close` (and usually `Volume` Binding shapes differ enough between these that guessing fails: read `get_doc` for `treemap-chart`, the geographic-map series types, the specific gauge, or `dashboard-tile` before writing markup. Map series (`IgbGeographicSymbolSeries`, `IgbGeographicShapeSeries`, `IgbGeographicPolylineSeries`, `IgbGeographicProportionalSymbolSeries`) are declared as child components, not added from code, and do not follow Data Chart axis conventions. +## Tooltips + +Tooltip support differs per component: + +| Component | Tooltip on hover | How to get one | +|---|---|---| +| `IgbCategoryChart`, `IgbFinancialChart` | Yes, by default | `ToolTipType`: `Data` (default), `Item`, `Category`, `Default`, `None` | +| `IgbDataPieChart` | Yes, by default | Built-in tooltip only — it has `ToolTipType` but **no** `TooltipTemplate`; `DataToolTipUnitsText="%"` appends a unit to the value | +| `IgbDataChart` series | No | `ShowDefaultTooltip="true"` or a `TooltipTemplate` on each series, **and** `IgbDataChartInteractivityModule` registered — without the module nothing shows and nothing is logged | +| `IgbPieChart` | No tooltip API | Handle `SliceHover` and position your own element at `e.Position`, which is relative to the chart element (wrap the chart in a `position: relative` element). `SliceEnter` / `SliceLeave` give the slice but no position (`e.Position` is `NaN`): use them to pick and hide the content, and show it once `SliceHover` supplies a position. Moving onto a new slice raises `SliceLeave` (old) and `SliceEnter` (new); `SliceHover` comes only with the next move | +| `IgbDoughnutChart` | No tooltip API; a template set from JS throws on hover ([#491](https://github.com/IgniteUI/igniteui-blazor/issues/491)) | For a ring with tooltips use `IgbDataPieChart` with `InnerExtent` (built-in tooltip; its `InnerExtent` scale differs from the doughnut's — about `0.35` gives a typical donut, `0.55` a thin ring), or `IgbPieChart` with `InnerExtent` plus the `SliceHover` approach above | +| `IgbSparkline`, `IgbRadialGauge` | No working tooltip | — | +| `IgbLinearGauge`, `IgbBulletGraph` | `ShowToolTip="true"` shows only an empty box | Wrap the gauge in an element with an `id` and anchor an `IgbTooltip` to it (see `data-display.md`) | + +- **`TooltipTemplate` on `IgbCategoryChart`** (a child `` `RenderFragment`; `context.Item` is your record) is used only with `ToolTipType` `Item`, `Category` or `Default`. With the default `Data` it is ignored and the built-in tooltip shows; with `None` nothing shows. +- **Guard the template context.** With `ToolTipType.Default`, and for an `IgbDataChart` series `TooltipTemplate`, the template is also rendered with a `null` `context`: `context.Item` then throws a `NullReferenceException` and Blazor shows its error UI. Write `@if (context?.Item is MyRecord row) { … }`. +- **Wrapper.** With `ToolTipType.Default` and on `IgbDataChart` series, the template sits in a `div.ui-tooltip-container` with a white background, a 1px `#666` border and 5px padding; `--tooltip-container-background-color` and `--tooltip-container-border-color` set on `:root` recolor it. With `Item` / `Category`, and with a tooltip layer, the wrapper is transparent over the canvas callout. +- **Placement.** `Data`, `Item` and `Category` tooltips render in a `div.ui-chart-pointer-tooltip-container` appended to ``, outside the chart. `IgbDataChart` series tooltips are a ``-level popover unless the series sets `AttachTooltipToRoot="false"` (ignored once a tooltip layer is present). Only `ToolTipType.Default` and `AttachTooltipToRoot="false"` keep the tooltip inside the chart element. +- **Styling templates.** Inline styles and global CSS always work. A plain selector in the page's `.razor.css` (`.tip`) matches a Razor `TooltipTemplate` wherever it renders, because the template's elements keep the scope attribute. In a ``-level tooltip, `::deep .x` reaches only elements nested inside the template's root, and selectors that start from a page element (`.page .tip`, `.page ::deep .tip`) match nothing; those work only when the tooltip stays inside the chart (`ToolTipType.Default`, or `AttachTooltipToRoot="false"` without a tooltip layer). A template set from JS (`series.tooltipTemplate = …`, for example in a `SeriesAddedScript` handler) carries no scope attribute: use global CSS or inline styles. +- **The `Data` tooltip is drawn on a canvas** — CSS cannot reach its text; use the `DataToolTip*` text parameters. +- **Callout box.** `Data`, `Item` and `Category` tooltips sit on a canvas callout (white fill, grey border) whose colors come from built-in defaults: no token or CSS rule sets them, and `IgbCategoryChart` / `IgbFinancialChart` have no parameter for it ([#493](https://github.com/IgniteUI/igniteui-blazor/issues/493)). In `IgbDataChart`, add an `IgbItemToolTipLayer` or `IgbCategoryToolTipLayer` and set `ToolTipBackground`, `ToolTipBorderBrush`, `ToolTipBorderThickness` (corner radius is not settable). A layer shows only series that have `ShowDefaultTooltip="true"` or a `TooltipTemplate`, and it also needs `IgbDataChartInteractivityModule`. + ## Cross-cutting rules **Explicit `Width` and `Height` are mandatory** — charts do not size to their container on their own. Inside a CSS Grid track also set `min-height: 0` on the cell and `Height="100%"` on the chart, or the track collapses to zero. @@ -124,4 +146,4 @@ Binding shapes differ enough between these that guessing fails: read `get_doc` f **Set visual parameters inline in markup, not via `@ref` in `OnAfterRenderAsync`** — assigning them to a component reference raises Blazor warning **BL0005** (component parameter set outside its component). -**Other common parameters:** default tooltips appear on hover with no configuration (`TooltipTemplate` replaces them); `IsTransitionInEnabled` / `TransitionInDuration` animate entry; `IsSeriesHighlightingEnabled` with `HighlightingMode` / `HighlightingBehavior` controls hover emphasis; `IsHorizontalZoomEnabled` / `IsVerticalZoomEnabled` and `CrosshairsDisplayMode` handle zoom and crosshairs. +**Other common parameters:** `IsTransitionInEnabled` / `TransitionInDuration` animate entry; `IsSeriesHighlightingEnabled` with `HighlightingMode` / `HighlightingBehavior` controls hover emphasis; `IsHorizontalZoomEnabled` / `IsVerticalZoomEnabled` and `CrosshairsDisplayMode` handle zoom and crosshairs. diff --git a/skills/igniteui-blazor-components/references/client-scripts.md b/skills/igniteui-blazor-components/references/client-scripts.md index c18dbb89..e8dca88e 100644 --- a/skills/igniteui-blazor-components/references/client-scripts.md +++ b/skills/igniteui-blazor-components/references/client-scripts.md @@ -97,4 +97,6 @@ registerScript('OnDialogClosing', (evt) => { }); ``` -The function is attached as a listener for the matching `igc*` DOM event on the component's element. `evt.detail` holds the event arguments where the event has any; cancelable events (`Opening`/`Closing` on dialogs, dropdowns and the like, `ActiveStepChanging` on the stepper, tree expand/collapse and selection changes, `Change` on some inputs) are cancelled with `evt.preventDefault()`. +The function is attached as a listener for the matching `igc*` DOM event on the component's element. `evt.detail` holds the event arguments where the event has any; cancelable events (`Opening`/`Closing` on dialogs, dropdowns and the like, `ActiveStepChanging` on the stepper, tree expand/collapse and selection changes, `Change` on some inputs) are cancelled with `evt.preventDefault()`. The grids (`IgbGrid`, `IgbTreeGrid`, `IgbHierarchicalGrid`) and `IgbPaginator` are different: none of their events is cancelable, and `preventDefault()` is ignored. Cancel a grid action by setting `evt.detail.cancel = true` in its `*Script` handler (`CellEditScript`, `RowEditScript`, `SortingScript`, `FilteringScript`, `RowAddScript`, `RowDeleteScript`, the paginator's `PagingScript`, …). + +A script handler that calls back into .NET (`dotNetRef.invokeMethodAsync('Method', …)`) lands in a `[JSInvokable]` method, and Blazor does not re-render after it. End that method with one `StateHasChanged()` when it changes what the page shows — no `InvokeAsync` is needed, the call already runs on the renderer's dispatcher. Prefer the C# event when you don't need the script's synchronous `preventDefault()`. If that event is an `EventCallback`, its handler re-renders automatically; the full product's `Action` events (gauge `ValueChanged`, chart move events such as `SeriesPointerMove` / `SeriesMouseMove`, `IgbGrid` `RowAdded` / `RowDeleted` / `CellEditDone`, …) do not, so keep one `StateHasChanged()` in those handlers. Chart series Enter / Leave / Click and the pie's `SliceEnter` / `SliceHover` / `SliceLeave` are `EventCallback`s and need none. diff --git a/skills/igniteui-blazor-components/references/layout.md b/skills/igniteui-blazor-components/references/layout.md index 40bc323d..c67359b3 100644 --- a/skills/igniteui-blazor-components/references/layout.md +++ b/skills/igniteui-blazor-components/references/layout.md @@ -28,6 +28,14 @@ Module for every component below is `IgbModule`. `IgbExpansionPanel` ships Tab headers come from the `Label` string or from children in the `label` slot; everything left in the default slot is the panel body. There is **no** `IgbTabPanel` component. `IgbTab` has `Label`, `Selected`, `Disabled`. `IgbTabs` has `Alignment`, `Activation`, `SelectAsync(id)`, `GetSelectedAsync()`. +**Alignment and panel width before igniteui-webcomponents 7.5.0** (`IgniteUI.Blazor.Lite` 1.0.x bundles 7.4.1, and `IgniteUI.Blazor` 26.2.x takes its tabs from that Lite dependency). With the Material, Fluent or Indigo theme the tabs' `inner` part is only as wide as the headers: `Alignment` `Center` / `End` / `Justify` look like `Start`, and the panel is only as wide as the header row. Bootstrap is not affected. Add this rule to global CSS, or to the page's `.razor.css` as `::deep igc-tabs::part(inner)` — scoped `::deep` needs an HTML element the page renders itself (e.g. a wrapper `div`) as an ancestor of the tabs: + +```css +igc-tabs::part(inner) { flex-grow: 1; } +``` + +It is the rule 7.5.0 moves into the base styles, so it changes nothing on Bootstrap or after the update. Do **not** use `width: 100%` on that part — once the headers overflow and a later tab is selected, the panel (and in some layouts the start scroll button) scrolls out of view. `igc-tab { width: 100%; }` has no effect (slotted tabs are `display: contents`). Before 7.5.0, `Justify` headers with labels of different lengths grow but are not equal-width. The rule also reaches `igc-tabs` rendered by JS templates in the page's light DOM, but not inside another shadow root. + ## Stepper ```razor diff --git a/skills/igniteui-blazor-grids/SKILL.md b/skills/igniteui-blazor-grids/SKILL.md index 936975fa..5dd7d8ee 100644 --- a/skills/igniteui-blazor-grids/SKILL.md +++ b/skills/igniteui-blazor-grids/SKILL.md @@ -86,7 +86,7 @@ The grid-specific stylesheet is easy to miss and is required whenever any full-f | State persistence | ❌ | ✅ | ✅ | ✅ | ✅ | | Virtualization | ✅ | ✅ | ✅ | ✅ | ✅ | | Load on demand | ❌ | ❌ | ✅ via `LoadChildrenOnDemandScript` | ✅ via `GridCreatedScript` | ❌ | -| Remote data ops | `DataPipelineConfiguration` | events + noop strategies | events + noop strategies | events + noop strategies | ❌ | +| Remote data ops | `DataPipelineConfiguration` | events (see `paging-remote.md`) | events | events | ❌ | **Batch editing is not available in Blazor** on any grid type. Supported editing modes are cell editing and row editing only — never generate batch-editing code. diff --git a/skills/igniteui-blazor-grids/references/editing.md b/skills/igniteui-blazor-grids/references/editing.md index 2eec4306..3336ca97 100644 --- a/skills/igniteui-blazor-grids/references/editing.md +++ b/skills/igniteui-blazor-grids/references/editing.md @@ -16,8 +16,11 @@ Row editing gives a clear confirm/cancel flow and prevents half-updated rows. Bo ## Cell editing ```razor +@inject EmployeeService EmployeeService +@inject ILogger Logger + + CellEditScript="RejectNegativeSalary" CellEditDone="OnCellEditDone"> @@ -26,30 +29,45 @@ Row editing gives a clear confirm/cancel flow and prevents half-updated rows. Bo @code { - private void OnCellEdit(IgbGridEditEventArgs args) + // CellEditDone is an Action, not an EventCallback: the handler must return void + // (an async Task handler fails with CS0407) and gets no automatic re-render. + private void OnCellEditDone(IgbGridEditDoneEventArgs args) { - if (args.Detail.Column.Field == "Salary" && Convert.ToDecimal(args.Detail.NewValue) < 0) - { -#pragma warning disable BL0005 - args.Detail.Valid = false; // reject before commit -#pragma warning restore BL0005 - } + var edit = args.Detail; + if (edit.Column?.Field is not { } field || edit.RowData is not Employee row) return; // both are nullable + _ = SaveAsync(() => EmployeeService.UpdateFieldAsync(row, field, edit.NewValue)); } - private async Task OnCellEditDone(IgbGridEditDoneEventArgs args) - => await EmployeeService.UpdateFieldAsync( - args.Detail.RowData, - args.Detail.Column.Field, - args.Detail.NewValue); + private async Task SaveAsync(Func save) + { + try { await save(); } + catch (Exception ex) { Logger.LogError(ex, "Saving the cell edit failed"); } + } } ``` +```js +// wwwroot/js/grid-validation.js, loaded after the app.bundle.js tag (see Validation below) +igRegisterScript("RejectNegativeSalary", (evt) => { + const d = evt.detail; // column, rowKey, rowData, oldValue, newValue, cancel + if (d.column.field === "Salary" && Number(d.newValue) < 0) { + d.cancel = true; // the cell stays in edit mode; Esc restores the old value + } +}, false); +``` + +In `CellEditDone`, `Detail.RowData` is your row object, already updated in the bound list, and `Detail.RowKey` is its key (a numeric key arrives as `double`). The fire-and-forget save runs on the renderer's dispatcher, and so does the code after its `await`. To show a save status, set a field there and call `StateHasChanged()` directly. + +`CellEditDone`, `RowAdded` and `RowDeleted` are `Action` parameters: return `void`, and call `StateHasChanged()` yourself if the page shows something they change (or forward to an `EventCallback` of a parent component, which re-renders that parent). Check other events' parameter type with `get_api_reference` before writing an `async Task` handler. + +`RowDeleted` delivers `IgbRowDataEventArgs`: read the key from `Detail.RowKey` (`Detail.PrimaryKey` is obsolete; a numeric key arrives as `double`). When it fires, the grid's built-in delete has **already removed the row from the bound `List`** — don't count deletes by removing from that same list. + Double-click, or Enter on a focused cell, enters edit mode. The editor follows the column's `DataType`: text box, numeric input, date picker, or checkbox. | Event | Args | Fires | |---|---|---| | `CellEditEnter` | `IgbGridEditEventArgs` | entering edit mode | -| `CellEdit` | `IgbGridEditEventArgs` | before commit — set `args.Detail.Valid = false` to reject | +| `CellEdit` | `IgbGridEditEventArgs` | on commit; the C# handler runs after the value is committed, so reject from `CellEditScript` | | `CellEditDone` | `IgbGridEditDoneEventArgs` | after commit — persist here | | `CellEditExit` | `IgbGridEditDoneEventArgs` | leaving edit mode | @@ -57,7 +75,8 @@ Double-click, or Enter on a focused cell, enters edit mode. The editor follows t ```razor + RowEditScript="ValidateTaskDates" RowEditEnter="OnRowEditEnter" + RowEditDone="OnRowEditDone" RowEditExit="OnRowEditExit"> @@ -68,24 +87,43 @@ Double-click, or Enter on a focused cell, enters edit mode. The editor follows t @code { - private void OnRowEdit(IgbGridEditEventArgs args) - { - if (args.Detail.RowData is ProjectTask task && task.EndDate < task.StartDate) + private ProjectTask? original; // copy taken when the row enters edit mode + + private void OnRowEditEnter(IgbGridEditEventArgs args) { -#pragma warning disable BL0005 - args.Detail.Valid = false; // cross-field validation -#pragma warning restore BL0005 - } + if (args.Detail.RowData is ProjectTask t) + original = new ProjectTask { Id = t.Id, Name = t.Name, StartDate = t.StartDate, EndDate = t.EndDate }; } private Task OnRowEditDone(IgbGridEditDoneEventArgs args) - => ProjectTaskService.UpdateAsync(args.Detail.RowData); + { + original = null; // committed: keep the edited values + return args.Detail.RowData is ProjectTask task ? ProjectTaskService.UpdateAsync(task) : Task.CompletedTask; + } + + // Cancel, Esc, or leaving after a rejected Done: put the object back + private void OnRowEditExit(IgbGridEditDoneEventArgs args) + { + if (original is { } o && projectTasks.Find(t => t.Id == o.Id) is { } item) + (item.Name, item.StartDate, item.EndDate) = (o.Name, o.StartDate, o.EndDate); + original = null; + } } ``` -Editing any cell opens a row overlay with Done and Cancel; the whole row is editable at once and nothing reaches the data source until Done. Events mirror the cell ones: `RowEditEnter`, `RowEdit` (cancellable), `RowEditDone`, `RowEditExit`. +```js +// wwwroot/js/grid-validation.js (continued) +igRegisterScript("ValidateTaskDates", (evt) => { + const row = evt.detail.newValue; // the edited row; evt.detail.rowData is the original + if (new Date(row.EndDate) < new Date(row.StartDate)) { + evt.detail.cancel = true; // Done is refused and the row stays in edit mode + } +}, false); +``` + +Editing any cell opens a row overlay with Done and Cancel, and the whole row is editable at once. Each cell you leave (Tab, click) is written to the bound item immediately; Cancel, Esc and a rejected Done restore only the grid's display, not your object, and the C# `RowEdit` / `RowEditExit` args carry no original values (`RowData`, `OldValue` and `NewValue` are all the updated object). Hence the copy in `RowEditEnter`: without it, a rejected value stays in your object and the next valid Done on that row persists it. Persist in `RowEditDone`. Events mirror the cell ones: `RowEditEnter`, `RowEdit`, `RowEditDone`, `RowEditExit`. -`IgbGridEditingActions` inside an `IgbActionStrip` adds per-row edit, delete, and (with `AddRow="true"`) add buttons. +`IgbGridEditingActions` inside an `IgbActionStrip` adds per-row edit, delete, and (with `AddRow="true"`) add buttons. Rows added with `AddRow` arrive in the `RowEdit*` events and in `RowAdded` as a `Dictionary`, not your type, so the `RowEditDone` above doesn't save them (and `ValidateTaskDates` accepts their empty dates). When `RowAdded` (an `Action`) fires, the grid has already added an instance of your type to the bound list: find it by `Detail.RowKey` (a `double`) and persist that, or drop `AddRow="true"`. With a read-only key column the new row's key is a grid-generated placeholder (`-1`), so let the server assign the real `Id`. ## Adding and deleting rows from code @@ -106,7 +144,15 @@ Editing any cell opens a row overlay with Done and Cancel; the whole row is edit ## Validation -Validate in `CellEdit` / `RowEdit` and set `args.Detail.Valid = false` to block the commit. Because `Valid` is generated as a component parameter, suppress `BL0005` only around that assignment, as shown above; do not disable it project-wide. In row editing, the row cannot be confirmed while a validation error stands. Show the message with `ErrorTemplate` on the column: +The C# `CellEdit` / `RowEdit` events arrive after the grid has committed the value, so setting `args.Detail.Valid = false` there changes nothing. To block a commit, handle `CellEditScript` / `RowEditScript` as shown above and set `evt.detail.cancel = true`; `evt.preventDefault()` and `evt.detail.valid = false` have no effect. The cell or row stays in edit mode. Esc restores a cell's old value; in row editing it restores only the grid's display (see the copy-and-restore above). A script that runs at page load, like this one, finds the `igRegisterScript` global only when the `app.bundle.js` tag comes before it (without the tag, Blazor installs the global a moment after startup, too late). Add the tag on every hosting model, standalone WebAssembly included; without it the script is never registered and nothing is validated: + +```html + + + +``` + +A value rejected with `evt.detail.cancel` shows no message; show your own (for example through a `[JSInvokable]` call). `ErrorTemplate` on a column renders only for the grid's own validators, which Blazor reaches only through `FormGroupCreatedScript` (`evt.detail.formGroup.get('Age').addValidators(…)`); they mark the cell invalid but do not block the commit: ```razor diff --git a/skills/igniteui-blazor-grids/references/features.md b/skills/igniteui-blazor-grids/references/features.md index 48d3eb6c..dd7e1c61 100644 --- a/skills/igniteui-blazor-grids/references/features.md +++ b/skills/igniteui-blazor-grids/references/features.md @@ -64,22 +64,45 @@ Merges visually identical adjacent cells. Sort by the merged columns first, or t ## Toolbar ```razor - - - Employees - - - - - +
+ + + Employees Refresh - - - … - + + + + + @* Excel and CSV *@ + + + … + +
+``` + +Put only the built-in action components in `IgbGridToolbarActions`, and declare your own buttons and inputs directly in `IgbGridToolbar`. Blazor renders every other child into `div.igx-grid-toolbar__custom-content`, **including children declared inside `IgbGridToolbarActions`**. That box sits between the title and `igc-grid-toolbar-actions.igx-grid-toolbar__actions`, so custom content always appears *before* the built-in actions, whatever the declaration order. Event handlers such as `@onclick` keep working. + +- Style custom content through `.igx-grid-toolbar__custom-content` — `.igx-grid-toolbar__actions igc-button` never matches it. +- In a `.razor.css` file, put `::deep` after an element the page renders itself (the wrapper `div` above). `class` on `IgbGrid` lands on a wrapper `div`, not on `igc-grid`, so `igc-grid.my-grid` matches nothing. + +```css +/* Employees.razor.css — show custom content after the built-in actions */ +.employees ::deep .igx-grid-toolbar__custom-content { + order: 1; + flex-grow: 0; /* without it the actions jump next to the title */ + margin-inline: 1rem 0; +} + +/* The box keeps empty igc-portal-* elements, so :empty never matches and an + "empty" box still takes space. Hide it when it holds no other element. + It checks element children only: wrap text in an element (see below). */ +.employees ::deep .igx-grid-toolbar__custom-content:not(:has(> :not(igc-portal-exit, igc-portal-entrance))) { + display: none; +} ``` -`IgbGridToolbarActions` accepts arbitrary content alongside the built-in action components. +The hiding rule sees only element children, and Blazor moves bare text into the box as text nodes — so custom content that is only text (`@selectedCount selected`) is hidden with it. Wrap such text in an element (`@selectedCount selected`) before using the rule. `order` changes only the visual order; keyboard focus still reaches custom content first. `IgbGridToolbarTitle` also keeps an empty `igc-portal-exit` before its content: if the title content is `display: inline-flex`, the title stops painting whenever that content is wider than the title area — the title is capped at 320px and shrinks further when the actions need room, for example once the toolbar wraps ([#497](https://github.com/IgniteUI/igniteui-blazor/issues/497)). Use `display: flex` for the title content, or hide the element with `.igx-grid-toolbar__title > igc-portal-exit { display: none; }`. ## Export diff --git a/skills/igniteui-blazor-grids/references/grid-migration.md b/skills/igniteui-blazor-grids/references/grid-migration.md index 5d5647c2..d373b18e 100644 --- a/skills/igniteui-blazor-grids/references/grid-migration.md +++ b/skills/igniteui-blazor-grids/references/grid-migration.md @@ -94,17 +94,19 @@ Row data inside a body template is `cell.Cell.Row.Data`. Editors use `InlineEdit ## Remote data -Grid Lite drives server-side work through `DataPipelineConfiguration`. `IgbGrid` uses events instead — handle `SortingDone` / `FilteringDone` / `PageChange` and reload `Data` yourself: +Grid Lite drives server-side work through `DataPipelineConfiguration`. `IgbGrid` uses events instead: reload `Data` on `SortingExpressionsChange` (its `Detail` holds every sorted column; `SortingDone` has only the column just clicked), on `FilteringDone` after reading the grid's filter tree through JS interop (the C# tree has no operands), and on the paginator's `PagingDone`: ```razor - + + + @code { - private async Task OnSortingDone(IgbSortingExpressionEventArgs args) + private async Task OnSortingChanged(IgbSortingExpressionEventArgs args) { - data = await DataService.SortAsync(args.Detail); - StateHasChanged(); + data = await DataService.SortAsync(args.Detail ?? []); + // No StateHasChanged(): this is an EventCallback, so the page re-renders when this Task completes. } } ``` @@ -122,7 +124,7 @@ See [`paging-remote.md`](./paging-remote.md) for the combined paging + sorting + - +
diff --git a/skills/igniteui-blazor-grids/references/paging-remote.md b/skills/igniteui-blazor-grids/references/paging-remote.md index 602d18e6..1ccf8a44 100644 --- a/skills/igniteui-blazor-grids/references/paging-remote.md +++ b/skills/igniteui-blazor-grids/references/paging-remote.md @@ -5,40 +5,34 @@ Paging is not a grid parameter — place an `IgbPaginator` **inside** the grid as a child component. ```razor - + - + - -@code { - private IgbGrid grid = default!; - private IgbPaginator paginator = default!; - - private Task First() => paginator.PaginateAsync(0); // 0-based page index - private Task Next() => paginator.NextPageAsync(); - private Task Prev() => paginator.PreviousPageAsync(); -} ``` +Users page with the paginator's built-in controls. Changing the page from code does not work: `PaginateAsync`, `NextPageAsync` and `PreviousPageAsync` fail (`target doesn't have prop: paginate` in the console; the `Task` faults), and a bound `Page` is ignored whenever the new value equals the last value set from code, even after the user has paged away (so setting it back to `0` a second time does nothing), and syncing the field from `PagingDone` doesn't avoid this ([#569](https://github.com/IgniteUI/igniteui-blazor/issues/569)). Don't build custom First / Next / Previous buttons on them. + | Parameter | Type | Default | Purpose | |---|---|---|---| | `PerPage` | `double` | `15` | Rows per page | | `TotalRecords` | `double` | — | Server-side total; required for remote paging | | `SelectOptions` | `double[]` | `[5, 10, 15, 25, 50]` | Page-size dropdown | -Events: `PageChange` and `PerPageChange` (`IgbNumberEventArgs`), `PagingDone` (`IgbPageEventArgs`). +Events: `PageChange` and `PerPageChange` (`IgbNumberEventArgs`), `PagingDone` (`IgbPageEventArgs`; `Detail.Previous` / `Detail.Current`). Drive page loads from **`PagingDone`, not `PageChange`**: a `PageChange` to page 0 — the first-page button, Previous back to the first page, or the reset after a page-size change — never reaches the handler, and nothing is logged ([#171](https://github.com/IgniteUI/igniteui-blazor/issues/171)), so the grid keeps showing the old page. `PagingDone` fires for every page change, including that reset. The Pivot Grid does not support paging. ## Remote paging -Bind `Data` to just the current page and tell the paginator the true total. +Bind `Data` to just the current page, set `PagingMode="GridPagingMode.Remote"`, and tell the paginator the true total. ```razor - + + PagingDone="OnPagingDone" PerPageChange="OnPerPageChange" /> @code { @@ -48,9 +42,11 @@ Bind `Data` to just the current page and tell the paginator the true total. protected override Task OnInitializedAsync() => LoadPageAsync(); - private Task OnPageChange(IgbNumberEventArgs args) + private Task OnPagingDone(IgbPageEventArgs args) { - currentPage = (int)args.Detail; + var page = (int)args.Detail.Current; + if (page == currentPage) return Task.CompletedTask; // the reset after a page-size change is already loaded + currentPage = page; return LoadPageAsync(); } @@ -61,76 +57,166 @@ Bind `Data` to just the current page and tell the paginator the true total. return LoadPageAsync(); } + private int loadVersion; + + // No StateHasChanged(): the event handlers and OnInitializedAsync return this Task, + // and the component re-renders when it completes. private async Task LoadPageAsync() { + var version = ++loadVersion; var result = await Api.GetEmployeesPagedAsync(currentPage, pageSize); + if (version != loadVersion) return; // a newer request started (fast clicks): drop this stale page currentPageData = result.Items; totalRecords = result.TotalCount; - StateHasChanged(); } } ``` -Without `TotalRecords` the paginator cannot compute the page count and paging silently misbehaves. +Without `PagingMode="GridPagingMode.Remote"` the grid pages only the rows it holds and overrides `TotalRecords`: the pager shows "1 of 1" and neither `PageChange` nor `PagingDone` fires. Without `TotalRecords` the paginator cannot compute the page count. ## Remote sorting and filtering -Handle `SortingDone` and `FilteringDone`, translate the expressions into a server query, and reassign `Data`. In production, fold paging, sorting, and filtering into one request rather than reloading per event. +Reload from the server when the sort or filter changes, and fold paging, sorting and filtering into one request. Three things differ from what the event names suggest: + +- **Sorting:** handle `SortingExpressionsChange`. Its `Detail` holds every sorted column in order. `SortingDone` carries only the column just clicked, so storing it loses multi-column sorting (the default). Sorting does not move the paginator, and the page can't be changed from code ([#569](https://github.com/IgniteUI/igniteui-blazor/issues/569)), so reload the **current** page rather than page 0. +- **Filtering:** the C# filter events (`FilteringDone`, `Filtering`, `FilteringExpressionsTreeChange`) deliver a tree with the right `FieldName` but **no operands** — no condition, no search value. Use `FilteringDone` only as the trigger and read the grid's filter trees through JS interop. Keep the and/or structure: the filter row's operator and the Excel-style custom dialog produce `or` groups, and the Excel-style value list produces an `or` group of `equals` for one or two values and a single `in` condition, whose value is a JS `Set`, for three or more. The advanced-filtering dialog keeps its conditions in a separate tree (`advancedFilteringExpressionsTree`); its Apply raises `FilteringDone`, but its **Clear filter** button raises no C# event (the JS `filteringDone` has a `null` `detail`), so the snippet listens for it in JS. +- **Paging after a filter:** adding, changing or removing one of several conditions moves the paginator to the first page and raises `PagingDone` before `FilteringDone`. Clearing a column's last condition, Reset, *Clear column filters* and the advanced dialog leave it on its page — even past the new last page, which then shows an empty page under e.g. "3 of 2" until the user pages back. Keep `currentPage` as `PagingDone` leaves it, and don't reset it in the filter handler. +- **Local pass:** the grid still sorts and filters the rows it holds, even with `PagingMode="GridPagingMode.Remote"`, and has no parameter to turn that off. It compares strings case-insensitively by character code and dates in local time. A server that sorts culture-aware or case-sensitively gets rows reordered within the page, and one that matches accents loosely (SQL `*_CI_AI` collations) returns rows the local pass then hides ("No records found" under a non-zero total). Match these rules on the server. +- **Excel-style value list:** it lists only the values on the current page, and there is no Blazor API to feed it from the server. Ticking values filters to exactly those; unticking one filters to the page's *other* values, not "everything except X"; and if the page holds a single value, picking it sends no filter at all. Prefer the filter row or the custom dialog for remote data. ```razor - - - - - +@inject IJSRuntime JS +@implements IDisposable + +
+ + + + + +
@code { + private ElementReference gridHost; private List data = new(); - private int totalRecords, currentPage; + private int totalRecords, currentPage, loadVersion; private int pageSize = 20; - private IgbSortingExpression[]? currentSort; - private IgbFilteringExpressionsTree? currentFilter; + private IgbSortingExpression[] currentSort = []; + private GridFilter[] currentFilter = []; // every group must match + private IDisposable? selfRef; - private Task OnSortingDone(IgbSortingExpressionEventArgs args) + public record GridFilter(string Operator, GridCondition[] Conditions, GridFilter[] Groups); // Operator: "and" | "or" + public record GridCondition(string Field, string Condition, System.Text.Json.JsonElement Value); + + protected override Task OnInitializedAsync() => LoadDataAsync(); + + protected override async Task OnAfterRenderAsync(bool firstRender) { - currentSort = args.Detail; - currentPage = 0; - return LoadDataAsync(); + if (!firstRender) return; + var self = DotNetObjectReference.Create(this); + selfRef = self; + await JS.InvokeVoidAsync("watchGridFilterClear", gridHost, self); } - private Task OnFilteringDone(IgbFilteringExpressionsTreeEventArgs args) + private Task OnSortingChanged(IgbSortingExpressionEventArgs args) { - currentFilter = args.Detail; - currentPage = 0; + currentSort = args.Detail ?? []; // all sorted columns, in order + return LoadDataAsync(); // the paginator stays on its page + } + + private Task OnFilteringDone(IgbFilteringExpressionsTreeEventArgs args) => ReloadFilterAsync(); + + // The advanced dialog's "Clear filter" raises no C# event; grid-filter.js reports it here. + [JSInvokable] + public async Task OnFilterCleared() + { + await ReloadFilterAsync(); + StateHasChanged(); // a [JSInvokable] call does not re-render on its own + } + + // args.Detail has no operands: read the grid's trees instead. + // No currentPage = 0: when the grid resets the paginator, PagingDone has already set it. + private async Task ReloadFilterAsync() + { + currentFilter = await JS.InvokeAsync("readGridFilter", gridHost); + await LoadDataAsync(); + } + + private Task OnPagingDone(IgbPageEventArgs args) + { + var page = (int)args.Detail.Current; + if (page == currentPage) return Task.CompletedTask; + currentPage = page; return LoadDataAsync(); } - private Task OnPageChange(IgbNumberEventArgs args) + private Task OnPerPageChange(IgbNumberEventArgs args) { - currentPage = (int)args.Detail; + pageSize = (int)args.Detail; + currentPage = 0; return LoadDataAsync(); } private async Task LoadDataAsync() { - var result = await Api.QueryAsync(new QueryRequest - { - Page = currentPage, - PageSize = pageSize, - SortField = currentSort?.FirstOrDefault()?.FieldName, - SortDirection = currentSort?.FirstOrDefault()?.Dir.ToString(), - Filter = Translate(currentFilter) - }); - + var version = ++loadVersion; + var result = await Api.QueryAsync(currentPage, pageSize, currentSort, currentFilter); + if (version != loadVersion) return; // a newer request started: drop this stale result data = result.Items; totalRecords = result.TotalCount; - StateHasChanged(); } + + public void Dispose() => selfRef?.Dispose(); } ``` -The grid still renders sort and filter UI while you own the actual data transformation. To stop it re-sorting or re-filtering the page it already has, assign noop sorting/filtering strategies on the grid — check `get_api_reference` for the current strategy types. +```js +// wwwroot/js/grid-filter.js — converts the grid's filter trees into { operator, conditions, groups } groups +window.readGridFilter = host => { + const grid = host.querySelector('igc-grid'); + const kind = field => grid.getColumnByName(field)?.dataType; // 'date' | 'dateTime' | 'time' | 'string' | … + // send local wall-clock text, not UTC instants: yyyy-MM-dd, yyyy-MM-dd HH:mm:ss or HH:mm:ss by column type + const text = (d, k) => k === 'dateTime' ? d.toLocaleString('sv') : k === 'time' ? d.toLocaleTimeString('sv') : d.toLocaleDateString('sv'); + // the Excel-style list's "in" Set holds strings: toDateString() (date), ISO instants (dateTime), display text (time) + const parse = (s, k) => new Date(k === 'time' ? `1970-01-01 ${s}` : s); + const one = (v, k) => v instanceof Date ? text(v, k) + : typeof v === 'string' && ['date', 'dateTime', 'time'].includes(k) && !isNaN(parse(v, k)) ? text(parse(v, k), k) + : v; + const value = o => { + const k = kind(o.fieldName); + return o.searchVal instanceof Set ? [...o.searchVal].map(v => one(v, k)) : one(o.searchVal ?? null, k); + }; + const group = tree => ({ + operator: tree.operator === 1 ? 'or' : 'and', + conditions: tree.filteringOperands.filter(o => !o.filteringOperands).map(o => ({ + field: o.fieldName, + condition: o.condition?.name ?? o.conditionName, + value: value(o) + })), + groups: tree.filteringOperands.filter(o => o.filteringOperands).map(group) + }); + // the filter row / Excel-style menu and the advanced-filtering dialog keep separate trees; a row must match both + return [grid.filteringExpressionsTree, grid.advancedFilteringExpressionsTree] + .filter(tree => tree?.filteringOperands?.length) + .map(group); +}; + +// The advanced dialog's "Clear filter" fires filteringDone with a null detail, which never reaches C#. +// Capture phase on the host: works for a non-bubbling event and before igc-grid exists. +window.watchGridFilterClear = (host, dotNetRef) => host.addEventListener('filteringDone', e => { + if (e.target.localName === 'igc-grid' && e.detail == null) dotNetRef.invokeMethodAsync('OnFilterCleared'); +}, true); +``` + +```html + + +``` + +A row matches a group when all (`and`) or any (`or`) of its conditions and subgroups match; groups nest, e.g. `an OR (ri AND x)` from a filter row with mixed operators. `Condition` is the condition name (`contains`, `equals`, `in`, `greaterThan`, `before`, `true`, …), and `Value` is a `JsonElement` because its type depends on the column and condition: a string, a number, local wall-clock text for date columns (`yyyy-MM-dd` for `Date`, `yyyy-MM-dd HH:mm:ss` for `DateTime`, `HH:mm:ss` for `Time`), an array of those for `in`, or `null` for unary conditions such as `empty` or `thisYear`. `DateTime` values have second precision, as in the grid itself: its value list merges times that differ only in milliseconds and stores them with `.000`, and `equals` compares to the second, so compare to the second on the server. A `Time` column's `in` values come from display text such as `8:00:00 AM`; if that text can't be parsed in the grid's locale, it is passed through unchanged. `IgbGridLite` handles remote operations differently, through `DataPipelineConfiguration` rather than events — see [`types.md`](./types.md). @@ -146,5 +232,6 @@ Two requirements: ## Rules - `IgbPaginator` is a **child** of the grid, not a sibling. -- Always call `StateHasChanged()` after reassigning `Data` from an async operation. +- For remote paging set `PagingMode="GridPagingMode.Remote"` on the grid. +- Don't call `StateHasChanged()` after the final `Data` assignment in an `EventCallback` handler (`PagingDone`, `PerPageChange`, `SortingDone`, `FilteringDone`, …) or in `OnInitializedAsync` / `OnParametersSetAsync`: the component re-renders when the returned `Task` completes, and an extra call inside an Ignite UI callback renders immediately, adding a render each time. The automatic renders come only at the first `await` and at completion, so an intermediate state set between two later `await`s (a "Saving…" message, the first of two loads) needs its own `StateHasChanged()`. Call it once also when `Data` changes outside those paths. In a `[JSInvokable]` method or an `Action` event (`RowAdded`, `RowDeleted`, `CellEditDone`) call it directly — they already run on the renderer's dispatcher. From a timer or a service event, wrap the update and the call: `await InvokeAsync(() => { Data = fresh; StateHasChanged(); });` — on Blazor Server those callbacks run off the dispatcher, and a direct `StateHasChanged()` throws `InvalidOperationException`. - `Data` must be a materialized `List` or `T[]` — do not hand the grid an `IQueryable` and expect it to compose `Skip`/`Take`. diff --git a/skills/igniteui-blazor-grids/references/types.md b/skills/igniteui-blazor-grids/references/types.md index 84976efb..ad5423ef 100644 --- a/skills/igniteui-blazor-grids/references/types.md +++ b/skills/igniteui-blazor-grids/references/types.md @@ -48,7 +48,7 @@ Grid Lite specifics that trip people up: - **`Field` on columns, `Key` in expressions.** `IgbGridLiteSortingExpression` and `IgbGridLiteFilterExpression` identify the field with `Key`. - Change the column set with `@if` — there is no `UpdateColumnsAsync()`. - Tri-state sorting (asc → desc → none) is always on and cannot be disabled. -- Remote operations go through `DataPipelineConfiguration`, not events + noop strategies. +- Remote operations go through `DataPipelineConfiguration`, not the events the full grids use. ## Tree Grid (`IgbTreeGrid`)