Skip to content

Commit

Permalink
[DataGrid] Add resizing columns by keyboard
Browse files Browse the repository at this point in the history
* Fix Aspire 3364 by adding IKeyCodeListner and handler

* process PR remarks

* Fix more script issues
  • Loading branch information
vnbaaij authored Apr 17, 2024
1 parent b3ac3cd commit e27e210
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1522,6 +1522,9 @@
Constructs an instance of <see cref="T:Microsoft.FluentUI.AspNetCore.Components.FluentDataGrid`1"/>.
</summary>
</member>
<member name="M:Microsoft.FluentUI.AspNetCore.Components.FluentDataGrid`1.OnInitialized">
<inheritdoc />
</member>
<member name="M:Microsoft.FluentUI.AspNetCore.Components.FluentDataGrid`1.OnParametersSetAsync">
<inheritdoc />
</member>
Expand Down
4 changes: 4 additions & 0 deletions examples/Demo/Shared/Pages/DataGrid/DataGridPage.razor
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
Pressing the <kbd>Enter</kbd> key then will toggle the options popover. Pressing <kbd>Esc</kbd> closes the popover
.
</p>
<p>
When a grid allows resizing of the columns, you can use the <kbd>+</kbd> and <kbd>-</kbd> keys to resize the column the focused header belongs to. Incrementing/decrementing
width is done in steps of 10 pixels at a time. You can reset to the original initial column widths by pressing <kbd>Shift</kbd> + <kbd>r</kbd>.
</p>

<h2 id="sorting">Sorting</h2>
<p>
Expand Down
8 changes: 8 additions & 0 deletions examples/Demo/Shared/wwwroot/css/site.css
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@ code {
background-color: var(--neutral-fill-secondary-hover);
}

kbd {
padding: 0.10rem 0.25rem;
font-size: 0.875em;
color: var(--neutral-foreground-rest);
background-color: var(--neutral-fill-secondary-rest);
border-radius: 0.25rem;
border: 1px solid var(--accent-fill-rest);
}

#blazor-error-ui {
background: lightyellow;
Expand Down
43 changes: 43 additions & 0 deletions src/Core/Components/DataGrid/FluentDataGrid.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ public partial class FluentDataGrid<TGridItem> : FluentComponentBase, IHandleEve
[Parameter] public RenderFragment? LoadingContent { get; set; }
[Inject] private IServiceProvider Services { get; set; } = default!;
[Inject] private IJSRuntime JSRuntime { get; set; } = default!;
[Inject] private IKeyCodeService KeyCodeService { get; set; } = default!;

private ElementReference? _gridReference;
private Virtualize<(int, TGridItem)>? _virtualizeComponent;
Expand Down Expand Up @@ -215,6 +216,12 @@ public FluentDataGrid()
columnsFirstCollectedSubscriber.SubscribeOrMove(_internalGridContext.ColumnsFirstCollected);
}

/// <inheritdoc />
protected override void OnInitialized()
{
KeyCodeService.RegisterListener(OnKeyDownAsync);
}

/// <inheritdoc />
protected override Task OnParametersSetAsync()
{
Expand Down Expand Up @@ -558,4 +565,40 @@ private async Task HandleOnRowFocusAsync(DataGridRowFocusEventArgs args)
}
}
}

public async Task OnKeyDownAsync(FluentKeyCodeEventArgs args)
{
if (args.ShiftKey == true && args.Key == KeyCode.KeyR)
{
await ResetColumnWidthsAsync();
}

if (args.Value == "-")
{
await SetColumnWidthAsync(-10);
}
if (args.Value == "+")
{
// Resize column up
await SetColumnWidthAsync(10);
}
//return Task.CompletedTask;
}

private async Task SetColumnWidthAsync(float widthChange)
{
if (_gridReference is not null && Module is not null)
{
await Module.InvokeVoidAsync("resizeColumn", _gridReference, widthChange);
}
}

private async Task ResetColumnWidthsAsync()
{
if (_gridReference is not null && Module is not null)
{
await Module.InvokeVoidAsync("resetColumnWidths", _gridReference);
}
}

}
64 changes: 55 additions & 9 deletions src/Core/Components/DataGrid/FluentDataGrid.razor.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
let initialColumnsWidths = '';
export function init(gridElement) {
if (gridElement === undefined || gridElement === null) {
return;
};

enableColumnResizing(gridElement);
if (gridElement.querySelectorAll('.column-header.resizable').length > 0) {
initialColumnsWidths = gridElement.gridTemplateColumns;
enableColumnResizing(gridElement);
}

const bodyClickHandler = event => {
const columnOptionsElement = gridElement?.querySelector('.col-options');
Expand Down Expand Up @@ -61,8 +65,6 @@ export function init(gridElement) {
};
}



export function checkColumnOptionsPosition(gridElement) {
const colOptions = gridElement?._rowItems[0] && gridElement?.querySelector('.col-options'); // Only match within *our* thead, not nested tables
if (colOptions) {
Expand Down Expand Up @@ -96,8 +98,6 @@ export function enableColumnResizing(gridElement) {
gridElement.querySelectorAll('.column-header.resizable').forEach(header => {
columns.push({ header });
const onPointerMove = (e) => requestAnimationFrame(() => {
//console.log(`onPointerMove${headerBeingResized ? '' : ' [not resizing]'}`);

if (!headerBeingResized) {
return;
}
Expand Down Expand Up @@ -130,15 +130,11 @@ export function enableColumnResizing(gridElement) {
});

const onPointerUp = () => {
//console.log('onPointerUp');

headerBeingResized = undefined;
resizeHandle = undefined;
};

const initResize = ({ target, pointerId }) => {
//console.log('initResize');

resizeHandle = target;
headerBeingResized = target.parentNode;

Expand All @@ -155,3 +151,53 @@ export function enableColumnResizing(gridElement) {
}
});
}

export function resetColumnWidths(gridElement) {

gridElement.gridTemplateColumns = initialColumnsWidths;
}

export function resizeColumn(gridElement, change) {

let headers = gridElement.querySelectorAll('.column-header.resizable');
if (headers.length <= 0) {
return
}

if (!(document.activeElement.classList.contains("column-header") && document.activeElement.classList.contains("resizable"))) {
return;
}
const columns = [];
let headerBeingResized = document.activeElement;
let min = 50;

headers.forEach(header => {
if (header === headerBeingResized) {
min = headerBeingResized.querySelector('.col-options-button') ? 75 : 50;

const width = headerBeingResized.getBoundingClientRect().width + change;

if (change < 0) {
header.size = Math.max(min, width) + 'px';
}
else {
header.size = width + 'px';
}
}
else {
if (header.size === undefined) {
if (header.clientWidth === undefined || header.clientWidth === 0) {
header.size = min + 'px';
} else {
header.size = header.clientWidth + 'px';
}
}
}

columns.push({ header });
});

gridElement.gridTemplateColumns = columns
.map(({ header }) => header.size)
.join(' ');
}

0 comments on commit e27e210

Please sign in to comment.