feat(Table): improve expanded row (#2485)

This commit is contained in:
kyyy
2024-11-05 21:52:10 +07:00
committed by GitHub
parent 0b2a3989a2
commit 1acd01a440
7 changed files with 301 additions and 25 deletions

View File

@@ -0,0 +1,75 @@
<script setup>
const people = [{
id: 1,
name: 'Lindsay Walton',
title: 'Front-end Developer',
email: 'lindsay.walton@example.com',
role: 'Member'
}, {
id: 2,
name: 'Courtney Henry',
title: 'Designer',
email: 'courtney.henry@example.com',
role: 'Admin',
disabledExpand: true
}, {
id: 3,
name: 'Tom Cook',
title: 'Director of Product',
email: 'tom.cook@example.com',
role: 'Member'
}, {
id: 4,
name: 'Whitney Francis',
title: 'Copywriter',
email: 'whitney.francis@example.com',
role: 'Admin',
disabledExpand: true
}, {
id: 5,
name: 'Leonard Krasner',
title: 'Senior Designer',
email: 'leonard.krasner@example.com',
role: 'Owner'
}, {
id: 6,
name: 'Floyd Miles',
title: 'Principal Designer',
email: 'floyd.miles@example.com',
role: 'Member',
disabledExpand: true
}]
const columns = [
{
label: 'Name',
key: 'name'
},
{
label: 'title',
key: 'title'
},
{
label: 'Email',
key: 'email'
},
{
label: 'role',
key: 'role'
}
]
const expand = ref({
openedRows: [],
row: null
})
</script>
<template>
<UTable v-model:expand="expand" :rows="people" :columns="columns">
<template #expand="{ row }">
<div class="p-4">
<pre>{{ row }}</pre>
</div>
</template>
</UTable>
</template>

View File

@@ -0,0 +1,65 @@
<script setup lang='ts'>
const people = [{
id: 1,
name: 'Lindsay Walton',
title: 'Front-end Developer',
email: 'lindsay.walton@example.com',
role: 'Member',
hasExpand: false
}, {
id: 2,
name: 'Courtney Henry',
title: 'Designer',
email: 'courtney.henry@example.com',
role: 'Admin',
hasExpand: true
}, {
id: 3,
name: 'Tom Cook',
title: 'Director of Product',
email: 'tom.cook@example.com',
role: 'Member',
hasExpand: false
}, {
id: 4,
name: 'Whitney Francis',
title: 'Copywriter',
email: 'whitney.francis@example.com',
role: 'Admin',
hasExpand: true
}, {
id: 5,
name: 'Leonard Krasner',
title: 'Senior Designer',
email: 'leonard.krasner@example.com',
role: 'Owner',
hasExpand: false
}, {
id: 6,
name: 'Floyd Miles',
title: 'Principal Designer',
email: 'floyd.miles@example.com',
role: 'Member',
hasExpand: true
}]
const expand = ref({
openedRows: [people.find(v => v.hasExpand)],
row: {}
})
</script>
<template>
<UTable v-model:expand="expand" :rows="people">
<template #expand="{ row }">
<div class="p-4">
<pre>{{ row }}</pre>
</div>
</template>
<template #expand-action="{ row, isExpanded, toggle }">
<UButton v-if="row.hasExpand" @click="toggle">
{{ isExpanded ? 'collapse' : 'expand' }}
</UButton>
</template>
</UTable>
</template>

View File

@@ -1,4 +1,4 @@
<script setup> <script setup lang='ts'>
const people = [{ const people = [{
id: 1, id: 1,
name: 'Lindsay Walton', name: 'Lindsay Walton',
@@ -36,10 +36,15 @@ const people = [{
email: 'floyd.miles@example.com', email: 'floyd.miles@example.com',
role: 'Member' role: 'Member'
}] }]
const expand = ref({
openedRows: [people[0]],
row: {}
})
</script> </script>
<template> <template>
<UTable :rows="people"> <UTable v-model:expand="expand" :rows="people">
<template #expand="{ row }"> <template #expand="{ row }">
<div class="p-4"> <div class="p-4">
<pre>{{ row }}</pre> <pre>{{ row }}</pre>

View File

@@ -315,7 +315,9 @@ componentProps:
### Expandable :u-badge{label="New" class="align-middle ml-2 !rounded-full" variant="subtle"} ### Expandable :u-badge{label="New" class="align-middle ml-2 !rounded-full" variant="subtle"}
You can use the `expand` slot to display extra information about a row. You will have access to the `row` property in the slot scope. You can use the `v-model:expand` to enables row expansion functionality in the table component. It maintains an object containing an `openedRows` an array and `row` an object, which tracks the indices of currently expanded rows.
When using the expand slot, you have access to the `row` property in the slot scope, which contains the data of the row that triggered the expand/collapse action. This allows you to customize the expanded content based on the row's data.
::component-example{class="grid"} ::component-example{class="grid"}
--- ---
@@ -327,6 +329,73 @@ componentProps:
--- ---
:: ::
#### Event expand
The `@update:expand` event is emitted when a row is expanded. This event provides the current state of expanded rows and the data of the row that triggered the event.
To use the `@update:expand` event, add it to your `UTable` component. The event handler will receive an object with the following properties:
- `openedRows`: An array of indices of the currently expanded rows.
- `row`: The row data that triggered the expand/collapse action.
```vue
<script setup lang="ts">
const { data, pending } = await useLazyFetch(() => `/api/users`)
const handleExpand = ({ openedRows, row }) => {
console.log('opened Rows:', openedRows);
console.log('Row Data:', row);
};
const expand = ref({
openedRows: [],
row: null
})
</script>
<template>
<UTable v-model="expand" :loading="pending" :rows="data" @update:expand="handleExpand">
<template #expand="{ row }">
<div class="p-4">
<pre>{{ row }}</pre>
</div>
</template>
</UTable>
</template>
```
#### Multiple expand
Controls whether multiple rows can be expanded simultaneously in the table.
```vue
<template>
<!-- Allow only one row to be expanded at a time -->
<UTable :multiple-expand="false" />
<!-- Default behavior: Allow multiple rows to be expanded simultaneously -->
<UTable :multiple-expand="true" />
<!-- Or simply -->
<UTable />
</template>
```
#### Disable Row Expansion
You can disable the expansion functionality for specific rows in the UTable component by adding the `disabledExpand` property to your row data.
> Important: When using `disabledExpand`, you must define the `columns` prop for the UTable component. Otherwise, the table will render all properties as columns, including the `disabledExpand` property.
::component-example{class="grid"}
---
extraClass: 'overflow-hidden'
padding: false
component: 'table-example-disabled-expandable'
componentProps:
class: 'flex-1'
---
::
### Loading ### Loading
Use the `loading` prop to indicate that data is currently loading with an indeterminate [Progress](/components/progress#indeterminate) bar. Use the `loading` prop to indicate that data is currently loading with an indeterminate [Progress](/components/progress#indeterminate) bar.
@@ -449,6 +518,43 @@ componentProps:
--- ---
:: ::
### `expand-action`
The `#expand-action` slot allows you to customize the expansion control interface for expandable table rows. This feature provides a flexible way to implement custom expand/collapse functionality while maintaining access to essential row data and state.
#### Usage
```vue
<template>
<UTable>
<template #expand-action="{ row, toggle, isExpanded }">
<!-- Your custom expand action content -->
</template>
</UTable>
</template>
```
#### Slot Props
The slot provides three key props:
| Prop | Type | Description |
|------|------|-------------|
| `row` | `Object` | Contains the current row's data |
| `toggle` | `Function` | Function to toggle the expanded state |
| `isExpanded` | `Boolean` | Current expansion state of the row |
::component-example{class="grid"}
---
extraClass: 'overflow-hidden'
padding: false
component: 'table-example-expand-action-slot'
componentProps:
class: 'flex-1'
---
::
### `loading-state` ### `loading-state`
Use the `#loading-state` slot to customize the loading state. Use the `#loading-state` slot to customize the loading state.

View File

@@ -18,7 +18,7 @@
/> />
</th> </th>
<th v-if="$slots.expand" scope="col" :class="ui.tr.base"> <th v-if="expand" scope="col" :class="ui.tr.base">
<span class="sr-only">Expand</span> <span class="sr-only">Expand</span>
</th> </th>
@@ -50,7 +50,7 @@
</thead> </thead>
<tbody :class="ui.tbody"> <tbody :class="ui.tbody">
<tr v-if="loadingState && loading && !rows.length"> <tr v-if="loadingState && loading && !rows.length">
<td :colspan="columns.length + (modelValue ? 1 : 0) + ($slots.expand ? 1 : 0)"> <td :colspan="columns.length + (modelValue ? 1 : 0) + (expand ? 1 : 0)">
<slot name="loading-state"> <slot name="loading-state">
<div :class="ui.loadingState.wrapper"> <div :class="ui.loadingState.wrapper">
<UIcon v-if="loadingState.icon" :name="loadingState.icon" :class="ui.loadingState.icon" aria-hidden="true" /> <UIcon v-if="loadingState.icon" :name="loadingState.icon" :class="ui.loadingState.icon" aria-hidden="true" />
@@ -63,7 +63,7 @@
</tr> </tr>
<tr v-else-if="emptyState && !rows.length"> <tr v-else-if="emptyState && !rows.length">
<td :colspan="columns.length + (modelValue ? 1 : 0) + ($slots.expand ? 1 : 0)"> <td :colspan="columns.length + (modelValue ? 1 : 0) + (expand ? 1 : 0)">
<slot name="empty-state"> <slot name="empty-state">
<div :class="ui.emptyState.wrapper"> <div :class="ui.emptyState.wrapper">
<UIcon v-if="emptyState.icon" :name="emptyState.icon" :class="ui.emptyState.icon" aria-hidden="true" /> <UIcon v-if="emptyState.icon" :name="emptyState.icon" :class="ui.emptyState.icon" aria-hidden="true" />
@@ -77,7 +77,7 @@
<template v-else> <template v-else>
<template v-for="(row, index) in rows" :key="index"> <template v-for="(row, index) in rows" :key="index">
<tr :class="[ui.tr.base, isSelected(row) && ui.tr.selected, $attrs.onSelect && ui.tr.active, row?.class]" @click="() => onSelect(row)"> <tr :class="[ui.tr.base, isSelected(row) && ui.tr.selected, isExpanded(row) && ui.tr.expanded, $attrs.onSelect && ui.tr.active, row?.class]" @click="() => onSelect(row)">
<td v-if="modelValue" :class="ui.checkbox.padding"> <td v-if="modelValue" :class="ui.checkbox.padding">
<UCheckbox <UCheckbox
:model-value="isSelected(row)" :model-value="isSelected(row)"
@@ -87,25 +87,28 @@
@click.capture.stop="() => onSelect(row)" @click.capture.stop="() => onSelect(row)"
/> />
</td> </td>
<td <td
v-if="$slots.expand" v-if="expand"
:class="[ui.td.base, ui.td.padding, ui.td.color, ui.td.font, ui.td.size]" :class="[ui.td.base, ui.td.padding, ui.td.color, ui.td.font, ui.td.size]"
> >
<template v-if="$slots['expand-action']">
<slot name="expand-action" :row="row" :is-expanded="isExpanded(row)" :toggle="() => toggleOpened(row)" />
</template>
<UButton <UButton
v-else
:disabled="row.disabledExpand"
v-bind="{ ...(ui.default.expandButton || {}), ...expandButton }" v-bind="{ ...(ui.default.expandButton || {}), ...expandButton }"
:ui="{ icon: { base: [ui.expand.icon, openedRows.includes(index) && 'rotate-180'].join(' ') } }" :ui="{ icon: { base: [ui.expand.icon, isExpanded(row) && 'rotate-180'].join(' ') } }"
@click="toggleOpened(index)" @click.capture.stop="toggleOpened(row)"
/> />
</td> </td>
<td v-for="(column, subIndex) in columns" :key="subIndex" :class="[ui.td.base, ui.td.padding, ui.td.color, ui.td.font, ui.td.size, column?.rowClass, row[column.key]?.class]"> <td v-for="(column, subIndex) in columns" :key="subIndex" :class="[ui.td.base, ui.td.padding, ui.td.color, ui.td.font, ui.td.size, column?.rowClass, row[column.key]?.class]">
<slot :name="`${column.key}-data`" :column="column" :row="row" :index="index" :get-row-data="(defaultValue) => getRowData(row, column.key, defaultValue)"> <slot :name="`${column.key}-data`" :column="column" :row="row" :index="index" :get-row-data="(defaultValue) => getRowData(row, column.key, defaultValue)">
{{ getRowData(row, column.key) }} {{ getRowData(row, column.key) }}
</slot> </slot>
</td> </td>
</tr> </tr>
<tr v-if="openedRows.includes(index)"> <tr v-if="isExpanded(row)">
<td colspan="100%"> <td colspan="100%">
<slot <slot
name="expand" name="expand"
@@ -122,7 +125,7 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { ref, computed, defineComponent, toRaw, toRef } from 'vue' import { computed, defineComponent, toRaw, toRef } from 'vue'
import type { PropType, AriaAttributes } from 'vue' import type { PropType, AriaAttributes } from 'vue'
import { upperFirst } from 'scule' import { upperFirst } from 'scule'
import { defu } from 'defu' import { defu } from 'defu'
@@ -133,7 +136,7 @@ import UProgress from '../elements/Progress.vue'
import UCheckbox from '../forms/Checkbox.vue' import UCheckbox from '../forms/Checkbox.vue'
import { useUI } from '../../composables/useUI' import { useUI } from '../../composables/useUI'
import { mergeConfig, get } from '../../utils' import { mergeConfig, get } from '../../utils'
import type { TableRow, TableColumn, Strategy, Button, ProgressColor, ProgressAnimation, DeepPartial } from '../../types/index' import type { TableRow, TableColumn, Strategy, Button, ProgressColor, ProgressAnimation, DeepPartial, Expanded } from '../../types/index'
// @ts-expect-error // @ts-expect-error
import appConfig from '#build/app.config' import appConfig from '#build/app.config'
import { table } from '#ui/ui.config' import { table } from '#ui/ui.config'
@@ -209,6 +212,10 @@ export default defineComponent({
type: Object as PropType<Button>, type: Object as PropType<Button>,
default: () => config.default.expandButton as Button default: () => config.default.expandButton as Button
}, },
expand: {
type: Object as PropType<Expanded<TableRow>>,
default: () => null
},
loading: { loading: {
type: Boolean, type: Boolean,
default: false default: false
@@ -236,17 +243,26 @@ export default defineComponent({
ui: { ui: {
type: Object as PropType<DeepPartial<typeof config> & { strategy?: Strategy }>, type: Object as PropType<DeepPartial<typeof config> & { strategy?: Strategy }>,
default: () => ({}) default: () => ({})
},
multipleExpand: {
type: Boolean,
default: true
} }
}, },
emits: ['update:modelValue', 'update:sort'], emits: ['update:modelValue', 'update:sort', 'update:expand'],
setup(props, { emit, attrs: $attrs }) { setup(props, { emit, attrs: $attrs }) {
const { ui, attrs } = useUI('table', toRef(props, 'ui'), config, toRef(props, 'class')) const { ui, attrs } = useUI('table', toRef(props, 'ui'), config, toRef(props, 'class'))
const columns = computed(() => props.columns ?? Object.keys(props.rows[0] ?? {}).map(key => ({ key, label: upperFirst(key), sortable: false, class: undefined, sort: defaultSort }) as TableColumn)) const columns = computed(() => props.columns ?? Object.keys(props.rows[0] ?? {}).map(key => ({ key, label: upperFirst(key), sortable: false, class: undefined, sort: defaultSort }) as TableColumn))
const sort = useVModel(props, 'sort', emit, { passive: true, defaultValue: defu({}, props.sort, { column: null, direction: 'asc' }) }) const sort = useVModel(props, 'sort', emit, { passive: true, defaultValue: defu({}, props.sort, { column: null, direction: 'asc' }) })
const expand = useVModel(props, 'expand', emit, {
const openedRows = ref([]) passive: true,
defaultValue: defu({}, props.expand, {
openedRows: [],
row: null
})
})
const savedSort = { column: sort.value.column, direction: null } const savedSort = { column: sort.value.column, direction: null }
@@ -383,11 +399,14 @@ export default defineComponent({
return get(row, rowKey, defaultValue) return get(row, rowKey, defaultValue)
} }
function toggleOpened(index: number) { function isExpanded(row: TableRow) {
if (openedRows.value.includes(index)) { return expand.value?.openedRows ? expand.value.openedRows.some(openedRow => compare(openedRow, row)) : false
openedRows.value = openedRows.value.filter(i => i !== index) }
} else {
openedRows.value.push(index) function toggleOpened(row: TableRow) {
expand.value = {
openedRows: isExpanded(row) ? expand.value.openedRows.filter(v => !compare(v, row)) : props.multipleExpand ? [...expand.value.openedRows, row] : [row],
row
} }
} }
@@ -429,14 +448,14 @@ export default defineComponent({
loadingState, loadingState,
isAllRowChecked, isAllRowChecked,
onChangeCheckbox, onChangeCheckbox,
openedRows,
isSelected, isSelected,
onSort, onSort,
onSelect, onSelect,
onChange, onChange,
getRowData, getRowData,
toggleOpened, toggleOpened,
getAriaSort getAriaSort,
isExpanded
} }
} }
}) })

View File

@@ -11,3 +11,8 @@ export interface TableColumn {
rowClass?: string rowClass?: string
[key: string]: any [key: string]: any
} }
export interface Expanded<T> {
openedRows: T[]
row: T | null
}

View File

@@ -8,6 +8,7 @@ export default {
tr: { tr: {
base: '', base: '',
selected: 'bg-gray-50 dark:bg-gray-800/50', selected: 'bg-gray-50 dark:bg-gray-800/50',
expanded: 'bg-gray-50 dark:bg-gray-800/50',
active: 'hover:bg-gray-50 dark:hover:bg-gray-800/50 cursor-pointer' active: 'hover:bg-gray-50 dark:hover:bg-gray-800/50 cursor-pointer'
}, },
th: { th: {