Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nds 191 - Table: API/technical Implementation #351

Closed
wants to merge 8 commits into from
Closed
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
1 change: 1 addition & 0 deletions packages/core/src/_system.scss
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
@forward 'components/switch' as switch-*;
@forward 'components/tab' as tab-*;
@forward 'components/tablist' as tab-list-*;
@forward 'components/table' as table-*;
@forward 'components/tabpanels' as tab-panels-*;
@forward 'components/tabscrollbutton' as tab-scroll-button-*;
@forward 'components/tag' as tag-*;
Expand Down
73 changes: 73 additions & 0 deletions packages/core/src/components/table/index.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
@use '../../util';

@mixin base {
display: inline-flex;
align-items: center;
justify-content: center;

&--left {
flex-direction: row;
}

&--top {
flex-direction: column;
}

&--right {
flex-direction: row-reverse;
}

&--bottom {
flex-direction: column-reverse;
}

&__label-background {
display: flex;
padding: 0.25rem;
border-radius: 2px;
}

&__label {
font-size: var(--nds-spacing-3);
font-weight: bold;
line-height: 1.5;
color: var(--nds-white);
text-transform: uppercase;
letter-spacing: normal;
}
}

@mixin style {
@include util.declare('table') {
.nds-table {
border-collapse: collapse;
width: 100%;

& th {
background-color: #f2f2f2;
}

& td, & th {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}

&-header {
&--sorted-asc::after {
content: ' ▲';
}

&--sorted-desc::after {
content: ' ▼';
}
}

&-body--collapsed {
tr:not(:first-child) {
display: none;
}
}
}
}
}
1 change: 1 addition & 0 deletions packages/core/src/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
@include nds.stepindicator-style;
@include nds.switch-style;
@include nds.tab-style;
@include nds.table-style;
@include nds.tab-list-style;
@include nds.tab-panels-style;
@include nds.tab-scroll-button-style;
Expand Down
19 changes: 19 additions & 0 deletions packages/react/src/components/Table/Table.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from 'react';
import { TableProps } from './types';
import { TableContext, useInitTableState } from './context';

export const Table: React.FC<TableProps> = ({
className: tableClassName = 'nds-table',
children,
selectable,
onSelect,
sortable,
}) => {
const value = useInitTableState({ selectable, onSelect, sortable });

return (
<TableContext.Provider value={value}>
<table className={tableClassName}>{children}</table>
</TableContext.Provider>
);
};
42 changes: 42 additions & 0 deletions packages/react/src/components/Table/TableBody.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React, { useEffect } from 'react';
import classNames from 'classnames';
import { TableBodyProps } from './types';
import { useTableState } from './context';
import { useId } from '../../utilities';

export const TableBody: React.FC<TableBodyProps> = ({
children,
className: baseName = 'nds-table__body',
collapsedClass = `${baseName}--collapsed`,
isCollapsed,
id: idProp,
}) => {
const { isSectionExpanded, registerSection } = useTableState();

const uniqueId = useId();
const id = idProp || uniqueId;

const bodyClassName = classNames(baseName, {
[collapsedClass]: isCollapsed,
});

const isSection = isCollapsed !== undefined;
const showSection = isSection && isSectionExpanded(id as string);

let label = '';
if (isSection) {
label = showSection ? 'Collapsed' : 'Expanded';
}

useEffect(() => {
if (isSection && registerSection && id) {
registerSection(id);
}
}, [isSection, registerSection, id]);

return (
<tbody className={bodyClassName} aria-label={label}>
{showSection ? children?.[0] : children}
</tbody>
);
};
23 changes: 23 additions & 0 deletions packages/react/src/components/Table/TableHeadCell.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react';
import className from 'classnames';
import { TableHeadCellProps } from './types';

export const TableHeadCell: React.FC<TableHeadCellProps> = ({
className: tableHeadCellClassName = 'nds-table__head-cell',
sortType,
children,
'aria-label': ariaLabel,
onSort,
}) => {
const tableHeadCellClass = className(tableHeadCellClassName, {
[`${tableHeadCellClassName}--ascending`]: sortType === 'ascending',
[`${tableHeadCellClassName}--descending`]: sortType === 'descending',
[`${tableHeadCellClassName}--other`]: sortType === 'other',
});

return (
<th className={tableHeadCellClass} aria-sort={sortType} onClick={onSort} aria-label={ariaLabel}>
{children}
</th>
);
};
34 changes: 34 additions & 0 deletions packages/react/src/components/Table/TableHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React from 'react';
import { TableHeaderProps } from './types';
import { useTableState } from './context';
import { TableHeadCell } from './TableHeadCell';
import { Checkbox } from '../Checkbox';
import { TableRow } from './TableRow';

const SELECT_ALL_HEADER_LABEL = 'Select All';

export const TableHeader: React.FC<TableHeaderProps> = ({
children,
className = 'nds-table__header',
}) => {
const { selectable, onSelect, onSelectedAll, isSelectedAll } = useTableState();

return (
<thead className={className}>
<TableRow isHeader>
{selectable && onSelect ? (
<TableHeadCell aria-label={SELECT_ALL_HEADER_LABEL}>
<Checkbox

Check failure on line 21 in packages/react/src/components/Table/TableHeader.tsx

View workflow job for this annotation

GitHub Actions / ESLint

Replace `⏎↹↹↹↹↹↹↹checked={isSelectedAll()}⏎↹↹↹↹↹↹↹labelClass="nds-sr-only"⏎↹↹↹↹↹↹↹onChange={onSelectedAll}⏎↹↹↹↹↹↹` with `·checked={isSelectedAll()}·labelClass="nds-sr-only"·onChange={onSelectedAll}`
checked={isSelectedAll()}
labelClass="nds-sr-only"
onChange={onSelectedAll}
>
{SELECT_ALL_HEADER_LABEL}
</Checkbox>
</TableHeadCell>
) : null}
{children}
</TableRow>
</thead>
);
};
57 changes: 57 additions & 0 deletions packages/react/src/components/Table/TableRow.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/* eslint-disable no-nested-ternary */
import React, { useEffect } from 'react';
import classNames from 'classnames';
import { TableRowProps } from './types';
import { useTableState } from './context';
import { TableSectionHeader } from './TableSectionHeader';
import { Checkbox } from '../Checkbox';
import { useId } from '../../utilities';

export const TableRow: React.FC<TableRowProps> = ({
baseName = 'nds-table-row',
headerClass = `${baseName}__header`,
sectionHeaderClass = `${baseName}__header--section`,
isHeader = false,
isSectionHeader = false,
sectionId = null,
sectionTitle = '',
id: idProp,
children,
}) => {
const { selectable, onSelect, onSelected, isSelected, isSelectedAll, registerId } =
useTableState();

const uniqueId = useId();
const id = idProp || uniqueId;

const isSelectable = selectable && onSelect && !isHeader && !isSectionHeader;
const isChecked = isSelectedAll() || isSelected(id as string);

useEffect(() => {
if (isSelectable && registerId) {
registerId(id as string, isChecked);
}
}, [isSelectable, registerId, id, isChecked]);

const onChange = () => onSelected?.(id as string, !isChecked);

const trClassName = classNames(baseName, {
[`${headerClass}`]: isHeader,
[`${sectionHeaderClass}`]: isSectionHeader,
});

return (
<tr className={trClassName} id={id}>
{isSectionHeader && sectionId ? (
<TableSectionHeader title={sectionTitle} id={sectionId} />
) : isSelectable ? (
<td>

Check failure on line 48 in packages/react/src/components/Table/TableRow.tsx

View workflow job for this annotation

GitHub Actions / ESLint

A control must be associated with a text label
<Checkbox checked={isChecked} onChange={onChange} />
</td>
) : (
<></>

Check failure on line 52 in packages/react/src/components/Table/TableRow.tsx

View workflow job for this annotation

GitHub Actions / ESLint

Fragments should contain more than one child - otherwise, there’s no need for a Fragment at all
)}
{children}
</tr>
);
};
26 changes: 26 additions & 0 deletions packages/react/src/components/Table/TableSectionHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from 'react';
import { IconButton } from '../Button';
import { useTableState } from './context';
import { TableSectionHeaderProps } from './types';

export const TableSectionHeader: React.FC<TableSectionHeaderProps> = ({ id, title = '' }) => {
const { onToggleSection, isSectionExpanded } = useTableState();

if (!id) return null;

const isOpen = isSectionExpanded(id);

const onToggle = () => onToggleSection?.(id);

const icon = isOpen ? 'chevron-up' : 'chevron-down';
const label = isOpen ? 'Close' : 'Open';

return (
<th colSpan={4}>
{title}
<IconButton variant="outline" icon={icon} onClick={onToggle}>
{label}
</IconButton>
</th>
);
};
97 changes: 97 additions & 0 deletions packages/react/src/components/Table/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import React, { useState, useMemo, ChangeEvent } from 'react';

Check failure on line 1 in packages/react/src/components/Table/context.ts

View workflow job for this annotation

GitHub Actions / ESLint

'useMemo' is defined but never used
// eslint-disable-next-line import/no-cycle
import { TableSections, Choices, TableSetup, TableState } from './types';

export const TableContext = React.createContext<TableState | undefined>(undefined);

export function useTableState() {
const result = React.useContext(TableContext);
if (!result) {
throw new Error('TableContext not initialized');
}

return result;
}

export function useInitTableState({ selectable, onSelect, sortable }: TableSetup): TableState {
const [choices, setChoices] = useState<Choices>({});
const [sections, setSections] = useState<TableSections>({});

const onSelectedAll = React.useCallback((event: ChangeEvent<HTMLInputElement>) => {
setChoices((old: Choices) => ({
...old,
...Object.fromEntries(Object.entries(old).map(([key]) => [key, event.target.checked])),
}));
}, []);

const onSelected = React.useCallback(
(id: string, checked: boolean) => {
setChoices((old: Choices) => ({ ...old, [id]: checked }));
onSelect?.();
},
[onSelect],
);

const onToggleSection = React.useCallback((sectionId?: string) => {
if (!sectionId) return;
setSections((old: TableSections) => ({ ...old, [sectionId]: !old[sectionId] }));
}, []);

const isSelected = React.useCallback(
(key: string): boolean => choices && choices[key],
[choices],
);

const isSectionExpanded = React.useCallback(
(sectionId: string): boolean => !sections[sectionId],
[sections],
);

const isSelectedAll = React.useCallback(
(): boolean => choices && Object.values(choices).every((value) => value === true),
[choices],
);

const registerId = React.useCallback((key: string, value = false) => {
setChoices((old: Choices) => ({ ...old, [key]: value }));
}, []);

const registerSection = React.useCallback((key: string, isOpen = false) => {
setSections((old: TableSections) => ({ ...old, [key]: isOpen }));
}, []);

const tableState = React.useMemo(
() => ({
selectable,
sortable,
onSelect,
selected: choices,
sections,
onSelected,
onSelectedAll,
isSelected,
isSelectedAll,
isSectionExpanded,
onToggleSection,
registerId,
registerSection,
}),
[
selectable,
sortable,
onSelect,
choices,
sections,
onSelected,
onSelectedAll,
isSelected,
isSelectedAll,
isSectionExpanded,
onToggleSection,
registerId,
registerSection,
],
);

return tableState;
}
Loading
Loading