Skip to content

feat: add a bindable KumikoViewState that the grid applies and writes back (#393) - #517

Open
michaelstonis wants to merge 2 commits into
mainfrom
feat/393-bindable-view-state
Open

michaelstonis wants to merge 2 commits into
mainfrom
feat/393-bindable-view-state

Conversation

@michaelstonis

Copy link
Copy Markdown
Contributor

Closes #393.

Changes

A view model can now own the grid's sort, column filters, filter predicate and grouping as a KumikoViewState, bound to a new ViewState property on both hosts. The grid applies the state, and it writes the user's changes back into it. Renderer, input controller and hit tester are not touched.

Core (KumikoUI.Core.Models)

  • KumikoViewState (INotifyPropertyChanged, used from the UI thread only):
    • Sorts (ObservableCollection<KumikoSortState>, in priority order)
    • Filters (ObservableCollection<KumikoColumnFilterState>)
    • Groups (ObservableCollection<GroupDescription>)
    • Predicate
    • Version and Changed: raised once per change, or once per DeferChanges() batch
    • Clear()
    • persistence through the existing layout JSON: ToLayoutState(), static FromLayoutState(layout) and LoadLayoutState(layout) (in place, as one change)
  • KumikoSortState(ColumnKey, Direction): a record.
  • KumikoColumnFilterState(ColumnKey, Filter): the column-free twin of FilterDescription. It reuses KumikoFilterLayoutState, so filters keep the shape and value encoding that saved layouts use. FromValues(key, values) and FromCondition(key, condition1, condition2?, combination) build one without hand-encoding values.
  • Columns are matched by Key, else PropertyName, the internal LayoutKey rule that KumikoLayoutState uses. No reflection is involved.
  • The internal KumikoViewStateBinder does the two-way sync. The hosts reach it through InternalsVisibleTo.
    • Grid reads. The state is applied in one BeginUpdate/EndUpdate batch, so one rebuild (in the background above BackgroundRebuildThreshold). This happens on bind, on every Changed, on reconnect, and when the source's columns are replaced. Only the parts that differ are touched, so a state that already matches costs no rebuild. Sorts go through ClearSort and SetSort, filters through SetColumnFilter, the predicate through SetFilter, and groups through SetGroupDescriptions, so the existing events still fire. This mirrors what KumikoLayoutState.ApplyTo does.
    • Grid writes. On a ViewChanged with kind Rebuild, the binder compares a snapshot of the source with the one taken after its last apply or write. If they differ, it writes the source's sort, filters, groups and predicate into the state as one DeferChanges batch, so one Changed. Entries for unknown columns are kept, and so are filters on columns that do not allow filtering. Filter entries that did not change stay the same objects. A canceled SortColumnsChanging does not rebuild, so nothing is written. Programmatic changes (including ApplyLayoutState) are written back the same way. Write-back runs once per rebuild, which coalesces a source batch into one write.
    • No loops. While the binder applies, it ignores the source's notifications. While it writes, it ignores the state's Changed and records the new Version as already shown.
    • Sharing. With two grids on one state, the second grid applies the change once and writes nothing back. A grouping level reversed in place (the same GroupDescription with a new direction) is detected through the snapshot, so the other grid rebuilds too.
    • Lifecycle. Disconnect() unsubscribes from the state, so a long-lived view model does not keep the grid alive. Reconnect() subscribes again and re-applies.
  • Small additive hooks in KumikoSource:
    • New partial file KumikoSource.ViewState.cs: internal FilterPredicate and internal event ColumnsReplaced.
    • SetColumns now runs inside its own BeginUpdate/EndUpdate and raises ColumnsReplaced inside that batch. A bound state is re-applied to the new column objects, for example when columns arrive after the state is bound or are generated later, and it costs no second rebuild.
    • Behavior without a bound state is unchanged. The full Core suite passes.
  • KumikoFilterLayoutState.ValueEquals and KumikoFilterConditionLayoutState.ValueEquals: new internal helpers.

Hosts (MAUI and Uno, same names)

  • New ViewState property: BindableProperty with BindingMode.TwoWay default on MAUI, DependencyProperty on Uno (docs say Mode=TwoWay).
    • The binder is created lazily, so a grid without a state pays nothing.
    • Setting null keeps the current view and stops following the state.
    • The grid only changes the state's contents, never the property itself.
  • Cleanup/Unloaded disconnect the binder. Reconnect/Loaded reconnect it after the bound collections are re-synced, so a state that changed while the page was away wins.
  • GroupDescriptions: with Grouping: GroupDescriptions keeps a group the user removed in the group panel #418 already merged, the host collection mirrors every source grouping change. While a state is bound, GroupDescriptions therefore mirrors ViewState.Groups, and a change to either reaches the other. It was not made a view over ViewState.Groups, so behavior without a state is unchanged.

Samples and docs

  • The MVVM page of both sample apps binds ViewState to a shared state that outlives the page, so sort and filters survive navigation. The page also has a "Top salaries" button (a DeferChanges batch from the view model), "Reset view", and a line showing the state as the view model sees it. That line is subscribed only while the page is shown.
  • README:
    • new "Keeping the view in the view model" section under Sorting and Filtering, with compiled snippets
    • notes in "Grouping" and "Saving and restoring the layout"
    • a ViewState row in the host properties table
  • CHANGELOG entry under Unreleased / Added.

Public API added (PublicAPI.Unshipped.txt)

  • Core: KumikoViewState (ctor, Sorts, Filters, Groups, Predicate, Version, Changed, PropertyChanged, DeferChanges, Clear, ToLayoutState, FromLayoutState, LoadLayoutState); KumikoSortState (record members); KumikoColumnFilterState (ctor, ColumnKey, Filter, FromValues, FromCondition).
  • MAUI: KumikoDataGrid.ViewState, ViewStateProperty. Uno: KumikoDataGrid.ViewState, ViewStateProperty.

Relation to #359 (KumikoQuery) and #354 (layout parts)

Acceptance criteria

  • Setting ViewState applies sort, filters, predicate and grouping in one rebuild; changing it later re-applies; tests in tests/KumikoUI.Core.Tests. Covered by the new KumikoViewStateTests.cs (19 tests), which counts ViewChanged rebuilds: binding is one rebuild, each change or batch is one, and a matching state is zero. It also covers background rebuild. The tests went into a new file instead of KumikoLayoutStateTests/ViewChangedTests so the binder's behavior stays in one place.
  • User sorting, filtering and group chip actions write back to the bound state without re-applying it. Tests cover ToggleSort, SetColumnFilter, RemoveGroupDescription (what the chip calls), ClearAllFilters, a source batch giving one write, a canceled sort writing nothing, and ApplyLayoutState.
  • Two grids bound to one state stay in sync without loops. Tests count exactly one Changed and one rebuild per grid for each change, from either grid or from the view model. A group reversed in place in one grid also rebuilds the other.
  • The host GroupDescriptions collection reflects group panel chip removals. Already true since Grouping: GroupDescriptions keeps a group the user removed in the group panel #418 / PR fix: keep the bound GroupDescriptions in step with grouping changed in the group panel (#418) #419. The new MAUI host test also checks it with a ViewState bound, in both directions.
  • Works on MAUI and Uno with two-way binding; the MVVM sample page keeps its sort and filter across navigation on both. Both hosts have the same property and lifecycle wiring, and both MVVM sample pages use a shared state. Six MAUI host tests (seven cases) cover: applied before or after the columns, a recreated page getting the same view, write-back, mirroring of GroupDescriptions, ApplyLayoutState, null, and the default binding mode. KumikoUI.Uno.Tests cannot construct the Uno grid on its plain test host, so Uno's behavior is covered by the shared Core binder tests and by the Uno sample build. Neither sample app was run interactively.
  • XML docs on every new public member; PublicAPI.Unshipped.txt updated with eng/update-public-api.sh. The docs are in place. On this machine eng/update-public-api.sh Core emptied the file instead of filling it (the same issue the Layout state: save and restore expanded groups, selection, scroll position and summary rows #354 and Data: define a remote view contract that pushes sort, filter, grouping and row windows to the server #359 sessions hit), so the change was reverted and the entries were added from the RS0016 diagnostics, sorted. Core, Maui and Uno build clean against them.
  • README "Sorting and Filtering", "Grouping" and "Saving and restoring the layout" sections updated; CHANGELOG entry under Unreleased.
  • Native AOT and trimming stay warning-free (no reflection in key matching). Keys are matched through KumikoColumn.LayoutKey strings, with no reflection. The Core Release build has 0 warnings with the trimming and AOT analyzers on. eng/AotSmoke was not run.

Verification

  • dotnet build src/KumikoUI.Core (Debug and Release): succeeded, 0 warnings.
  • dotnet build src/KumikoUI.Maui -f net10.0-maccatalyst: succeeded, 0 warnings.
  • dotnet build src/KumikoUI.Uno -f net10.0-desktop: succeeded. The only warnings are the existing 2 Uno0001 ones in Editing.cs and Input.cs.
  • dotnet build samples/SampleApp.Uno -f net10.0-desktop: succeeded.
  • dotnet build samples/SampleApp.Maui -f net10.0-maccatalyst: restore fails with NU1605 on this machine's MAUI workload (Microsoft.Maui.Controls 10.0.41 against the 10.0.110 that SkiaSharp.Views.Maui needs). That is unrelated to this change. With -p:NoWarn=NU1605 (local check only, nothing committed) it builds, with no warnings in the changed page.
  • dotnet test tests/KumikoUI.Core.Tests: 4,380 passed, 5 skipped, 0 failed (19 new tests).
  • dotnet test tests/KumikoUI.SkiaSharp.Tests: 42 passed.
  • dotnet test tests/KumikoUI.Maui.Tests: 456 passed (6 new tests, 7 cases).
  • dotnet test tests/KumikoUI.Uno.Tests: 321 passed.
  • dotnet run --project eng/DocsSnippets -c Release, then dotnet build tests/KumikoUI.Docs.Snippets.Uno -c Release and dotnet build tests/KumikoUI.Docs.Snippets.Maui -c Release: both succeeded, new README snippets included.
  • dotnet run --project eng/TypeNameCheck -c Release -- src/KumikoUI.Core/bin/Release/net10.0/KumikoUI.Core.dll: no public type name collides.

var (source, binder) = CreateDisconnectedGrid(state);
for (int i = 0; i < 3; i++)
{
GC.Collect();
Comment on lines +151 to +158
foreach (var sort in Sorts)
{
if (sort is null || string.IsNullOrEmpty(sort.ColumnKey) || sort.Direction == KumikoSortDirection.None) continue;
var entry = Entry(sort.ColumnKey);
if (entry.SortDirection != KumikoSortDirection.None) continue; // the first entry for a column wins
entry.SortDirection = sort.Direction;
entry.SortOrder = order++;
}
Comment on lines +159 to +164
foreach (var filter in Filters)
{
if (filter is null || string.IsNullOrEmpty(filter.ColumnKey)) continue;
var entry = Entry(filter.ColumnKey);
entry.Filter ??= Copy(filter.Filter);
}
Comment on lines +165 to +174
foreach (var group in Groups)
{
if (group is null || string.IsNullOrEmpty(group.PropertyName)) continue;
layout.Groups!.Add(new KumikoGroupLayoutState
{
PropertyName = group.PropertyName,
Header = group.Header,
SortDirection = group.GroupSortDirection,
});
}
Comment on lines +156 to +161
foreach (var sort in state.Sorts)
{
if (sort is null || sort.Direction == KumikoSortDirection.None || string.IsNullOrEmpty(sort.ColumnKey)) continue;
if (!byKey.TryGetValue(sort.ColumnKey, out var column) || !seen.Add(column)) continue;
desired.Add((column, sort.Direction));
}
Comment on lines +178 to +182
foreach (var filter in state.Filters)
{
if (filter is null || string.IsNullOrEmpty(filter.ColumnKey)) continue;
if (byKey.TryGetValue(filter.ColumnKey, out var column)) desired.TryAdd(column, filter.Filter);
}
Comment on lines +226 to +230
foreach (var sort in state.Sorts)
{
if (sort is not null && !string.IsNullOrEmpty(sort.ColumnKey) && !byKey.ContainsKey(sort.ColumnKey))
sorts.Add(sort); // a column the grid does not have (yet)
}
Comment on lines +244 to +254
foreach (var filter in state.Filters)
{
if (filter is null || string.IsNullOrEmpty(filter.ColumnKey) || written.Contains(filter.ColumnKey)) continue;
// Kept: a column the grid does not have, or one that does not allow filtering (the user could
// not have removed its filter).
if (!byKey.TryGetValue(filter.ColumnKey, out var column) || !column.AllowFiltering)
{
written.Add(filter.ColumnKey);
filters.Add(filter);
}
}
Comment on lines +293 to +297
foreach (var column in source.Columns)
{
if (KumikoFilterLayoutState.From(column.ActiveFilter) is { } filter)
snapshot.Filters.Add((column, filter));
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Data: let a view model own a bindable view state (sort, filters, grouping) that the grid reads and writes

2 participants