Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Table): add select event #2822

Open
wants to merge 6 commits into
base: v3
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
<script setup lang="ts">
import { h, resolveComponent } from 'vue'
import type { TableColumn, TableRow } from '@nuxt/ui'

const UBadge = resolveComponent('UBadge')

type Payment = {
id: string
date: string
status: 'paid' | 'failed' | 'refunded'
email: string
amount: number
}

const data = ref<Payment[]>([{
id: '4600',
date: '2024-03-11T15:30:00',
status: 'paid',
email: '[email protected]',
amount: 594
}, {
id: '4599',
date: '2024-03-11T10:10:00',
status: 'failed',
email: '[email protected]',
amount: 276
}, {
id: '4598',
date: '2024-03-11T08:50:00',
status: 'refunded',
email: '[email protected]',
amount: 315
}, {
id: '4597',
date: '2024-03-10T19:45:00',
status: 'paid',
email: '[email protected]',
amount: 529
}, {
id: '4596',
date: '2024-03-10T15:55:00',
status: 'paid',
email: '[email protected]',
amount: 639
}])

const columns: TableColumn<Payment>[] = [{
accessorKey: 'date',
header: 'Date',
cell: ({ row }) => {
return new Date(row.getValue('date')).toLocaleString('en-US', {
day: 'numeric',
month: 'short',
hour: '2-digit',
minute: '2-digit',
hour12: false
})
}
}, {
accessorKey: 'status',
header: 'Status',
cell: ({ row }) => {
const color = ({
paid: 'success' as const,
failed: 'error' as const,
refunded: 'neutral' as const
})[row.getValue('status') as string]

return h(UBadge, { class: 'capitalize', variant: 'subtle', color }, () => row.getValue('status'))
}
}, {
accessorKey: 'email',
header: 'Email'
}, {
accessorKey: 'amount',
header: () => h('div', { class: 'text-right' }, 'Amount'),
cell: ({ row }) => {
const amount = Number.parseFloat(row.getValue('amount'))

const formatted = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'EUR'
}).format(amount)

return h('div', { class: 'text-right font-medium' }, formatted)
}
}]

const table = useTemplateRef('table')

const rowSelection = ref<Record<string, boolean>>({ })
function onSelect(row: TableRow<Payment>, e?: Event) {
/* If you decide to also select the column you can do this */
row.toggleSelected(!row.getIsSelected())
console.info(e)
}
const selectedRows = computed(() => {
if (!rowSelection.value) return []
const indexes = Object.entries(rowSelection.value).filter(rs => rs[1])?.map(rs => Number.parseInt(rs[0])) || []
if (indexes.length === 0) return []
return data.value.filter((_, index) => indexes.includes(index))
})
function quitSelect(row: TableRow<Payment>) {
const index = data.value.findIndex(r => r.id === row.original.id)
if (rowSelection.value[index]) {
rowSelection.value = { ...rowSelection.value, [index]: false }
}
}
</script>

<template>
<div class=" flex w-full flex-1 gap-1">
<div class="flex-1">
<UTable
ref="table"
v-model:row-selection="rowSelection"
:data="data"
:columns="columns"
@select="onSelect"
/>
<div class="px-4 py-3.5 border-t border-[var(--ui-border-accented)] text-sm text-[var(--ui-text-muted)]">
{{ table?.tableApi?.getFilteredSelectedRowModel().rows.length || 0 }} of
{{ table?.tableApi?.getFilteredRowModel().rows.length || 0 }} row(s) selected.
</div>
</div>
<div v-if="selectedRows.length>0">
<UTable

:data="selectedRows"
:ui="{
td: 'truncate ... max-w-28'
}"
:columns="[
{ accessorKey: 'email', header: 'Remove' }
]"
class="border border-[var(--ui-border-accented)] rounded-[var(--ui-radius)] "
@select="quitSelect"
/>
</div>
</div>
</template>
18 changes: 18 additions & 0 deletions docs/content/3.components/table.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,24 @@ class: '!p-0'
::tip
You can use the `row-selection` prop to control the selection state of the rows (can be binded with `v-model`).
::
### With @select event

You can also add a select listener on your Table to make the rows clickable. The function will receive the TableRow as the first argument and second argument optional the event.

You can use this to navigate to a page, open a modal or even to select the row manually.


::component-example
---
prettier: true
collapse: true
name: 'table-row-selection-event-example'
highlights:
- 55
- 70
class: '!p-0'
---
::

### With column sorting

Expand Down
11 changes: 10 additions & 1 deletion src/runtime/components/Table.vue
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const table = tv({ extend: tv(theme), ...(appConfig.ui?.table || {}) })
type TableVariants = VariantProps<typeof table>

export type TableColumn<T> = ColumnDef<T>
export type TableRow<T> = Row<T>

export interface TableData {
[key: string]: any
Expand All @@ -58,6 +59,7 @@ export interface TableProps<T> {
* @defaultValue false
*/
sticky?: boolean
onSelect?: (row: TableRow<T>, e?: Event) => void
/** Whether the table should be in loading state. */
loading?: boolean
loadingColor?: TableVariants['loadingColor']
Expand Down Expand Up @@ -197,6 +199,13 @@ function valueUpdater<T extends Updater<any>>(updaterOrValue: T, ref: Ref) {
ref.value = typeof updaterOrValue === 'function' ? updaterOrValue(ref.value) : updaterOrValue
}

function handleRowSelect(row: TableRow<T>, e: Event) {
if (!props.onSelect)
return
e.preventDefault()
e.stopPropagation()
props.onSelect(row, e)
}
defineExpose({
tableApi
})
Expand Down Expand Up @@ -229,7 +238,7 @@ defineExpose({
<tbody :class="ui.tbody({ class: [props.ui?.tbody] })">
<template v-if="tableApi.getRowModel().rows?.length">
<template v-for="row in tableApi.getRowModel().rows" :key="row.id">
<tr :data-selected="row.getIsSelected()" :data-expanded="row.getIsExpanded()" :class="ui.tr({ class: [props.ui?.tr] })">
<tr :data-selected="row.getIsSelected()" :data-can-select="!!props.onSelect" :data-expanded="row.getIsExpanded()" :class="ui.tr({ class: [props.ui?.tr] })" @click="handleRowSelect(row, $event)">
Copy link
Member

Choose a reason for hiding this comment

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

nice! but out of curiosity, how would this work for accessibility / screenreaders as this behaves like a button?

Copy link
Member

Choose a reason for hiding this comment

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

maybe the tanstack table docs also would be missing to address this (or my question is silly!)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Maybe this could be solved if we add this attribute?

:role="props.onSelect ? 'button' : undefined"

Copy link
Member

@ineshbose ineshbose Dec 16, 2024

Choose a reason for hiding this comment

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

It might need tabIndex="0" too (and in that case, should it be white outline, or primary colour, or maybe hover effect that bg changes, maybe for simplity we stick to white outline, similar to anchor tags)
(and implement navigation using arrow keys I suppose)

<td
v-for="cell in row.getVisibleCells()"
:key="cell.id"
Expand Down
2 changes: 1 addition & 1 deletion src/theme/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default (options: Required<ModuleOptions>) => ({
caption: 'sr-only',
thead: 'relative [&>tr]:after:absolute [&>tr]:after:inset-x-0 [&>tr]:after:bottom-0 [&>tr]:after:h-px [&>tr]:after:bg-[var(--ui-border-accented)]',
tbody: 'divide-y divide-[var(--ui-border)]',
tr: 'data-[selected=true]:bg-[var(--ui-bg-elevated)]/50',
tr: 'data-[selected=true]:bg-[var(--ui-bg-elevated)]/50 data-[can-select=true]:hover:bg-[var(--ui-bg-elevated)]/50',
th: 'px-4 py-3.5 text-sm text-[var(--ui-text-highlighted)] text-left rtl:text-right font-semibold [&:has([role=checkbox])]:pe-0',
td: 'p-4 text-sm text-[var(--ui-text-muted)] whitespace-nowrap [&:has([role=checkbox])]:pe-0',
empty: 'py-6 text-center text-sm text-[var(--ui-text-muted)]'
Expand Down
Loading
Loading