diff --git a/Documentation/DataTables/data-table-for-observable-query.md b/Documentation/DataTables/data-table-for-observable-query.md index 5025e4cc..638e473c 100644 --- a/Documentation/DataTables/data-table-for-observable-query.md +++ b/Documentation/DataTables/data-table-for-observable-query.md @@ -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 diff --git a/Documentation/DataTables/data-table-for-query.md b/Documentation/DataTables/data-table-for-query.md index 5d376c33..43860945 100644 --- a/Documentation/DataTables/data-table-for-query.md +++ b/Documentation/DataTables/data-table-for-query.md @@ -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 diff --git a/Documentation/DataTables/index.md b/Documentation/DataTables/index.md index 9c3146ea..02c5777b 100644 --- a/Documentation/DataTables/index.md +++ b/Documentation/DataTables/index.md @@ -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 ( + + + + + ); +} +``` + +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: diff --git a/Source/Common/CratisComponentsProvider.tsx b/Source/Common/CratisComponentsProvider.tsx index 17d66d67..a3505ee4 100644 --- a/Source/Common/CratisComponentsProvider.tsx +++ b/Source/Common/CratisComponentsProvider.tsx @@ -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. */ diff --git a/Source/DataTables/DataTableCard.tsx b/Source/DataTables/DataTableCard.tsx new file mode 100644 index 00000000..a5dc8e61 --- /dev/null +++ b/Source/DataTables/DataTableCard.tsx @@ -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) => { + 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 = (event: MouseEvent, props: DataTableRowProps) => { + props.parts?.card?.onClick?.(event); + if (!event.defaultPrevented && !hasInteractiveTarget(event)) props.onActivate(event); +}; + +const activateOnKey = (event: KeyboardEvent, props: DataTableRowProps) => { + 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 = (props: DataTableRowProps) => { + const { selectionMode, selectionGroupName, resolvedSelectionAriaLabel, isSelected, isRowSelected, onToggleSelection } = props; + if (!selectionMode) return null; + const multiple = selectionMode === 'multiple'; + return ; +}; + +const CardFields = ({ columns, row, parts: pt }: DataTableRowProps) => ( +
+ {columns.filter(column => !column.props.selectionMode).map((column, index) => ( +
+
+ {column.props.header ?? column.props.field ?? ''} +
+
+ {dataTableCellContent(column.props, row)} +
+
+ ))} +
+); + +/** One semantic card for the same processed row and activation callbacks as the table. */ +export const DataTableCard = (props: DataTableRowProps) => { + const { row, rowKey, parts: pt, isSelected, isInteractive, isRowSelected, rowClassName } = props; + return ( +
  • activateOnClick(event, props)} onKeyDown={event => activateOnKey(event, props)}> + + +
  • + ); +}; diff --git a/Source/DataTables/DataTableCardControls.tsx b/Source/DataTables/DataTableCardControls.tsx new file mode 100644 index 00000000..d4421392 --- /dev/null +++ b/Source/DataTables/DataTableCardControls.tsx @@ -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
    ; +}; + +/** 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 ( +
    + {selectionMode === 'multiple' && } + {columns.filter(column => !column.props.selectionMode && (column.props.sortable || column.props.filter)).map((column, index) => ( + + ))} +
    + ); +}; diff --git a/Source/DataTables/DataTableCards.tsx b/Source/DataTables/DataTableCards.tsx new file mode 100644 index 00000000..c428b92f --- /dev/null +++ b/Source/DataTables/DataTableCards.tsx @@ -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 extends Omit, 'resolvedSelectionAriaLabel'>, Omit { + data: TData[]; + status: DataTableStatus; + isBusy: boolean; + emptyMessage: ReactNode; + scrollable?: boolean; + scrollHeight?: string; +} + +const isFailure = (status: DataTableStatus) => status === DataTableStatus.Failed || status === DataTableStatus.Unauthorized; +const statusMessage = ({ status, data, state, messages, emptyMessage }: DataTableCardsProps): 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 = (props: DataTableCardsProps) => { + const { parts: pt, status } = props; + const message = statusMessage(props); + if (message === undefined) return null; + return
    {message}
    ; +}; +const CardList = ({ state, columns, parts: pt, messages, selectionMode, selectionGroupName, rowClassName, isBusy }: DataTableCardsProps) => ( +
      + {state.filteredRows.map(({ row, loadedIndex }) => ( + state.activateRow(row, loadedIndex, event)} + onToggleSelection={() => state.toggleRowSelection(row)} + /> + ))} +
    +); +const canShowRows = ({ status, data, state }: DataTableCardsProps) => { + 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 = (props: DataTableCardsProps) => { + const { state, parts: pt, scrollable, scrollHeight } = props; + return ( +
    + + + {canShowRows(props) && } +
    + ); +}; diff --git a/Source/DataTables/DataTableCore.css b/Source/DataTables/DataTableCore.css index 5d02ace9..c6125495 100644 --- a/Source/DataTables/DataTableCore.css +++ b/Source/DataTables/DataTableCore.css @@ -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; diff --git a/Source/DataTables/DataTableCore.stories.tsx b/Source/DataTables/DataTableCore.stories.tsx index ee2760f8..6daa21dc 100644 --- a/Source/DataTables/DataTableCore.stories.tsx +++ b/Source/DataTables/DataTableCore.stories.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import type { Meta, StoryObj } from '@storybook/react'; -import { DataTableCore } from './DataTableCore'; +import { DataTableCore, type DataTableCoreProps } from './DataTableCore'; import { Column } from './Column'; import { DataTableStatus } from './DataTableStatus'; @@ -109,6 +109,41 @@ export const QueryStates: Story = { ), }; +interface MobileProject { + id: string; + name: string; + details: { status: string }; + notes?: string; +} +const mobileProjects: MobileProject[] = [ + { id: 'example-1', name: 'Example Project', details: { status: 'Ready' }, notes: 'A long synthetic description that wraps within a narrow card without hiding the column label or the body action.' }, + { id: 'example-2', name: 'Demo Project', details: { status: 'Draft' } }, +]; +const mobileArgs: DataTableCoreProps = { + data: mobileProjects, dataKey: 'id', emptyMessage: 'No projects.', mobileLayout: 'cards', + selectionMode: 'multiple', globalFilterFields: ['name'], +}; +const mobileColumns = [ + Project} sortable filter />, + , + , + key='action' header='Action' body={row => Open project} />, +]; + +/** Resize across 640px; search, selection and controls retain their state. */ +export const MobileCards: Story = { + render: function MobileCardsExample() { + const [selectedItems, setSelectedItems] = useState([]); + return {mobileColumns}; + }, +}; +export const MobileLoading: Story = { render: () => {mobileColumns} }; +export const MobileRefetch: Story = { render: () => {mobileColumns} }; +export const MobileFailed: Story = { render: () => {mobileColumns} }; +export const MobileUnauthorized: Story = { render: () => {mobileColumns} }; +export const MobileEmpty: Story = { render: () => {mobileColumns} }; +export const MobileFilteredEmpty: Story = { render: () => {mobileColumns} }; + export const Empty: Story = { render: () => ( data={[]} emptyMessage='No people'> diff --git a/Source/DataTables/DataTableCore.tsx b/Source/DataTables/DataTableCore.tsx index 88793ef2..cedce94a 100644 --- a/Source/DataTables/DataTableCore.tsx +++ b/Source/DataTables/DataTableCore.tsx @@ -19,8 +19,13 @@ import { DataTableTable } from './DataTableTable'; import { useDataTableMessages } from './useDataTableMessages'; import { useDataTableRows } from './useDataTableRows'; import { useDataTableState } from './useDataTableState'; +import type { DataTableMobileLayoutProps } from './DataTableMobileLayoutProps'; +import { useMobileLayout } from './useMobileLayout'; +import { DataTableCards } from './DataTableCards'; +import { useDataTablePresentationFocus } from './useDataTablePresentationFocus'; export type { DataTableParts } from './DataTableParts'; +export type { DataTableMobileLayoutProps } from './DataTableMobileLayoutProps'; export type { DataTableRowClickEvent } from './DataTableRowClickEvent'; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -35,7 +40,7 @@ const useColumns = (children: React.ReactNode): React.ReactElement { +export interface DataTableCoreProps extends DataTableMobileLayoutProps { /** Loaded page rows. */ data: TData[]; /** Declarative {@link Column} markers. */ @@ -126,6 +131,31 @@ export interface DataTableCoreProps { unstyled?: boolean; } +type DataTableRootProps = Pick, 'children' | 'scrollable' | 'className' | 'style' | 'pt' | 'mobileLayout'> & { + elementRef: React.Ref; + isBusy: boolean; +}; + +const DataTableRoot = ({ children, scrollable, className, style, pt, mobileLayout, elementRef, isBusy }: DataTableRootProps) => ( +
    + {children} +
    +); + /** A semantic, renderer-independent data table over one already-loaded page. */ export const DataTableCore = (props: DataTableCoreProps) => { const { @@ -134,14 +164,14 @@ export const DataTableCore = (props: DataTableCoreProps 0; const columns = useColumns(props.children); const selectionGroupName = useId(); + const useCards = useMobileLayout(props); + const presentationRoot = useDataTablePresentationFocus(useCards); const { filters, updateFilter, globalFilter, setGlobalFilter, sort, setSort } = useDataTableState(props); const rows = useDataTableRows({ @@ -153,19 +183,7 @@ export const DataTableCore = (props: DataTableCoreProps + {!!globalFilterFields?.length && ( (props: DataTableCoreProps )} - + ) : (props: DataTableCoreProps )} /> - - + } + ); }; diff --git a/Source/DataTables/DataTableForObservableQuery.stories.tsx b/Source/DataTables/DataTableForObservableQuery.stories.tsx index d1435033..7182cef0 100644 --- a/Source/DataTables/DataTableForObservableQuery.stories.tsx +++ b/Source/DataTables/DataTableForObservableQuery.stories.tsx @@ -126,6 +126,19 @@ class TasksQuery extends ObservableQueryFor { } } +/** The same observable updates reach the current presentation without resubscribing on resize. */ +export const MobileCards: Story = { + render: () => ( +
    + + Example} sortable filter /> + + header='Action' body={row => Open example} /> + +
    + ), +}; + class LiveTasksQuery extends TasksQuery { override subscribe( callback: (result: QueryResult) => void, diff --git a/Source/DataTables/DataTableForObservableQuery.tsx b/Source/DataTables/DataTableForObservableQuery.tsx index ef596968..10117ded 100644 --- a/Source/DataTables/DataTableForObservableQuery.tsx +++ b/Source/DataTables/DataTableForObservableQuery.tsx @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. import type { DataTableParts } from './DataTableCore'; +import type { DataTableMobileLayoutProps } from './DataTableMobileLayoutProps'; import type { Constructor } from '@cratis/fundamentals'; import { type IObservableQueryFor, Paging } from '@cratis/arc/queries'; import { useObservableQueryWithPaging } from '@cratis/arc.react/queries'; @@ -33,7 +34,7 @@ export interface DataTableForObservableQueryProps< | IObservableQueryFor, TDataType extends object, TArguments extends object, -> { +> extends DataTableMobileLayoutProps { /** * Children to render — `` elements describing the visible columns. */ @@ -305,6 +306,8 @@ export const DataTableForObservableQuery = <
    data={rows} + mobileLayout={props.mobileLayout} + mobileBreakpoint={props.mobileBreakpoint} dataKey={props.dataKey} emptyMessage={props.emptyMessage} filteredEmptyMessage={props.filteredEmptyMessage} diff --git a/Source/DataTables/DataTableForQuery.stories.tsx b/Source/DataTables/DataTableForQuery.stories.tsx index b10cb5c9..9a629bc1 100644 --- a/Source/DataTables/DataTableForQuery.stories.tsx +++ b/Source/DataTables/DataTableForQuery.stories.tsx @@ -65,6 +65,19 @@ class ProductsQuery extends QueryFor { } } +/** Uses the paged synthetic query; resize below 640px to exercise cards and paginator together. */ +export const MobileCards: Story = { + render: () => ( +
    + + Example} sortable filter /> + + header='Action' body={row => Open example} /> + +
    + ), +}; + const manyProducts: Product[] = Array.from({ length: 24 }, (_, index) => ({ id: index + 1, name: `Product ${index + 1}`, diff --git a/Source/DataTables/DataTableForQuery.tsx b/Source/DataTables/DataTableForQuery.tsx index 56cda250..204fe101 100644 --- a/Source/DataTables/DataTableForQuery.tsx +++ b/Source/DataTables/DataTableForQuery.tsx @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. import type { DataTableParts } from './DataTableCore'; +import type { DataTableMobileLayoutProps } from './DataTableMobileLayoutProps'; import type { Constructor } from '@cratis/fundamentals'; import { type IQueryFor, Paging } from '@cratis/arc/queries'; import { useQueryWithPaging } from '@cratis/arc.react/queries'; @@ -32,7 +33,7 @@ export interface DataTableForQueryProps< TQuery extends IQueryFor | IQueryFor, TDataType extends object, TArguments extends object, -> { +> extends DataTableMobileLayoutProps { /** * Children to render — `` elements describing the visible columns. */ @@ -267,6 +268,8 @@ export const DataTableForQuery = <
    data={rows} + mobileLayout={props.mobileLayout} + mobileBreakpoint={props.mobileBreakpoint} dataKey={props.dataKey} emptyMessage={props.emptyMessage} filteredEmptyMessage={props.filteredEmptyMessage} diff --git a/Source/DataTables/DataTableHeaderCell.tsx b/Source/DataTables/DataTableHeaderCell.tsx index a2f1c71b..96dff953 100644 --- a/Source/DataTables/DataTableHeaderCell.tsx +++ b/Source/DataTables/DataTableHeaderCell.tsx @@ -5,16 +5,11 @@ import { cloneElement, type ReactElement, type ReactNode, type RefObject } from import { useComponentPresentation } from '../configuration/identity/useComponentPresentation'; import { columnDescriptor } from './columnDescriptor'; import type { ColumnProps } from './Column'; -import { ColumnFilterMenu } from './ColumnFilterMenu'; import { classNames } from '../ClassNames/classNames'; -import type { - DataTableFilterConstraint, - DataTableFilterMeta, -} from './DataTableFilterMeta'; +import type { DataTableFilterConstraint, DataTableFilterMeta } from './DataTableFilterMeta'; import type { DataTableParts } from './DataTableParts'; import type { DataTableSort } from './DataTableSort'; -import { DataTableSortDirection } from './DataTableSortDirection'; -import { firstConstraint } from './matchesFilterEntry'; +import { DataTableHeaderContent } from './DataTableHeaderContent'; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -26,10 +21,7 @@ export interface DataTableHeaderCellProps { sort: DataTableSort | null; onSort: (sort: DataTableSort) => void; filters: DataTableFilterMeta; - updateFilter: ( - field: string, - constraint: DataTableFilterConstraint | undefined, - ) => void; + updateFilter: (field: string, constraint: DataTableFilterConstraint | undefined) => void; resolvedSelectionAriaLabel: string; resolvedSelectAllAriaLabel: string; allFilteredRowsSelected: boolean; @@ -39,119 +31,25 @@ export interface DataTableHeaderCellProps { sortDescendingIcon: ReactNode; } -/** One column header: its label, sort control, filter menu, and select-all or selection label. */ -export const DataTableHeaderCell = ({ - column: declaredColumn, - parts: pt, - sort, - onSort, - filters, - updateFilter, - resolvedSelectionAriaLabel, - resolvedSelectAllAriaLabel, - allFilteredRowsSelected, - selectAllRef, - toggleSelectAll, - sortAscendingIcon, - sortDescendingIcon, -}: DataTableHeaderCellProps) => { - const [columnProps, marker] = useComponentPresentation( - columnDescriptor, - declaredColumn.props, - declaredColumn.props.field, - ); +/** One column header, retaining the semantic table wrapper around the shared controls. */ +export const DataTableHeaderCell = (props: DataTableHeaderCellProps) => { + const { column: declaredColumn, parts: pt, sort, resolvedSelectionAriaLabel } = props; + const [columnProps, marker] = useComponentPresentation(columnDescriptor, declaredColumn.props, declaredColumn.props.field); const column = columnProps === declaredColumn.props ? declaredColumn : cloneElement(declaredColumn, columnProps); - const field = column.props.filterField ?? column.props.field; - const ariaSort = - sort && sort.field === column.props.field ? sort.direction : undefined; + const ariaSort = sort && sort.field === column.props.field ? sort.direction : undefined; return ( -
    - {column.props.selectionMode === 'multiple' ? ( - - ) : ( - column.props.selectionMode && ( - - {resolvedSelectionAriaLabel} - - ) - )} - {column.props.sortable && column.props.field ? ( - - ) : ( - column.props.header - )} - {column.props.filter && field && ( - updateFilter(field, constraint)} - onClear={() => updateFilter(field, undefined)} - /> - )} -
    + ); }; diff --git a/Source/DataTables/DataTableHeaderContent.tsx b/Source/DataTables/DataTableHeaderContent.tsx new file mode 100644 index 00000000..9a175a3f --- /dev/null +++ b/Source/DataTables/DataTableHeaderContent.tsx @@ -0,0 +1,64 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +import { useId } from 'react'; +import { ColumnFilterMenu } from './ColumnFilterMenu'; +import type { DataTableHeaderCellProps } from './DataTableHeaderCell'; +import { DataTableSortDirection } from './DataTableSortDirection'; +import { firstConstraint } from './matchesFilterEntry'; + +type HeaderContentProps = DataTableHeaderCellProps & { cardSortDirection?: string; cardMode?: boolean }; + +/** The shared select-all control for headers and cards. */ +export const DataTableSelectAll = ({ resolvedSelectAllAriaLabel, allFilteredRowsSelected, selectAllRef, toggleSelectAll }: Pick) => ( + +); +const sortDirection = ({ column, sort }: DataTableHeaderCellProps) => { + const isAscending = sort?.field === column.props.field && sort?.direction === DataTableSortDirection.Ascending; + return isAscending ? DataTableSortDirection.Descending : DataTableSortDirection.Ascending; +}; +const HeaderSort = (props: HeaderContentProps) => { + const { column, sort, onSort, sortAscendingIcon, sortDescendingIcon, cardSortDirection, cardMode } = props; + const directionId = useId(); + if (!column.props.sortable || !column.props.field) return column.props.header; + const ariaSort = sort && sort.field === column.props.field ? sort.direction : undefined; + return <> + + {cardSortDirection && {cardSortDirection}} + ; +}; +const HeaderFilter = ({ column, filters, updateFilter }: DataTableHeaderCellProps) => { + const field = column.props.filterField ?? column.props.field; + if (!column.props.filter || !field) return null; + return updateFilter(field, constraint)} onClear={() => updateFilter(field, undefined)} + />; +}; +const HeaderSelection = (props: DataTableHeaderCellProps) => { + if (props.column.props.selectionMode === 'multiple') return ; + return props.column.props.selectionMode ? {props.resolvedSelectionAriaLabel} : null; +}; + +/** Sort, filter and selection content shared without changing the desktop header markup. */ +export const DataTableHeaderContent = (props: HeaderContentProps) => { + const selected = props.sort?.field === props.column.props.field && !!props.sort; + return ( +
    + + + +
    + ); +}; diff --git a/Source/DataTables/DataTableMessages.ts b/Source/DataTables/DataTableMessages.ts index 0c506b31..d0722c98 100644 --- a/Source/DataTables/DataTableMessages.ts +++ b/Source/DataTables/DataTableMessages.ts @@ -5,6 +5,8 @@ import type { ReactNode } from 'react'; /** The table messages to show, after props and provider messages are applied. */ export interface DataTableMessages { + resolvedSortAscending: string; + resolvedSortDescending: string; resolvedSelectionAriaLabel: string; resolvedSelectAllAriaLabel: string; resolvedGlobalSearchPlaceholder: string; diff --git a/Source/DataTables/DataTableMobileLayoutProps.ts b/Source/DataTables/DataTableMobileLayoutProps.ts new file mode 100644 index 00000000..262479ea --- /dev/null +++ b/Source/DataTables/DataTableMobileLayoutProps.ts @@ -0,0 +1,10 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +/** Optional viewport-based presentation for the DataTable family. */ +export interface DataTableMobileLayoutProps { + /** Render cards below the viewport breakpoint. Omit to keep the semantic table at every width. */ + mobileLayout?: 'cards'; + /** Exclusive viewport threshold in CSS pixels. Defaults to 640; nonfinite/nonpositive values use the default. */ + mobileBreakpoint?: number; +} diff --git a/Source/DataTables/DataTableParts.ts b/Source/DataTables/DataTableParts.ts index 68ec8c02..41db9583 100644 --- a/Source/DataTables/DataTableParts.ts +++ b/Source/DataTables/DataTableParts.ts @@ -19,6 +19,18 @@ export interface DataTableParts { searchInput?: React.InputHTMLAttributes; /** Scroll container. */ tableContainer?: HTMLAttributes; + /** Semantic card list. */ + cards?: HTMLAttributes; + /** One row presented as a card. */ + card?: HTMLAttributes; + /** Column label in a card. */ + cardLabel?: HTMLAttributes; + /** Column value in a card. */ + cardValue?: HTMLAttributes; + /** Sorting, filtering and select-all controls above cards. */ + cardControls?: HTMLAttributes; + /** Non-table loading, failure or empty status. */ + cardStatus?: HTMLAttributes; /** Semantic table element. */ table?: TableHTMLAttributes; /** Table head. */ diff --git a/Source/DataTables/DataTableRow.tsx b/Source/DataTables/DataTableRow.tsx index b1c2464a..5416c1de 100644 --- a/Source/DataTables/DataTableRow.tsx +++ b/Source/DataTables/DataTableRow.tsx @@ -1,26 +1,19 @@ // Copyright (c) Cratis. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -import type { ReactElement, ReactNode, SyntheticEvent } from 'react'; +import type { ReactElement, SyntheticEvent } from 'react'; import type { ColumnProps } from './Column'; import { classNames } from '../ClassNames/classNames'; import type { DataTableParts } from './DataTableParts'; -import { valueAtPath } from './valueAtPath'; +import { dataTableCellContent } from './dataTableCellContent'; /* eslint-disable @typescript-eslint/no-explicit-any */ -const renderCellContent = ( - column: ColumnProps, - row: Record, -): ReactNode => { - if (column.body) return column.body(row); - const value = valueAtPath(row, column.field); - return value == null ? '' : String(value); -}; - /** Props for {@link DataTableRow}. */ export interface DataTableRowProps { row: TData; + /** Shared identity for focus transfer between presentations. */ + rowKey?: string; columns: ReactElement>[]; /** The table's part attributes. */ parts?: DataTableParts; @@ -38,6 +31,7 @@ export interface DataTableRowProps { /** One data row, activated by click, Enter or Space. */ export const DataTableRow = ({ row, + rowKey, columns, parts: pt, selectionMode, @@ -60,6 +54,7 @@ export const DataTableRow = ({ rowClassName?.(row), )} data-cratis-part='row' + data-datatable-row-key={rowKey} data-selected={isSelected || undefined} data-interactive={isInteractive || undefined} onClick={(event) => onActivate(event)} @@ -109,7 +104,7 @@ export const DataTableRow = ({ checked={isSelected} /> ) : ( - renderCellContent(column.props, row as Record) + dataTableCellContent(column.props, row) )} ))} diff --git a/Source/DataTables/DataTableRows.tsx b/Source/DataTables/DataTableRows.tsx index 901d34c2..20148009 100644 --- a/Source/DataTables/DataTableRows.tsx +++ b/Source/DataTables/DataTableRows.tsx @@ -33,6 +33,7 @@ export const DataTableRows = ({ key={state.rowKeys[loadedIndex]} row={row} + rowKey={state.rowKeys[loadedIndex]} selectionMode={selectionMode} isSelected={selectionMode === 'single' && state.isSelectedRow(row, loadedIndex)} isInteractive={state.isInteractive} diff --git a/Source/DataTables/dataTableCellContent.ts b/Source/DataTables/dataTableCellContent.ts new file mode 100644 index 00000000..8f14999d --- /dev/null +++ b/Source/DataTables/dataTableCellContent.ts @@ -0,0 +1,13 @@ +// 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 type { ColumnProps } from './Column'; +import { valueAtPath } from './valueAtPath'; + +/** Resolves a body template or nested field identically in either presentation. */ +export const dataTableCellContent = (column: ColumnProps, row: TData): ReactNode => { + if (column.body) return column.body(row); + const value = valueAtPath(row as Record, column.field); + return value == null ? '' : String(value); +}; diff --git a/Source/DataTables/for_DataTableCore/given/a_mobile_viewport.ts b/Source/DataTables/for_DataTableCore/given/a_mobile_viewport.ts new file mode 100644 index 00000000..afbf0ba7 --- /dev/null +++ b/Source/DataTables/for_DataTableCore/given/a_mobile_viewport.ts @@ -0,0 +1,33 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +import { vi } from 'vitest'; + +/** A controllable viewport that follows the strict CSS width query used by mobile cards. */ +export const aMobileViewport = (initialWidth = 639) => { + let width = initialWidth; + const queries = new Map(); + const listeners = new Map>(); + vi.stubGlobal('matchMedia', (media: string) => { + if (!queries.has(media)) { + const changes = new Set(); + listeners.set(media, changes); + queries.set(media, { + media, + get matches() { return width < Number(media.match(/[\d.]+/)?.[0]); }, + addEventListener: (_type: string, listener: EventListenerOrEventListenerObject) => changes.add(listener), + removeEventListener: (_type: string, listener: EventListenerOrEventListenerObject) => changes.delete(listener), + } as MediaQueryList); + } + return queries.get(media); + }); + return { + resize: (nextWidth: number) => { + width = nextWidth; + listeners.forEach((changes) => changes.forEach((listener) => { + if (typeof listener === 'function') listener(new Event('change')); + })); + }, + listenerCount: () => [...listeners.values()].reduce((count, changes) => count + changes.size, 0), + }; +}; diff --git a/Source/DataTables/for_DataTableCore/when_hydrating_mobile_layout.tsx b/Source/DataTables/for_DataTableCore/when_hydrating_mobile_layout.tsx new file mode 100644 index 00000000..3b80852f --- /dev/null +++ b/Source/DataTables/for_DataTableCore/when_hydrating_mobile_layout.tsx @@ -0,0 +1,48 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// @vitest-environment jsdom + +import { should } from 'chai'; +import { act } from 'react'; +import { hydrateRoot, type Root } from 'react-dom/client'; +import { renderToString } from 'react-dom/server'; +import { afterEach, beforeEach, describe, it, vi } from 'vitest'; +import { Column } from '../Column'; +import { DataTableCore } from '../DataTableCore'; +import { aMobileViewport } from './given/a_mobile_viewport'; + +should(); +const table = ; + +it('should server-render table markup regardless of a narrow viewport', () => { + aMobileViewport(); + renderToString(table).should.contain(' { + let container: HTMLDivElement; + let root: Root; + let errors: unknown[]; + beforeEach(async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + aMobileViewport(); + errors = []; + container = document.createElement('div'); + container.innerHTML = renderToString(table); + document.body.append(container); + await act(async () => { root = hydrateRoot(container, table, { onRecoverableError: error => errors.push(error) }); }); + }); + afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + }); + it('should not have a hydration mismatch', () => { + errors.should.have.lengthOf(0); + }); + it('should switch to cards after hydration', () => { + container.querySelectorAll('ul').length.should.equal(1); + }); +}); diff --git a/Source/DataTables/for_DataTableCore/when_rendering_mobile_cards.tsx b/Source/DataTables/for_DataTableCore/when_rendering_mobile_cards.tsx new file mode 100644 index 00000000..f45e83c5 --- /dev/null +++ b/Source/DataTables/for_DataTableCore/when_rendering_mobile_cards.tsx @@ -0,0 +1,189 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// @vitest-environment jsdom + +import { should } from 'chai'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, it, vi } from 'vitest'; +import { CratisComponentsProvider } from '../../Common/CratisComponentsProvider'; +import { Column } from '../Column'; +import { DataTableCore, type DataTableCoreProps } from '../DataTableCore'; +import { DataTableStatus } from '../DataTableStatus'; +import { DataTableRowProcessing } from '../DataTableRowProcessing'; +import { DataTableSortDirection } from '../DataTableSortDirection'; +import { aMobileViewport } from './given/a_mobile_viewport'; + +should(); +const data = [{ id: 1, name: 'Example Project' }, { id: 2, name: 'Demo Project' }]; +type Row = (typeof data)[number]; + +describe('when rendering mobile cards', () => { + let container: HTMLDivElement; + let root: Root; + let viewport: ReturnType; + const activated = vi.fn(); + const selectionChanged = vi.fn(); + const render = async (props: Partial> = {}, descending?: string) => { + await act(async () => root.render( + + + + + field='name' header={Project name} sortable filter body={row => <>{row.name}Link