Skip to content

Commit

Permalink
fix(Table): provide aria-sort for sortable table headings (#1675)
Browse files Browse the repository at this point in the history
  • Loading branch information
noook authored Apr 15, 2024
1 parent cba9ad7 commit 6f60fa9
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions src/runtime/components/data/Table.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@
<UCheckbox :model-value="indeterminate || selected.length === rows.length" :indeterminate="indeterminate" v-bind="ui.default.checkbox" aria-label="Select all" @change="onChange" />
</th>

<th v-for="(column, index) in columns" :key="index" scope="col" :class="[ui.th.base, ui.th.padding, ui.th.color, ui.th.font, ui.th.size, column.class]">
<th
v-for="(column, index) in columns"
:key="index"
scope="col"
:class="[ui.th.base, ui.th.padding, ui.th.color, ui.th.font, ui.th.size, column.class]"
:aria-sort="getAriaSort(column)"
>
<slot :name="`${column.key}-header`" :column="column" :sort="sort" :on-sort="onSort">
<UButton
v-if="column.sortable"
Expand Down Expand Up @@ -74,7 +80,7 @@

<script lang="ts">
import { computed, defineComponent, toRaw, toRef } from 'vue'
import type { PropType } from 'vue'
import type { PropType, AriaAttributes } from 'vue'
import { upperFirst } from 'scule'
import { defu } from 'defu'
import { useVModel } from '@vueuse/core'
Expand Down Expand Up @@ -107,6 +113,15 @@ function defaultSort (a: any, b: any, direction: 'asc' | 'desc') {
}
}
interface Column {
key: string
sortable?: boolean
sort?: (a: any, b: any, direction: 'asc' | 'desc') => number
direction?: 'asc' | 'desc'
class?: string
[key: string]: any
}
export default defineComponent({
components: {
UIcon,
Expand All @@ -129,7 +144,7 @@ export default defineComponent({
default: () => []
},
columns: {
type: Array as PropType<{ key: string, sortable?: boolean, sort?: (a: any, b: any, direction: 'asc' | 'desc') => number, direction?: 'asc' | 'desc', class?: string, [key: string]: any }[]>,
type: Array as PropType<Column[]>,
default: null
},
columnAttribute: {
Expand Down Expand Up @@ -292,6 +307,26 @@ export default defineComponent({
return get(row, rowKey, defaultValue)
}
function getAriaSort (column: Column): AriaAttributes['aria-sort'] {
if (!column.sortable) {
return undefined
}
if (sort.value.column !== column.key) {
return 'none'
}
if (sort.value.direction === 'asc') {
return 'ascending'
}
if (sort.value.direction === 'desc') {
return 'descending'
}
return undefined
}
return {
// eslint-disable-next-line vue/no-dupe-keys
ui,
Expand All @@ -312,7 +347,8 @@ export default defineComponent({
onSort,
onSelect,
onChange,
getRowData
getRowData,
getAriaSort
}
}
})
Expand Down

0 comments on commit 6f60fa9

Please sign in to comment.