Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/core/table/sort-button/__tests__/sort-button.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { render, screen } from '@testing-library/react'
import { TableCellSortButton } from '../sort-button'

test('renders as a button element', () => {
render(
<TableCellSortButton name="address" value="none">
Property
</TableCellSortButton>,
)
expect(screen.getByRole('button', { name: 'Property' })).toBeVisible()
})

test('renders an ARIA hidden icon', () => {
const { container } = render(
<TableCellSortButton name="address" value="none">
Property
</TableCellSortButton>,
)
expect(container.querySelector('svg')).toBeInTheDocument()
})

test('has .el-table-cell-sort-button class', () => {
render(
<TableCellSortButton name="address" value="none">
Property
</TableCellSortButton>,
)
expect(screen.getByRole('button')).toHaveClass('el-table-cell-sort-button')
})

test('accepts other classes', () => {
render(
<TableCellSortButton className="custom-class" name="address" value="none">
Property
</TableCellSortButton>,
)
expect(screen.getByRole('button')).toHaveClass('el-table-cell-sort-button custom-class')
})

test('forwards additional props to the button', () => {
render(
<TableCellSortButton data-testid="test-id" name="address" value="none">
Property
</TableCellSortButton>,
)
expect(screen.getByTestId('test-id')).toBe(screen.getByRole('button'))
})
41 changes: 41 additions & 0 deletions src/core/table/sort-button/__tests__/sort-direction.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { parseSortDirection, getNextSortDirection } from '../sort-direction'

describe('parseSortDirection', () => {
test('returns "ascending" when value is "ascending"', () => {
expect(parseSortDirection('ascending')).toBe('ascending')
})

test('returns "descending" when value is "ascending"', () => {
expect(parseSortDirection('descending')).toBe('descending')
})

test('returns "none" for all other values', () => {
expect(parseSortDirection('none')).toBe('none')

// invalid sort directions
expect(parseSortDirection(0)).toBe('none')
expect(parseSortDirection(null)).toBe('none')
expect(parseSortDirection(undefined)).toBe('none')
expect(parseSortDirection('invalid')).toBe('none')
})
})

describe('getNextSortDirection', () => {
test('returns "ascending" when current value is "descending"', () => {
expect(getNextSortDirection('descending')).toBe('ascending')
})

test('returns "descending" when current value is "ascending"', () => {
expect(getNextSortDirection('ascending')).toBe('descending')
})

test('returns "descending" for all other current values', () => {
expect(getNextSortDirection('none')).toBe('descending')

// invalid sort directions
expect(getNextSortDirection(0)).toBe('descending')
expect(getNextSortDirection(null)).toBe('descending')
expect(getNextSortDirection(undefined)).toBe('descending')
expect(getNextSortDirection('invalid')).toBe('descending')
})
})
2 changes: 2 additions & 0 deletions src/core/table/sort-button/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './sort-button'
export * from './styles'
132 changes: 132 additions & 0 deletions src/core/table/sort-button/sort-button.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { getNextSortDirection } from './sort-direction'
import { TableCellSortButton } from './sort-button'
import { useArgs } from 'storybook/preview-api'

import type { Meta, StoryObj } from '@storybook/react-vite'
import type { MouseEventHandler } from 'react'
import type { SortDirection } from './sort-direction'
import { Text } from '../../text'
import { Tooltip } from '../../tooltip'

const meta = {
title: 'Core/Table/SortButton',
component: TableCellSortButton,
argTypes: {
children: {
control: 'text',
},
value: {
control: 'select',
options: ['ascending', 'descending', 'none'] satisfies SortDirection[],
},
},
} satisfies Meta<typeof TableCellSortButton>

export default meta
type Story = StoryObj<typeof meta>

/**
* To indicate that no sort is active for the column, use a value of "none". To change the sort
* direction when the button is clicked, the consumer must handle click events and update the state
* that determines what value is provided to the button's `value` prop.
*
* Since the button's value represents the _current_ sort direction, the click event handler must
* calculate what the _next_ sort direction will be. This can be acheived using the
* `getNextSortDirection` function available from `@reapit/elements/core/table`.
*/
export const Example: Story = {
args: {
children: 'Property',
name: 'address',
value: 'none',
},
render: (args) => {
const [, setArgs] = useArgs()
const updateSortDirection: MouseEventHandler<HTMLButtonElement> = (event) => {
setArgs({ value: getNextSortDirection(event.currentTarget.value) })
}
return <TableCellSortButton {...args} onClick={updateSortDirection} />
},
}

/**
* To indicate an ascending sort order for the column, use a value of "ascending".
*/
export const Ascending: Story = {
args: {
...Example.args,
value: 'ascending',
},
}

/**
* To indicate a descending sort order for the column, use a value of "descending".
*/
export const Descending: Story = {
args: {
...Example.args,
value: 'descending',
},
}

/**
* The sort button inherits `justify-content` from its parent. This allows it to match the alignment
* specified for the table header cell in which it resides.
*/
export const Alignment: Story = {
args: {
...Example.args,
value: 'descending',
},
decorators: [
(Story) => (
<div
style={{
boxSizing: 'content-box',
border: '1px solid #FA00FF',
width: '300px',
justifyContent: 'end',
}}
>
<Story />
</div>
),
],
}

/**
* Column headers should rarely be permitted to truncate, but when it is unavoidable, it's possible
* to allow truncation to occur and to display a tooltip with the unabridged text. When this is
* necessary, the tooltip should label the sort button and be displayed when the sort button is
* hovered or focused.
*/
export const Truncation: Story = {
args: {
...Descending.args,
'aria-labelledby': 'tooltip',
children: (
<>
<Text id="text" size="2xs" overflow="truncate" weight="bold">
Long column header
</Text>
<Tooltip id="tooltip" triggerId="sort-button" truncationTargetId="text">
Long column header
</Tooltip>
</>
),
id: 'sort-button',
},
decorators: [
(Story) => (
<div
style={{
boxSizing: 'content-box',
border: '1px solid #FA00FF',
width: '100px',
}}
>
<Story />
</div>
),
],
}
32 changes: 32 additions & 0 deletions src/core/table/sort-button/sort-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { cx } from '@linaria/core'
import { elTableCellSortButton, elTableCellSortButtonIcon } from './styles'
import { SortDescendIcon } from '#src/icons/sort-descend'

import type { ButtonHTMLAttributes, ReactNode } from 'react'
import type { SortDirection } from './sort-direction'

// NOTE: we omit...
// - disabled, because the sort button should never be disabled
type AttributesToOmit = 'disabled'

interface TableCellSortButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, AttributesToOmit> {
/** The sort button's label. */
children: ReactNode
/** The name of the "field" in the table's data sorted by this button. */
name: string
/** The current sort direction for this column, if any. */
value: SortDirection
}

/**
* A simple button for table column headers that allows users to sort the column in ascending
* or descending order. Typically used via `Table.SortButton`.
*/
export function TableCellSortButton({ children, className, name, value, ...rest }: TableCellSortButtonProps) {
return (
<button {...rest} className={cx(elTableCellSortButton, className)} name={name} value={value}>
{children}
<SortDescendIcon aria-hidden className={elTableCellSortButtonIcon} />
</button>
)
}
41 changes: 41 additions & 0 deletions src/core/table/sort-button/sort-direction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export type SortDirection = 'ascending' | 'descending' | 'none'

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: some or all of this may move to a component-agnostic place in future (e.g., perhaps utils). In particular, when we have our search params schema implemented, we'll likely want a sort param schema to help us serialise and parse sort fields and directions to and from the URL.

/**
* Parses an unknown value into a valid sort direction. Values that are not valid sort directions
* will return the default of "none", meaning no sort direction is specified.
*/
export function parseSortDirection(value: unknown): SortDirection {
switch (value) {
case 'ascending':
case 'descending':
return value
default:
return 'none'
}
}

/**
* Given the current sort direction, if any, determines what the next sort direction will be if the
* column sort is changed. The behaviour of column sort directions is described by the
* following simple state machine:
*
* ```
* No sort ──► Descending sort ◄─────┐
* └──────► Ascending sort
* ```
*
* If the current sort direction is not valid, it will be treated as "none", which means the next
* sort direction will be "descending".
*/
export function getNextSortDirection(value: unknown): SortDirection {
const currentDirection = parseSortDirection(value)

switch (currentDirection) {
case 'ascending':
return 'descending'
case 'descending':
return 'ascending'
case 'none':
return 'descending'
}
}
54 changes: 54 additions & 0 deletions src/core/table/sort-button/styles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { css } from '@linaria/core'
import { font } from '#src/core/text'

export const elTableCellSortButton = css`
display: inline-grid;
grid-template-columns: minmax(auto, min-content) min-content;
grid-template-rows: auto;
align-items: center;
justify-content: inherit;
gap: var(--spacing-1);
width: 100%;

border: none;
border-radius: var(--border-radius-m);
padding: var(--spacing-2);

background: transparent;
color: var(--colour-text-secondary);

cursor: pointer;

${font('2xs', 'bold')}
text-align: center;
text-transform: uppercase;

&:focus-visible {
outline: var(--border-width-double) solid var(--colour-border-focus);
outline-offset: var(--border-width-default);
}

&:hover {
background: var(--colour-fill-neutral-lightest);
}
`

export const elTableCellSortButtonIcon = css`
display: inline-flex;
align-items: center;
justify-content: center;

width: var(--icon_size-s);
height: var(--icon_size-s);

color: var(--colour-icon-disabled);

[value='ascending'] & {
color: var(--colour-icon-secondary);
transform: rotate(180deg);
}

[value='descending'] & {
color: var(--colour-icon-secondary);
}
`
Loading
Loading