Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 4 additions & 21 deletions src/Core/Components/DataGrid/FluentDataGrid.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,7 @@ protected override async Task OnAfterRenderAsync(bool firstRender)

_selfReference = DotNetObjectReference.Create(this);

_gridController = await JSModule.ObjectReference.InvokeAsync<IJSObjectReference>("Microsoft.FluentUI.Blazor.DataGrid.Initialize", _gridReference, AutoFocus);
_gridController = await JSModule.ObjectReference.InvokeAsync<IJSObjectReference>("Microsoft.FluentUI.Blazor.DataGrid.Initialize", _gridReference, AutoFocus, _selfReference);
if (AutoItemsPerPage)
{

Expand Down Expand Up @@ -1755,6 +1755,7 @@ public async Task RemoveSortByColumnAsync(ColumnBase<TGridItem> column)
/// sort declared by the columns is restored.
/// </summary>
/// <returns>A <see cref="Task"/> representing the completion of the operation.</returns>
[JSInvokable] // Shift+S, which the grid's script handles
public Task RemoveSortByColumnAsync()
{
if (SortMode == DataGridSortMode.Multiple)
Expand Down Expand Up @@ -2628,26 +2629,8 @@ public async Task UpdateItemsPerPageAsync(int visibleRows)
/// <returns></returns>
public async Task OnKeyDownAsync(FluentKeyCodeEventArgs args)
{
if (args.ShiftKey && args.Key == KeyCode.KeyR)
{
await ResetColumnWidthsAsync();
}

if (args.ShiftKey && args.Key == KeyCode.KeyS)
{
await RemoveSortByColumnAsync();
}

if (string.Equals(args.Value, "-", StringComparison.Ordinal))
{
await SetColumnWidthDiscreteAsync(columnIndex: null, -10);
}

if (string.Equals(args.Value, "+", StringComparison.Ordinal))
{
await SetColumnWidthDiscreteAsync(columnIndex: null, 10);
}

// Shift+R, Shift+S, + and - are handled by the grid's script, which only acts on key presses made in the grid
// and outside of text fields, rather than here, where every key press on the page arrives.
var activeColumn =
_activeHeaderUiKind == ColumnHeaderUiKind.Reorder
? _activeHeaderUiColumn
Expand Down
34 changes: 33 additions & 1 deletion src/Core/Components/DataGrid/FluentDataGrid.razor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export namespace Microsoft.FluentUI.Blazor.DataGrid {
// Use a dictionary for grids for id-based access
let grids: Grid[] = []; // { [id: string]: Grid } = {};

export function Initialize(gridElement: HTMLElement, autoFocus: boolean) {
export function Initialize(gridElement: HTMLElement, autoFocus: boolean, dotNetHelper: any) {
if (!gridElement) {
return;
}
Expand Down Expand Up @@ -234,7 +234,39 @@ export namespace Microsoft.FluentUI.Blazor.DataGrid {

return targetRow.cells[cell.cellIndex] as HTMLTableCellElement | null;
};
// Shift+R, Shift+S, + and - type the very characters they are made of, so they only act on a key press aimed
// at the grid itself: the table, one of its cells or one of its column header buttons (WCAG 2.1.4, Character Key
// Shortcuts). Whatever a cell holds (a text field, a date picker, a custom component...) is left alone, as it is
// by arrow key navigation, and so is a grid nested in the row details, whose cells belong to another table.
// Handling them here keeps the key presses made anywhere else on the page from reaching .NET: only Shift+S,
// which changes the sort, calls it.
const handleCharacterKeyShortcut = (event: KeyboardEvent) => {
if (event.ctrlKey || event.altKey || event.metaKey) {
return;
}

// A key press made inside a web component is retargeted to its host, which is what event.target holds here.
const target = event.target;
const isAimedAtGrid = target === gridElement
|| (target instanceof HTMLElement
&& target.matches('td, th, [col-sort-button], [col-options-button]')
&& target.closest('table') === gridElement);
if (!isAimedAtGrid) {
return;
}

if (event.key === '+' || event.key === '-') {
ResizeColumnDiscrete(gridElement, undefined, event.key === '+' ? 10 : -10);
} else if (event.shiftKey && event.code === 'KeyR') {
ResetColumnWidths(gridElement);
} else if (event.shiftKey && event.code === 'KeyS') {
dotNetHelper?.invokeMethodAsync('RemoveSortByColumnAsync');
}
};

const keyDownHandler = (event: KeyboardEvent) => {
handleCharacterKeyShortcut(event);

if ((event as any)[handledArrowNavigationEventFlag]) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -975,7 +975,7 @@
await grid.AddSortByColumnAsync("Level", DataGridSortDirection.Ascending);

// Act
await grid.OnKeyDownAsync(new FluentKeyCodeEventArgs { Key = KeyCode.KeyS, ShiftKey = true, Value = "S" });
await grid.RemoveSortByColumnAsync(); // What the grid's script calls on Shift+S

// Assert: unchanged from single sort mode, where Shift+S restores the starting situation.
Assert.Single(grid.SortColumns);
Expand All @@ -993,7 +993,7 @@
await grid.AddSortByColumnAsync("Name", DataGridSortDirection.Descending);

// Act
await grid.OnKeyDownAsync(new FluentKeyCodeEventArgs { Key = KeyCode.KeyS, ShiftKey = true, Value = "S" });
await grid.RemoveSortByColumnAsync(); // What the grid's script calls on Shift+S

// Assert
Assert.Empty(grid.SortColumns);
Expand Down
50 changes: 50 additions & 0 deletions tests/Core/Components/DataGrid/FluentDataGridTests.razor
Original file line number Diff line number Diff line change
Expand Up @@ -2145,6 +2145,56 @@
Assert.True(true);
}

[Theory]
[InlineData(KeyCode.KeyS, "S", true)]
[InlineData(KeyCode.KeyR, "R", true)]
[InlineData(KeyCode.Minus, "-", false)]
[InlineData(KeyCode.NumpadAdd, "+", false)]
public async Task FluentDataGrid_KeyDown_CharacterKeyShortcuts_AreLeftToTheGridScript(KeyCode key, string value, bool shiftKey)
{
// Arrange: the document-wide key listener reports every key press on the page, typing in a field included.
var module = JSInterop.SetupModule(matcher => matcher.Arguments.Any(arg => arg?.ToString()?.EndsWith("DataGrid/FluentDataGrid.razor.js") == true));
module.Mode = JSRuntimeMode.Loose;
FluentDataGrid<Customer>? grid = default!;
var cut = Render<FluentDataGrid<Customer>>(
@<FluentDataGrid TGridItem="Customer" @ref="@grid" Items="@GetCustomers().AsQueryable()" ResizableColumns="true">
<PropertyColumn Property="@(x => x.Id)" Sortable="true" IsDefaultSortColumn="true" />
<PropertyColumn Property="@(x => x.Name)" Sortable="true" />
</FluentDataGrid>);

await cut.InvokeAsync(() => grid.SortByColumnAsync("Name", DataGridSortDirection.Descending));

// Act
await cut.InvokeAsync(() => grid.OnKeyDownAsync(new FluentKeyCodeEventArgs { Key = key, Value = value, ShiftKey = shiftKey }));

// Assert: the grid's own script handles these keys, as it knows whether they were typed in the grid.
Assert.Equal("Name", grid.SortColumns[0].Column.Title);
Assert.Empty(module.Invocations["Microsoft.FluentUI.Blazor.DataGrid.ResetColumnWidths"]);
Assert.Empty(module.Invocations["Microsoft.FluentUI.Blazor.DataGrid.ResizeColumnDiscrete"]);
}

[Fact]
public void FluentDataGrid_Initialize_GivesTheScriptAReferenceToTheGridForShiftS()
{
// Arrange
var module = JSInterop.SetupModule(matcher => matcher.Arguments.Any(arg => arg?.ToString()?.EndsWith("DataGrid/FluentDataGrid.razor.js") == true));
module.Mode = JSRuntimeMode.Loose;

// Act
var cut = Render<FluentDataGrid<Customer>>(
@<FluentDataGrid Items="@GetCustomers().AsQueryable()">
<PropertyColumn Property="@(x => x.Name)" Sortable="true" />
</FluentDataGrid>);

// Assert: the script calls RemoveSortByColumnAsync through this reference on Shift+S.
var initialize = Assert.Single(module.Invocations["Microsoft.FluentUI.Blazor.DataGrid.Initialize"]);
Assert.IsType<DotNetObjectReference<FluentDataGrid<Customer>>>(initialize.Arguments[2]);
Assert.NotNull(typeof(FluentDataGrid<Customer>)
.GetMethod(nameof(FluentDataGrid<Customer>.RemoveSortByColumnAsync), Type.EmptyTypes)!
.GetCustomAttributes(typeof(JSInvokableAttribute), inherit: false)
.SingleOrDefault());
}

[Theory]
[InlineData("status", KeyCode.KeyF, new[] { "status", "name", "created" })]
[InlineData("status", KeyCode.KeyP, new[] { "name", "status", "created" })]
Expand Down