diff --git a/package.json b/package.json index 48dece8de52..d7688375239 100644 --- a/package.json +++ b/package.json @@ -183,7 +183,7 @@ { "path": "lib/components/internal/widget-exports.js", "brotli": false, - "limit": "1470 kB", + "limit": "1480 kB", "ignore": "react-dom" } ], diff --git a/pages/table-root/sorting.page.tsx b/pages/table-root/sorting.page.tsx index 599996acbdf..fd55ee150a2 100644 --- a/pages/table-root/sorting.page.tsx +++ b/pages/table-root/sorting.page.tsx @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import React, { useMemo, useState } from 'react'; +import Button from '~components/button'; import Header from '~components/header'; import Icon from '~components/icon'; import SpaceBetween from '~components/space-between'; @@ -12,46 +13,33 @@ import TableHeaderCell from '~components/table-header-cell'; import TableRoot from '~components/table-root'; import TableRow from '~components/table-row'; +import { useAppContext } from '../app/app-context'; import { SimplePage } from '../app/templates'; import { Item, makeItems } from './common'; -import styles from './styles.scss'; - type SortKey = 'name' | 'type' | 'size' | 'status'; type SortDirection = 'ascending' | 'descending'; -const COLUMNS: ReadonlyArray<{ key: SortKey; label: string }> = [ +interface SortEntry { + key: SortKey; + descending: boolean; +} + +// Status can't be sorted, to show the disabled state. +const COLUMNS: ReadonlyArray<{ key: SortKey; label: string; disabled?: boolean }> = [ { key: 'name', label: 'Name' }, { key: 'type', label: 'Type' }, { key: 'size', label: 'Size' }, - { key: 'status', label: 'Status' }, + { key: 'status', label: 'Status', disabled: true }, ]; -function compare(key: SortKey, a: Item, b: Item): number { - if (key === 'size') { - return parseInt(a.size, 10) - parseInt(b.size, 10); - } - return a[key].localeCompare(b[key]); -} - export default function TableSortingPage() { - const items = makeItems(12); - const [sortKey, setSortKey] = useState('name'); - const [direction, setDirection] = useState('ascending'); - - const rows = useMemo(() => { - const sorted = [...items].sort((a, b) => compare(sortKey, a, b)); - return direction === 'ascending' ? sorted : sorted.reverse(); - }, [items, sortKey, direction]); + const { urlParams, setUrlParams } = useAppContext<'sortKey' | 'sortDescending'>(); + const sortKey = (urlParams.sortKey as SortKey | undefined) ?? 'name'; + const descending = !!urlParams.sortDescending; - const handleSort = (key: SortKey) => { - if (key === sortKey) { - setDirection(prev => (prev === 'ascending' ? 'descending' : 'ascending')); - } else { - setSortKey(key); - setDirection('ascending'); - } - }; + const items = useMemo(() => makeItems(12), []); + const rows = useMemo(() => sortItems(items, [{ key: sortKey, descending }]), [items, sortKey, descending]); return ( @@ -60,41 +48,133 @@ export default function TableSortingPage() { - {COLUMNS.map(({ key, label }) => { - const active = key === sortKey; + {COLUMNS.map(({ key, label, disabled }) => { + const direction = key === sortKey ? toDirection(descending) : undefined; return ( - - + + ); })} - - {rows.map(item => ( - - {item.name} - {item.type} - {item.size} - {item.status} - - ))} - + +
Multi-column sort
+
); } + +function MultiSortTable({ items }: { items: Item[] }) { + const [sorting, setSorting] = useState([ + { key: 'type', descending: false }, + { key: 'size', descending: true }, + ]); + const rows = useMemo(() => sortItems(items, sorting), [items, sorting]); + + return ( + + + + {COLUMNS.map(({ key, label, disabled }) => { + const index = sorting.findIndex(entry => entry.key === key); + const entry = sorting[index]; + const direction = entry ? toDirection(entry.descending) : undefined; + const priority = sorting.length > 1 && entry ? index + 1 : undefined; + return ( + + + + ); + })} + + + + + ); +} + +// A disabled column that isn't sorted has nothing to indicate, as in the existing Table. +function sortIcon(direction: SortDirection | undefined, disabled = false) { + if (!direction) { + return disabled ? null : ; + } + return ; +} + +function ResourceRows({ rows }: { rows: Item[] }) { + return ( + + {rows.map(item => ( + + {item.name} + {item.type} + {item.size} + {item.status} + + ))} + + ); +} + +function toDirection(descending: boolean): SortDirection { + return descending ? 'descending' : 'ascending'; +} + +function sortItems(items: Item[], sorting: SortEntry[]): Item[] { + return [...items].sort((a, b) => { + for (const { key, descending } of sorting) { + const result = compare(key, a, b); + if (result !== 0) { + return descending ? -result : result; + } + } + return 0; + }); +} + +function compare(key: SortKey, a: Item, b: Item): number { + if (key === 'size') { + return parseInt(a.size, 10) - parseInt(b.size, 10); + } + return a[key].localeCompare(b[key]); +} diff --git a/pages/table-root/sticky-header.page.tsx b/pages/table-root/sticky-header.page.tsx index 258f69fe179..7d5fc8bb4bc 100644 --- a/pages/table-root/sticky-header.page.tsx +++ b/pages/table-root/sticky-header.page.tsx @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import React, { useMemo } from 'react'; +import Button from '~components/button'; import Header from '~components/header'; +import Icon from '~components/icon'; import SegmentedControl from '~components/segmented-control'; import SpaceBetween from '~components/space-between'; import TableBody from '~components/table-body'; @@ -15,8 +17,6 @@ import TableRow from '~components/table-row'; import { useAppContext } from '../app/app-context'; import { SimplePage } from '../app/templates'; -import styles from './styles.scss'; - // Wide enough to scroll sideways, and long enough to scroll the page, so the pinned header can be checked // against both. The Name header's sort button exercises pointer interaction with the pinned copy. @@ -85,14 +85,16 @@ export default function TableStickyHeaderPage() { stickyHeader={ - - + Name + Type Size diff --git a/pages/table-root/styles.scss b/pages/table-root/styles.scss index 7185bd5e95b..75be9c32a23 100644 --- a/pages/table-root/styles.scss +++ b/pages/table-root/styles.scss @@ -2,47 +2,6 @@ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ -@use '~design-tokens' as tokens; - -// A minimal sort control for the demo: a native button that inherits the header cell's colour and -// typography (so the label stays the column-header colour, not link blue). It fills the cell and -// pushes the caret to the end, so the label stays left-aligned with the column while the sort -// indicator sits at the right. -.sort-button { - display: flex; - align-items: center; - justify-content: space-between; - inline-size: 100%; - gap: tokens.$space-static-xxs; - padding-block: 0; - padding-inline: 0; - border-block: none; - border-inline: none; - background: none; - color: inherit; - font: inherit; - cursor: pointer; -} - -// Centres the selection control within a disablePaddings control cell, matching classic Table. -// The Cloudscape checkbox/radio control carries an intrinsic 2px top margin (it aligns the box with -// the first line of a label); with no visible label in a centred control column that margin biases -// the control ~1px below centre. Classic's own SelectionControl absorbs it with a compensating -// block-end padding on the control label; mirror that here so the control lands on the row centre. -.selection-cell { - display: flex; - justify-content: center; - align-items: center; - padding-block-end: 2px; -} - -// Sort affordance at the right of a sortable header (the caret icon). -.sort-indicator { - display: inline-flex; - align-items: center; - gap: tokens.$space-static-xxs; -} - // A fixed-height region that scrolls its table in both directions. .scroll-container { block-size: 400px; diff --git a/src/__tests__/snapshot-tests/__snapshots__/documenter.test.ts.snap b/src/__tests__/snapshot-tests/__snapshots__/documenter.test.ts.snap index b369da37cbd..b0cf9ef6fbe 100644 --- a/src/__tests__/snapshot-tests/__snapshots__/documenter.test.ts.snap +++ b/src/__tests__/snapshot-tests/__snapshots__/documenter.test.ts.snap @@ -6281,7 +6281,9 @@ This property only applies when an \`href\` is provided.", * \`link\` for tertiary buttons. * \`icon\` to display an icon only (no text). * \`inline-icon\` to display an icon-only (no text) button within a text context. -* \`inline-link\` to display a tertiary button with no outer padding.", +* \`inline-link\` to display a tertiary button with no outer padding. +* \`table-header\` to fill a table column header, for example to sort the column. Place it in a \`TableHeaderCell\` + with \`disablePaddings="headerButton"\`, use \`iconEnd\` for a sort indicator, and set \`formAction="none"\` inside forms.", "inlineType": { "name": "ButtonProps.Variant", "type": "union", @@ -6292,6 +6294,7 @@ This property only applies when an \`href\` is provided.", "primary", "inline-icon", "inline-link", + "table-header", ], }, "name": "variant", @@ -6321,6 +6324,14 @@ Do not place interactive elements like links or buttons.", "isDefault": false, "name": "disabledReason", }, + { + "description": "Displays content after the text, for example a sort indicator with its sort priority. +Use \`Icon\` components, which inherit the button's color. Pass \`null\` when there's nothing to show. + +Don't combine it with a right-aligned icon (\`iconAlign="right"\`).", + "isDefault": false, + "name": "iconEnd", + }, { "description": "Specifies the SVG of a custom icon. @@ -31078,10 +31089,23 @@ exports[`Components definition for table-header-cell matches the snapshot: table "type": "string", }, { - "description": "Removes the cell's built-in padding so you can compose your own spacing. Defaults to \`false\`.", + "description": "Removes the cell's built-in padding so you can compose your own spacing. +* \`true\` - Removes all padding. +* \`headerButton\` - Leaves the content padding to a \`Button\` with \`variant="table-header"\`. + +Defaults to \`false\`.", + "inlineType": { + "name": "boolean | "headerButton"", + "type": "union", + "values": [ + "false", + "true", + ""headerButton"", + ], + }, "name": "disablePaddings", "optional": true, - "type": "boolean", + "type": "boolean | "headerButton"", }, { "deprecatedTag": "The usage of the \`id\` attribute is reserved for internal use cases. For testing and other use cases, @@ -36600,6 +36624,20 @@ The dismiss button is only rendered when the \`dismissible\` property is set to ], }, }, + { + "description": "Returns the content of the \`iconEnd\` slot, or \`null\` if there isn't any.", + "name": "findIconEnd", + "parameters": [], + "returnType": { + "isNullable": true, + "name": "ElementWrapper", + "typeArguments": [ + { + "name": "HTMLElement", + }, + ], + }, + }, { "name": "findLoadingIndicator", "parameters": [], @@ -40223,6 +40261,23 @@ To find a specific item use the \`findBreadcrumbLink(n)\` function as chaining \ ], }, }, + { + "description": "Returns the content of the \`iconEnd\` slot, or \`null\` if there isn't any.", + "inheritedFrom": { + "name": "ButtonWrapper.findIconEnd", + }, + "name": "findIconEnd", + "parameters": [], + "returnType": { + "isNullable": true, + "name": "ElementWrapper", + "typeArguments": [ + { + "name": "HTMLElement", + }, + ], + }, + }, { "inheritedFrom": { "name": "ButtonWrapper.findLoadingIndicator", @@ -50306,6 +50361,15 @@ The dismiss button is only rendered when the \`dismissible\` property is set to "name": "ElementWrapper", }, }, + { + "description": "Returns the content of the \`iconEnd\` slot, or \`null\` if there isn't any.", + "name": "findIconEnd", + "parameters": [], + "returnType": { + "isNullable": false, + "name": "ElementWrapper", + }, + }, { "name": "findLoadingIndicator", "parameters": [], @@ -52894,6 +52958,18 @@ To find a specific item use the \`findBreadcrumbLink(n)\` function as chaining \ "name": "ElementWrapper", }, }, + { + "description": "Returns the content of the \`iconEnd\` slot, or \`null\` if there isn't any.", + "inheritedFrom": { + "name": "ButtonWrapper.findIconEnd", + }, + "name": "findIconEnd", + "parameters": [], + "returnType": { + "isNullable": false, + "name": "ElementWrapper", + }, + }, { "inheritedFrom": { "name": "ButtonWrapper.findLoadingIndicator", diff --git a/src/__tests__/snapshot-tests/__snapshots__/test-utils-selectors.test.tsx.snap b/src/__tests__/snapshot-tests/__snapshots__/test-utils-selectors.test.tsx.snap index 961856949e3..9f8eb776052 100644 --- a/src/__tests__/snapshot-tests/__snapshots__/test-utils-selectors.test.tsx.snap +++ b/src/__tests__/snapshot-tests/__snapshots__/test-utils-selectors.test.tsx.snap @@ -94,6 +94,7 @@ exports[`test-utils selectors 1`] = ` "awsui_button_vjswe", "awsui_content_vjswe", "awsui_disabled-reason-tooltip_1ueyk", + "awsui_icon-end_vjswe", "awsui_icon-left_vjswe", ], "button-dropdown": [ diff --git a/src/button/__tests__/button.test.tsx b/src/button/__tests__/button.test.tsx index 438855a92ad..d59750a6b19 100644 --- a/src/button/__tests__/button.test.tsx +++ b/src/button/__tests__/button.test.tsx @@ -542,6 +542,35 @@ describe('Button Component', () => { }); }); + describe('iconEnd property', () => { + test('renders the slot after the text', () => { + const wrapper = renderButton({ children: 'Name', iconEnd: 1 }); + expect(wrapper.findIconEnd()!.find('[data-testid="end"]')).not.toBeNull(); + expect(wrapper.findTextRegion()!.getElement().nextElementSibling).toBe(wrapper.findIconEnd()!.getElement()); + }); + + test('renders no slot by default', () => { + expect(renderButton({ children: 'Name' }).findIconEnd()).toBeNull(); + }); + + test.each([null, false, ''])('renders no slot for %p', iconEnd => { + expect(renderButton({ children: 'Name', iconEnd }).findIconEnd()).toBeNull(); + }); + + test('renders the slot for 0', () => { + expect(renderButton({ children: 'Name', iconEnd: 0 }).findIconEnd()!.getElement()).toHaveTextContent('0'); + }); + + test('warns when combined with a right-aligned icon', () => { + const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + renderButton({ children: 'Name', iconName: 'add-plus', iconAlign: 'right', iconEnd: }); + expect(warnSpy).toHaveBeenCalledWith( + '[AwsUi] [Button] A right-aligned icon should not be combined with `iconEnd`.' + ); + warnSpy.mockRestore(); + }); + }); + describe('Loading property', () => { test("should disable the button with aria-disabled when in 'loading' status", () => { const onClickSpy = jest.fn(); diff --git a/src/button/constants.scss b/src/button/constants.scss index 20c59555caf..708d6512215 100644 --- a/src/button/constants.scss +++ b/src/button/constants.scss @@ -181,4 +181,20 @@ $variants: ( 'disabled-border-color': transparent, 'disabled-color': awsui.$color-text-interactive-disabled, ), + 'table-header': ( + 'default-background': transparent, + 'default-border-color': transparent, + 'default-color': inherit, + 'hover-background': transparent, + 'hover-border-color': transparent, + 'hover-color': awsui.$color-text-interactive-active, + 'active-background': transparent, + 'active-border-color': transparent, + 'active-color': awsui.$color-text-interactive-active, + 'disabled-background': transparent, + 'disabled-border-color': transparent, + 'disabled-color': inherit, + 'border-width': 0, + 'font-weight': awsui.$font-weight-heading-s, + ), ); diff --git a/src/button/index.tsx b/src/button/index.tsx index e0ae555256c..9bba6a668f0 100644 --- a/src/button/index.tsx +++ b/src/button/index.tsx @@ -17,6 +17,7 @@ const Button = React.forwardRef( children, iconName, iconAlign = 'left', + iconEnd, iconUrl, iconSvg, iconAlt, @@ -61,6 +62,7 @@ const Button = React.forwardRef( ref={ref} iconName={iconName} iconAlign={iconAlign} + iconEnd={iconEnd} iconUrl={iconUrl} iconSvg={iconSvg} iconAlt={iconAlt} diff --git a/src/button/interfaces.ts b/src/button/interfaces.ts index ced1c609a36..8823d83e0d5 100644 --- a/src/button/interfaces.ts +++ b/src/button/interfaces.ts @@ -145,6 +145,14 @@ export interface ButtonProps extends BaseComponentProps, BaseButtonProps { */ iconAlign?: ButtonProps.IconAlign; + /** + * Displays content after the text, for example a sort indicator with its sort priority. + * Use `Icon` components, which inherit the button's color. Pass `null` when there's nothing to show. + * + * Don't combine it with a right-aligned icon (`iconAlign="right"`). + */ + iconEnd?: React.ReactNode; + /** * The form action that is performed by a button click. */ @@ -213,6 +221,8 @@ export interface ButtonProps extends BaseComponentProps, BaseButtonProps { * * `icon` to display an icon only (no text). * * `inline-icon` to display an icon-only (no text) button within a text context. * * `inline-link` to display a tertiary button with no outer padding. + * * `table-header` to fill a table column header, for example to sort the column. Place it in a `TableHeaderCell` + * with `disablePaddings="headerButton"`, use `iconEnd` for a sort indicator, and set `formAction="none"` inside forms. */ variant?: ButtonProps.Variant; @@ -231,7 +241,7 @@ export interface ButtonProps extends BaseComponentProps, BaseButtonProps { } export namespace ButtonProps { - export type Variant = 'normal' | 'primary' | 'link' | 'icon' | 'inline-icon' | 'inline-link'; + export type Variant = 'normal' | 'primary' | 'link' | 'icon' | 'inline-icon' | 'inline-link' | 'table-header'; export type ClickDetail = _ClickDetail; export type FollowDetail = BaseNavigationDetail; diff --git a/src/button/internal.tsx b/src/button/internal.tsx index 9fd71577a90..d5bfd0adb47 100644 --- a/src/button/internal.tsx +++ b/src/button/internal.tsx @@ -78,6 +78,7 @@ export const InternalButton = React.forwardRef( onClick, onFollow, iconAlign = 'left', + iconEnd, iconUrl, iconSvg, iconAlt, @@ -149,6 +150,11 @@ export const InternalButton = React.forwardRef( if ((iconName || iconUrl || iconSvg) && iconAlign === 'right' && external) { warnOnce('Button', 'A right-aligned icon should not be combined with an external icon.'); } + // React renders nothing for these, but it does render `0`. + const hasIconEnd = iconEnd !== undefined && iconEnd !== null && iconEnd !== false && iconEnd !== ''; + if ((iconName || iconUrl || iconSvg) && iconAlign === 'right' && hasIconEnd) { + warnOnce('Button', 'A right-aligned icon should not be combined with `iconEnd`.'); + } const buttonRef = useRef(null); useForwardFocus(ref, buttonRef); @@ -289,6 +295,7 @@ export const InternalButton = React.forwardRef( )} )} + {hasIconEnd && {iconEnd}} ); diff --git a/src/button/styles.scss b/src/button/styles.scss index 1678ac0b4ee..766c21c5283 100644 --- a/src/button/styles.scss +++ b/src/button/styles.scss @@ -214,6 +214,12 @@ $tokens: style-api.resolve(style-api.$focus-ring, carrier); margin-inline-start: awsui.$space-xxs; } + > .icon-end { + position: relative; + inset-inline-end: calc(-1 * #{awsui.$space-xxs}); + margin-inline-start: awsui.$space-xxs; + } + &.variant-inline-link { text-decoration-line: awsui.$font-decoration-line-button-inline-link; text-underline-offset: 3.5px; @@ -229,6 +235,77 @@ $tokens: style-api.resolve(style-api.$focus-ring, carrier); } } + // Fills a table header cell, which keeps its inline padding as the space around the button. + // The cell's content wrapper doesn't draw a box but still sets the content padding for its column (for example + // none for the first column), and the button inherits it, so its whole area is clickable. + &.variant-table-header { + display: flex; + align-items: center; + box-sizing: border-box; + inline-size: 100%; + min-inline-size: 0; + text-align: start; + font-size: inherit; + letter-spacing: normal; + // Keeps a header's minimum width at its longest word, so a wrapping header cannot shrink the column below it. + word-break: normal; + border-start-start-radius: 0; + border-start-end-radius: 0; + border-end-start-radius: 0; + border-end-end-radius: 0; + padding-block: inherit; + padding-inline: inherit; + + > .content { + flex: 1; + min-inline-size: 0; + line-height: awsui.$line-height-heading-xs; + padding-block: calc(#{awsui.$space-xxxs} / 2); + } + + &.button-no-wrap > .content { + overflow: hidden; + text-overflow: ellipsis; + } + + // With a 16px icon the text ends where the existing Table's does: the icon sits 4px from the end, after an 8px gap. + > .icon-end { + display: flex; + align-items: center; + flex-shrink: 0; + inset-inline-end: 0; + margin-inline-start: awsui.$space-xs; + margin-inline-end: calc(#{awsui.$space-xxs} - #{awsui.$space-s}); + } + + &.disabled > .icon-end { + color: awsui.$color-text-interactive-disabled; + } + + // The button spans the full height of the header row, and its ring sits inside it above and below, as on the + // column resize handle. Inline the ring sits outside the button, as on other buttons; the cell's padding leaves + // room for it. + @mixin table-header-focus-ring { + @include style-api.focus-highlight( + $gutter-block: calc(#{awsui.$space-table-header-focus-outline-gutter} - 2px), + $radius: var(#{custom-props.$styleFocusRingBorderRadius}, awsui.$border-radius-control-default-focus-ring), + $width: var(#{custom-props.$styleFocusRingBorderWidth}, foundation.$box-shadow-focused-width), + $color: $focus-border-color + ); + } + + @include focus-visible.when-visible { + @include table-header-focus-ring; + } + + // Mirrors the focus of another element, for example in the table root's sticky header copy. + &.fake-focus { + @include focus-visible.when-visible-unfocused { + @include table-header-focus-ring; + } + } + } + &.button-no-text > .icon { margin-inline-start: auto; margin-inline-end: auto; diff --git a/src/internal/components/sticky-scrollbar/__tests__/update-position.test.ts b/src/internal/components/sticky-scrollbar/__tests__/update-position.test.ts index 00b0769f19a..097979e3365 100644 --- a/src/internal/components/sticky-scrollbar/__tests__/update-position.test.ts +++ b/src/internal/components/sticky-scrollbar/__tests__/update-position.test.ts @@ -37,4 +37,11 @@ describe('updatePosition', () => { expect(scrollbar.style.inlineSize).toBe('600px'); expect(scrollbarContent.style.inlineSize).toBe('1200px'); }); + + test("sizes the scrollbar from a custom measurement of the wrapper's visible width when one is given", () => { + const { scrollbar, scrollbarContent, table, wrapper } = setupElements(); + updatePosition(table, wrapper, scrollbar, scrollbarContent, true, undefined, () => 594); + expect(scrollbar.style.inlineSize).toBe('594px'); + expect(scrollbarContent.style.inlineSize).toBe('800px'); + }); }); diff --git a/src/internal/components/sticky-scrollbar/sticky-scrollbar.tsx b/src/internal/components/sticky-scrollbar/sticky-scrollbar.tsx index 282d85c38f7..e032b0a6dd7 100644 --- a/src/internal/components/sticky-scrollbar/sticky-scrollbar.tsx +++ b/src/internal/components/sticky-scrollbar/sticky-scrollbar.tsx @@ -22,7 +22,15 @@ interface StickyScrollbarProps extends StickyScrollbarContentOptions { export default forwardRef(StickyScrollbar); function StickyScrollbar( - { wrapperRef, tableRef, onScroll, hasStickyColumns, getContentInlineSize, contentKey }: StickyScrollbarProps, + { + wrapperRef, + tableRef, + onScroll, + hasStickyColumns, + getContentInlineSize, + getWrapperInlineSize, + contentKey, + }: StickyScrollbarProps, ref: React.Ref ) { const isVisualRefresh = useVisualRefresh(); @@ -38,6 +46,7 @@ function StickyScrollbar( useStickyScrollbar(scrollbarRef, scrollbarContentRef, tableRef, wrapperRef, offsetScrollbar, { getContentInlineSize, + getWrapperInlineSize, contentKey, }); diff --git a/src/internal/components/sticky-scrollbar/use-sticky-scrollbar.ts b/src/internal/components/sticky-scrollbar/use-sticky-scrollbar.ts index 41241fc375c..b7833ae4504 100644 --- a/src/internal/components/sticky-scrollbar/use-sticky-scrollbar.ts +++ b/src/internal/components/sticky-scrollbar/use-sticky-scrollbar.ts @@ -12,6 +12,7 @@ import { getOverflowParents } from '../../utils/scrollable-containers'; import styles from './styles.css.js'; type ContentInlineSizeGetter = (tableEl: HTMLElement, wrapperEl: HTMLElement) => number; +type WrapperInlineSizeGetter = (wrapperEl: HTMLElement) => number; export const updatePosition = ( tableEl: HTMLElement | null, @@ -19,14 +20,15 @@ export const updatePosition = ( scrollbarEl: HTMLElement | null, scrollbarContentEl: HTMLElement | null, inScrollableContainer: boolean, - getContentInlineSize: ContentInlineSizeGetter = tableEl => getLogicalBoundingClientRect(tableEl).inlineSize + getContentInlineSize: ContentInlineSizeGetter = tableEl => getLogicalBoundingClientRect(tableEl).inlineSize, + getWrapperInlineSize: WrapperInlineSizeGetter = wrapperEl => getLogicalBoundingClientRect(wrapperEl).inlineSize ) => { if (!tableEl || !scrollbarEl || !wrapperEl) { return; } const tableInlineSize = getContentInlineSize(tableEl, wrapperEl); - const { inlineSize: wrapperInlineSize } = getLogicalBoundingClientRect(wrapperEl); + const wrapperInlineSize = getWrapperInlineSize(wrapperEl); // using 15 px as a height of transparent scrollbar on mac const scrollbarHeight = browserScrollbarSize().height; @@ -70,6 +72,8 @@ export const updatePosition = ( export interface StickyScrollbarContentOptions { // Measures the scrollable content's width; defaults to the table's width. getContentInlineSize?: ContentInlineSizeGetter; + // Measures the visible width of the wrapper, which is the scrollbar's track; defaults to the wrapper's width. + getWrapperInlineSize?: WrapperInlineSizeGetter; // Re-measures when this changes, for content that changes width without resizing the table or wrapper. contentKey?: unknown; } @@ -80,11 +84,13 @@ export function useStickyScrollbar( tableRef: RefObject, wrapperRef: RefObject, offsetScrollbar: boolean, - { getContentInlineSize, contentKey }: StickyScrollbarContentOptions + { getContentInlineSize, getWrapperInlineSize, contentKey }: StickyScrollbarContentOptions ) { const [inScrollableContainer, setInScrollableContainer] = useState(false); const getContentInlineSizeRef = useRef(getContentInlineSize); getContentInlineSizeRef.current = getContentInlineSize; + const getWrapperInlineSizeRef = useRef(getWrapperInlineSize); + getWrapperInlineSizeRef.current = getWrapperInlineSize; const wrapperEl = wrapperRef.current; useEffect(() => { @@ -104,7 +110,8 @@ export function useStickyScrollbar( scrollbarRef.current, scrollbarContentRef.current, inScrollableContainer, - getContentInlineSizeRef.current + getContentInlineSizeRef.current, + getWrapperInlineSizeRef.current ); } }); @@ -128,7 +135,8 @@ export function useStickyScrollbar( scrollbarRef.current, scrollbarContentRef.current, inScrollableContainer, - getContentInlineSizeRef.current + getContentInlineSizeRef.current, + getWrapperInlineSizeRef.current ); }; resizeHandler(); diff --git a/src/table-header-cell/__tests__/padding.test.tsx b/src/table-header-cell/__tests__/padding.test.tsx new file mode 100644 index 00000000000..680b1eb946f --- /dev/null +++ b/src/table-header-cell/__tests__/padding.test.tsx @@ -0,0 +1,55 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import React from 'react'; +import { render } from '@testing-library/react'; + +import TableHead from '../../../lib/components/table-head'; +import TableHeaderCell, { TableHeaderCellProps } from '../../../lib/components/table-header-cell'; +import TableRoot from '../../../lib/components/table-root'; +import TableRow from '../../../lib/components/table-row'; +import createWrapper from '../../../lib/components/test-utils/dom'; + +import tableHeaderCellStyles from '../../../lib/components/table/header-cell/styles.css.js'; +import styles from '../../../lib/components/table-header-cell/styles.css.js'; + +describe('TableHeaderCell disablePaddings', () => { + test.each<[TableHeaderCellProps['disablePaddings'], string]>([ + [undefined, 'padded-content'], + [false, 'padded-content'], + [true, 'disable-paddings'], + ['headerButton', 'header-button'], + ])('disablePaddings=%p applies the %s padding mode', (disablePaddings, mode) => { + const cell = renderHeaderCell(disablePaddings); + const modes = ['padded-content', 'disable-paddings', 'header-button']; + modes.forEach(other => expect(cell.classList.contains(styles[other])).toBe(other === mode)); + }); + + test.each([undefined, true, 'headerButton'])( + "disablePaddings=%p doesn't apply the existing Table's cell padding", + disablePaddings => { + expect(renderHeaderCell(disablePaddings)).not.toHaveClass(tableHeaderCellStyles['with-paddings']); + } + ); + + test('keeps the content wrapper for a header button, which inherits its padding', () => { + const cell = renderHeaderCell('headerButton', ); + expect(cell.firstElementChild).toHaveClass(styles['header-cell-content']); + expect(cell.firstElementChild!.firstElementChild!.tagName).toBe('BUTTON'); + }); +}); + +function renderHeaderCell( + disablePaddings: TableHeaderCellProps['disablePaddings'], + children: React.ReactNode = 'Name' +) { + const { container } = render( + + + + {children} + + + + ); + return createWrapper(container).findTableHeaderCell()!.getElement(); +} diff --git a/src/table-header-cell/interfaces.ts b/src/table-header-cell/interfaces.ts index c5943cc7908..4dd4bd7c2e2 100644 --- a/src/table-header-cell/interfaces.ts +++ b/src/table-header-cell/interfaces.ts @@ -17,9 +17,13 @@ export interface TableHeaderCellProps extends BaseComponentProps { */ ariaSort?: React.AriaAttributes['aria-sort']; /** - * Removes the cell's built-in padding so you can compose your own spacing. Defaults to `false`. + * Removes the cell's built-in padding so you can compose your own spacing. + * * `true` - Removes all padding. + * * `headerButton` - Leaves the content padding to a `Button` with `variant="table-header"`. + * + * Defaults to `false`. */ - disablePaddings?: boolean; + disablePaddings?: boolean | 'headerButton'; /** The header content, such as a column label or a sort control. */ children?: React.ReactNode; } diff --git a/src/table-header-cell/internal.tsx b/src/table-header-cell/internal.tsx index 2d955d30df2..0d1bc9d8e46 100644 --- a/src/table-header-cell/internal.tsx +++ b/src/table-header-cell/internal.tsx @@ -64,8 +64,12 @@ export const InternalTableHeaderCell = React.forwardRef .header-cell-content { padding-block: 0; padding-inline: 0; } -// VR-gated: the substrate is shared with the existing Table, which still supports non-VR mode. -.header-cell.is-visual-refresh:first-child > .header-cell-content { +.header-cell.header-button.header-button > .header-cell-content { + display: contents; + padding-block: calc(#{$gap-block} + #{$content-block}); + padding-inline-start: calc(#{$gap-inline} + #{$content-inline} - #{$button-gap-inline-start}); + padding-inline-end: calc(#{$content-inline} - #{$button-ring-room}); +} + +.header-cell.padded-content.padded-content > .header-cell-content { + padding-block: calc(#{$gap-block} + #{$content-block}); + padding-inline: calc(#{$gap-inline} + #{$content-inline}); +} + +.header-cell.padded-content.padded-content:last-child > .header-cell-content { + padding-inline-end: calc(#{$gap-inline-end-last} + #{$content-inline}); +} + +.header-cell.header-button.header-button.is-visual-refresh:first-child > .header-cell-content { padding-inline-start: 0; } +.header-cell.padded-content.padded-content.is-visual-refresh:first-child > .header-cell-content { + padding-inline-start: $gap-inline-start-first; +} + // Stretch to the row track, else an empty control header collapses to ~1px, leaving a stray divider stub. .header-cell-grid { min-inline-size: 0; diff --git a/src/table-root/__tests__/scroller-content-size.test.ts b/src/table-root/__tests__/scroller-content-size.test.ts new file mode 100644 index 00000000000..abc241575c7 --- /dev/null +++ b/src/table-root/__tests__/scroller-content-size.test.ts @@ -0,0 +1,41 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import { + getScrollerContentInlineSize, + getScrollerVisibleInlineSize, +} from '../../../lib/components/table-root/internal'; + +describe('getScrollerContentInlineSize', () => { + test('measures overflowing content without the scroller padding', () => { + expect(getScrollerContentInlineSize(table(), scroller({ scrollWidth: 1004, clientWidth: 604, width: 604 }))).toBe( + 1000 + ); + }); + + test('measures content that fits as the scroller width, without the scroller padding', () => { + expect(getScrollerContentInlineSize(table(), scroller({ scrollWidth: 604, clientWidth: 604, width: 604.5 }))).toBe( + 600.5 + ); + }); +}); + +describe('getScrollerVisibleInlineSize', () => { + test('measures the scroller width without its inline padding', () => { + const element = scroller({ scrollWidth: 604, clientWidth: 604, width: 604 }); + element.style.paddingInlineEnd = '2px'; + expect(getScrollerVisibleInlineSize(element)).toBe(598); + }); +}); + +function table() { + return document.createElement('table'); +} + +function scroller({ scrollWidth, clientWidth, width }: { scrollWidth: number; clientWidth: number; width: number }) { + const element = document.createElement('div'); + element.style.paddingInlineStart = '4px'; + Object.defineProperty(element, 'scrollWidth', { value: scrollWidth }); + Object.defineProperty(element, 'clientWidth', { value: clientWidth }); + element.getBoundingClientRect = () => ({ width }) as DOMRect; + return element; +} diff --git a/src/table-root/__tests__/sticky-header.test.tsx b/src/table-root/__tests__/sticky-header.test.tsx index 3eb20103f0f..985952268fa 100644 --- a/src/table-root/__tests__/sticky-header.test.tsx +++ b/src/table-root/__tests__/sticky-header.test.tsx @@ -3,6 +3,7 @@ import React from 'react'; import { fireEvent, render } from '@testing-library/react'; +import Button from '../../../lib/components/button'; import Checkbox from '../../../lib/components/checkbox'; import TableBody from '../../../lib/components/table-body'; import TableBodyCell from '../../../lib/components/table-body-cell'; @@ -11,6 +12,7 @@ import TableHeaderCell from '../../../lib/components/table-header-cell'; import TableRoot, { TableRootProps } from '../../../lib/components/table-root'; import TableRow from '../../../lib/components/table-row'; +import buttonStyles from '../../../lib/components/button/styles.css.js'; import abstractSwitchStyles from '../../../lib/components/internal/components/abstract-switch/styles.selectors.js'; import styles from '../../../lib/components/table-root/styles.selectors.js'; @@ -128,6 +130,36 @@ describe('TableRoot sticky header', () => { expect(copyButton).not.toHaveClass(styles['sticky-copy-focus']); }); + test('shows a table header button its own focus ring in the copy', () => { + const { container } = render( + + + + + + Status + + + } + > + + + ); + const realButton = findRealTable(container).querySelector('button')!; + const copyButton = findSlot(container)!.querySelector('button')!; + + fireEvent.focus(realButton); + expect(copyButton).toHaveClass(buttonStyles['fake-focus']); + expect(copyButton).not.toHaveClass(styles['sticky-copy-focus']); + + fireEvent.blur(realButton); + expect(copyButton).not.toHaveClass(buttonStyles['fake-focus']); + }); + test('hides the real header under the copy and restores it when sticky is turned off', () => { const restore = mockRects(element => (element.tagName === 'THEAD' ? { height: 40 } : undefined)); try { diff --git a/src/table-root/internal.tsx b/src/table-root/internal.tsx index ebba59729c5..09119d212e3 100644 --- a/src/table-root/internal.tsx +++ b/src/table-root/internal.tsx @@ -3,7 +3,11 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import clsx from 'clsx'; -import { useMergeRefs, useResizeObserver } from '@cloudscape-design/component-toolkit/internal'; +import { + getLogicalBoundingClientRect, + useMergeRefs, + useResizeObserver, +} from '@cloudscape-design/component-toolkit/internal'; import { getBaseProps } from '../internal/base-component'; import { StickyScrollbar } from '../internal/components/sticky-scrollbar'; @@ -22,10 +26,22 @@ export interface InternalTableRootProps extends TableRootProps, InternalBaseComp // In grid layout the rows overflow the table element, so the scroller, not the table, measures the // scrollable width. scrollWidth is rounded to a whole pixel, so content that fits a fractional-width // scroller reports the scroller's own width instead, using the same tolerance as measureScrollable. -function getScrollerContentInlineSize(_table: HTMLElement, scroller: HTMLElement) { - return scroller.scrollWidth - scroller.clientWidth > 1 - ? scroller.scrollWidth - : scroller.getBoundingClientRect().width; +// The scroller's inline padding (room for focus rings at the table's edges) is part of neither the content nor +// the visible track of the sticky scrollbar. +function getScrollerInlinePadding(scroller: HTMLElement) { + const { paddingInlineStart, paddingInlineEnd } = getComputedStyle(scroller); + return (parseFloat(paddingInlineStart) || 0) + (parseFloat(paddingInlineEnd) || 0); +} + +export function getScrollerContentInlineSize(_table: HTMLElement, scroller: HTMLElement) { + return ( + (scroller.scrollWidth - scroller.clientWidth > 1 ? scroller.scrollWidth : scroller.getBoundingClientRect().width) - + getScrollerInlinePadding(scroller) + ); +} + +export function getScrollerVisibleInlineSize(scroller: HTMLElement) { + return getLogicalBoundingClientRect(scroller).inlineSize - getScrollerInlinePadding(scroller); } export default function InternalTableRoot({ @@ -141,6 +157,7 @@ export default function InternalTableRoot({ tableRef={sticky.realTableRef} onScroll={handleScroll} getContentInlineSize={getScrollerContentInlineSize} + getWrapperInlineSize={getScrollerVisibleInlineSize} contentKey={gridTemplateColumns} /> diff --git a/src/table-root/styles.scss b/src/table-root/styles.scss index 0af4f9c95a7..3b82b6fcb6e 100644 --- a/src/table-root/styles.scss +++ b/src/table-root/styles.scss @@ -20,6 +20,10 @@ // Its scrollbar is hidden in favour of the sticky scrollbar, which stays reachable however tall the body is. .body-scroller { overflow-x: auto; + // Leaves room before the table's start edge for focus rings, such as a first-column header button's, without + // moving the table. Only the start: browsers leave inline-end padding out of the scrollable area. + padding-inline-start: awsui.$space-button-focus-outline-gutter; + margin-inline-start: calc(-1 * #{awsui.$space-button-focus-outline-gutter}); @include sticky-scrollbar.hidden-scrollbar; @include focus-visible.when-visible { @include styles.container-focus(); @@ -60,6 +64,9 @@ .sticky-copy-scroller { @include sticky-header.copy-scroller; + // The same room before the table's start edge as the body scroller, so the two stay aligned. + padding-inline-start: awsui.$space-button-focus-outline-gutter; + margin-inline-start: calc(-1 * #{awsui.$space-button-focus-outline-gutter}); } .sticky-copy-focus { diff --git a/src/table-root/use-sticky-header.ts b/src/table-root/use-sticky-header.ts index d464dbf3f92..9a97166af7c 100644 --- a/src/table-root/use-sticky-header.ts +++ b/src/table-root/use-sticky-header.ts @@ -9,6 +9,7 @@ import { useUntabbableDescendants } from '../internal/components/sticky-header/u import useMouseDownTarget from '../internal/hooks/use-mouse-down-target'; import { setElementWidths } from '../table/column-widths-utils'; +import buttonStyles from '../button/styles.css.js'; import abstractSwitchStyles from '../internal/components/abstract-switch/styles.css.js'; import styles from './styles.css.js'; @@ -119,6 +120,7 @@ export function useTableRootStickyHeader({ // The real header is covered by the copy, so the copy shows its focus ring. A checkbox or radio draws its // ring on the outline next to its hidden input, which is shown only for keyboard focus, like other rings. + // A table header button draws its own ring, which sits outside it inline. const [focusedHeaderPath, setFocusedHeaderPath] = useState(null); useLayoutEffect(() => { const copyElement = @@ -128,10 +130,13 @@ export function useTableRootStickyHeader({ isKeyboardFocus && copyElement?.nextElementSibling?.classList.contains(abstractSwitchStyles.outline) ? copyElement.nextElementSibling : null; - copyElement?.classList.add(styles['sticky-copy-focus']); + const focusClass = copyElement?.classList.contains(buttonStyles['variant-table-header']) + ? buttonStyles['fake-focus'] + : styles['sticky-copy-focus']; + copyElement?.classList.add(focusClass); switchOutline?.classList.add(abstractSwitchStyles['show-outline']); return () => { - copyElement?.classList.remove(styles['sticky-copy-focus']); + copyElement?.classList.remove(focusClass); switchOutline?.classList.remove(abstractSwitchStyles['show-outline']); }; }); diff --git a/src/test-utils/dom/button/index.ts b/src/test-utils/dom/button/index.ts index 12af65e2bee..963ff72e59e 100644 --- a/src/test-utils/dom/button/index.ts +++ b/src/test-utils/dom/button/index.ts @@ -17,6 +17,13 @@ export default class ButtonWrapper extends ComponentWrapper { return this.find(`.${styles.content}`); } + /** + * Returns the content of the `iconEnd` slot, or `null` if there isn't any. + */ + findIconEnd(): ElementWrapper | null { + return this.findByClassName(styles['icon-end']); + } + @usesDom isDisabled(): boolean { return this.element.disabled || this.element.getAttribute('aria-disabled') === 'true';