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 12 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: 'james.anderson@example.com',
amount: 594
}, {
id: '4599',
date: '2024-03-11T10:10:00',
status: 'failed',
email: 'mia.white@example.com',
amount: 276
}, {
id: '4598',
date: '2024-03-11T08:50:00',
status: 'refunded',
email: 'william.brown@example.com',
amount: 315
}, {
id: '4597',
date: '2024-03-10T19:45:00',
status: 'paid',
email: 'emma.davis@example.com',
amount: 529
}, {
id: '4596',
date: '2024-03-10T15:55:00',
status: 'paid',
email: 'ethan.harris@example.com',
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 @@ -271,6 +271,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
23 changes: 22 additions & 1 deletion src/runtime/components/Table.vue
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,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 @@ -64,6 +65,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 @@ -198,6 +200,17 @@ 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
const target = e.target as HTMLElement
const isInteractive = target.closest('button')
if (isInteractive)
return
e.preventDefault()
e.stopPropagation()
props.onSelect(row, e)
}
defineExpose({
tableApi
})
Expand Down Expand Up @@ -230,7 +243,15 @@ 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()"
:role="props.onSelect ? 'button' : undefined"
:tabindex="props.onSelect ? 0 : undefined"
:class="ui.tr({ class: [props.ui?.tr] })"
@click="handleRowSelect(row, $event)"
>
<td
v-for="cell in row.getVisibleCells()"
:key="cell.id"
Expand Down
4 changes: 2 additions & 2 deletions src/theme/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ export default (options: Required<ModuleOptions>) => ({
base: 'min-w-full overflow-clip',
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',
tbody: 'divide-y divide-[var(--ui-border)] [&>tr]:data-[can-select=true]:hover:bg-[var(--ui-bg-elevated)]/50 [&>tr]:data-[can-select=true]:cursor-pointer ',
tr: 'data-[selected=true]: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