From 0c231abcf88cf28302a2c96c32ea62eb8636af62 Mon Sep 17 00:00:00 2001 From: damyanpetev Date: Thu, 8 Oct 2026 11:28:19 +0300 Subject: [PATCH 1/2] feat!: type the filter condition, criteria, filtering type and search term --- .github/copilot-instructions.md | 2 +- CHANGELOG.md | 4 ++ README.md | 10 +++ docs/TRIMMING.md | 6 +- docs/security/threat-model.md | 2 +- .../Internal/AppValueSerializer.cs | 24 ++++--- .../Internal/GridLiteJsonContext.cs | 2 +- .../Events/IgbGridLiteFilteredEventArgs.cs | 2 +- .../Events/IgbGridLiteFilteringEventArgs.cs | 24 +++++-- .../Models/IgbGridLiteFilterExpression.cs | 52 ++++++++++++-- .../igc-grid-lite-entry.js | 22 ++++-- .../GridLiteTests.cs | 24 +++++++ .../Components/Pages/GridPage.razor | 7 +- .../EnumSerializationTests.cs | 23 ++++++ .../GridLiteJsInteropTests.cs | 2 +- .../ModelSerializationTests.cs | 72 ++++++++++++++++--- 16 files changed, 236 insertions(+), 42 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index c40852c..c809e8c 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -40,7 +40,7 @@ This repository is the **source of the `IgniteUI.Blazor.GridLite` package**: a R - PascalCase for public members; camelCase for private fields; `var` when the type is obvious; no `dynamic` - `[Parameter]` for component inputs; `EventCallback` for events - Every public type and member has XML docs; overrides use ``. The library builds its docs file and every warning is an error, so a missing doc fails the build (CS1591) -- Library-owned payloads serialize through the source-generated `GridLiteJsonContext`; app-owned values (`Data`, filter `Condition`/`SearchTerm`) go through `AppValueSerializer`, the only reflection-based serialization in `src/` +- Library-owned payloads serialize through the source-generated `GridLiteJsonContext`; app-owned values (`Data`, filter `SearchTerm`) go through `AppValueSerializer`, the only reflection-based serialization in `src/` - Trim/AOT diagnostics (IL2xxx/IL3xxx) are build errors; suppress only on the smallest member, with `[UnconditionalSuppressMessage]` and a justification that says why the pattern is safe - never `#pragma` for ILxxxx, except IL3050 on dynamic code Native AOT is not claimed for (see docs/TRIMMING.md) ### JavaScript diff --git a/CHANGELOG.md b/CHANGELOG.md index ba8e6b3..4794150 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 _content/IgniteUI.Blazor.GridLite/themes/ ``` matching the layout the `IgniteUI.Blazor` and `IgniteUI.Blazor.Lite` packages use. The old paths still work, through a stylesheet that imports the theme from its new location, and will be removed in a future release. +- **BREAKING**: `IgbGridLiteFilterExpression.Condition` is a `string`, the name of a grid-lite filter condition, instead of `object`. Its documentation and the README list the names for each column data type. In the `Filtering` and `Filtered` events it holds the condition's name; before, it held grid-lite's condition object as a `JsonElement`. +- **BREAKING**: In the `Filtering` and `Filtered` events, `IgbGridLiteFilterExpression.SearchTerm` holds a `string`, `double` or `bool` instead of a `JsonElement`. Numbers are always `double`, as JavaScript has one number type, so a search term set as an `int` comes back as a `double`. +- **BREAKING**: `IgbGridLiteFilterExpression.Criteria` is a `GridLiteFilterCriteria?` (`And`, `Or`) instead of a `string?`, and `IgbGridLiteFilteringEventArgs.Type` is a `GridLiteFilteringType` (`Add`, `Modify`, `Remove`) instead of a `string`. +- **BREAKING**: `IgbGridLiteFilteringEventArgs.Expressions` and `IgbGridLiteFilteredEventArgs.State` are `IReadOnlyList` instead of `List`. ## 0.10.0 - 2026-09-29 diff --git a/README.md b/README.md index e8ce49e..e02adcf 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,16 @@ Configure pre-applied sorting and filtering when the grid first renders: } ``` +`Condition` is a grid-lite condition name. The names a column accepts depend on its `DataType`; a column without one counts as `String`: + +| `DataType` | Condition names | +| :--------- | :---------------------------------------------------------------------------------------------------------------- | +| `String` | `contains`, `doesNotContain`, `startsWith`, `endsWith`, `equals`, `doesNotEqual`, `empty`, `notEmpty` | +| `Number` | `equals`, `doesNotEqual`, `greaterThan`, `lessThan`, `greaterThanOrEqual`, `lessThanOrEqual`, `empty`, `notEmpty` | +| `Boolean` | `all`, `true`, `false`, `empty`, `notEmpty` | + +The `Boolean` conditions, `empty` and `notEmpty` take no `SearchTerm`. + ### Sorting Enable sorting on individual columns and optionally make sorting case-sensitive: diff --git a/docs/TRIMMING.md b/docs/TRIMMING.md index e45311b..9cf9d8f 100644 --- a/docs/TRIMMING.md +++ b/docs/TRIMMING.md @@ -1,6 +1,6 @@ # Trimming support -`IgniteUI.Blazor.GridLite` is trim-compatible (`IsTrimmable=true`): the library builds warning-free under the .NET trim analyzer, and its own interop payloads serialize through source-generated `System.Text.Json` metadata. The only values it serializes with reflection are your app's own: the grid's `Data` items and the filter expressions' `Condition`/`SearchTerm`. +`IgniteUI.Blazor.GridLite` is trim-compatible (`IsTrimmable=true`): the library builds warning-free under the .NET trim analyzer, and its own interop payloads serialize through source-generated `System.Text.Json` metadata. The only values it serializes with reflection are your app's own: the grid's `Data` items and the filter expressions' `SearchTerm`. ## Are your types trimmed at all? @@ -28,7 +28,7 @@ public partial class ProductGrid<[DynamicallyAccessedMembers(DynamicallyAccessed - **Complex types reachable from the item type.** If `Product` has a `Supplier` property whose members a column shows (`Field="Supplier.Name"`), `Supplier` needs its public properties preserved as well, and so does every complex type below it. The annotation on `TItem` covers the item type itself, not the types of its properties. - **Members outside the public properties.** A public field opted into serialization with `[JsonInclude]`, or a non-public `[JsonInclude]` member, is not covered by the annotation. -- **App-defined filter values.** A `Condition` or `SearchTerm` of a built-in type (string, number, date, `Guid`, enum) needs nothing. A value of an app-defined type needs its public properties preserved. +- **App-defined filter search terms.** A `SearchTerm` of a built-in type (string, number, date, `Guid`, enum) needs nothing. A value of an app-defined type needs its public properties preserved. Preserve such types with a `DynamicDependency` attribute on any method that is kept, such as your root component or `Program.Main`: @@ -47,7 +47,7 @@ or with a [trimmer root descriptor](https://learn.microsoft.com/dotnet/core/depl ## Native AOT -Not claimed. The library builds warning-free under the [AOT analyzer](https://learn.microsoft.com/dotnet/core/deploying/native-aot/) (`EnableAotAnalyzer`, errors via `.editorconfig`), but the `Data` items and the filter values are serialized with reflection, which Native AOT does not guarantee, and Blazor itself is not AOT-compatible yet (`Microsoft.AspNetCore.Components` ships `IsTrimmable` only; [dotnet/aspnetcore#51598](https://github.com/dotnet/aspnetcore/issues/51598) tracks it). What this means per deployment model: +Not claimed. The library builds warning-free under the [AOT analyzer](https://learn.microsoft.com/dotnet/core/deploying/native-aot/) (`EnableAotAnalyzer`, errors via `.editorconfig`), but the `Data` items and the filter search terms are serialized with reflection, which Native AOT does not guarantee, and Blazor itself is not AOT-compatible yet (`Microsoft.AspNetCore.Components` ships `IsTrimmable` only; [dotnet/aspnetcore#51598](https://github.com/dotnet/aspnetcore/issues/51598) tracks it). What this means per deployment model: - **Blazor WebAssembly**: unaffected. Both the default interpreter and `RunAOTCompilation=true` publishes run on Mono with the interpreter retained, so no Native AOT semantics apply. The manual `Wasm AOT Smoke` workflow runs the trimmed-publish browser checks against a `RunAOTCompilation` publish. - **Blazor Server**: unaffected; it runs on CoreCLR. diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 29e6c8d..bcf9238 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -70,7 +70,7 @@ The consuming application must first apply Microsoft's guidance for its hosting | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A client forges a call targeting another user's components | Impossible under Interactive Server. The interop callback object is handed to the browser as a reference scoped to one circuit, because the framework binds a `DotNetObjectReference` to the circuit that issued it; there is one per grid and no shared registry on the .NET side to address. On WebAssembly and Hybrid there is one user per runtime and nothing to forge across. | | A client raises an event the application did not subscribe to | Dropped. An event is dispatched only if the application bound the matching `EventCallback`; the interop module attaches a listener only for events that have one, and each callback returns before parsing when none is bound. | -| A client-supplied payload activates an arbitrary .NET type or executes code | Not possible. Payloads are parsed with source-generated `System.Text.Json` into types the library itself defines, with the object-typed filter members (`Condition`, `SearchTerm`) kept as `JsonElement`; there is no polymorphic deserialization and no arbitrary type activation. | +| A client-supplied payload activates an arbitrary .NET type or executes code | Not possible. Payloads are parsed with source-generated `System.Text.Json` into types the library itself defines, with the object-typed filter `SearchTerm` read as a `string`, `double` or `bool`, or else kept as `JsonElement`; there is no polymorphic deserialization and no arbitrary type activation. | | A client answers the column query with arbitrary content | Bounded to the column configuration type. The result is parsed through the same source-generated context, and anything that is not an array yields an empty result. | | Resource exhaustion through interop floods or oversized payloads | Bounded per payload and per connection, not per rate. `MaximumReceiveMessageSize` bounds each payload and `CircuitOptions` bounds retained circuits and unacknowledged render batches. The framework dispatches inbound invocations one at a time per connection, so one client's calls queue rather than interleave; each callback awaits the application's handler, whose work draws on shared server CPU and memory, and the library keeps no per-call state on the .NET side. Neither the framework nor the library caps the call rate; see [§5](#5-guidance-for-application-developers). | diff --git a/src/IgniteUI.Blazor.GridLite/Internal/AppValueSerializer.cs b/src/IgniteUI.Blazor.GridLite/Internal/AppValueSerializer.cs index e0defe6..a218508 100644 --- a/src/IgniteUI.Blazor.GridLite/Internal/AppValueSerializer.cs +++ b/src/IgniteUI.Blazor.GridLite/Internal/AppValueSerializer.cs @@ -6,8 +6,8 @@ namespace IgniteUI.Blazor.Controls.Internal; /// -/// Reflection-based metadata for the values whose types belong to the app: the Data items and the -/// object-typed filter values, which are compared against them. Everything else goes through +/// Reflection-based metadata for the values whose types belong to the app: the Data items and the filter +/// expressions' SearchTerm, which is compared against them. Everything else goes through /// . /// internal static class AppValueSerializer @@ -21,9 +21,9 @@ public static JsonTypeInfo> GetDataTypeInfo() [UnconditionalSuppressMessage("Trimming", "IL2026:RequiresUnreferencedCode", Justification = "The grid's DynamicallyAccessedMembers(PublicProperties) annotation on TItem keeps the " - + "item type's public properties in trimmed apps, and filter values of built-in types need no " + + "item type's public properties in trimmed apps, and filter search terms of built-in types need no " + "preserved members. Any other type reached here (a complex type nested in TItem, an app-defined " - + "filter value) belongs to the consuming app, and the trimming docs make preserving it the app's " + + "filter search term) belongs to the consuming app, and the trimming docs make preserving it the app's " + "responsibility.")] private static JsonSerializerOptions CreateOptions() { @@ -41,14 +41,22 @@ private static JsonSerializerOptions CreateOptions() } /// -/// Writes an -typed payload member (the filter Condition and SearchTerm) by -/// its runtime type, the way the Data items are written, and reads it back as a -/// . +/// Writes the filter expressions' SearchTerm, the only -typed payload member, by +/// its runtime type, the way the Data items are written, and reads it back as the primitive it is. /// internal sealed class FilterValueConverter : JsonConverter { + // JSON has one number type OOB, so every number reads as a double. An array or object can only be a value + // the app set itself; it stays a JsonElement. public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - => JsonElement.ParseValue(ref reader); + => reader.TokenType switch + { + JsonTokenType.String => reader.GetString()!, + JsonTokenType.Number => reader.GetDouble(), + JsonTokenType.True => true, + JsonTokenType.False => false, + _ => JsonElement.ParseValue(ref reader), + }; public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) => JsonSerializer.Serialize(writer, value, AppValueSerializer.GetValueTypeInfo(value)); diff --git a/src/IgniteUI.Blazor.GridLite/Internal/GridLiteJsonContext.cs b/src/IgniteUI.Blazor.GridLite/Internal/GridLiteJsonContext.cs index ce57394..73614de 100644 --- a/src/IgniteUI.Blazor.GridLite/Internal/GridLiteJsonContext.cs +++ b/src/IgniteUI.Blazor.GridLite/Internal/GridLiteJsonContext.cs @@ -5,7 +5,7 @@ namespace IgniteUI.Blazor.Controls.Internal; /// /// Source-generated serializer metadata for every payload the library owns. The app-owned values inside /// them go through : Data through , -/// the object-typed filter values through . +/// the filter expressions' SearchTerm through . /// [JsonSourceGenerationOptions( DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, diff --git a/src/IgniteUI.Blazor.GridLite/Models/Events/IgbGridLiteFilteredEventArgs.cs b/src/IgniteUI.Blazor.GridLite/Models/Events/IgbGridLiteFilteredEventArgs.cs index 689e145..33ae403 100644 --- a/src/IgniteUI.Blazor.GridLite/Models/Events/IgbGridLiteFilteredEventArgs.cs +++ b/src/IgniteUI.Blazor.GridLite/Models/Events/IgbGridLiteFilteredEventArgs.cs @@ -17,5 +17,5 @@ public class IgbGridLiteFilteredEventArgs /// The filter state of the column after the operation. /// [JsonPropertyName("state")] - public required List State { get; init; } + public required IReadOnlyList State { get; init; } } diff --git a/src/IgniteUI.Blazor.GridLite/Models/Events/IgbGridLiteFilteringEventArgs.cs b/src/IgniteUI.Blazor.GridLite/Models/Events/IgbGridLiteFilteringEventArgs.cs index 4bd3075..cdecb26 100644 --- a/src/IgniteUI.Blazor.GridLite/Models/Events/IgbGridLiteFilteringEventArgs.cs +++ b/src/IgniteUI.Blazor.GridLite/Models/Events/IgbGridLiteFilteringEventArgs.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using IgniteUI.Blazor.Controls.Internal; namespace IgniteUI.Blazor.Controls; @@ -17,14 +18,27 @@ public class IgbGridLiteFilteringEventArgs /// The filter expression(s) to apply. /// [JsonPropertyName("expressions")] - public required List Expressions { get; init; } + public required IReadOnlyList Expressions { get; init; } /// /// The type of modification which will be applied to the filter state of the column. - /// 'add' - a new filter expression will be added to the state of the column. - /// 'modify' - an existing filter expression will be modified. - /// 'remove' - the expression(s) will be removed from the state of the column. /// [JsonPropertyName("type")] - public required string Type { get; init; } // TODO: "add", "modify", or "remove" + public required GridLiteFilteringType Type { get; init; } +} + +/// +/// The type of modification a filter operation applies to the filter state of a column. +/// +[JsonConverter(typeof(CamelCaseEnumConverter))] +public enum GridLiteFilteringType +{ + /// A new filter expression will be added to the state of the column. + Add, + + /// An existing filter expression will be modified. + Modify, + + /// The expression(s) will be removed from the state of the column. + Remove, } diff --git a/src/IgniteUI.Blazor.GridLite/Models/IgbGridLiteFilterExpression.cs b/src/IgniteUI.Blazor.GridLite/Models/IgbGridLiteFilterExpression.cs index 37e71ea..468e964 100644 --- a/src/IgniteUI.Blazor.GridLite/Models/IgbGridLiteFilterExpression.cs +++ b/src/IgniteUI.Blazor.GridLite/Models/IgbGridLiteFilterExpression.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using IgniteUI.Blazor.Controls.Internal; namespace IgniteUI.Blazor.Controls; @@ -14,27 +15,53 @@ public class IgbGridLiteFilterExpression public required string Key { get; set; } /// - /// The filter condition to apply. Can be a condition name (string) or a FilterOperation // TODO + /// The name of the filter condition to apply. The valid names depend on the column's + /// ; a column without one counts as . /// + /// + /// + /// Data typeCondition names + /// + /// + /// contains, doesNotContain, startsWith, endsWith, equals, + /// doesNotEqual, empty, notEmpty + /// + /// + /// + /// equals, doesNotEqual, greaterThan, lessThan, greaterThanOrEqual, + /// lessThanOrEqual, empty, notEmpty + /// + /// + /// + /// all, true, false, empty, notEmpty + /// + /// + /// + /// The boolean conditions, empty and notEmpty are unary: they take no . + /// + /// [JsonPropertyName("condition")] - public required object Condition { get; set; } + public required string Condition { get; set; } /// /// The filtering value used in the filter condition function. /// Optional for unary conditions. /// + /// + /// Typically matches the holding a , + /// a (any number, including one set as an ) or a ; + /// falls back to for other unrecognized/app-provided types. + /// [JsonPropertyName("searchTerm")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public object? SearchTerm { get; set; } /// - /// Dictates how this expression should resolve in the filter operation. - /// 'and' - the record must pass all the conditions. - /// 'or' - the record must pass at least one condition. + /// How this expression resolves in relation to the column's other expressions. /// [JsonPropertyName("criteria")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? Criteria { get; set; } // "and" or "or" + public GridLiteFilterCriteria? Criteria { get; set; } /// /// Whether the filter operation should be case sensitive. @@ -44,3 +71,16 @@ public class IgbGridLiteFilterExpression [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public bool? CaseSensitive { get; set; } } + +/// +/// How a filter expression resolves in relation to the column's other expressions. +/// +[JsonConverter(typeof(CamelCaseEnumConverter))] +public enum GridLiteFilterCriteria +{ + /// The record must pass all the conditions. + And, + + /// The record must pass at least one condition. + Or, +} diff --git a/src/IgniteUI.Blazor.GridLite/igc-grid-lite-entry.js b/src/IgniteUI.Blazor.GridLite/igc-grid-lite-entry.js index 8d46dec..235f5cf 100644 --- a/src/IgniteUI.Blazor.GridLite/igc-grid-lite-entry.js +++ b/src/IgniteUI.Blazor.GridLite/igc-grid-lite-entry.js @@ -54,12 +54,23 @@ export const blazor_igc_grid_lite = { this.listeners.set(id, controller); // The returned promise is left to the browser, so a failed .NET handler shows as an unhandled rejection. - const listen = (type, method) => { - gridElement.addEventListener(type, (e) => dotNetObject.invokeMethodAsync(method, e.detail), { + const listen = (type, method, transformDetail = (detail) => detail) => { + gridElement.addEventListener(type, (e) => dotNetObject.invokeMethodAsync(method, transformDetail(e.detail)), { signal: controller.signal, }); }; + /** + * Transform conditions as names only to match .NET model. grid-lite 0.11.0 still reports + * a condition as either that name or operation object `({ name, label, unary, logic })`. + * Safely support both. TODO: Remove once grid-lite updates condition handling. + */ + const withConditionsAsNames = (expressions) => + expressions.map((expression) => { + const { condition } = expression; + return { ...expression, condition: typeof condition === 'string' ? condition : condition?.name }; + }); + // TODO: the sorting and filtering handlers cannot cancel: grid-lite reads dispatchEvent's result synchronously, // so a preventDefault after the .NET call would come too late. Cancelling needs a client-side script parameter // (the *Script pattern, e.g. IgbCombo.ItemTemplateScript) or a synchronous callback. @@ -72,11 +83,14 @@ export const blazor_igc_grid_lite = { } if (events.hasFiltering) { - listen('filtering', 'JSFiltering'); + listen('filtering', 'JSFiltering', (detail) => ({ + ...detail, + expressions: withConditionsAsNames(detail.expressions), + })); } if (events.hasFiltered) { - listen('filtered', 'JSFiltered'); + listen('filtered', 'JSFiltered', (detail) => ({ ...detail, state: withConditionsAsNames(detail.state) })); } }, diff --git a/tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs b/tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs index 03bc1a4..511ee1f 100644 --- a/tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs +++ b/tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs @@ -39,6 +39,30 @@ public async Task Refresh_DoesNotDuplicateEventCallbacks() await Expect(Page.Locator("#sorted-count")).ToHaveTextAsync("1"); } + // TODO: grid-lite 0.11.0's client mapping a condition object to its name, remove after its updated + [Test] + public async Task FilteringEvent_WithConditionObject_ReachesDotNetAsItsName() + { + await Page.GotoAsync(Host.ServerAddress); + var grid = Page.Locator("igc-grid-lite"); + await Expect(grid.GetByText("Chai", new() { Exact = true })).ToBeVisibleAsync(); + + await grid.EvaluateAsync( + @"grid => grid.dispatchEvent(new CustomEvent('filtering', { + detail: { + key: 'ProductName', + expressions: [{ + key: 'ProductName', + condition: { name: 'contains', label: 'Contains', unary: false }, + searchTerm: 'Ch' + }], + type: 'add' + } + }))"); + + await Expect(Page.Locator("#last-filtering")).ToHaveTextAsync("Add contains"); + } + // Without it, a callback bound after the first render has no listener on the client and never fires. [Test] public async Task CallbackBoundAfterRender_Fires() diff --git a/tests/IgniteUI.Blazor.GridLite.TestBed/Components/Pages/GridPage.razor b/tests/IgniteUI.Blazor.GridLite.TestBed/Components/Pages/GridPage.razor index 967130a..4403196 100644 --- a/tests/IgniteUI.Blazor.GridLite.TestBed/Components/Pages/GridPage.razor +++ b/tests/IgniteUI.Blazor.GridLite.TestBed/Components/Pages/GridPage.razor @@ -3,7 +3,7 @@

GridLite TestBed

- + @@ -22,6 +22,7 @@

@refreshCount

@sortedCount

+

@lastFiltering

@@ -35,6 +36,7 @@ private EventCallback filtered; private int refreshCount; private int sortedCount; + private string lastFiltering = "none"; private int filteredCount; private void BindFiltered() => filtered = EventCallback.Factory.Create(this, OnFiltered); @@ -50,4 +52,7 @@ } private void OnSorted(IgbGridLiteSortedEventArgs args) => sortedCount++; + + private void OnFiltering(IgbGridLiteFilteringEventArgs args) + => lastFiltering = $"{args.Type} {string.Join(", ", args.Expressions.Select(e => e.Condition))}"; } diff --git a/tests/IgniteUI.Blazor.GridLite.Tests/EnumSerializationTests.cs b/tests/IgniteUI.Blazor.GridLite.Tests/EnumSerializationTests.cs index 3a9fcb7..f473234 100644 --- a/tests/IgniteUI.Blazor.GridLite.Tests/EnumSerializationTests.cs +++ b/tests/IgniteUI.Blazor.GridLite.Tests/EnumSerializationTests.cs @@ -44,12 +44,35 @@ public void SortingMode_SerializesToCamelCase(GridLiteSortingMode value, string Assert.Equal(value, JsonSerializer.Deserialize($"\"{expected}\"")); } + // Without the converter, the criteria reach grid-lite as numbers, which it does not read as 'and' / 'or'. + [Theory] + [InlineData(GridLiteFilterCriteria.And, "and")] + [InlineData(GridLiteFilterCriteria.Or, "or")] + public void FilterCriteria_SerializesToCamelCase(GridLiteFilterCriteria value, string expected) + { + Assert.Equal($"\"{expected}\"", JsonSerializer.Serialize(value)); + Assert.Equal(value, JsonSerializer.Deserialize($"\"{expected}\"")); + } + + // Without the converter, grid-lite's 'add' / 'modify' / 'remove' fail to deserialize and Filtering never runs. + [Theory] + [InlineData(GridLiteFilteringType.Add, "add")] + [InlineData(GridLiteFilteringType.Modify, "modify")] + [InlineData(GridLiteFilteringType.Remove, "remove")] + public void FilteringType_SerializesToCamelCase(GridLiteFilteringType value, string expected) + { + Assert.Equal($"\"{expected}\"", JsonSerializer.Serialize(value)); + Assert.Equal(value, JsonSerializer.Deserialize($"\"{expected}\"")); + } + [Fact] public void Enums_RejectIntegerValues() { Assert.Throws(() => JsonSerializer.Deserialize("0")); Assert.Throws(() => JsonSerializer.Deserialize("1")); Assert.Throws(() => JsonSerializer.Deserialize("0")); + Assert.Throws(() => JsonSerializer.Deserialize("1")); + Assert.Throws(() => JsonSerializer.Deserialize("0")); } [Fact] diff --git a/tests/IgniteUI.Blazor.GridLite.Tests/GridLiteJsInteropTests.cs b/tests/IgniteUI.Blazor.GridLite.Tests/GridLiteJsInteropTests.cs index 0e36dd8..855166f 100644 --- a/tests/IgniteUI.Blazor.GridLite.Tests/GridLiteJsInteropTests.cs +++ b/tests/IgniteUI.Blazor.GridLite.Tests/GridLiteJsInteropTests.cs @@ -367,7 +367,7 @@ public async Task FilterAsync_ExpressionList_InvokesFilter_WithArrayPayload() await cut.InvokeAsync(() => cut.Instance.FilterAsync( [ new IgbGridLiteFilterExpression { Key = "Name", Condition = "contains", SearchTerm = "a" }, - new IgbGridLiteFilterExpression { Key = "Name", Condition = "contains", SearchTerm = "b", Criteria = "or" }, + new IgbGridLiteFilterExpression { Key = "Name", Condition = "contains", SearchTerm = "b", Criteria = GridLiteFilterCriteria.Or }, ])); var expressions = ParseJsonArgument(GridApi.VerifyInvoke($"{Api}.filter").Arguments[1]); diff --git a/tests/IgniteUI.Blazor.GridLite.Tests/ModelSerializationTests.cs b/tests/IgniteUI.Blazor.GridLite.Tests/ModelSerializationTests.cs index 32dea25..bf20bb7 100644 --- a/tests/IgniteUI.Blazor.GridLite.Tests/ModelSerializationTests.cs +++ b/tests/IgniteUI.Blazor.GridLite.Tests/ModelSerializationTests.cs @@ -58,21 +58,21 @@ public void SortingExpression_RoundTripsFromJsPayload() } [Fact] - public void FilterExpression_SerializesWithCamelCaseKeys() + public void FilterExpression_SerializesWithCamelCaseKeys_AndPlainStringConditionAndCriteria() { var json = SerializeToElement(new IgbGridLiteFilterExpression { Key = "ProductName", Condition = "contains", SearchTerm = "Cha", - Criteria = "and", + Criteria = GridLiteFilterCriteria.Or, CaseSensitive = false, }, Context.IgbGridLiteFilterExpression); Assert.Equal("ProductName", json.GetProperty("key").GetString()); - Assert.Equal("contains", json.GetProperty("condition").GetString()); + Assert.Equal("\"contains\"", json.GetProperty("condition").GetRawText()); Assert.Equal("Cha", json.GetProperty("searchTerm").GetString()); - Assert.Equal("and", json.GetProperty("criteria").GetString()); + Assert.Equal("\"or\"", json.GetProperty("criteria").GetRawText()); Assert.False(json.GetProperty("caseSensitive").GetBoolean()); } @@ -91,17 +91,69 @@ public void FilterExpression_OmitsUnsetOptionalValues() Assert.False(json.TryGetProperty("caseSensitive", out _)); } - // The filtering events hand these back to app code, which reads them as JsonElement. - [Fact] - public void FilterExpression_ReadsObjectValuesFromJsPayload_AsJsonElement() + [Theory] + [InlineData("\"Ch\"", "Ch")] + [InlineData("10", 10.0)] + [InlineData("10.5", 10.5)] + [InlineData("true", true)] + [InlineData("false", false)] + public void FilterExpression_ReadsSearchTermFromJsPayload_AsPrimitive(string searchTerm, object expected) { - const string payload = """{"key":"Price","condition":"greaterThan","searchTerm":10}"""; + var payload = $$"""{"key":"Price","condition":"greaterThan","searchTerm":{{searchTerm}}}"""; var expression = JsonSerializer.Deserialize(payload, Context.IgbGridLiteFilterExpression); Assert.NotNull(expression); - Assert.Equal("greaterThan", Assert.IsType(expression.Condition).GetString()); - Assert.Equal(10, Assert.IsType(expression.SearchTerm).GetInt32()); + Assert.Equal("greaterThan", expression.Condition); + Assert.Equal(expected, expression.SearchTerm); + Assert.IsType(expected.GetType(), expression.SearchTerm); + } + + [Fact] + public void FilterExpression_ReadsNullOrStructuredSearchTerm() + { + var withNull = JsonSerializer.Deserialize("""{"key":"Name","condition":"empty","searchTerm":null}""", Context.IgbGridLiteFilterExpression); + var withArray = JsonSerializer.Deserialize("""{"key":"Price","condition":"equals","searchTerm":[1,2]}""", Context.IgbGridLiteFilterExpression); + + Assert.Null(withNull!.SearchTerm); + Assert.Equal(JsonValueKind.Array, Assert.IsType(withArray!.SearchTerm).ValueKind); + } + + [Theory] + [InlineData("add", GridLiteFilteringType.Add)] + [InlineData("modify", GridLiteFilteringType.Modify)] + [InlineData("remove", GridLiteFilteringType.Remove)] + public void FilteringEventArgs_DeserializeFromJsPayload(string type, GridLiteFilteringType expected) + { + var payload = $$""" + {"key":"Name","type":"{{type}}","expressions":[ + {"key":"Name","condition":"contains","searchTerm":"a"}, + {"key":"Name","condition":"startsWith","searchTerm":"b","criteria":"or"}]} + """; + + var args = JsonSerializer.Deserialize(payload, Context.IgbGridLiteFilteringEventArgs); + + Assert.NotNull(args); + Assert.Equal(expected, args.Type); + Assert.Equal(2, args.Expressions.Count); + Assert.Null(args.Expressions[0].Criteria); + Assert.Equal("startsWith", args.Expressions[1].Condition); + Assert.Equal(GridLiteFilterCriteria.Or, args.Expressions[1].Criteria); + } + + [Fact] + public void FilteredEventArgs_DeserializeFromJsPayload() + { + const string payload = """ + {"key":"Name","state":[{"key":"Name","condition":"contains","searchTerm":"a","criteria":"and"}]} + """; + + var args = JsonSerializer.Deserialize(payload, Context.IgbGridLiteFilteredEventArgs); + + Assert.NotNull(args); + var expression = Assert.Single(args.State); + Assert.Equal("contains", expression.Condition); + Assert.Equal(GridLiteFilterCriteria.And, expression.Criteria); } [Theory] From e082c58cf83895fb36b1ee88c7d82cf3430f152d Mon Sep 17 00:00:00 2001 From: Damyan Petev Date: Thu, 8 Oct 2026 11:40:03 +0300 Subject: [PATCH 2/2] Update tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs --- .../IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs b/tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs index 511ee1f..6bc12a4 100644 --- a/tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs +++ b/tests/IgniteUI.Blazor.GridLite.IntegrationTests/GridLiteTests.cs @@ -39,7 +39,7 @@ public async Task Refresh_DoesNotDuplicateEventCallbacks() await Expect(Page.Locator("#sorted-count")).ToHaveTextAsync("1"); } - // TODO: grid-lite 0.11.0's client mapping a condition object to its name, remove after its updated + // TODO: grid-lite 0.11.0's client mapping a condition object to its name, remove after it's updated. [Test] public async Task FilteringEvent_WithConditionObject_ReachesDotNetAsItsName() {