mirror of
https://github.com/portainer/portainer.git
synced 2025-07-22 23:09:41 +02:00
refactor(app): move react components to react codebase [EE-3179] (#6971)
This commit is contained in:
parent
212400c283
commit
18252ab854
346 changed files with 642 additions and 644 deletions
27
app/react/components/datatables/ActionsMenu.module.css
Normal file
27
app/react/components/datatables/ActionsMenu.module.css
Normal file
|
@ -0,0 +1,27 @@
|
|||
.actions {
|
||||
float: right;
|
||||
margin: 5px 10px 0 0;
|
||||
}
|
||||
|
||||
.actions-active {
|
||||
color: var(--blue-2);
|
||||
}
|
||||
|
||||
.table-actions-menu-list {
|
||||
background: var(--bg-widget-color);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.table-actions-menu-list [data-reach-menu-item] {
|
||||
padding: 5px 15px;
|
||||
}
|
||||
|
||||
.table-actions-menu-btn {
|
||||
border: none;
|
||||
background: none;
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
[data-reach-menu-link] {
|
||||
text-decoration: none !important;
|
||||
}
|
31
app/react/components/datatables/ActionsMenu.tsx
Normal file
31
app/react/components/datatables/ActionsMenu.tsx
Normal file
|
@ -0,0 +1,31 @@
|
|||
import { ReactNode } from 'react';
|
||||
import clsx from 'clsx';
|
||||
import { Menu, MenuList, MenuButton } from '@reach/menu-button';
|
||||
|
||||
import styles from './ActionsMenu.module.css';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ActionsMenu({ children }: Props) {
|
||||
return (
|
||||
<Menu className={styles.actions}>
|
||||
{({ isExpanded }) => (
|
||||
<>
|
||||
<MenuButton
|
||||
className={clsx(
|
||||
styles.tableActionsMenuBtn,
|
||||
isExpanded && styles.actionsActive
|
||||
)}
|
||||
>
|
||||
<i className="fa fa-ellipsis-v" aria-hidden="true" />
|
||||
</MenuButton>
|
||||
<MenuList>
|
||||
<div className={styles.tableActionsMenuList}>{children}</div>
|
||||
</MenuList>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
);
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
.table-actions-title {
|
||||
color: var(--blue-2);
|
||||
padding: 5px 10px;
|
||||
}
|
11
app/react/components/datatables/ActionsMenuTitle.tsx
Normal file
11
app/react/components/datatables/ActionsMenuTitle.tsx
Normal file
|
@ -0,0 +1,11 @@
|
|||
import { ReactNode } from 'react';
|
||||
|
||||
import styles from './ActionsMenuTitle.module.css';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ActionsMenuTitle({ children }: Props) {
|
||||
return <div className={styles.tableActionsTitle}>{children}</div>;
|
||||
}
|
68
app/react/components/datatables/ColumnVisibilityMenu.tsx
Normal file
68
app/react/components/datatables/ColumnVisibilityMenu.tsx
Normal file
|
@ -0,0 +1,68 @@
|
|||
import clsx from 'clsx';
|
||||
import { Menu, MenuButton, MenuList } from '@reach/menu-button';
|
||||
import { ColumnInstance } from 'react-table';
|
||||
|
||||
import { Checkbox } from '@@/form-components/Checkbox';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
|
||||
interface Props<D extends object> {
|
||||
columns: ColumnInstance<D>[];
|
||||
onChange: (value: string[]) => void;
|
||||
value: string[];
|
||||
}
|
||||
|
||||
export function ColumnVisibilityMenu<D extends object>({
|
||||
columns,
|
||||
onChange,
|
||||
value,
|
||||
}: Props<D>) {
|
||||
useTableContext();
|
||||
|
||||
return (
|
||||
<Menu className="setting">
|
||||
{({ isExpanded }) => (
|
||||
<>
|
||||
<MenuButton
|
||||
className={clsx('table-setting-menu-btn', {
|
||||
'setting-active': isExpanded,
|
||||
})}
|
||||
>
|
||||
<i className="fa fa-columns" aria-hidden="true" /> Columns
|
||||
</MenuButton>
|
||||
<MenuList>
|
||||
<div className="tableMenu">
|
||||
<div className="menuHeader">Show / Hide Columns</div>
|
||||
<div className="menuContent">
|
||||
{columns.map((column) => (
|
||||
<div key={column.id}>
|
||||
<Checkbox
|
||||
checked={column.isVisible}
|
||||
label={column.Header as string}
|
||||
id={`visibility_${column.id}`}
|
||||
onChange={(e) =>
|
||||
handleChangeColumnVisibility(
|
||||
column.id,
|
||||
e.target.checked
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</MenuList>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
);
|
||||
|
||||
function handleChangeColumnVisibility(colId: string, visible: boolean) {
|
||||
if (visible) {
|
||||
onChange(value.filter((id) => id !== colId));
|
||||
return;
|
||||
}
|
||||
|
||||
onChange([...value, colId]);
|
||||
}
|
||||
}
|
9
app/react/components/datatables/ExpandingCell.module.css
Normal file
9
app/react/components/datatables/ExpandingCell.module.css
Normal file
|
@ -0,0 +1,9 @@
|
|||
.expand-button {
|
||||
background: none;
|
||||
color: inherit;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
outline: inherit;
|
||||
}
|
36
app/react/components/datatables/ExpandingCell.tsx
Normal file
36
app/react/components/datatables/ExpandingCell.tsx
Normal file
|
@ -0,0 +1,36 @@
|
|||
import { PropsWithChildren } from 'react';
|
||||
import { Row } from 'react-table';
|
||||
|
||||
import styles from './ExpandingCell.module.css';
|
||||
|
||||
interface Props<D extends Record<string, unknown> = Record<string, unknown>> {
|
||||
row: Row<D>;
|
||||
showExpandArrow: boolean;
|
||||
}
|
||||
|
||||
export function ExpandingCell<
|
||||
D extends Record<string, unknown> = Record<string, unknown>
|
||||
>({ row, showExpandArrow, children }: PropsWithChildren<Props<D>>) {
|
||||
return (
|
||||
<>
|
||||
{showExpandArrow && (
|
||||
<button type="button" className={styles.expandButton}>
|
||||
<i
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...row.getToggleRowExpandedProps()}
|
||||
className={`fas ${arrowClass(row.isExpanded)} space-right`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
)}
|
||||
{children}
|
||||
</>
|
||||
);
|
||||
|
||||
function arrowClass(isExpanded: boolean) {
|
||||
if (isExpanded) {
|
||||
return 'fa-angle-down';
|
||||
}
|
||||
return 'fa-angle-right';
|
||||
}
|
||||
}
|
93
app/react/components/datatables/Filter.tsx
Normal file
93
app/react/components/datatables/Filter.tsx
Normal file
|
@ -0,0 +1,93 @@
|
|||
import clsx from 'clsx';
|
||||
import { useMemo } from 'react';
|
||||
import { Menu, MenuButton, MenuPopover } from '@reach/menu-button';
|
||||
import { ColumnInstance } from 'react-table';
|
||||
|
||||
export function DefaultFilter({
|
||||
column: { filterValue, setFilter, preFilteredRows, id },
|
||||
}: {
|
||||
column: ColumnInstance;
|
||||
}) {
|
||||
const options = useMemo(() => {
|
||||
const options = new Set<string>();
|
||||
preFilteredRows.forEach((row) => {
|
||||
options.add(row.values[id]);
|
||||
});
|
||||
|
||||
return Array.from(options);
|
||||
}, [id, preFilteredRows]);
|
||||
|
||||
return (
|
||||
<MultipleSelectionFilter
|
||||
options={options}
|
||||
filterKey={id}
|
||||
value={filterValue}
|
||||
onChange={setFilter}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface MultipleSelectionFilterProps {
|
||||
options: string[];
|
||||
value: string[];
|
||||
filterKey: string;
|
||||
onChange: (value: string[]) => void;
|
||||
}
|
||||
|
||||
function MultipleSelectionFilter({
|
||||
options,
|
||||
value = [],
|
||||
filterKey,
|
||||
onChange,
|
||||
}: MultipleSelectionFilterProps) {
|
||||
const enabled = value.length > 0;
|
||||
return (
|
||||
<div>
|
||||
<Menu>
|
||||
<MenuButton
|
||||
className={clsx('table-filter', { 'filter-active': enabled })}
|
||||
>
|
||||
Filter
|
||||
<i
|
||||
className={clsx(
|
||||
'fa',
|
||||
'space-left',
|
||||
enabled ? 'fa-check' : 'fa-filter'
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</MenuButton>
|
||||
<MenuPopover className="dropdown-menu">
|
||||
<div className="tableMenu">
|
||||
<div className="menuHeader">Filter by state</div>
|
||||
<div className="menuContent">
|
||||
{options.map((option, index) => (
|
||||
<div className="md-checkbox" key={index}>
|
||||
<input
|
||||
id={`filter_${filterKey}_${index}`}
|
||||
type="checkbox"
|
||||
checked={value.includes(option)}
|
||||
onChange={() => handleChange(option)}
|
||||
/>
|
||||
<label htmlFor={`filter_${filterKey}_${index}`}>
|
||||
{option}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</MenuPopover>
|
||||
</Menu>
|
||||
</div>
|
||||
);
|
||||
|
||||
function handleChange(option: string) {
|
||||
if (value.includes(option)) {
|
||||
onChange(value.filter((o) => o !== option));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
onChange([...value, option]);
|
||||
}
|
||||
}
|
15
app/react/components/datatables/FilterSearchBar.module.css
Normal file
15
app/react/components/datatables/FilterSearchBar.module.css
Normal file
|
@ -0,0 +1,15 @@
|
|||
.searchBar {
|
||||
padding: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.searchBar .iconSpan {
|
||||
display: inline-block;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.searchBar .textSpan {
|
||||
display: inline-block;
|
||||
width: 90%;
|
||||
}
|
45
app/react/components/datatables/FilterSearchBar.tsx
Normal file
45
app/react/components/datatables/FilterSearchBar.tsx
Normal file
|
@ -0,0 +1,45 @@
|
|||
import { useLocalStorage } from '@/portainer/hooks/useLocalStorage';
|
||||
|
||||
import styles from './FilterSearchBar.module.css';
|
||||
|
||||
interface Props {
|
||||
value: string;
|
||||
placeholder?: string;
|
||||
onChange(value: string): void;
|
||||
}
|
||||
|
||||
export function FilterSearchBar({
|
||||
value,
|
||||
placeholder = 'Search...',
|
||||
onChange,
|
||||
}: Props) {
|
||||
return (
|
||||
<div className={styles.searchBar}>
|
||||
<span className={styles.iconSpan}>
|
||||
<i className="fa fa-search" aria-hidden="true" />
|
||||
</span>
|
||||
<span className={styles.textSpan}>
|
||||
<input
|
||||
type="text"
|
||||
className="searchInput"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSearchBarState(
|
||||
key: string
|
||||
): [string, (value: string) => void] {
|
||||
const filterKey = keyBuilder(key);
|
||||
const [value, setValue] = useLocalStorage(filterKey, '', sessionStorage);
|
||||
|
||||
return [value, setValue];
|
||||
|
||||
function keyBuilder(key: string) {
|
||||
return `datatable_text_filter_${key}`;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
.inner-datatable thead {
|
||||
background-color: var(--bg-inner-datatable-thead) !important;
|
||||
}
|
7
app/react/components/datatables/InnerDatatable.tsx
Normal file
7
app/react/components/datatables/InnerDatatable.tsx
Normal file
|
@ -0,0 +1,7 @@
|
|||
import { PropsWithChildren } from 'react';
|
||||
|
||||
import styles from './InnerDatatable.module.css';
|
||||
|
||||
export function InnerDatatable({ children }: PropsWithChildren<unknown>) {
|
||||
return <div className={styles.innerDatatable}>{children}</div>;
|
||||
}
|
48
app/react/components/datatables/QuickActionsSettings.tsx
Normal file
48
app/react/components/datatables/QuickActionsSettings.tsx
Normal file
|
@ -0,0 +1,48 @@
|
|||
import { Checkbox } from '@@/form-components/Checkbox';
|
||||
|
||||
import { useTableSettings } from './useTableSettings';
|
||||
|
||||
export interface Action {
|
||||
id: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
actions: Action[];
|
||||
}
|
||||
|
||||
export interface QuickActionsSettingsType {
|
||||
hiddenQuickActions: string[];
|
||||
}
|
||||
|
||||
export function QuickActionsSettings({ actions }: Props) {
|
||||
const { settings, setTableSettings } =
|
||||
useTableSettings<QuickActionsSettingsType>();
|
||||
|
||||
return (
|
||||
<>
|
||||
{actions.map(({ id, label }) => (
|
||||
<Checkbox
|
||||
key={id}
|
||||
label={label}
|
||||
id={`quick-actions-${id}`}
|
||||
checked={!settings.hiddenQuickActions.includes(id)}
|
||||
onChange={(e) => toggleAction(id, e.target.checked)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
|
||||
function toggleAction(key: string, value: boolean) {
|
||||
setTableSettings(({ hiddenQuickActions = [], ...settings }) => ({
|
||||
...settings,
|
||||
hiddenQuickActions: value
|
||||
? hiddenQuickActions.filter((id) => id !== key)
|
||||
: [...hiddenQuickActions, key],
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAction(id: string, label: string): Action {
|
||||
return { id, label };
|
||||
}
|
39
app/react/components/datatables/SearchBar.tsx
Normal file
39
app/react/components/datatables/SearchBar.tsx
Normal file
|
@ -0,0 +1,39 @@
|
|||
import { useLocalStorage } from '@/portainer/hooks/useLocalStorage';
|
||||
|
||||
interface Props {
|
||||
value: string;
|
||||
placeholder?: string;
|
||||
onChange(value: string): void;
|
||||
}
|
||||
|
||||
export function SearchBar({
|
||||
value,
|
||||
placeholder = 'Search...',
|
||||
onChange,
|
||||
}: Props) {
|
||||
return (
|
||||
<div className="searchBar">
|
||||
<i className="fa fa-search searchIcon" aria-hidden="true" />
|
||||
<input
|
||||
type="text"
|
||||
className="searchInput"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSearchBarState(
|
||||
key: string
|
||||
): [string, (value: string) => void] {
|
||||
const filterKey = keyBuilder(key);
|
||||
const [value, setValue] = useLocalStorage(filterKey, '', sessionStorage);
|
||||
|
||||
return [value, setValue];
|
||||
|
||||
function keyBuilder(key: string) {
|
||||
return `datatable_text_filter_${key}`;
|
||||
}
|
||||
}
|
9
app/react/components/datatables/SelectedRowsCount.tsx
Normal file
9
app/react/components/datatables/SelectedRowsCount.tsx
Normal file
|
@ -0,0 +1,9 @@
|
|||
interface SelectedRowsCountProps {
|
||||
value: number;
|
||||
}
|
||||
|
||||
export function SelectedRowsCount({ value }: SelectedRowsCountProps) {
|
||||
return value !== 0 ? (
|
||||
<div className="infoBar">{value} item(s) selected</div>
|
||||
) : null;
|
||||
}
|
18
app/react/components/datatables/SortbySelector.module.css
Normal file
18
app/react/components/datatables/SortbySelector.module.css
Normal file
|
@ -0,0 +1,18 @@
|
|||
.sort-by-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.sort-by-element {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.sort-button {
|
||||
background-color: var(--bg-sortbutton-color);
|
||||
color: var(--text-ui-select-color);
|
||||
border: 1px solid var(--border-sortbutton);
|
||||
display: inline-block;
|
||||
padding: 8px 10px;
|
||||
border-radius: 5px;
|
||||
}
|
66
app/react/components/datatables/SortbySelector.tsx
Normal file
66
app/react/components/datatables/SortbySelector.tsx
Normal file
|
@ -0,0 +1,66 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { Filter } from '@/portainer/home/types';
|
||||
|
||||
import { Select } from '@@/form-components/ReactSelect';
|
||||
|
||||
import styles from './SortbySelector.module.css';
|
||||
|
||||
interface Props {
|
||||
filterOptions: Filter[];
|
||||
onChange: (filterOptions: Filter) => void;
|
||||
onDescending: () => void;
|
||||
placeHolder: string;
|
||||
sortByDescending: boolean;
|
||||
sortByButton: boolean;
|
||||
value?: Filter;
|
||||
}
|
||||
|
||||
export function SortbySelector({
|
||||
filterOptions,
|
||||
onChange,
|
||||
onDescending,
|
||||
placeHolder,
|
||||
sortByDescending,
|
||||
sortByButton,
|
||||
value,
|
||||
}: Props) {
|
||||
const upIcon = 'fa fa-sort-alpha-up';
|
||||
const downIcon = 'fa fa-sort-alpha-down';
|
||||
const [iconStyle, setIconStyle] = useState(downIcon);
|
||||
|
||||
useEffect(() => {
|
||||
if (sortByDescending) {
|
||||
setIconStyle(upIcon);
|
||||
} else {
|
||||
setIconStyle(downIcon);
|
||||
}
|
||||
}, [sortByDescending]);
|
||||
|
||||
return (
|
||||
<div className={styles.sortByContainer}>
|
||||
<div className={styles.sortByElement}>
|
||||
<Select
|
||||
placeholder={placeHolder}
|
||||
options={filterOptions}
|
||||
onChange={(option) => onChange(option as Filter)}
|
||||
isClearable
|
||||
value={value}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.sortByElement}>
|
||||
<button
|
||||
className={styles.sortButton}
|
||||
type="button"
|
||||
disabled={!sortByButton}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
onDescending();
|
||||
}}
|
||||
>
|
||||
<i className={iconStyle} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
29
app/react/components/datatables/Table.tsx
Normal file
29
app/react/components/datatables/Table.tsx
Normal file
|
@ -0,0 +1,29 @@
|
|||
import clsx from 'clsx';
|
||||
import { PropsWithChildren } from 'react';
|
||||
import { TableProps } from 'react-table';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
|
||||
export function Table({
|
||||
children,
|
||||
className,
|
||||
role,
|
||||
style,
|
||||
}: PropsWithChildren<TableProps>) {
|
||||
useTableContext();
|
||||
|
||||
return (
|
||||
<div className="table-responsive">
|
||||
<table
|
||||
className={clsx(
|
||||
'table table-hover table-filters nowrap-cells',
|
||||
className
|
||||
)}
|
||||
role={role}
|
||||
style={style}
|
||||
>
|
||||
{children}
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
17
app/react/components/datatables/TableActions.tsx
Normal file
17
app/react/components/datatables/TableActions.tsx
Normal file
|
@ -0,0 +1,17 @@
|
|||
import clsx from 'clsx';
|
||||
import { PropsWithChildren } from 'react';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function TableActions({
|
||||
children,
|
||||
className,
|
||||
}: PropsWithChildren<Props>) {
|
||||
useTableContext();
|
||||
|
||||
return <div className={clsx('actionBar', className)}>{children}</div>;
|
||||
}
|
25
app/react/components/datatables/TableContainer.tsx
Normal file
25
app/react/components/datatables/TableContainer.tsx
Normal file
|
@ -0,0 +1,25 @@
|
|||
import { createContext, PropsWithChildren, useContext } from 'react';
|
||||
|
||||
import { Widget, WidgetBody } from '@@/Widget';
|
||||
|
||||
const Context = createContext<null | boolean>(null);
|
||||
|
||||
export function useTableContext() {
|
||||
const context = useContext(Context);
|
||||
|
||||
if (context == null) {
|
||||
throw new Error('Should be nested inside a TableContainer component');
|
||||
}
|
||||
}
|
||||
|
||||
export function TableContainer({ children }: PropsWithChildren<unknown>) {
|
||||
return (
|
||||
<Context.Provider value>
|
||||
<div className="datatable">
|
||||
<Widget>
|
||||
<WidgetBody className="no-padding">{children}</WidgetBody>
|
||||
</Widget>
|
||||
</div>
|
||||
</Context.Provider>
|
||||
);
|
||||
}
|
49
app/react/components/datatables/TableContent.tsx
Normal file
49
app/react/components/datatables/TableContent.tsx
Normal file
|
@ -0,0 +1,49 @@
|
|||
import { PropsWithChildren } from 'react';
|
||||
import { Row, TableRowProps } from 'react-table';
|
||||
|
||||
interface Props<T extends Record<string, unknown> = Record<string, unknown>> {
|
||||
isLoading?: boolean;
|
||||
rows: Row<T>[];
|
||||
emptyContent?: string;
|
||||
prepareRow(row: Row<T>): void;
|
||||
renderRow(row: Row<T>, rowProps: TableRowProps): React.ReactNode;
|
||||
}
|
||||
|
||||
export function TableContent<
|
||||
T extends Record<string, unknown> = Record<string, unknown>
|
||||
>({
|
||||
isLoading = false,
|
||||
rows,
|
||||
emptyContent = 'No items available',
|
||||
prepareRow,
|
||||
renderRow,
|
||||
}: Props<T>) {
|
||||
if (isLoading) {
|
||||
return <TableContentOneColumn>Loading...</TableContentOneColumn>;
|
||||
}
|
||||
|
||||
if (!rows.length) {
|
||||
return <TableContentOneColumn>{emptyContent}</TableContentOneColumn>;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{rows.map((row) => {
|
||||
prepareRow(row);
|
||||
const { key, className, role, style } = row.getRowProps();
|
||||
return renderRow(row, { key, className, role, style });
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function TableContentOneColumn({ children }: PropsWithChildren<unknown>) {
|
||||
// using MAX_SAFE_INTEGER to make sure the single column will be the size of the table
|
||||
return (
|
||||
<tr>
|
||||
<td colSpan={Number.MAX_SAFE_INTEGER} className="text-center text-muted">
|
||||
{children}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
9
app/react/components/datatables/TableFooter.tsx
Normal file
9
app/react/components/datatables/TableFooter.tsx
Normal file
|
@ -0,0 +1,9 @@
|
|||
import { PropsWithChildren } from 'react';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
|
||||
export function TableFooter({ children }: PropsWithChildren<unknown>) {
|
||||
useTableContext();
|
||||
|
||||
return <footer className="footer">{children}</footer>;
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
.sort-icon {
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
display: inline-block;
|
||||
}
|
90
app/react/components/datatables/TableHeaderCell.tsx
Normal file
90
app/react/components/datatables/TableHeaderCell.tsx
Normal file
|
@ -0,0 +1,90 @@
|
|||
import clsx from 'clsx';
|
||||
import { PropsWithChildren, ReactNode } from 'react';
|
||||
import { TableHeaderProps } from 'react-table';
|
||||
|
||||
import { Button } from '@@/buttons';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
import styles from './TableHeaderCell.module.css';
|
||||
|
||||
interface Props {
|
||||
canFilter: boolean;
|
||||
canSort: boolean;
|
||||
headerProps: TableHeaderProps;
|
||||
isSorted: boolean;
|
||||
isSortedDesc?: boolean;
|
||||
onSortClick: (desc: boolean) => void;
|
||||
render: () => ReactNode;
|
||||
renderFilter: () => ReactNode;
|
||||
}
|
||||
|
||||
export function TableHeaderCell({
|
||||
headerProps: { className, role, style },
|
||||
canSort,
|
||||
render,
|
||||
onSortClick,
|
||||
isSorted,
|
||||
isSortedDesc,
|
||||
canFilter,
|
||||
renderFilter,
|
||||
}: Props) {
|
||||
useTableContext();
|
||||
|
||||
return (
|
||||
<th role={role} style={style} className={className}>
|
||||
<SortWrapper
|
||||
canSort={canSort}
|
||||
onClick={onSortClick}
|
||||
isSorted={isSorted}
|
||||
isSortedDesc={isSortedDesc}
|
||||
>
|
||||
{render()}
|
||||
</SortWrapper>
|
||||
{canFilter ? renderFilter() : null}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
interface SortWrapperProps {
|
||||
canSort: boolean;
|
||||
isSorted: boolean;
|
||||
isSortedDesc?: boolean;
|
||||
onClick: (desc: boolean) => void;
|
||||
}
|
||||
|
||||
function SortWrapper({
|
||||
canSort,
|
||||
children,
|
||||
onClick,
|
||||
isSorted,
|
||||
isSortedDesc,
|
||||
}: PropsWithChildren<SortWrapperProps>) {
|
||||
if (!canSort) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
color="link"
|
||||
type="button"
|
||||
onClick={() => onClick(!isSortedDesc)}
|
||||
className="sortable"
|
||||
>
|
||||
<span className="sortable-label">{children}</span>
|
||||
|
||||
{isSorted ? (
|
||||
<i
|
||||
className={clsx(
|
||||
'fa',
|
||||
'space-left',
|
||||
isSortedDesc ? 'fa-sort-alpha-up' : 'fa-sort-alpha-down',
|
||||
styles.sortIcon
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<div className={styles.sortIcon} />
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
51
app/react/components/datatables/TableHeaderRow.tsx
Normal file
51
app/react/components/datatables/TableHeaderRow.tsx
Normal file
|
@ -0,0 +1,51 @@
|
|||
import { HeaderGroup, TableHeaderProps } from 'react-table';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
import { TableHeaderCell } from './TableHeaderCell';
|
||||
|
||||
interface Props<D extends Record<string, unknown> = Record<string, unknown>> {
|
||||
headers: HeaderGroup<D>[];
|
||||
onSortChange?(colId: string, desc: boolean): void;
|
||||
}
|
||||
|
||||
export function TableHeaderRow<
|
||||
D extends Record<string, unknown> = Record<string, unknown>
|
||||
>({
|
||||
headers,
|
||||
onSortChange,
|
||||
className,
|
||||
role,
|
||||
style,
|
||||
}: Props<D> & TableHeaderProps) {
|
||||
useTableContext();
|
||||
|
||||
return (
|
||||
<tr className={className} role={role} style={style}>
|
||||
{headers.map((column) => (
|
||||
<TableHeaderCell
|
||||
headerProps={{
|
||||
...column.getHeaderProps({
|
||||
className: column.className,
|
||||
style: {
|
||||
width: column.disableResizing ? column.width : '',
|
||||
},
|
||||
}),
|
||||
}}
|
||||
key={column.id}
|
||||
canSort={column.canSort}
|
||||
onSortClick={(desc) => {
|
||||
column.toggleSortBy(desc);
|
||||
if (onSortChange) {
|
||||
onSortChange(column.id, desc);
|
||||
}
|
||||
}}
|
||||
isSorted={column.isSorted}
|
||||
isSortedDesc={column.isSortedDesc}
|
||||
render={() => column.render('Header')}
|
||||
canFilter={!column.disableFilters}
|
||||
renderFilter={() => column.render('Filter')}
|
||||
/>
|
||||
))}
|
||||
</tr>
|
||||
);
|
||||
}
|
35
app/react/components/datatables/TableRow.tsx
Normal file
35
app/react/components/datatables/TableRow.tsx
Normal file
|
@ -0,0 +1,35 @@
|
|||
import { Cell, TableRowProps } from 'react-table';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
|
||||
interface Props<D extends Record<string, unknown> = Record<string, unknown>>
|
||||
extends TableRowProps {
|
||||
cells: Cell<D>[];
|
||||
}
|
||||
|
||||
export function TableRow<
|
||||
D extends Record<string, unknown> = Record<string, unknown>
|
||||
>({ cells, className, role, style }: Props<D>) {
|
||||
useTableContext();
|
||||
|
||||
return (
|
||||
<tr className={className} role={role} style={style}>
|
||||
{cells.map((cell) => {
|
||||
const cellProps = cell.getCellProps({
|
||||
className: cell.className,
|
||||
});
|
||||
|
||||
return (
|
||||
<td
|
||||
className={cellProps.className}
|
||||
role={cellProps.role}
|
||||
style={cellProps.style}
|
||||
key={cellProps.key}
|
||||
>
|
||||
{cell.render('Cell')}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
}
|
44
app/react/components/datatables/TableSettingsMenu.tsx
Normal file
44
app/react/components/datatables/TableSettingsMenu.tsx
Normal file
|
@ -0,0 +1,44 @@
|
|||
import clsx from 'clsx';
|
||||
import { Menu, MenuButton, MenuList } from '@reach/menu-button';
|
||||
import { PropsWithChildren, ReactNode } from 'react';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
|
||||
interface Props {
|
||||
quickActions?: ReactNode;
|
||||
}
|
||||
|
||||
export function TableSettingsMenu({
|
||||
quickActions,
|
||||
children,
|
||||
}: PropsWithChildren<Props>) {
|
||||
useTableContext();
|
||||
|
||||
return (
|
||||
<Menu className="setting">
|
||||
{({ isExpanded }) => (
|
||||
<>
|
||||
<MenuButton
|
||||
className={clsx('table-setting-menu-btn', {
|
||||
'setting-active': isExpanded,
|
||||
})}
|
||||
>
|
||||
<i className="fa fa-cog" aria-hidden="true" /> Settings
|
||||
</MenuButton>
|
||||
<MenuList>
|
||||
<div className="tableMenu">
|
||||
<div className="menuHeader">Table settings</div>
|
||||
<div className="menuContent">{children}</div>
|
||||
{quickActions && (
|
||||
<div>
|
||||
<div className="menuHeader">Quick actions</div>
|
||||
<div className="menuContent">{quickActions}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</MenuList>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
);
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
.alert-visible {
|
||||
opacity: 1;
|
||||
transition: all 250ms linear;
|
||||
}
|
||||
|
||||
.alert-hidden {
|
||||
opacity: 0;
|
||||
transition: all 250ms ease-out 2s;
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
import clsx from 'clsx';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { Checkbox } from '@@/form-components/Checkbox';
|
||||
|
||||
import styles from './TableSettingsMenuAutoRefresh.module.css';
|
||||
|
||||
interface Props {
|
||||
onChange(value: number): void;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export function TableSettingsMenuAutoRefresh({ onChange, value }: Props) {
|
||||
const [isCheckVisible, setIsCheckVisible] = useState(false);
|
||||
|
||||
const isEnabled = value > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Checkbox
|
||||
id="settings-auto-refresh"
|
||||
label="Auto refresh"
|
||||
checked={isEnabled}
|
||||
onChange={(e) => onChange(e.target.checked ? 10 : 0)}
|
||||
/>
|
||||
|
||||
{isEnabled && (
|
||||
<div>
|
||||
<label htmlFor="settings_refresh_rate">Refresh rate</label>
|
||||
<select
|
||||
id="settings_refresh_rate"
|
||||
className="small-select"
|
||||
value={value}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
>
|
||||
<option value={10}>10s</option>
|
||||
<option value={30}>30s</option>
|
||||
<option value={60}>1min</option>
|
||||
<option value={120}>2min</option>
|
||||
<option value={300}>5min</option>
|
||||
</select>
|
||||
<span
|
||||
className={clsx(
|
||||
isCheckVisible ? styles.alertVisible : styles.alertHidden,
|
||||
styles.check
|
||||
)}
|
||||
onTransitionEnd={() => setIsCheckVisible(false)}
|
||||
>
|
||||
<i
|
||||
id="refreshRateChange"
|
||||
className="fa fa-check green-icon"
|
||||
aria-hidden="true"
|
||||
style={{ marginTop: '7px' }}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
function handleChange(value: string) {
|
||||
onChange(Number(value));
|
||||
setIsCheckVisible(true);
|
||||
}
|
||||
}
|
27
app/react/components/datatables/TableTitle.tsx
Normal file
27
app/react/components/datatables/TableTitle.tsx
Normal file
|
@ -0,0 +1,27 @@
|
|||
import clsx from 'clsx';
|
||||
import { PropsWithChildren } from 'react';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
|
||||
interface Props {
|
||||
icon: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function TableTitle({
|
||||
icon,
|
||||
label,
|
||||
children,
|
||||
}: PropsWithChildren<Props>) {
|
||||
useTableContext();
|
||||
|
||||
return (
|
||||
<div className="toolBar">
|
||||
<div className="toolBarTitle">
|
||||
<i className={clsx('space-right', 'fa', icon)} aria-hidden="true" />
|
||||
{label}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
9
app/react/components/datatables/TableTitleActions.tsx
Normal file
9
app/react/components/datatables/TableTitleActions.tsx
Normal file
|
@ -0,0 +1,9 @@
|
|||
import { PropsWithChildren } from 'react';
|
||||
|
||||
import { useTableContext } from './TableContainer';
|
||||
|
||||
export function TableTitleActions({ children }: PropsWithChildren<unknown>) {
|
||||
useTableContext();
|
||||
|
||||
return <div className="settings">{children}</div>;
|
||||
}
|
14
app/react/components/datatables/filter-types.ts
Normal file
14
app/react/components/datatables/filter-types.ts
Normal file
|
@ -0,0 +1,14 @@
|
|||
import { Row } from 'react-table';
|
||||
|
||||
export function multiple<
|
||||
D extends Record<string, unknown> = Record<string, unknown>
|
||||
>(rows: Row<D>[], columnIds: string[], filterValue: string[] = []) {
|
||||
if (filterValue.length === 0 || columnIds.length === 0) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
return rows.filter((row) => {
|
||||
const value = row.values[columnIds[0]];
|
||||
return filterValue.includes(value);
|
||||
});
|
||||
}
|
50
app/react/components/datatables/index.tsx
Normal file
50
app/react/components/datatables/index.tsx
Normal file
|
@ -0,0 +1,50 @@
|
|||
import { Table as MainComponent } from './Table';
|
||||
import { TableActions } from './TableActions';
|
||||
import { TableTitleActions } from './TableTitleActions';
|
||||
import { TableHeaderCell } from './TableHeaderCell';
|
||||
import { TableSettingsMenu } from './TableSettingsMenu';
|
||||
import { TableTitle } from './TableTitle';
|
||||
import { TableContainer } from './TableContainer';
|
||||
import { TableHeaderRow } from './TableHeaderRow';
|
||||
import { TableRow } from './TableRow';
|
||||
import { TableContent } from './TableContent';
|
||||
import { TableFooter } from './TableFooter';
|
||||
|
||||
interface SubComponents {
|
||||
Container: typeof TableContainer;
|
||||
Actions: typeof TableActions;
|
||||
TitleActions: typeof TableTitleActions;
|
||||
HeaderCell: typeof TableHeaderCell;
|
||||
SettingsMenu: typeof TableSettingsMenu;
|
||||
Title: typeof TableTitle;
|
||||
Row: typeof TableRow;
|
||||
HeaderRow: typeof TableHeaderRow;
|
||||
Content: typeof TableContent;
|
||||
Footer: typeof TableFooter;
|
||||
}
|
||||
|
||||
const Table: typeof MainComponent & SubComponents =
|
||||
MainComponent as typeof MainComponent & SubComponents;
|
||||
|
||||
Table.Actions = TableActions;
|
||||
Table.TitleActions = TableTitleActions;
|
||||
Table.Container = TableContainer;
|
||||
Table.HeaderCell = TableHeaderCell;
|
||||
Table.SettingsMenu = TableSettingsMenu;
|
||||
Table.Title = TableTitle;
|
||||
Table.Row = TableRow;
|
||||
Table.HeaderRow = TableHeaderRow;
|
||||
Table.Content = TableContent;
|
||||
Table.Footer = TableFooter;
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableActions,
|
||||
TableTitleActions,
|
||||
TableHeaderCell,
|
||||
TableSettingsMenu,
|
||||
TableTitle,
|
||||
TableContainer,
|
||||
TableHeaderRow,
|
||||
TableRow,
|
||||
};
|
19
app/react/components/datatables/types.ts
Normal file
19
app/react/components/datatables/types.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
export interface PaginationTableSettings {
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface SortableTableSettings {
|
||||
sortBy: { id: string; desc: boolean };
|
||||
}
|
||||
|
||||
export interface SettableColumnsTableSettings {
|
||||
hiddenColumns: string[];
|
||||
}
|
||||
|
||||
export interface SettableQuickActionsTableSettings<TAction> {
|
||||
hiddenQuickActions: TAction[];
|
||||
}
|
||||
|
||||
export interface RefreshableTableSettings {
|
||||
autoRefreshRate: number;
|
||||
}
|
42
app/react/components/datatables/useRepeater.ts
Normal file
42
app/react/components/datatables/useRepeater.ts
Normal file
|
@ -0,0 +1,42 @@
|
|||
import { useEffect, useCallback, useState } from 'react';
|
||||
|
||||
export function useRepeater(
|
||||
refreshRate: number,
|
||||
onRefresh?: () => Promise<void>
|
||||
) {
|
||||
const [intervalId, setIntervalId] = useState<NodeJS.Timeout | null>(null);
|
||||
|
||||
const stopRepeater = useCallback(() => {
|
||||
if (!intervalId) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearInterval(intervalId);
|
||||
setIntervalId(null);
|
||||
}, [intervalId]);
|
||||
|
||||
const startRepeater = useCallback(
|
||||
(refreshRate) => {
|
||||
if (intervalId || !onRefresh) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIntervalId(
|
||||
setInterval(async () => {
|
||||
await onRefresh();
|
||||
}, refreshRate * 1000)
|
||||
);
|
||||
},
|
||||
[intervalId, onRefresh]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!refreshRate || !onRefresh) {
|
||||
stopRepeater();
|
||||
} else {
|
||||
startRepeater(refreshRate);
|
||||
}
|
||||
|
||||
return stopRepeater;
|
||||
}, [refreshRate, startRepeater, stopRepeater, intervalId, onRefresh]);
|
||||
}
|
478
app/react/components/datatables/useRowSelect.ts
Normal file
478
app/react/components/datatables/useRowSelect.ts
Normal file
|
@ -0,0 +1,478 @@
|
|||
/* eslint no-param-reassign: ["error", { "props": false }] */
|
||||
import { ChangeEvent, useCallback, useMemo } from 'react';
|
||||
import {
|
||||
actions,
|
||||
makePropGetter,
|
||||
ensurePluginOrder,
|
||||
useGetLatest,
|
||||
useMountedLayoutEffect,
|
||||
Hooks,
|
||||
TableInstance,
|
||||
TableState,
|
||||
ActionType,
|
||||
ReducerTableState,
|
||||
IdType,
|
||||
Row,
|
||||
PropGetter,
|
||||
TableToggleRowsSelectedProps,
|
||||
TableToggleAllRowsSelectedProps,
|
||||
} from 'react-table';
|
||||
|
||||
type DefaultType = Record<string, unknown>;
|
||||
|
||||
interface UseRowSelectTableInstance<D extends DefaultType = DefaultType>
|
||||
extends TableInstance<D> {
|
||||
isAllRowSelected: boolean;
|
||||
selectSubRows: boolean;
|
||||
getSubRows(row: Row<D>): Row<D>[];
|
||||
isRowSelectable(row: Row<D>): boolean;
|
||||
}
|
||||
|
||||
const pluginName = 'useRowSelect';
|
||||
|
||||
// Actions
|
||||
actions.resetSelectedRows = 'resetSelectedRows';
|
||||
actions.toggleAllRowsSelected = 'toggleAllRowsSelected';
|
||||
actions.toggleRowSelected = 'toggleRowSelected';
|
||||
actions.toggleAllPageRowsSelected = 'toggleAllPageRowsSelected';
|
||||
|
||||
export function useRowSelect<D extends DefaultType>(hooks: Hooks<D>) {
|
||||
hooks.getToggleRowSelectedProps = [
|
||||
defaultGetToggleRowSelectedProps as PropGetter<
|
||||
D,
|
||||
TableToggleRowsSelectedProps
|
||||
>,
|
||||
];
|
||||
hooks.getToggleAllRowsSelectedProps = [
|
||||
defaultGetToggleAllRowsSelectedProps as PropGetter<
|
||||
D,
|
||||
TableToggleAllRowsSelectedProps
|
||||
>,
|
||||
];
|
||||
hooks.getToggleAllPageRowsSelectedProps = [
|
||||
defaultGetToggleAllPageRowsSelectedProps as PropGetter<
|
||||
D,
|
||||
TableToggleAllRowsSelectedProps
|
||||
>,
|
||||
];
|
||||
hooks.stateReducers.push(
|
||||
reducer as (
|
||||
newState: TableState<D>,
|
||||
action: ActionType,
|
||||
previousState?: TableState<D>,
|
||||
instance?: TableInstance<D>
|
||||
) => ReducerTableState<D> | undefined
|
||||
);
|
||||
hooks.useInstance.push(useInstance as (instance: TableInstance<D>) => void);
|
||||
hooks.prepareRow.push(prepareRow);
|
||||
}
|
||||
|
||||
useRowSelect.pluginName = pluginName;
|
||||
|
||||
function defaultGetToggleRowSelectedProps<D extends DefaultType>(
|
||||
props: D,
|
||||
{ instance, row }: { instance: UseRowSelectTableInstance<D>; row: Row<D> }
|
||||
) {
|
||||
const { manualRowSelectedKey = 'isSelected' } = instance;
|
||||
let checked = false;
|
||||
|
||||
if (row.original && row.original[manualRowSelectedKey]) {
|
||||
checked = true;
|
||||
} else {
|
||||
checked = row.isSelected;
|
||||
}
|
||||
|
||||
return [
|
||||
props,
|
||||
{
|
||||
onChange: (e: ChangeEvent<HTMLInputElement>) => {
|
||||
row.toggleRowSelected(e.target.checked);
|
||||
},
|
||||
style: {
|
||||
cursor: 'pointer',
|
||||
},
|
||||
checked,
|
||||
title: 'Toggle Row Selected',
|
||||
indeterminate: row.isSomeSelected,
|
||||
disabled: !instance.isRowSelectable(row),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function defaultGetToggleAllRowsSelectedProps<D extends DefaultType>(
|
||||
props: D,
|
||||
{ instance }: { instance: UseRowSelectTableInstance<D> }
|
||||
) {
|
||||
return [
|
||||
props,
|
||||
{
|
||||
onChange: (e: ChangeEvent<HTMLInputElement>) => {
|
||||
instance.toggleAllRowsSelected(e.target.checked);
|
||||
},
|
||||
style: {
|
||||
cursor: 'pointer',
|
||||
},
|
||||
checked: instance.isAllRowsSelected,
|
||||
title: 'Toggle All Rows Selected',
|
||||
indeterminate: Boolean(
|
||||
!instance.isAllRowsSelected &&
|
||||
Object.keys(instance.state.selectedRowIds).length
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function defaultGetToggleAllPageRowsSelectedProps<D extends DefaultType>(
|
||||
props: D,
|
||||
{ instance }: { instance: UseRowSelectTableInstance<D> }
|
||||
) {
|
||||
return [
|
||||
props,
|
||||
{
|
||||
onChange(e: ChangeEvent<HTMLInputElement>) {
|
||||
instance.toggleAllPageRowsSelected(e.target.checked);
|
||||
},
|
||||
style: {
|
||||
cursor: 'pointer',
|
||||
},
|
||||
checked: instance.isAllPageRowsSelected,
|
||||
title: 'Toggle All Current Page Rows Selected',
|
||||
indeterminate: Boolean(
|
||||
!instance.isAllPageRowsSelected &&
|
||||
instance.page.some(({ id }) => instance.state.selectedRowIds[id])
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function reducer<D extends Record<string, unknown>>(
|
||||
state: TableState<D>,
|
||||
action: ActionType,
|
||||
_previousState?: TableState<D>,
|
||||
instance?: UseRowSelectTableInstance<D>
|
||||
) {
|
||||
if (action.type === actions.init) {
|
||||
return {
|
||||
...state,
|
||||
selectedRowIds: <Record<IdType<D>, boolean>>{},
|
||||
};
|
||||
}
|
||||
|
||||
if (action.type === actions.resetSelectedRows) {
|
||||
return {
|
||||
...state,
|
||||
selectedRowIds: instance?.initialState.selectedRowIds || {},
|
||||
};
|
||||
}
|
||||
|
||||
if (action.type === actions.toggleAllRowsSelected) {
|
||||
const { value: setSelected } = action;
|
||||
|
||||
if (!instance) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const {
|
||||
isAllRowsSelected,
|
||||
rowsById,
|
||||
nonGroupedRowsById = rowsById,
|
||||
isRowSelectable = defaultIsRowSelectable,
|
||||
} = instance;
|
||||
|
||||
const selectAll =
|
||||
typeof setSelected !== 'undefined' ? setSelected : !isAllRowsSelected;
|
||||
|
||||
// Only remove/add the rows that are visible on the screen
|
||||
// Leave all the other rows that are selected alone.
|
||||
const selectedRowIds = { ...state.selectedRowIds };
|
||||
|
||||
Object.keys(nonGroupedRowsById).forEach((rowId: IdType<D>) => {
|
||||
if (selectAll) {
|
||||
const row = rowsById[rowId];
|
||||
if (isRowSelectable(row)) {
|
||||
selectedRowIds[rowId] = true;
|
||||
}
|
||||
} else {
|
||||
delete selectedRowIds[rowId];
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
...state,
|
||||
selectedRowIds,
|
||||
};
|
||||
}
|
||||
|
||||
if (action.type === actions.toggleRowSelected) {
|
||||
if (!instance) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const { id, value: setSelected } = action;
|
||||
const {
|
||||
rowsById,
|
||||
selectSubRows = true,
|
||||
getSubRows,
|
||||
isRowSelectable = defaultIsRowSelectable,
|
||||
} = instance;
|
||||
|
||||
const isSelected = state.selectedRowIds[id];
|
||||
const shouldExist =
|
||||
typeof setSelected !== 'undefined' ? setSelected : !isSelected;
|
||||
|
||||
if (isSelected === shouldExist) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const newSelectedRowIds = { ...state.selectedRowIds };
|
||||
|
||||
// eslint-disable-next-line no-inner-declarations
|
||||
function handleRowById(id: IdType<D>) {
|
||||
const row = rowsById[id];
|
||||
|
||||
if (!isRowSelectable(row)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!row.isGrouped) {
|
||||
if (shouldExist) {
|
||||
newSelectedRowIds[id] = true;
|
||||
} else {
|
||||
delete newSelectedRowIds[id];
|
||||
}
|
||||
}
|
||||
|
||||
if (selectSubRows && getSubRows(row)) {
|
||||
getSubRows(row).forEach((row) => handleRowById(row.id));
|
||||
}
|
||||
}
|
||||
|
||||
handleRowById(id);
|
||||
|
||||
return {
|
||||
...state,
|
||||
selectedRowIds: newSelectedRowIds,
|
||||
};
|
||||
}
|
||||
|
||||
if (action.type === actions.toggleAllPageRowsSelected) {
|
||||
if (!instance) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const { value: setSelected } = action;
|
||||
const {
|
||||
page,
|
||||
rowsById,
|
||||
selectSubRows = true,
|
||||
isAllPageRowsSelected,
|
||||
getSubRows,
|
||||
} = instance;
|
||||
|
||||
const selectAll =
|
||||
typeof setSelected !== 'undefined' ? setSelected : !isAllPageRowsSelected;
|
||||
|
||||
const newSelectedRowIds = { ...state.selectedRowIds };
|
||||
|
||||
// eslint-disable-next-line no-inner-declarations
|
||||
function handleRowById(id: IdType<D>) {
|
||||
const row = rowsById[id];
|
||||
|
||||
if (!row.isGrouped) {
|
||||
if (selectAll) {
|
||||
newSelectedRowIds[id] = true;
|
||||
} else {
|
||||
delete newSelectedRowIds[id];
|
||||
}
|
||||
}
|
||||
|
||||
if (selectSubRows && getSubRows(row)) {
|
||||
getSubRows(row).forEach((row) => handleRowById(row.id));
|
||||
}
|
||||
}
|
||||
|
||||
page.forEach((row) => handleRowById(row.id));
|
||||
|
||||
return {
|
||||
...state,
|
||||
selectedRowIds: newSelectedRowIds,
|
||||
};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
function useInstance<D extends Record<string, unknown>>(
|
||||
instance: UseRowSelectTableInstance<D>
|
||||
) {
|
||||
const {
|
||||
data,
|
||||
rows,
|
||||
getHooks,
|
||||
plugins,
|
||||
rowsById,
|
||||
nonGroupedRowsById = rowsById,
|
||||
autoResetSelectedRows = true,
|
||||
state: { selectedRowIds },
|
||||
selectSubRows = true,
|
||||
dispatch,
|
||||
page,
|
||||
getSubRows,
|
||||
isRowSelectable,
|
||||
} = instance;
|
||||
|
||||
ensurePluginOrder(
|
||||
plugins,
|
||||
['useFilters', 'useGroupBy', 'useSortBy', 'useExpanded', 'usePagination'],
|
||||
'useRowSelect'
|
||||
);
|
||||
|
||||
const selectedFlatRows = useMemo(() => {
|
||||
const selectedFlatRows = <Array<Row<D>>>[];
|
||||
|
||||
rows.forEach((row) => {
|
||||
const isSelected = selectSubRows
|
||||
? getRowIsSelected(row, selectedRowIds, getSubRows)
|
||||
: !!selectedRowIds[row.id];
|
||||
row.isSelected = !!isSelected;
|
||||
row.isSomeSelected = isSelected === null;
|
||||
|
||||
if (isSelected) {
|
||||
selectedFlatRows.push(row);
|
||||
}
|
||||
});
|
||||
|
||||
return selectedFlatRows;
|
||||
}, [rows, selectSubRows, selectedRowIds, getSubRows]);
|
||||
|
||||
let isAllRowsSelected = Boolean(
|
||||
Object.keys(nonGroupedRowsById).length && Object.keys(selectedRowIds).length
|
||||
);
|
||||
|
||||
let isAllPageRowsSelected = isAllRowsSelected;
|
||||
|
||||
if (isAllRowsSelected) {
|
||||
if (
|
||||
Object.keys(nonGroupedRowsById).some((id) => {
|
||||
const row = rowsById[id];
|
||||
|
||||
return !selectedRowIds[id] && isRowSelectable(row);
|
||||
})
|
||||
) {
|
||||
isAllRowsSelected = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAllRowsSelected) {
|
||||
if (
|
||||
page &&
|
||||
page.length &&
|
||||
page.some(({ id }) => {
|
||||
const row = rowsById[id];
|
||||
|
||||
return !selectedRowIds[id] && isRowSelectable(row);
|
||||
})
|
||||
) {
|
||||
isAllPageRowsSelected = false;
|
||||
}
|
||||
}
|
||||
|
||||
const getAutoResetSelectedRows = useGetLatest(autoResetSelectedRows);
|
||||
|
||||
useMountedLayoutEffect(() => {
|
||||
if (getAutoResetSelectedRows()) {
|
||||
dispatch({ type: actions.resetSelectedRows });
|
||||
}
|
||||
}, [dispatch, data]);
|
||||
|
||||
const toggleAllRowsSelected = useCallback(
|
||||
(value) => dispatch({ type: actions.toggleAllRowsSelected, value }),
|
||||
[dispatch]
|
||||
);
|
||||
|
||||
const toggleAllPageRowsSelected = useCallback(
|
||||
(value) => dispatch({ type: actions.toggleAllPageRowsSelected, value }),
|
||||
[dispatch]
|
||||
);
|
||||
|
||||
const toggleRowSelected = useCallback(
|
||||
(id, value) => dispatch({ type: actions.toggleRowSelected, id, value }),
|
||||
[dispatch]
|
||||
);
|
||||
|
||||
const getInstance = useGetLatest(instance);
|
||||
|
||||
const getToggleAllRowsSelectedProps = makePropGetter(
|
||||
getHooks().getToggleAllRowsSelectedProps,
|
||||
{ instance: getInstance() }
|
||||
);
|
||||
|
||||
const getToggleAllPageRowsSelectedProps = makePropGetter(
|
||||
getHooks().getToggleAllPageRowsSelectedProps,
|
||||
{ instance: getInstance() }
|
||||
);
|
||||
|
||||
Object.assign(instance, {
|
||||
selectedFlatRows,
|
||||
isAllRowsSelected,
|
||||
isAllPageRowsSelected,
|
||||
toggleRowSelected,
|
||||
toggleAllRowsSelected,
|
||||
getToggleAllRowsSelectedProps,
|
||||
getToggleAllPageRowsSelectedProps,
|
||||
toggleAllPageRowsSelected,
|
||||
});
|
||||
}
|
||||
|
||||
function prepareRow<D extends Record<string, unknown>>(
|
||||
row: Row<D>,
|
||||
{ instance }: { instance: TableInstance<D> }
|
||||
) {
|
||||
row.toggleRowSelected = (set) => instance.toggleRowSelected(row.id, set);
|
||||
|
||||
row.getToggleRowSelectedProps = makePropGetter(
|
||||
instance.getHooks().getToggleRowSelectedProps,
|
||||
{ instance, row }
|
||||
);
|
||||
}
|
||||
|
||||
function getRowIsSelected<D extends Record<string, unknown>>(
|
||||
row: Row<D>,
|
||||
selectedRowIds: Record<IdType<D>, boolean>,
|
||||
getSubRows: (row: Row<D>) => Array<Row<D>>
|
||||
) {
|
||||
if (selectedRowIds[row.id]) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const subRows = getSubRows(row);
|
||||
|
||||
if (subRows && subRows.length) {
|
||||
let allChildrenSelected = true;
|
||||
let someSelected = false;
|
||||
|
||||
subRows.forEach((subRow) => {
|
||||
// Bail out early if we know both of these
|
||||
if (someSelected && !allChildrenSelected) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (getRowIsSelected(subRow, selectedRowIds, getSubRows)) {
|
||||
someSelected = true;
|
||||
} else {
|
||||
allChildrenSelected = false;
|
||||
}
|
||||
});
|
||||
|
||||
if (allChildrenSelected) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return someSelected ? null : false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function defaultIsRowSelectable<D extends DefaultType>(row: Row<D>) {
|
||||
return !!row.original.disabled;
|
||||
}
|
90
app/react/components/datatables/useTableSettings.tsx
Normal file
90
app/react/components/datatables/useTableSettings.tsx
Normal file
|
@ -0,0 +1,90 @@
|
|||
import {
|
||||
Context,
|
||||
createContext,
|
||||
ReactNode,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
import { useLocalStorage } from '@/portainer/hooks/useLocalStorage';
|
||||
|
||||
export interface TableSettingsContextInterface<T> {
|
||||
settings: T;
|
||||
setTableSettings(partialSettings: Partial<T>): void;
|
||||
setTableSettings(mutation: (settings: T) => T): void;
|
||||
}
|
||||
|
||||
const TableSettingsContext = createContext<TableSettingsContextInterface<
|
||||
Record<string, unknown>
|
||||
> | null>(null);
|
||||
|
||||
export function useTableSettings<T>() {
|
||||
const Context = getContextType<T>();
|
||||
|
||||
const context = useContext(Context);
|
||||
|
||||
if (context === null) {
|
||||
throw new Error('must be nested under TableSettingsProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
interface ProviderProps<T> {
|
||||
children: ReactNode;
|
||||
defaults?: T;
|
||||
storageKey: string;
|
||||
}
|
||||
|
||||
export function TableSettingsProvider<T>({
|
||||
children,
|
||||
defaults,
|
||||
storageKey,
|
||||
}: ProviderProps<T>) {
|
||||
const Context = getContextType<T>();
|
||||
|
||||
const [storage, setStorage] = useLocalStorage<T>(
|
||||
keyBuilder(storageKey),
|
||||
defaults as T
|
||||
);
|
||||
|
||||
const [settings, setTableSettings] = useState(storage);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(mutation: Partial<T> | ((settings: T) => T)): void => {
|
||||
setTableSettings((settings) => {
|
||||
const newTableSettings =
|
||||
mutation instanceof Function
|
||||
? mutation(settings)
|
||||
: { ...settings, ...mutation };
|
||||
|
||||
setStorage(newTableSettings);
|
||||
|
||||
return newTableSettings;
|
||||
});
|
||||
},
|
||||
[setStorage]
|
||||
);
|
||||
|
||||
const contextValue = useMemo(
|
||||
() => ({
|
||||
settings,
|
||||
setTableSettings: handleChange,
|
||||
}),
|
||||
[settings, handleChange]
|
||||
);
|
||||
|
||||
return <Context.Provider value={contextValue}>{children}</Context.Provider>;
|
||||
|
||||
function keyBuilder(key: string) {
|
||||
return `datatable_TableSettings_${key}`;
|
||||
}
|
||||
}
|
||||
|
||||
function getContextType<T>() {
|
||||
return TableSettingsContext as unknown as Context<
|
||||
TableSettingsContextInterface<T>
|
||||
>;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue