Skip to content

Commit

Permalink
[On-week] Add persisting page size and sorting for Management tables (#…
Browse files Browse the repository at this point in the history
…186997)

Addresses #56406

## Summary

This PR is part of my June 2024 On-week project. It adds functionality
for persisting table page size (rows per page) and sorting in EUI
tables. When a user changes the size or sort, the new values are saved
in local storage, so that when the user navigates out of the page and
comes back, the page size and sort will be the same.

In this PR, the functionality is added to the following tables:
- Ingest Pipelines
- Index Management - all tables (indices, data streams, index templates,
component templates, enrich policies)
- ILM policies




https://github.com/elastic/kibana/assets/59341489/08b0c004-65a1-4a58-b8fb-99010e1c3248



<!--
### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
-->

---------

Co-authored-by: kibanamachine <[email protected]>
  • Loading branch information
ElenaStoeva and kibanamachine authored Aug 21, 2024
1 parent 072eb9c commit d9da7f6
Show file tree
Hide file tree
Showing 35 changed files with 1,103 additions and 63 deletions.
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,7 @@ packages/shared-ux/router/types @elastic/appex-sharedux
packages/shared-ux/storybook/config @elastic/appex-sharedux
packages/shared-ux/storybook/mock @elastic/appex-sharedux
packages/shared-ux/modal/tabbed @elastic/appex-sharedux
packages/shared-ux/table_persist @elastic/appex-sharedux
packages/kbn-shared-ux-utility @elastic/appex-sharedux
x-pack/plugins/observability_solution/slo @elastic/obs-ux-management-team
x-pack/packages/kbn-slo-schema @elastic/obs-ux-management-team
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,7 @@
"@kbn/shared-ux-storybook-config": "link:packages/shared-ux/storybook/config",
"@kbn/shared-ux-storybook-mock": "link:packages/shared-ux/storybook/mock",
"@kbn/shared-ux-tabbed-modal": "link:packages/shared-ux/modal/tabbed",
"@kbn/shared-ux-table-persist": "link:packages/shared-ux/table_persist",
"@kbn/shared-ux-utility": "link:packages/kbn-shared-ux-utility",
"@kbn/slo-plugin": "link:x-pack/plugins/observability_solution/slo",
"@kbn/slo-schema": "link:x-pack/packages/kbn-slo-schema",
Expand Down
51 changes: 51 additions & 0 deletions packages/shared-ux/table_persist/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# @kbn/shared-ux-table-persist

This package contains the `useEuiTablePersist` hook that can be used in components
containing Eui tables for storing their page size ("rows per page" value) or
the current sort criteria in local storage so that the user's preferences for
these properties can persist.

The package also exports some table-related constants (e.g. `DEFAULT_PAGE_SIZE_OPTIONS`)
for use across tables in Kibana Stack Management for consistency.

Usage:

```
interface Props {
items: T[];
}
const MyTableComponent: FunctionComponent<Props> = ({ items }) => {
const columns = [
{
field: 'name',
name: 'Name',
sortable: true,
},
...
];
const { pageSize, sorting, onTableChange } = useEuiTablePersist<T>({
tableId: 'myTableId',
initialPageSize: 50,
initialSort: {
field: 'name',
direction: 'asc',
},
});
const pagination = {
pageSize,
pageSizeOptions: DEFAULT_PAGE_SIZE_OPTIONS,
};
return (
<EuiInMemoryTable
items={items}
columns={columns}
pagination={pagination}
sorting={sorting}
/>
);
};
```
9 changes: 9 additions & 0 deletions packages/shared-ux/table_persist/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

export { useEuiTablePersist, DEFAULT_PAGE_SIZE_OPTIONS } from './src';
13 changes: 13 additions & 0 deletions packages/shared-ux/table_persist/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

module.exports = {
preset: '@kbn/test',
rootDir: '../../..',
roots: ['<rootDir>/packages/shared-ux/table_persist'],
};
5 changes: 5 additions & 0 deletions packages/shared-ux/table_persist/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "shared-common",
"id": "@kbn/shared-ux-table-persist",
"owner": "@elastic/appex-sharedux"
}
6 changes: 6 additions & 0 deletions packages/shared-ux/table_persist/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "@kbn/shared-ux-table-persist",
"private": true,
"version": "1.0.0",
"license": "SSPL-1.0 OR Elastic License 2.0"
}
12 changes: 12 additions & 0 deletions packages/shared-ux/table_persist/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

export const DEFAULT_PAGE_SIZE_OPTIONS = [25, 50, 100];
export const DEFAULT_INITIAL_PAGE_SIZE = 50;

export const LOCAL_STORAGE_PREFIX = 'tablePersist';
10 changes: 10 additions & 0 deletions packages/shared-ux/table_persist/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

export { useEuiTablePersist } from './use_table_persist';
export { DEFAULT_PAGE_SIZE_OPTIONS } from './constants';
51 changes: 51 additions & 0 deletions packages/shared-ux/table_persist/src/storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { LOCAL_STORAGE_PREFIX } from './constants';

type IStorageEngine = typeof window.localStorage;

class Storage {
engine: IStorageEngine = window.localStorage;
prefix: string = LOCAL_STORAGE_PREFIX;

encode(val: unknown) {
return JSON.stringify(val);
}

decode(val: string | null) {
if (typeof val === 'string') {
return JSON.parse(val);
}
}

encodeKey(key: string) {
return `${this.prefix}:${key}`;
}

set(key: string, val: unknown) {
this.engine.setItem(this.encodeKey(key), this.encode(val));
return val;
}

has(key: string) {
return this.engine.getItem(this.encodeKey(key)) != null;
}

get<T>(key: string, _default?: T) {
if (this.has(key)) {
return this.decode(this.engine.getItem(this.encodeKey(key)));
} else {
return _default;
}
}
}

export function createStorage() {
return new Storage();
}
17 changes: 17 additions & 0 deletions packages/shared-ux/table_persist/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

export interface PropertySort<T> {
field: keyof T;
direction: 'asc' | 'desc';
}

export interface PersistData<T> {
pageSize?: number;
sort?: PropertySort<T>;
}
130 changes: 130 additions & 0 deletions packages/shared-ux/table_persist/src/use_table_persist.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { Criteria } from '@elastic/eui';
import { renderHook, act } from '@testing-library/react-hooks';
import { useEuiTablePersist } from './use_table_persist';
import { createStorage } from './storage'; // Mock this if it's external

jest.mock('./storage');

describe('useEuiTablePersist', () => {
const mockStorage = {
get: jest.fn(),
set: jest.fn(),
};

beforeEach(() => {
(createStorage as jest.Mock).mockReturnValue(mockStorage);
mockStorage.get.mockClear();
mockStorage.set.mockClear();
});

it('should initialize with default values if local storage is empty', () => {
mockStorage.get.mockReturnValueOnce(undefined);

const { result } = renderHook(() => useEuiTablePersist({ tableId: 'testTable' }));

expect(result.current.pageSize).toBe(50); // Default initialPageSize
expect(result.current.sorting).toBe(true); // Allow sorting by default
expect(mockStorage.get).toHaveBeenCalledWith('testTable', undefined);
});

it('should initialize with values from local storage', () => {
const persistedData = { pageSize: 25, sort: { field: 'name', direction: 'asc' } };
mockStorage.get.mockReturnValueOnce(persistedData);

const { result } = renderHook(() => useEuiTablePersist({ tableId: 'testTable' }));

expect(result.current.pageSize).toBe(25);
expect(result.current.sorting).toEqual({ sort: { field: 'name', direction: 'asc' } });
});

it('should update pageSize and sort in state and local storage when onTableChange is called', () => {
const persistedData = { pageSize: 25, sort: { field: 'name', direction: 'asc' } };
mockStorage.get.mockReturnValueOnce(persistedData);

const { result } = renderHook(() => useEuiTablePersist({ tableId: 'testTable' }));

const nextCriteria = {
page: { size: 100 },
sort: { field: 'age', direction: 'desc' },
};

act(() => {
result.current.onTableChange(nextCriteria as Criteria<any>);
});

expect(result.current.pageSize).toBe(100);
expect(result.current.sorting).toEqual({ sort: { field: 'age', direction: 'desc' } });
expect(mockStorage.set).toHaveBeenCalledWith('testTable', {
pageSize: 100,
sort: { field: 'age', direction: 'desc' },
});
});

it('should call customOnTableChange if provided', () => {
const customOnTableChange = jest.fn();

const { result } = renderHook(() =>
useEuiTablePersist({
tableId: 'testTable',
customOnTableChange,
})
);

const nextCriteria = {
page: { size: 20 },
sort: { field: 'age', direction: 'desc' },
};

act(() => {
result.current.onTableChange(nextCriteria as Criteria<any>);
});

expect(customOnTableChange).toHaveBeenCalledWith(nextCriteria);
});

it('should maintain sort and pageSize if new values are not provided on change', () => {
const persistedData = { pageSize: 25, sort: { field: 'name', direction: 'asc' } };
mockStorage.get.mockReturnValueOnce(persistedData);

const { result } = renderHook(() => useEuiTablePersist({ tableId: 'testTable' }));

act(() => {
result.current.onTableChange({}); // Empty change
});

expect(result.current.pageSize).toBe(25);
expect(result.current.sorting).toEqual({ sort: { field: 'name', direction: 'asc' } });
expect(mockStorage.set).not.toHaveBeenCalled();
});

it('should remove sort in state and local storage if field is an empty string', () => {
const persistedData = { pageSize: 25, sort: { field: 'name', direction: 'asc' } };
mockStorage.get.mockReturnValueOnce(persistedData);

const { result } = renderHook(() => useEuiTablePersist({ tableId: 'testTable' }));

const nextCriteria = {
page: { size: 100 },
sort: { field: '', direction: 'asc' },
};

act(() => {
result.current.onTableChange(nextCriteria as Criteria<any>);
});

expect(result.current.pageSize).toBe(100);
expect(result.current.sorting).toEqual(true);
expect(mockStorage.set).toHaveBeenCalledWith('testTable', {
pageSize: 100,
sort: undefined,
});
});
});
Loading

0 comments on commit d9da7f6

Please sign in to comment.