Skip to content
Merged
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
2 changes: 2 additions & 0 deletions Documentation/DataTables/data-table-for-observable-query.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ Same as DataTableForQuery, but the query must derive from `ObservableQueryFor`.
### Optional Props

- `children`: `Column` elements
- `mobileLayout`: Set to `'cards'` to show labeled cards below the viewport breakpoint; omitted by default, preserving tables at every width
- `mobileBreakpoint`: Exclusive viewport threshold in CSS pixels (default 640); only effective with `mobileLayout='cards'`. Nonfinite/nonpositive values use 640. See [Mobile cards](index.md#mobile-cards) for controls, selection, focus and card-specific parts. Live-result updates, selection reconciliation and paging keep their existing behavior.
- `queryArguments`: Arguments for the query. The table resubscribes when any argument changes.
- `filteredEmptyMessage`: Message shown instead of `emptyMessage` when a search or column filter is active and no rows are shown. Defaults to `messages.dataTable.filteredEmpty` (`No rows on this page match the search.`) or, with `serverQuery`, `messages.dataTable.filteredEmptyServer` (`No rows match the search.`)
- `loadingMessage`, `failureMessage`, `unauthorizedMessage`: Optional React content for the loading, failed, and unauthorized states; each overrides its `messages.dataTable` provider message and English default
Expand Down
2 changes: 2 additions & 0 deletions Documentation/DataTables/data-table-for-query.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ export function Products() {
### Optional Props

- `children`: `Column` elements
- `mobileLayout`: Set to `'cards'` to show labeled cards below the viewport breakpoint; omitted by default, preserving tables at every width
- `mobileBreakpoint`: Exclusive viewport threshold in CSS pixels (default 640); only effective with `mobileLayout='cards'`. Nonfinite/nonpositive values use 640. See [Mobile cards](index.md#mobile-cards) for controls, selection, focus and card-specific parts.
- `queryArguments`: Arguments for the query. The query runs again when a required argument changes.
- `filteredEmptyMessage`: Message shown instead of `emptyMessage` when a search or column filter is active and no rows are shown. Defaults to `messages.dataTable.filteredEmpty` (`No rows on this page match the search.`) or, with `serverQuery`, `messages.dataTable.filteredEmptyServer` (`No rows match the search.`)
- `loadingMessage`, `failureMessage`, `unauthorizedMessage`: Optional React content for the loading, failed, and unauthorized states; each overrides its `messages.dataTable` provider message and English default
Expand Down
29 changes: 29 additions & 0 deletions Documentation/DataTables/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,35 @@ Here `onOpen` and the `order-overdue` class belong to your application. The tabl

The status, message, filtering, sorting and `rowProcessing` props are described in [Components](#components) above.

## Mobile cards

Set `mobileLayout='cards'` to show each row as a labeled card when the **viewport** is narrower than 640 CSS pixels. At exactly 640 pixels and above, the semantic table remains. Without this prop the table stays a table at every width; `mobileBreakpoint` alone does not enable cards.

```tsx
import { Column, DataTableCore } from '@cratis/components/DataTables';

const projects = [{ id: 'example-1', name: 'Example Project', details: { status: 'Ready' } }];

export function ExampleProjects() {
return (
<DataTableCore data={projects} dataKey='id' emptyMessage='No projects.' mobileLayout='cards'>
<Column field='name' header='Project' sortable />
<Column field='details.status' header='Status' />
</DataTableCore>
);
}
```

On a narrow viewport this renders a list of cards with “Project” and “Status” labels, using the same `Column.body` templates and nested fields as the table. A missing field renders a blank value. Use `mobileBreakpoint={768}` alongside `mobileLayout='cards'` for a different exclusive threshold; nonfinite or nonpositive values fall back to 640. The breakpoint measures the viewport, not the width of a containing panel. Server rendering and browsers without `matchMedia` use the table; hydration then checks the viewport.

`DataTableForQuery` and `DataTableForObservableQuery` accept the same two props. Changing presentation does not reset sorting, filters, search, selection or pagination and does not rerun the query. Loaded-page processing stays loaded-page processing; `serverQuery` still sends those operations to the server before paging.

Sortable and filterable columns have controls above the cards. Multiple selection has one select-all checkbox and one checkbox per card, even without a selection-marker column. Single selection uses a radio control. Click or press Enter/Space on an interactive card to activate it; links, buttons and editable content inside its body remain independent. When switching layouts removes the focused row or selection control, focus follows the same keyed row/control if available, otherwise the table root. Search and paginator focus are left alone.

Card sorting announces the active direction with `messages.dataTable.sortAscending` and `sortDescending` on `CratisComponentsProvider` (defaults `Ascending` and `Descending`). Existing loading, failure, unauthorized and empty messages are also used outside table markup. Refetching keeps loaded cards visible and busy. The paginator remains unchanged, including its localized messages.

Use the card-specific `pt` slots `cards`, `card`, `cardLabel`, `cardValue`, `cardControls` and `cardStatus`. Their `data-cratis-part` names are `cards`, `card`, `card-label`, `card-value`, `card-controls` and `card-status`. `pt.card` can add classes, styles and event handlers; preventing the click or key event cancels built-in activation. Existing row, cell and header slots still target the desktop table. Column body styles/classes and `rowClassName` also apply to cards. Width, wrapping and body-template layout remain under your control; long values wrap by default.

## Common Features

All three table components share:
Expand Down
4 changes: 4 additions & 0 deletions Source/Common/CratisComponentsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ export interface CratisDataTableMessages {
selectRow?: string;
/** Accessible name for the select-all control in a multiple-selection header. */
selectAllRows?: string;
/** Audible ascending sort direction in card controls. Defaults to 'Ascending'. */
sortAscending?: string;
/** Audible descending sort direction in card controls. Defaults to 'Descending'. */
sortDescending?: string;
/** Placeholder for the loaded-page search input. */
search?: string;
/** Accessible name for the loaded-page search input. */
Expand Down
74 changes: 74 additions & 0 deletions Source/DataTables/DataTableCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

import type { KeyboardEvent, MouseEvent } from 'react';
import { classNames } from '../ClassNames/classNames';
import type { DataTableRowProps } from './DataTableRow';
import { dataTableCellContent } from './dataTableCellContent';

const interactiveDescendant = 'a, button, input, select, textarea, label, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]';

const hasInteractiveTarget = (event: MouseEvent<HTMLLIElement>) => {
const target = event.target;
if (!(target instanceof Element)) return false;
if (target.hasAttribute('data-cratis-card-selection')) return false;
const interactive = target.closest(interactiveDescendant);
return !!interactive && interactive !== event.currentTarget;
};

const activateOnClick = <TData extends object>(event: MouseEvent<HTMLLIElement>, props: DataTableRowProps<TData>) => {
props.parts?.card?.onClick?.(event);
if (!event.defaultPrevented && !hasInteractiveTarget(event)) props.onActivate(event);
};

const activateOnKey = <TData extends object>(event: KeyboardEvent<HTMLLIElement>, props: DataTableRowProps<TData>) => {
props.parts?.card?.onKeyDown?.(event);
if (event.defaultPrevented || event.target !== event.currentTarget) return;
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
props.onActivate(event);
};

const CardSelection = <TData extends object>(props: DataTableRowProps<TData>) => {
const { selectionMode, selectionGroupName, resolvedSelectionAriaLabel, isSelected, isRowSelected, onToggleSelection } = props;
if (!selectionMode) return null;
const multiple = selectionMode === 'multiple';
return <input type={multiple ? 'checkbox' : 'radio'} name={multiple ? undefined : selectionGroupName}
aria-label={resolvedSelectionAriaLabel} checked={multiple ? isRowSelected : isSelected}
readOnly={!multiple} tabIndex={multiple ? undefined : -1}
data-cratis-card-selection={multiple ? undefined : 'single'}
onChange={multiple ? onToggleSelection : undefined} />;
};

const CardFields = <TData extends object>({ columns, row, parts: pt }: DataTableRowProps<TData>) => (
<dl>
{columns.filter(column => !column.props.selectionMode).map((column, index) => (
<div key={index} className='cratis-datatable__card-field'>
<dt {...pt?.cardLabel} className={classNames('cratis-datatable__card-label', pt?.cardLabel?.className)} data-cratis-component='DataTableCore' data-cratis-part='card-label'>
{column.props.header ?? column.props.field ?? ''}
</dt>
<dd {...pt?.cardValue} style={{ ...pt?.cardValue?.style, ...column.props.style, ...column.props.bodyStyle }}
className={classNames('cratis-datatable__card-value', pt?.cardValue?.className, column.props.bodyClassName ?? column.props.className)}
data-cratis-component='DataTableCore' data-cratis-part='card-value'>
{dataTableCellContent(column.props, row)}
</dd>
</div>
))}
</dl>
);

/** One semantic card for the same processed row and activation callbacks as the table. */
export const DataTableCard = <TData extends object>(props: DataTableRowProps<TData>) => {
const { row, rowKey, parts: pt, isSelected, isInteractive, isRowSelected, rowClassName } = props;
return (
<li {...pt?.card}
tabIndex={isInteractive ? 0 : pt?.card?.tabIndex}
className={classNames('cratis-datatable__card', pt?.card?.className, rowClassName?.(row))}
data-cratis-component='DataTableCore' data-cratis-part='card' data-datatable-row-key={rowKey}
data-selected={isSelected || isRowSelected || undefined} data-interactive={isInteractive || undefined}
onClick={event => activateOnClick(event, props)} onKeyDown={event => activateOnKey(event, props)}>
<CardSelection {...props} />
<CardFields {...props} />
</li>
);
};
44 changes: 44 additions & 0 deletions Source/DataTables/DataTableCardControls.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

import { cloneElement } from 'react';
import { classNames } from '../ClassNames/classNames';
import { useComponentPresentation } from '../configuration/identity/useComponentPresentation';
import { useCratisIcon } from '../configuration/useCratisIcon';
import { columnDescriptor } from './columnDescriptor';
import { DataTableHeaderContent, DataTableSelectAll } from './DataTableHeaderContent';
import type { DataTableHeaderCellProps } from './DataTableHeaderCell';
import type { DataTableHeadProps } from './DataTableHead';

const CardColumnControl = (props: DataTableHeaderCellProps & { cardSortDirection?: string }) => {
const [columnProps, marker] = useComponentPresentation(columnDescriptor, props.column.props, props.column.props.field);
return <div {...marker}><DataTableHeaderContent {...props} cardMode column={cloneElement(props.column, columnProps)} /></div>;
};

/** The one reachable set of column and select-all controls while the table is unmounted. */
export const DataTableCardControls = ({ columns, parts: pt, messages, selection, selectionMode, ...controls }: DataTableHeadProps & { selectionMode?: 'single' | 'multiple' }) => {
const icon = useCratisIcon();
const selectionProps = {
resolvedSelectAllAriaLabel: messages.resolvedSelectAllAriaLabel,
allFilteredRowsSelected: selection.allFilteredRowsSelected,
selectAllRef: selection.selectAllRef,
toggleSelectAll: selection.toggleSelectAll,
};
return (
<div {...pt?.cardControls} className={classNames('cratis-datatable__card-controls', pt?.cardControls?.className)} data-cratis-component='DataTableCore' data-cratis-part='card-controls'>
{selectionMode === 'multiple' && <DataTableSelectAll {...selectionProps} />}
{columns.filter(column => !column.props.selectionMode && (column.props.sortable || column.props.filter)).map((column, index) => (
<CardColumnControl key={index} {...controls} {...selectionProps}
column={column}
parts={pt}
resolvedSelectionAriaLabel={messages.resolvedSelectionAriaLabel}
sortAscendingIcon={icon('sortAscending', '▲')}
sortDescendingIcon={icon('sortDescending', '▼')}
cardSortDirection={controls.sort?.field === column.props.field
? controls.sort?.direction === 'ascending' ? messages.resolvedSortAscending : messages.resolvedSortDescending
: undefined}
/>
))}
</div>
);
};
69 changes: 69 additions & 0 deletions Source/DataTables/DataTableCards.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

import type { ReactNode } from 'react';
import { classNames } from '../ClassNames/classNames';
import type { DataTableRowsProps } from './DataTableRows';
import type { DataTableHeadProps } from './DataTableHead';
import { DataTableCard } from './DataTableCard';
import { DataTableCardControls } from './DataTableCardControls';
import { DataTableStatus } from './DataTableStatus';

interface DataTableCardsProps<TData extends object> extends Omit<DataTableRowsProps<TData>, 'resolvedSelectionAriaLabel'>, Omit<DataTableHeadProps, 'selection'> {
data: TData[];
status: DataTableStatus;
isBusy: boolean;
emptyMessage: ReactNode;
scrollable?: boolean;
scrollHeight?: string;
}

const isFailure = (status: DataTableStatus) => status === DataTableStatus.Failed || status === DataTableStatus.Unauthorized;
const statusMessage = <TData extends object>({ status, data, state, messages, emptyMessage }: DataTableCardsProps<TData>): ReactNode => {
if (status === DataTableStatus.Failed) return messages.resolvedFailureMessage;
if (status === DataTableStatus.Unauthorized) return messages.resolvedUnauthorizedMessage;
if (status === DataTableStatus.Loading && !data.length) return messages.resolvedLoadingMessage;
if (state.filteredRows.length) return undefined;
return state.isFiltered ? messages.resolvedFilteredEmptyMessage : emptyMessage;
};
const CardStatus = <TData extends object>(props: DataTableCardsProps<TData>) => {
const { parts: pt, status } = props;
const message = statusMessage(props);
if (message === undefined) return null;
return <div {...pt?.cardStatus} className={classNames('cratis-datatable__card-status', pt?.cardStatus?.className)} data-cratis-component='DataTableCore' data-cratis-part='card-status' data-reason={status} role={isFailure(status) ? 'alert' : 'status'}>{message}</div>;
};
const CardList = <TData extends object>({ state, columns, parts: pt, messages, selectionMode, selectionGroupName, rowClassName, isBusy }: DataTableCardsProps<TData>) => (
<ul {...pt?.cards} role='list' className={classNames('cratis-datatable__cards', pt?.cards?.className)} data-cratis-component='DataTableCore' data-cratis-part='cards' data-busy={isBusy || undefined} aria-busy={isBusy || undefined}>
{state.filteredRows.map(({ row, loadedIndex }) => (
<DataTableCard key={state.rowKeys[loadedIndex]} rowKey={state.rowKeys[loadedIndex]} row={row} columns={columns} parts={pt}
selectionMode={selectionMode}
isSelected={selectionMode === 'single' && state.isSelectedRow(row, loadedIndex)}
isInteractive={state.isInteractive}
isRowSelected={state.isRowSelected(row)}
rowClassName={rowClassName}
resolvedSelectionAriaLabel={messages.resolvedSelectionAriaLabel}
selectionGroupName={selectionGroupName}
onActivate={event => state.activateRow(row, loadedIndex, event)}
onToggleSelection={() => state.toggleRowSelection(row)}
/>
))}
</ul>
);
const canShowRows = <TData extends object>({ status, data, state }: DataTableCardsProps<TData>) => {
if (isFailure(status)) return false;
if (status === DataTableStatus.Loading && !data.length) return false;
return state.filteredRows.length > 0;
};

/** Non-table presentation of the already processed loaded-page rows. */
export const DataTableCards = <TData extends object>(props: DataTableCardsProps<TData>) => {
const { state, parts: pt, scrollable, scrollHeight } = props;
return (
<div {...pt?.tableContainer} className={classNames('cratis-datatable__container', pt?.tableContainer?.className)}
style={{ ...pt?.tableContainer?.style, ...(scrollable ? { maxHeight: scrollHeight ?? '100%', overflow: 'auto' } : {}) }} data-cratis-part='table-container'>
<DataTableCardControls {...props} selection={state} />
<CardStatus {...props} />
{canShowRows(props) && <CardList {...props} />}
</div>
);
};
66 changes: 66 additions & 0 deletions Source/DataTables/DataTableCore.css
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,72 @@
text-align: center;
}

.cratis-datatable__cards {
display: grid;
gap: 1rem;
padding: 0.5rem;
margin: 0;
list-style: none;
}
.cratis-datatable__card {
min-width: 0;
padding: 1rem;
border: 1px solid var(--cratis-surface-border);
border-radius: var(--cratis-border-radius);
background: var(--cratis-surface-card);
overflow-wrap: anywhere;
}
.cratis-datatable__card[data-interactive='true']:hover {
background: var(--cratis-surface-hover);
}
.cratis-datatable__card[data-selected='true'] {
background: var(--cratis-highlight-bg);
color: var(--cratis-highlight-text-color);
}
.cratis-datatable__card:focus-visible {
outline: var(--cratis-focus-outline);
outline-offset: var(--cratis-focus-outline-offset);
box-shadow: var(--cratis-focus-ring);
}
.cratis-datatable__card dl {
display: grid;
gap: 0.75rem;
margin: 0;
}
.cratis-datatable__card-field {
min-width: 0;
}
.cratis-datatable__card-label {
font-size: var(--cratis-font-size-sm);
font-weight: var(--cratis-type-weight-bold);
}
.cratis-datatable__card-value {
min-width: 0;
margin: 0;
}
.cratis-datatable__card-controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 1rem;
padding: 0.5rem;
}
.cratis-datatable__card-status {
padding: 2rem 1rem;
color: var(--cratis-text-color-secondary);
text-align: center;
}
@media (forced-colors: active) {
.cratis-datatable__card {
border-color: CanvasText;
}
.cratis-datatable__card[data-selected='true'],
.cratis-datatable__card:focus-visible {
outline: 2px solid Highlight;
box-shadow: none;
}
}

@media (prefers-reduced-motion: reduce) {
.cratis-datatable__row {
transition: none;
Expand Down
Loading
Loading