feat(Table): implement component (#2364)

This commit is contained in:
Benjamin Canac
2024-10-23 17:32:30 +02:00
committed by GitHub
parent 34bddd45be
commit b54950e3ed
40 changed files with 4000 additions and 62 deletions

View File

@@ -10,40 +10,40 @@ export interface ModuleOptions {
/**
* Prefix for components
* @defaultValue `U`
* @see https://ui3.nuxt.dev/getting-started/installation#prefix
* @link https://ui3.nuxt.dev/getting-started/installation#prefix
*/
prefix?: string
/**
* Enable or disable `@nuxt/fonts` module
* @defaultValue `true`
* @see https://ui3.nuxt.dev/getting-started/installation#fonts
* @link https://ui3.nuxt.dev/getting-started/installation#fonts
*/
fonts?: boolean
/**
* Enable or disable `@nuxtjs/color-mode` module
* @defaultValue `true`
* @see https://ui3.nuxt.dev/getting-started/installation#colormode
* @link https://ui3.nuxt.dev/getting-started/installation#colormode
*/
colorMode?: boolean
/**
* Customize how the theme is generated
* @see https://ui3.nuxt.dev/getting-started/theme
* @link https://ui3.nuxt.dev/getting-started/theme
*/
theme?: {
/**
* Define the color aliases available for components
* @defaultValue `['primary', 'secondary', 'success', 'info', 'warning', 'error']`
* @see https://ui3.nuxt.dev/getting-started/installation#themecolors
* @link https://ui3.nuxt.dev/getting-started/installation#themecolors
*/
colors?: string[]
/**
* Enable or disable transitions on components
* @defaultValue `true`
* @see https://ui3.nuxt.dev/getting-started/installation#themetransitions
* @link https://ui3.nuxt.dev/getting-started/installation#themetransitions
*/
transitions?: boolean
}

View File

@@ -55,32 +55,32 @@ export interface CarouselProps<T> extends Omit<EmblaOptionsType, 'axis' | 'conta
items?: T[]
/**
* Enable Autoplay plugin
* @see https://www.embla-carousel.com/plugins/autoplay/
* @link https://www.embla-carousel.com/plugins/autoplay/
*/
autoplay?: boolean | AutoplayOptionsType
/**
* Enable Auto Scroll plugin
* @see https://www.embla-carousel.com/plugins/auto-scroll/
* @link https://www.embla-carousel.com/plugins/auto-scroll/
*/
autoScroll?: boolean | AutoScrollOptionsType
/**
* Enable Auto Height plugin
* @see https://www.embla-carousel.com/plugins/auto-height/
* @link https://www.embla-carousel.com/plugins/auto-height/
*/
autoHeight?: boolean | AutoHeightOptionsType
/**
* Enable Class Names plugin
* @see https://www.embla-carousel.com/plugins/class-names/
* @link https://www.embla-carousel.com/plugins/class-names/
*/
classNames?: boolean | ClassNamesOptionsType
/**
* Enable Fade plugin
* @see https://www.embla-carousel.com/plugins/fade/
* @link https://www.embla-carousel.com/plugins/fade/
*/
fade?: boolean | FadeOptionsType
/**
* Enable Wheel Gestures plugin
* @see https://www.embla-carousel.com/plugins/wheel-gestures/
* @link https://www.embla-carousel.com/plugins/wheel-gestures/
*/
wheelGestures?: boolean | WheelGesturesPluginOptions
class?: any

View File

@@ -0,0 +1,232 @@
<!-- eslint-disable vue/block-tag-newline -->
<script lang="ts">
import type { Ref } from 'vue'
import { tv, type VariantProps } from 'tailwind-variants'
import type { AppConfig } from '@nuxt/schema'
import type {
Row,
ColumnDef,
ColumnFiltersState,
ColumnPinningState,
RowSelectionState,
SortingState,
ExpandedState,
VisibilityState,
GlobalFilterOptions,
ColumnFiltersOptions,
ColumnPinningOptions,
VisibilityOptions,
ExpandedOptions,
SortingOptions,
RowSelectionOptions,
Updater
} from '@tanstack/vue-table'
import _appConfig from '#build/app.config'
import theme from '#build/ui/table'
const appConfig = _appConfig as AppConfig & { ui: { table: Partial<typeof theme> } }
const table = tv({ extend: tv(theme), ...(appConfig.ui?.table || {}) })
type TableVariants = VariantProps<typeof table>
export type TableColumn<T> = ColumnDef<T>
export interface TableData {
[key: string]: any
}
export interface TableProps<T> {
data?: T[]
columns?: TableColumn<T>[]
/**
* Whether the table should have a sticky header.
* @defaultValue false
*/
sticky?: boolean
/** Whether the table should be in loading state. */
loading?: boolean
loadingColor?: TableVariants['loadingColor']
loadingAnimation?: TableVariants['loadingAnimation']
/**
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#table-options)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
globalFilterOptions?: Omit<GlobalFilterOptions<T>, 'onGlobalFilterChange'>
/**
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#table-options)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
columnFiltersOptions?: Omit<ColumnFiltersOptions<T>, 'getFilteredRowModel' | 'onColumnFiltersChange'>
/**
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#table-options)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
columnPinningOptions?: Omit<ColumnPinningOptions, 'onColumnPinningChange'>
/**
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#table-options)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
visibilityOptions?: Omit<VisibilityOptions, 'onColumnVisibilityChange'>
/**
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#table-options)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
sortingOptions?: Omit<SortingOptions<T>, 'getSortedRowModel' | 'onSortingChange'>
/**
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#table-options)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
expandedOptions?: Omit<ExpandedOptions<T>, 'getExpandedRowModel' | 'onExpandedChange'>
/**
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#table-options)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
rowSelectionOptions?: Omit<RowSelectionOptions<T>, 'onRowSelectionChange'>
class?: any
ui?: Partial<typeof table.slots>
}
export interface TableSlots<T> {
expanded(props: { row: Row<T> }): any
empty(props?: {}): any
}
</script>
<script setup lang="ts" generic="T extends TableData">
import { computed } from 'vue'
import {
FlexRender,
getCoreRowModel,
getFilteredRowModel,
getSortedRowModel,
getExpandedRowModel,
useVueTable
} from '@tanstack/vue-table'
import { upperFirst } from 'scule'
const props = defineProps<TableProps<T>>()
defineSlots<TableSlots<T>>()
const data = computed(() => props.data ?? [])
const columns = computed<TableColumn<T>[]>(() => props.columns ?? Object.keys(data.value[0] ?? {}).map((accessorKey: string) => ({ accessorKey, header: upperFirst(accessorKey) })))
const ui = computed(() => table({
sticky: props.sticky,
loading: props.loading,
loadingColor: props.loadingColor,
loadingAnimation: props.loadingAnimation
}))
const globalFilterState = defineModel<string>('globalFilter', { default: undefined })
const columnFiltersState = defineModel<ColumnFiltersState>('columnFilters', { default: [] })
const columnVisibilityState = defineModel<VisibilityState>('columnVisibility', { default: {} })
const columnPinningState = defineModel<ColumnPinningState>('columnPinning', { default: {} })
const rowSelectionState = defineModel<RowSelectionState>('rowSelection', { default: {} })
const sortingState = defineModel<SortingState>('sorting', { default: [] })
const expandedState = defineModel<ExpandedState>('expanded', { default: {} })
const tableApi = useVueTable({
data,
columns: columns.value,
getCoreRowModel: getCoreRowModel(),
...(props.globalFilterOptions || {}),
onGlobalFilterChange: updaterOrValue => valueUpdater(updaterOrValue, globalFilterState),
...(props.columnFiltersOptions || {}),
getFilteredRowModel: getFilteredRowModel(),
onColumnFiltersChange: updaterOrValue => valueUpdater(updaterOrValue, columnFiltersState),
...(props.visibilityOptions || {}),
onColumnVisibilityChange: updaterOrValue => valueUpdater(updaterOrValue, columnVisibilityState),
...(props.columnPinningOptions || {}),
onColumnPinningChange: updaterOrValue => valueUpdater(updaterOrValue, columnPinningState),
...(props.rowSelectionOptions || {}),
onRowSelectionChange: updaterOrValue => valueUpdater(updaterOrValue, rowSelectionState),
...(props.sortingOptions || {}),
getSortedRowModel: getSortedRowModel(),
onSortingChange: updaterOrValue => valueUpdater(updaterOrValue, sortingState),
...(props.expandedOptions || {}),
getExpandedRowModel: getExpandedRowModel(),
onExpandedChange: updaterOrValue => valueUpdater(updaterOrValue, expandedState),
state: {
get globalFilter() {
return globalFilterState.value
},
get columnFilters() {
return columnFiltersState.value
},
get columnVisibility() {
return columnVisibilityState.value
},
get columnPinning() {
return columnPinningState.value
},
get expanded() {
return expandedState.value
},
get rowSelection() {
return rowSelectionState.value
},
get sorting() {
return sortingState.value
}
}
})
function valueUpdater<T extends Updater<any>>(updaterOrValue: T, ref: Ref) {
ref.value = typeof updaterOrValue === 'function' ? updaterOrValue(ref.value) : updaterOrValue
}
defineExpose({
tableApi
})
</script>
<template>
<div :class="ui.root({ class: [props.class, props.ui?.root] })">
<table :class="ui.base({ class: [props.ui?.base] })">
<thead :class="ui.thead({ class: [props.ui?.thead] })">
<tr v-for="headerGroup in tableApi.getHeaderGroups()" :key="headerGroup.id" :class="ui.tr({ class: [props.ui?.tr] })">
<th
v-for="header in headerGroup.headers"
:key="header.id"
:data-pinned="header.column.getIsPinned()"
:class="ui.th({ class: [props.ui?.th], pinned: !!header.column.getIsPinned() })"
>
<FlexRender v-if="!header.isPlaceholder" :render="header.column.columnDef.header" :props="header.getContext()" />
</th>
</tr>
</thead>
<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] })">
<td
v-for="cell in row.getVisibleCells()"
:key="cell.id"
:data-pinned="cell.column.getIsPinned()"
:class="ui.td({ class: [props.ui?.td], pinned: !!cell.column.getIsPinned() })"
>
<FlexRender :render="cell.column.columnDef.cell" :props="cell.getContext()" />
</td>
</tr>
<tr v-if="row.getIsExpanded()" :class="ui.tr({ class: [props.ui?.tr] })">
<td :colspan="row.getAllCells().length" :class="ui.td({ class: [props.ui?.td] })">
<slot name="expanded" :row="row" />
</td>
</tr>
</template>
</template>
<tr v-else :class="ui.tr({ class: [props.ui?.tr] })">
<td :colspan="columns?.length" :class="ui.empty({ class: props.ui?.empty })">
<slot name="empty">
No results
</slot>
</td>
</tr>
</tbody>
</table>
</div>
</template>

View File

@@ -1,8 +1,8 @@
import { ref, inject } from 'vue'
import type { ShallowRef, Component, InjectionKey } from 'vue'
import type { ComponentProps } from 'vue-component-type-helpers'
import { createSharedComposable } from '@vueuse/core'
import type { ModalProps } from '../types'
import type { ComponentProps } from '../types/component'
export interface ModalState {
component: Component | string

View File

@@ -1,8 +1,8 @@
import { ref, inject } from 'vue'
import type { ShallowRef, Component, InjectionKey } from 'vue'
import type { ComponentProps } from 'vue-component-type-helpers'
import { createSharedComposable } from '@vueuse/core'
import type { SlideoverProps } from '../types'
import type { ComponentProps } from '../types/component'
export interface SlideoverState {
component: Component | string

View File

@@ -1,14 +0,0 @@
export type ComponentProps<T> =
T extends new () => { $props: infer P } ? NonNullable<P> :
T extends (props: infer P, ...args: any) => any ? P :
Record<string, never>
export type ComponentSlots<T> =
T extends new () => { $slots: infer S } ? NonNullable<S> :
T extends (props: any, ctx: { slots: infer S, attrs: any, emit: any }, ...args: any) => any ? NonNullable<S> :
Record<string, never>
export type ComponentEmit<T> =
T extends new () => { $emit: infer E } ? NonNullable<E> :
T extends (props: any, ctx: { slots: any, attrs: any, emit: infer E }, ...args: any) => any ? NonNullable<E> :
Record<string, never>

View File

@@ -35,6 +35,7 @@ export * from '../components/Skeleton.vue'
export * from '../components/Slideover.vue'
export * from '../components/Slider.vue'
export * from '../components/Switch.vue'
export * from '../components/Table.vue'
export * from '../components/Tabs.vue'
export * from '../components/Textarea.vue'
export * from '../components/Toast.vue'

View File

@@ -8,7 +8,7 @@ export default (options: Required<ModuleOptions>) => ({
content: 'relative overflow-hidden',
viewport: 'divide-y divide-[var(--ui-border)] scroll-py-1',
group: 'p-1 isolate',
empty: 'py-6 text-center text-sm',
empty: 'py-6 text-center text-sm text-[var(--ui-text-muted)]',
label: 'px-2 py-1.5 text-xs font-semibold text-[var(--ui-text-highlighted)]',
item: ['group relative w-full flex items-center gap-2 px-2 py-1.5 text-sm select-none outline-none before:absolute before:z-[-1] before:inset-px before:rounded-[calc(var(--ui-radius)*1.5)] data-disabled:cursor-not-allowed data-disabled:opacity-75 text-[var(--ui-text)] data-highlighted:text-[var(--ui-text-highlighted)] data-highlighted:before:bg-[var(--ui-bg-elevated)]/50', options.theme.transitions && 'transition-colors before:transition-colors'],
itemLeadingIcon: ['shrink-0 size-5 text-[var(--ui-text-dimmed)] group-data-highlighted:text-[var(--ui-text)]', options.theme.transitions && 'transition-colors'],

View File

@@ -35,6 +35,7 @@ export { default as skeleton } from './skeleton'
export { default as slideover } from './slideover'
export { default as slider } from './slider'
export { default as switch } from './switch'
export { default as table } from './table'
export { default as tabs } from './tabs'
export { default as textarea } from './textarea'
export { default as toast } from './toast'

83
src/theme/table.ts Normal file
View File

@@ -0,0 +1,83 @@
import type { ModuleOptions } from '../module'
export default (options: Required<ModuleOptions>) => ({
slots: {
root: 'relative overflow-auto',
base: 'min-w-full overflow-clip',
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',
th: 'px-4 py-3.5 text-sm text-[var(--ui-text-highlighted)] text-left rtl:text-right font-semibold [&:has([role=checkbox])]:pr-0',
td: 'p-4 text-sm text-[var(--ui-text-muted)] whitespace-nowrap [&:has([role=checkbox])]:pr-0',
empty: 'py-6 text-center text-sm text-[var(--ui-text-muted)]'
},
variants: {
pinned: {
true: {
th: 'sticky bg-[var(--ui-bg)]/75 data-[pinned=left]:left-0 data-[pinned=right]:right-0',
td: 'sticky bg-[var(--ui-bg)]/75 data-[pinned=left]:left-0 data-[pinned=right]:right-0'
}
},
sticky: {
true: {
thead: 'sticky top-0 inset-x-0 bg-[var(--ui-bg)]/75 z-[1] backdrop-blur'
}
},
loading: {
true: {
thead: 'after:absolute after:bottom-0 after:inset-x-0 after:h-px'
}
},
loadingAnimation: {
'carousel': '',
'carousel-inverse': '',
'swing': '',
'elastic': ''
},
loadingColor: {
...Object.fromEntries((options.theme.colors || []).map((color: string) => [color, ''])),
neutral: ''
}
},
compoundVariants: [...(options.theme.colors || []).map((loadingColor: string) => ({
loading: true,
loadingColor,
class: {
thead: `after:bg-[var(--ui-${loadingColor})]`
}
})), {
loading: true,
loadingColor: 'neutral',
class: {
thead: 'after:bg-[var(--ui-bg-inverted)]'
}
}, {
loading: true,
loadingAnimation: 'carousel',
class: {
thead: 'after:animate-[carousel_2s_ease-in-out_infinite]'
}
}, {
loading: true,
loadingAnimation: 'carousel-inverse',
class: {
thead: 'after:animate-[carousel-inverse_2s_ease-in-out_infinite]'
}
}, {
loading: true,
loadingAnimation: 'swing',
class: {
thead: 'after:animate-[swing_2s_ease-in-out_infinite]'
}
}, {
loading: true,
loadingAnimation: 'elastic',
class: {
thead: 'after:animate-[elastic_2s_ease-in-out_infinite]'
}
}],
defaultVariants: {
loadingColor: 'primary',
loadingAnimation: 'carousel'
}
})