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
509 changes: 207 additions & 302 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"@redhat-cloud-services/frontend-components-utilities": ">= 6.1.0",
"@tanstack/react-pacer": ">= 0.15.0",
"@tanstack/react-query": ">= 5.83.0",
"deepmerge": ">= 4.3.1",
"p-all": ">= 4.0.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand Down
30 changes: 21 additions & 9 deletions public/mockServiceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
* - Please do NOT modify this file.
*/

const PACKAGE_VERSION = '2.13.3'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const PACKAGE_VERSION = '2.15.0'
const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()

Expand Down Expand Up @@ -137,8 +137,18 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
if (client && activeClientIds.has(client.id)) {
const serializedRequest = await serializeRequest(requestCloneForEvents)

// Omit the body of server-sent event stream responses.
// Cloning such responses would prevent client-side stream cancelations
// from reaching the original stream (a teed stream only cancels its
// source once both of its branches cancel) and would buffer the
// entire stream into the unconsumed clone indefinitely.
const isEventStreamResponse = response.headers
.get('content-type')
?.toLowerCase()
.startsWith('text/event-stream')

// Clone the response so both the client and the library could consume it.
const responseClone = response.clone()
const responseClone = isEventStreamResponse ? null : response.clone()

sendToClient(
client,
Expand All @@ -151,15 +161,17 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
...serializedRequest,
},
response: {
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
headers: Object.fromEntries(responseClone.headers.entries()),
body: responseClone.body,
type: response.type,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
body: responseClone ? responseClone.body : null,
},
},
},
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
responseClone && responseClone.body
? [serializedRequest.body, responseClone.body]
: [],
)
}

Expand Down
12 changes: 12 additions & 0 deletions src/components/BaseTableToolsTable/BaseTableToolsTable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React from 'react';
import TableToolsTable from '~/components/TableToolsTable';

import useWithDefaults from './hooks/useWithDefaults';

const BaseTableToolsTable = (props) => {
const propsWithDefaults = useWithDefaults(props);

return <TableToolsTable {...propsWithDefaults} />;
};

export default BaseTableToolsTable;
109 changes: 109 additions & 0 deletions src/components/BaseTableToolsTable/BaseTableToolsTable.stories.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

import defaultStoryMeta from '~/support/defaultStoryMeta';
import columns from '~/support/factories/columns';
import filters, {
customNumberFilterType,
customNumberFilter,
} from '~/support/factories/filters';
import useExampleDataQuery from '~/support/hooks/useExampleDataQuery';

import { BaseTableToolsTable, TableStateProvider } from '~/components';
import paginationSerialiser from '~/components/StaticTableToolsTable/helpers/serialisers/pagination';
import sortSerialiser from '~/components/StaticTableToolsTable/helpers/serialisers/sort';
import filtersSerialiser from '~/components/StaticTableToolsTable/helpers/serialisers/filters';

const queryClient = new QueryClient();

const meta = {
title: 'BaseTableToolsTable',
args: {
debug: true,
columns,
filters,
},
...defaultStoryMeta,
};

const defaultOptions = {
serialisers: {
pagination: paginationSerialiser,
sort: sortSerialiser,
filters: filtersSerialiser,
},
};

const ShareableTable = (props) => (
<BaseTableToolsTable
props={props}
defaults={{
options: defaultOptions,
columns,
filters: {
filterConfig: [...filters, customNumberFilter],
customFilterTypes: {
number: customNumberFilterType,
},
},
}}
/>
);

const SharableVariantTable = (props) => (
<ShareableTable
props={props}
defaults={{
columns: [
{
title: 'Another Artist',
Component: ({ artist }) => artist,
},
],
}}
/>
);

const ShareableTableToolsTableExample = () => {
const {
loading,
result: { data, meta: { total } = {} } = {},
error,
} = useExampleDataQuery({
endpoint: '/api',
useTableState: true,
tableQueries: {
extraParams: {
itemIdsInTable: { idsOnly: true },
},
},
});

return (
<SharableVariantTable
loading={loading}
items={data}
total={total}
error={error}
filters={{ filterConfig: ['title', 'number-filter'] }}
columns={['title', { key: 'artist' }, 'another-artist']}
/>
);
};

ShareableTableToolsTableExample.propTypes = {};

export const ShareableTableToolsTable = {
decorators: [
(Story) => (
<QueryClientProvider client={queryClient}>
<TableStateProvider>
<Story />
</TableStateProvider>
</QueryClientProvider>
),
],
render: (args) => <ShareableTableToolsTableExample {...args} />,
};

export default meta;
91 changes: 91 additions & 0 deletions src/components/BaseTableToolsTable/BaseTableToolsTable.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import React from 'react';
import { render, screen } from '@testing-library/react';

import items from '~/support/factories/items';
import columns from '~/support/factories/columns';
import filters, {
customNumberFilterType,
customNumberFilter,
} from '~/support/factories/filters';

import BaseTableToolsTable from './BaseTableToolsTable';

const ShareableTable = (props) => (
<BaseTableToolsTable
props={props}
defaults={{
options: {
// debug: true,
},
columns,
filters: {
filterConfig: [...filters, customNumberFilter],
customFilterTypes: {
number: customNumberFilterType,
},
},
}}
/>
);

const SharableVariantTable = (props) => (
<ShareableTable
props={props}
defaults={{
columns: [
{
title: 'Another Artist',
Component: ({ artist }) => artist,
},
],
}}
/>
);

describe('BaseTableToolsTable', () => {
const exampleItems = items(100).sort((item) => item.name);
const itemsFunc = async () => [
exampleItems.slice(0, 10),
exampleItems.length,
];

it('should render a table with all defaults', async () => {
render(<SharableVariantTable items={itemsFunc} />);

expect(await screen.findByText(exampleItems[1].title)).toBeInTheDocument();

expect(
screen.getByRole('columnheader', {
name: /title/i,
}),
).toBeInTheDocument();
});

it('should render a table with one default and one additional column', async () => {
const ariaLabel = 'Async Test Table';
const props = {
'aria-label': ariaLabel,
columns: [
'another-artist',
{
title: 'Title',
key: 'title',
},
],
items: itemsFunc,
};

render(<SharableVariantTable {...props} />);

expect(await screen.findByText(exampleItems[1].title)).toBeInTheDocument();

expect(await screen.findByText('Another Artist')).toBeInTheDocument();

expect(
screen.getByRole('columnheader', {
name: /title/i,
}),
).toBeInTheDocument();
screen.logTestingPlaygroundURL();

Check warning on line 89 in src/components/BaseTableToolsTable/BaseTableToolsTable.test.js

View workflow job for this annotation

GitHub Actions / build (22.x)

Unexpected debug statement

Check warning on line 89 in src/components/BaseTableToolsTable/BaseTableToolsTable.test.js

View workflow job for this annotation

GitHub Actions / build (21.x)

Unexpected debug statement

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unexpected debug statement [eslint:testing-library/no-debugging-utils]

});
});
30 changes: 30 additions & 0 deletions src/components/BaseTableToolsTable/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import deepmerge from 'deepmerge';

const getId = (item) => {
const key = item.key || item.label || item.title || item;
return typeof key === 'string' ? key.replaceAll(' ', '-').toLowerCase() : key;
};

const findDefault = (defaults, ext) =>
defaults.find((def) => getId(def) === getId(ext));

const selectByKeyAndMerge = (defaults, extension) =>
extension
.map((ext) => {
const def = findDefault(defaults, ext);

if (typeof ext === 'string') {
return def;
} else if (typeof ext === 'object') {
return deepmerge(def, ext);
}
})
.filter((v) => !!v);

export const compileWithDefaults = (defaults, extension) => {
if (typeof extension === 'undefined') {
return defaults;
} else if (Array.isArray(extension)) {
return selectByKeyAndMerge(defaults, extension);
}
};
59 changes: 59 additions & 0 deletions src/components/BaseTableToolsTable/hooks/useWithDefaults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { useMemo } from 'react';
import deepmerge from 'deepmerge';

import { compileWithDefaults } from '../helpers';

const useWithDefaults = (props) => {
const result = useMemo(() => {
const {
props: { props: parentProps, defaults: parentDefaults, ...thisProps },
defaults: thisDefaults,
} = props;
const allProps = deepmerge(parentProps || {}, {
...(thisProps || {}),
...(props || {}),
});
const allDefaults = deepmerge(parentDefaults || {}, thisDefaults || {});

const columns = compileWithDefaults(
allDefaults.columns || [],
allProps.columns,
);

const filters = {
...allDefaults.filters,
...allProps.filters,
filterConfig: compileWithDefaults(
allDefaults.filters?.filterConfig,
allProps.filters?.filterConfig,
),
};

const options = deepmerge(
allDefaults.options || {},
allProps.options || {},
);

const result = {
...allProps,
columns,
filters,
options,
};

if (result.options?.debug) {
console.group('Table with defaults');
console.log('Props:', props);
console.log('Combined props:', allProps);
console.log('Combined defaults:', allDefaults);
console.log('Result:', result);
console.groupEnd();
}

return result;
}, [props]);

return result;
};

export default useWithDefaults;
1 change: 1 addition & 0 deletions src/components/BaseTableToolsTable/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './BaseTableToolsTable';
19 changes: 19 additions & 0 deletions src/components/QueryProviderWithUtilities.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from 'react';
import propTypes from 'prop-types';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();
window.__TANSTACK_QUERY_CLIENT__ = queryClient;

const QueryProviderWithUtilities = ({ children }) => {
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
};

QueryProviderWithUtilities.propTypes = {
children: propTypes.node,
};

export default QueryProviderWithUtilities;
Loading
Loading