From 5ffe95139ef7d8107c9ba0b6d93f07731fd15038 Mon Sep 17 00:00:00 2001 From: woksin Date: Sat, 21 Nov 2026 18:15:16 +0100 Subject: [PATCH 1/4] Extract focused conformance evidence checks --- Conformance/src/runConformance.tsx | 207 ++++++++++++++++++----------- 1 file changed, 129 insertions(+), 78 deletions(-) diff --git a/Conformance/src/runConformance.tsx b/Conformance/src/runConformance.tsx index ca694b56..731dd42a 100644 --- a/Conformance/src/runConformance.tsx +++ b/Conformance/src/runConformance.tsx @@ -131,6 +131,30 @@ const interactionMessages = { dismissal: 'The slot dismisses on Escape.', } as const; +const recordInteractions = ( + checks: ConformanceCheck[], + profile: SlotProfile, + observed: Awaited>>, +) => { + for (const concern of ['keyboard', 'focus', 'dismissal'] as const) { + const passed = observed[concern]; + if (passed === undefined) continue; + addCheck( + checks, + ConformanceFamily.Behavior, + `behavior.${profile.slotId}.${concern}`, + { + passed, + message: passed + ? interactionMessages[concern] + : `${interactionMessages[concern]} It did not respond as required.`, + slotId: profile.slotId, + evidence: { concern, passed, ...observed.detail }, + }, + ); + } +}; + /** * Drives a fresh fixture of a stable atomic slot with dispatched keyboard and focus events and adds * one check per concern the slot reports: `behavior..keyboard`, `.focus` and `.dismissal`. @@ -154,23 +178,7 @@ const checkInteractions = async ( const interacted = (await act(async () => profile.interact?.(document, mounted.container))) ?? {}; const observed = { ...interacted, ...(await interacted.settled?.()) }; - for (const concern of ['keyboard', 'focus', 'dismissal'] as const) { - const passed = observed[concern]; - if (passed === undefined) continue; - addCheck( - checks, - ConformanceFamily.Behavior, - `behavior.${profile.slotId}.${concern}`, - { - passed, - message: passed - ? interactionMessages[concern] - : `${interactionMessages[concern]} It did not respond as required.`, - slotId: profile.slotId, - evidence: { concern, passed, ...observed.detail }, - }, - ); - } + recordInteractions(checks, profile, observed); } catch (error) { addError(checks, ConformanceFamily.Behavior, `behavior.${profile.slotId}.interaction`, { error, slotId: profile.slotId }); } finally { @@ -317,7 +325,7 @@ const isImmutableLibrary = (library: unstable_UiLibrary) => (declaration) => declaration === undefined || Object.isFrozen(declaration), ); -const checkManifest = ( +const checkMetadata = ( checks: ConformanceCheck[], library: unstable_UiLibrary, options: ConformanceOptions, @@ -364,6 +372,14 @@ const checkManifest = ( ); } +}; + +const checkManifest = ( + checks: ConformanceCheck[], + library: unstable_UiLibrary, + options: ConformanceOptions, +) => { + checkMetadata(checks, library, options); const overDeclarations = overDeclaredCapabilities(library); addCheck( checks, @@ -858,49 +874,55 @@ const checkStateCoverage = ( ); }; -const checkServerRendering = ( +const checkSlotServerRendering = ( checks: ConformanceCheck[], - library: unstable_UiLibrary, - profiles: readonly SlotProfile[], - wrapper: ConformanceOptions['wrapper'], + { library, profile, wrapper }: { + library: unstable_UiLibrary; + profile: SlotProfile; + wrapper: ConformanceOptions['wrapper']; + }, + outputs: Map, ) => { - const outputs = new Map(); - for (const profile of profiles) { - const declaration = library.slots[profile.slotId]; - if (!declaration) continue; - try { - const element = withProvider( - renderComponent( - declaration as unstable_SlotDeclaration, - profile.createProps(), - ), - wrapper, - ); - const first = renderToString(element); - const second = renderToString(element); - outputs.set(profile.slotId, first); - addCheck( - checks, - ConformanceFamily.ServerRendering, - `ssr.${profile.slotId}`, - { - passed: first === second, - message: first === second - ? 'Server render is DOM-free and deterministic.' - : 'Repeated server renders differ.', - slotId: profile.slotId, - evidence: { bytes: first.length }, - }, - ); - } catch (error) { - addError( - checks, - ConformanceFamily.ServerRendering, - `ssr.${profile.slotId}`, - { error, slotId: profile.slotId }, - ); - } + const declaration = library.slots[profile.slotId]; + if (!declaration) return; + try { + const element = withProvider( + renderComponent( + declaration as unstable_SlotDeclaration, + profile.createProps(), + ), + wrapper, + ); + const first = renderToString(element); + const second = renderToString(element); + outputs.set(profile.slotId, first); + addCheck( + checks, + ConformanceFamily.ServerRendering, + `ssr.${profile.slotId}`, + { + passed: first === second, + message: first === second + ? 'Server render is DOM-free and deterministic.' + : 'Repeated server renders differ.', + slotId: profile.slotId, + evidence: { bytes: first.length }, + }, + ); + } catch (error) { + addError( + checks, + ConformanceFamily.ServerRendering, + `ssr.${profile.slotId}`, + { error, slotId: profile.slotId }, + ); } +}; + +const checkServerOverlays = ( + checks: ConformanceCheck[], + outputs: ReadonlyMap, +) => { const tooltipOutput = outputs.get('common.tooltip'); const dialogOutput = outputs.get('dialogs.dialog'); const overlayPassed = @@ -922,6 +944,12 @@ const checkServerRendering = ( }, }, ); +}; + +const checkServerOutputIsolation = ( + checks: ConformanceCheck[], + outputs: ReadonlyMap, +) => { const distinctOutputs = new Set(outputs.values()).size === outputs.size; addCheck( checks, @@ -937,6 +965,20 @@ const checkServerRendering = ( ); }; +const checkServerRendering = ( + checks: ConformanceCheck[], + library: unstable_UiLibrary, + profiles: readonly SlotProfile[], + wrapper: ConformanceOptions['wrapper'], +) => { + const outputs = new Map(); + for (const profile of profiles) { + checkSlotServerRendering(checks, { library, profile, wrapper }, outputs); + } + checkServerOverlays(checks, outputs); + checkServerOutputIsolation(checks, outputs); +}; + const checkHydration = async ( checks: ConformanceCheck[], library: unstable_UiLibrary, @@ -995,6 +1037,34 @@ const checkHydration = async ( ); }; +const recordEnvironmentalEvidence = ( + checks: ConformanceCheck[], + profile: SlotProfile, + native: Element | null, + host: HTMLElement, +) => { + const inputs = { + rtl: Boolean(native) && native?.closest('[dir="rtl"]') === host, + forcedColors: Boolean(native) && host.style.forcedColorAdjust === 'auto', + 'motion.reduced': Boolean(native) && host.style.transitionDuration === '0s', + } as const; + for (const mode of ['rtl', 'forcedColors', 'motion.reduced'] as const) { + addCheck( + checks, + ConformanceFamily.Accessibility, + `a11y.environment.${mode}`, + { + passed: inputs[mode], + message: inputs[mode] + ? `The ${profile.slotId} fixture rendered inside the bounded ${mode} DOM host input.` + : `The ${profile.slotId} fixture did not preserve the bounded ${mode} DOM host input.`, + slotId: profile.slotId, + evidence: { selector: profile.nativeSelector }, + }, + ); + } +}; + const checkEnvironmentalEvidence = async ( checks: ConformanceCheck[], document: Document, @@ -1036,26 +1106,7 @@ const checkEnvironmentalEvidence = async ( host, ); const native = fixture.container.querySelector(profile.nativeSelector); - const inputs = { - rtl: Boolean(native) && native?.closest('[dir="rtl"]') === host, - forcedColors: Boolean(native) && host.style.forcedColorAdjust === 'auto', - 'motion.reduced': Boolean(native) && host.style.transitionDuration === '0s', - } as const; - for (const mode of ['rtl', 'forcedColors', 'motion.reduced'] as const) { - addCheck( - checks, - ConformanceFamily.Accessibility, - `a11y.environment.${mode}`, - { - passed: inputs[mode], - message: inputs[mode] - ? `The ${profile.slotId} fixture rendered inside the bounded ${mode} DOM host input.` - : `The ${profile.slotId} fixture did not preserve the bounded ${mode} DOM host input.`, - slotId: profile.slotId, - evidence: { selector: profile.nativeSelector }, - }, - ); - } + recordEnvironmentalEvidence(checks, profile, native, host); } catch (error) { for (const mode of ['rtl', 'forcedColors', 'motion.reduced'] as const) { addError( From 0214710e62a9333b4b486800ff76bcb809207495 Mon Sep 17 00:00:00 2001 From: woksin Date: Sat, 21 Nov 2026 18:15:22 +0100 Subject: [PATCH 2/4] Separate data table row cells and keyboard activation --- Source/DataTables/DataTableRow.tsx | 137 ++++++++++------ .../when_rendering_and_activating_a_row.tsx | 146 ++++++++++++++++++ 2 files changed, 235 insertions(+), 48 deletions(-) create mode 100644 Source/DataTables/for_DataTableRow/when_rendering_and_activating_a_row.tsx diff --git a/Source/DataTables/DataTableRow.tsx b/Source/DataTables/DataTableRow.tsx index 5416c1de..f5327376 100644 --- a/Source/DataTables/DataTableRow.tsx +++ b/Source/DataTables/DataTableRow.tsx @@ -1,7 +1,7 @@ // 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, SyntheticEvent } from 'react'; +import type { KeyboardEvent, ReactElement, SyntheticEvent } from 'react'; import type { ColumnProps } from './Column'; import { classNames } from '../ClassNames/classNames'; import type { DataTableParts } from './DataTableParts'; @@ -28,6 +28,82 @@ export interface DataTableRowProps { onToggleSelection: () => void; } +const activateFromKeyboard = ( + event: KeyboardEvent, + onActivate: DataTableRowProps['onActivate'], +) => { + if (event.target !== event.currentTarget || !['Enter', ' '].includes(event.key)) { + return; + } + event.preventDefault(); + onActivate(event); +}; + +const rowTabIndex = (isInteractive: boolean, parts: DataTableParts | undefined) => + isInteractive ? 0 : parts?.row?.tabIndex; + +interface RowCellProps extends Pick, + 'row' | 'isSelected' | 'isRowSelected' | 'resolvedSelectionAriaLabel' | + 'selectionGroupName' | 'onToggleSelection'> { + column: DataTableRowProps['columns'][number]; + parts?: DataTableParts; +} + +const rowCellContent = ({ + column, + row, + isSelected, + isRowSelected, + resolvedSelectionAriaLabel, + selectionGroupName, + onToggleSelection, +}: RowCellProps) => { + if (column.props.selectionMode === 'multiple') { + return ( + event.stopPropagation()} + onChange={() => onToggleSelection()} + /> + ); + } + if (column.props.selectionMode) { + return ( + + ); + } + return dataTableCellContent(column.props, row); +}; + +const RowCell = ({ parts: pt, ...props }: RowCellProps) => ( + + {rowCellContent(props)} + +); + /** One data row, activated by click, Enter or Space. */ export const DataTableRow = ({ row, @@ -46,7 +122,7 @@ export const DataTableRow = ({ }: DataTableRowProps) => ( ({ data-selected={isSelected || undefined} data-interactive={isInteractive || undefined} onClick={(event) => onActivate(event)} - onKeyDown={(event) => { - if ( - event.target !== event.currentTarget || - (event.key !== 'Enter' && event.key !== ' ') - ) { - return; - } - event.preventDefault(); - onActivate(event); - }} + onKeyDown={(event) => activateFromKeyboard(event, onActivate)} > {columns.map((column, columnIndex) => ( - - {column.props.selectionMode === 'multiple' ? ( - event.stopPropagation()} - onChange={() => onToggleSelection()} - /> - ) : column.props.selectionMode ? ( - - ) : ( - dataTableCellContent(column.props, row) - )} - + column={column} + row={row} + parts={pt} + isSelected={isSelected} + isRowSelected={isRowSelected} + resolvedSelectionAriaLabel={resolvedSelectionAriaLabel} + selectionGroupName={selectionGroupName} + onToggleSelection={onToggleSelection} + /> ))} ); diff --git a/Source/DataTables/for_DataTableRow/when_rendering_and_activating_a_row.tsx b/Source/DataTables/for_DataTableRow/when_rendering_and_activating_a_row.tsx new file mode 100644 index 00000000..966e4711 --- /dev/null +++ b/Source/DataTables/for_DataTableRow/when_rendering_and_activating_a_row.tsx @@ -0,0 +1,146 @@ +// 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 { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, it, vi } from 'vitest'; +import { Column } from '../Column'; +import { DataTableRow, type DataTableRowProps } from '../DataTableRow'; + +const row = { id: 1, name: 'Example product' }; + +describe('when rendering and activating a data table row', () => { + let container: HTMLDivElement; + let root: Root; + let props: DataTableRowProps; + const onActivate = vi.fn(); + const onToggleSelection = vi.fn(); + const tableRow = () => container.querySelector('tr')!; + const cells = () => container.querySelectorAll('td'); + const render = async (overrides: Partial = {}) => { + await act(async () => root.render( +
, + )); + }; + + beforeEach(async () => { + (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + props = { + row, + rowKey: 'example-1', + selectionMode: 'single', + columns: [ + , + , + , + {product.id}} />, + ], + isSelected: true, + isRowSelected: false, + isInteractive: true, + resolvedSelectionAriaLabel: 'Select example product', + selectionGroupName: 'example-selection', + rowClassName: product => `product-${product.id}`, + parts: { + row: { className: 'row-part', tabIndex: 7, title: 'Example row' }, + cell: { className: 'cell-part', style: { color: 'green', margin: '1px' }, title: 'Example cell' }, + }, + onActivate, + onToggleSelection, + }; + await render(); + }); + + afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + onActivate.mockReset(); + onToggleSelection.mockReset(); + }); + + it('should preserve row parts, state, identity, classes and interactive tab order', () => { + const element = tableRow(); + element.title.should.equal('Example row'); + element.className.should.equal('cratis-datatable__row row-part product-1'); + element.tabIndex.should.equal(0); + element.getAttribute('aria-selected')!.should.equal('true'); + element.dataset.cratisPart!.should.equal('row'); + element.dataset.datatableRowKey!.should.equal('example-1'); + element.dataset.selected!.should.equal('true'); + element.dataset.interactive!.should.equal('true'); + }); + + it('should merge cell parts before column and body styles and render field and body content', () => { + const cell = cells()[0]; + cell.title.should.equal('Example cell'); + cell.className.should.equal('cratis-datatable__cell cell-part body'); + cell.style.color.should.equal('blue'); + cell.style.padding.should.equal('2px'); + cell.style.margin.should.equal('1px'); + cell.dataset.cratisPart!.should.equal('cell'); + cell.dataset.selected!.should.equal('true'); + cell.textContent!.should.equal(row.name); + cells()[3].querySelector('strong')!.textContent!.should.equal('1'); + }); + + it('should retain radio semantics independently of the multiple-selection state', () => { + const radio = container.querySelector('input[type="radio"]')!; + radio.name.should.equal('example-selection'); + radio.readOnly.should.equal(true); + radio.tabIndex.should.equal(-1); + radio.checked.should.equal(true); + radio.getAttribute('aria-label')!.should.equal('Select example product'); + container.querySelector('input[type="checkbox"]')!.checked.should.equal(false); + }); + + it('should toggle the checkbox without activating the row', async () => { + const checkbox = container.querySelector('input[type="checkbox"]')!; + await act(async () => checkbox.click()); + onToggleSelection.mock.calls.should.have.lengthOf(1); + onActivate.mock.calls.should.have.lengthOf(0); + checkbox.getAttribute('aria-label')!.should.equal('Select example product'); + }); + + it('should activate the row once on click', async () => { + await act(async () => tableRow().click()); + onActivate.mock.calls.should.have.lengthOf(1); + }); + + it.each(['Enter', ' '])('should activate and prevent the default for %s on the row', async key => { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + await act(async () => tableRow().dispatchEvent(event)); + onActivate.mock.calls.should.have.lengthOf(1); + event.defaultPrevented.should.equal(true); + }); + + it.each(['Enter', ' '])('should ignore %s from a nested selection control', async key => { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + await act(async () => container.querySelector('input')!.dispatchEvent(event)); + onActivate.mock.calls.should.have.lengthOf(0); + event.defaultPrevented.should.equal(false); + }); + + it('should leave other row keys to their default behavior', async () => { + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + await act(async () => tableRow().dispatchEvent(event)); + onActivate.mock.calls.should.have.lengthOf(0); + event.defaultPrevented.should.equal(false); + }); + + it('should retain the consumer tab index and omit inactive state attributes', async () => { + await render({ isInteractive: false, isSelected: false, isRowSelected: true, selectionMode: 'multiple' }); + tableRow().tabIndex.should.equal(7); + tableRow().hasAttribute('aria-selected').should.equal(false); + tableRow().hasAttribute('data-selected').should.equal(false); + tableRow().hasAttribute('data-interactive').should.equal(false); + cells()[0].hasAttribute('data-selected').should.equal(false); + container.querySelector('input[type="radio"]')!.checked.should.equal(false); + container.querySelector('input[type="checkbox"]')!.checked.should.equal(true); + }); +}); From 7c6711a2bf1fae609a524f6649a4e93718052d69 Mon Sep 17 00:00:00 2001 From: woksin Date: Sat, 21 Nov 2026 18:15:26 +0100 Subject: [PATCH 3/4] Share bounded product table stories and query helpers --- .../DataTables/DataTableForQuery.stories.tsx | 117 ++++++++++-------- 1 file changed, 63 insertions(+), 54 deletions(-) diff --git a/Source/DataTables/DataTableForQuery.stories.tsx b/Source/DataTables/DataTableForQuery.stories.tsx index 9a629bc1..5c0e786d 100644 --- a/Source/DataTables/DataTableForQuery.stories.tsx +++ b/Source/DataTables/DataTableForQuery.stories.tsx @@ -3,7 +3,7 @@ import React, { useState } from 'react'; import { Meta, StoryObj } from '@storybook/react'; -import { DataTableForQuery } from './DataTableForQuery'; +import { DataTableForQuery, type DataTableForQueryProps } from './DataTableForQuery'; import { Column } from './Column'; import { Tag } from '../Display/Tag'; import { QueryFor, QueryResult, SortDirection } from '@cratis/arc/queries'; @@ -122,6 +122,25 @@ interface ServerProductsArguments { search?: string; } +const contains = (value: string, text?: string) => + !text || value.toLowerCase().includes(text.toLowerCase()); + +const matchesProduct = (product: Product, args?: ServerProductsArguments) => + contains(product.name, args?.nameContains) && + (contains(product.name, args?.search) || contains(product.category, args?.search)); + +const compareProducts = (left: Product, right: Product, field: keyof Product) => { + if (left[field] < right[field]) return -1; + return left[field] > right[field] ? 1 : 0; +}; + +const sortProducts = (products: Product[], sorting: ServerProductsQuery['sorting']) => { + if (!sorting.hasSorting) return products; + const field = sorting.field as keyof Product; + const direction = sorting.direction === SortDirection.descending ? -1 : 1; + return [...products].sort((left, right) => compareProducts(left, right, field) * direction); +}; + // Stands in for a server query that filters, sorts and pages the complete result itself, the way // an `IQueryable` query applies its filter arguments and Arc applies sorting and paging. class ServerProductsQuery extends QueryFor { @@ -135,15 +154,8 @@ class ServerProductsQuery extends QueryFor { super(Object, true); } override perform(args?: ServerProductsArguments): Promise> { - const contains = (value: string, text?: string) => !text || value.toLowerCase().includes(text.toLowerCase()); - const matching = manyProducts.filter(product => - contains(product.name, args?.nameContains) && - (contains(product.name, args?.search) || contains(product.category, args?.search))); - const field = this.sorting.field as keyof Product; - const direction = this.sorting.direction === SortDirection.descending ? -1 : 1; - const sorted = this.sorting.hasSorting - ? [...matching].sort((left, right) => (left[field] < right[field] ? -1 : left[field] > right[field] ? 1 : 0) * direction) - : matching; + const matching = manyProducts.filter(product => matchesProduct(product, args)); + const sorted = sortProducts(matching, this.sorting); const page = this.paging?.page ?? 0; const size = this.paging?.pageSize ?? 20; const first = page * size; @@ -205,34 +217,47 @@ export const Default: Story = { ) }; +interface BoundedProductsProps extends Pick< + DataTableForQueryProps, Product, TArguments>, + 'query' | 'serverQuery' | 'globalFilterFields' +> { + filterName?: boolean; +} + +const BoundedProducts = ({ + filterName = false, + ...props +}: BoundedProductsProps) => ( +
+
+ + + + + `$${rowData.price.toFixed(2)}`} + /> + +
+
+); + /** * The table's own `height: 100%` only means something inside a container that * has a height. Here it gets 560px and 24 records at a page size of 20, so the * rows scroll while the paginator stays pinned to the bottom edge. */ export const InBoundedHeight: Story = { - render: () => ( -
-
- - query={ManyProductsQuery} - emptyMessage="No products found" - dataKey="id" - > - - - - `$${rowData.price.toFixed(2)}`} - /> - -
-
- ) + render: () => }; export const WithSelection: Story = { @@ -282,27 +307,11 @@ export const WithSelection: Story = { */ export const ServerMode: Story = { render: () => ( -
-
- - query={ServerProductsQuery} - serverQuery={serverProductsQuery} - emptyMessage="No products found" - dataKey="id" - globalFilterFields={['name', 'category']} - > - - - - `$${rowData.price.toFixed(2)}`} - /> - -
-
+ ) }; From 3b51dda43b47a207693dce8a2a1c8098144d70fb Mon Sep 17 00:00:00 2001 From: woksin Date: Sat, 21 Nov 2026 18:15:30 +0100 Subject: [PATCH 4/4] Use severity lookups in observable query stories --- .../DataTableForObservableQuery.stories.tsx | 33 ++++++++----------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/Source/DataTables/DataTableForObservableQuery.stories.tsx b/Source/DataTables/DataTableForObservableQuery.stories.tsx index 7182cef0..5a1f4148 100644 --- a/Source/DataTables/DataTableForObservableQuery.stories.tsx +++ b/Source/DataTables/DataTableForObservableQuery.stories.tsx @@ -184,27 +184,20 @@ class LiveTasksQuery extends TasksQuery { // Status/priority render as theme-aware Tags with a severity, which stay // WCAG-legible on both light and dark surfaces (unlike fixed text colors). -const getStatusSeverity = (status: string): TagSeverity => { - switch (status) { - case 'done': - return 'success'; - case 'in-progress': - return 'info'; - default: - return 'secondary'; - } -}; +const statusSeverities = new Map([ + ['done', 'success'], + ['in-progress', 'info'], +]); +const prioritySeverities = new Map([ + ['high', 'danger'], + ['medium', 'warn'], +]); -const getPrioritySeverity = (priority: string): TagSeverity => { - switch (priority) { - case 'high': - return 'danger'; - case 'medium': - return 'warn'; - default: - return 'secondary'; - } -}; +const getStatusSeverity = (status: string): TagSeverity => + statusSeverities.get(status) ?? 'secondary'; + +const getPrioritySeverity = (priority: string): TagSeverity => + prioritySeverities.get(priority) ?? 'secondary'; export const Default: Story = { render: () => (