chore: 升级 shadcn-vue 组件到v4最新版 (#7972)

* fix: useStore is deprecated

* chore: update deps

* feat: 升级shadcn-ui v4

* fix: workbench style

* feat: 升级shadcn-ui v4 step2

* feat: 升级shadcn-ui v4 step3

* chore: 升级shadcn v4

* fix: pagination

* fix: dark style

* fix: doc import

* feat: 增加详情组件,参考 antdv-next

* docs: descriptions docs

* docs: Browser Support

* feat: add table action

* feat: icon use vbenIcon

* fix: type error

* fix: dropdown popConfirm

* feat: 使用默认的文字交互

* feat: 优化渲染性能
This commit is contained in:
xingyu
2026-05-31 15:18:46 +08:00
committed by GitHub
parent 108d7ff335
commit 04fbb7a556
239 changed files with 6015 additions and 3205 deletions

View File

@@ -34,7 +34,7 @@ const { handleClick, visible } = useBackTop(props);
:style="backTopStyle"
class="data z-popup bg-background shadow-float hover:bg-heavy dark:bg-accent dark:hover:bg-heavy fixed bottom-10 size-10 rounded-full duration-500"
size="icon"
variant="icon"
variant="ghost"
@click="handleClick"
>
<ArrowUpToLine class="size-4" />

View File

@@ -2,7 +2,7 @@ import type { AsTag } from 'reka-ui';
import type { Component } from 'vue';
import type { ButtonVariants, ButtonVariantSize } from '../../ui';
import type { ButtonVariants } from '../../ui';
export interface VbenButtonProps {
/**
@@ -19,8 +19,8 @@ export interface VbenButtonProps {
class?: any;
disabled?: boolean;
loading?: boolean;
size?: ButtonVariantSize;
variant?: ButtonVariants;
size?: ButtonVariants['size'];
variant?: ButtonVariants['variant'];
}
export type CustomRenderType = (() => Component | string) | string;

View File

@@ -16,7 +16,7 @@ interface Props extends VbenButtonProps {
tooltip?: string;
tooltipDelayDuration?: number;
tooltipSide?: 'bottom' | 'left' | 'right' | 'top';
variant?: ButtonVariants;
variant?: ButtonVariants['variant'];
}
const props = withDefaults(defineProps<Props>(), {
@@ -24,7 +24,7 @@ const props = withDefaults(defineProps<Props>(), {
onClick: () => {},
tooltipDelayDuration: 200,
tooltipSide: 'bottom',
variant: 'icon',
variant: 'ghost',
});
const slots = useSlots();

View File

@@ -7,7 +7,7 @@ import { computed, nextTick, ref, useTemplateRef, watch } from 'vue';
import { useNamespace } from '@vben-core/composables';
import { ChevronsDown } from 'lucide-vue-next';
import { ChevronsDown } from '@lucide/vue';
import {
CollapsibleContent,
CollapsibleRoot,

View File

@@ -5,7 +5,7 @@ import type { ClassType } from '@vben-core/typings';
import { computed } from 'vue';
import { ChevronsDown } from 'lucide-vue-next';
import { ChevronsDown } from '@lucide/vue';
import {
CollapsibleContent,
CollapsibleRoot,

View File

@@ -0,0 +1,129 @@
<script setup lang="ts">
import type { CSSProperties } from 'vue';
import type { DescriptionsRenderNode, DescriptionsSize } from './types';
import { computed } from 'vue';
import { cn } from '@vben-core/shared/utils';
import { VbenRenderContent } from '../render-content';
interface Props {
/** 是否边框模式 */
bordered?: boolean;
/** 是否显示冒号(仅非边框模式生效) */
colon?: boolean;
/** 内容 */
content?: DescriptionsRenderNode | null;
/** 内容样式 */
contentStyle?: CSSProperties;
/** 单项自定义类名 */
itemClass?: string;
/** 标签 */
label?: DescriptionsRenderNode | null;
/** 标签样式 */
labelStyle?: CSSProperties;
/** 尺寸 */
size?: DescriptionsSize;
/** 跨列数 */
span?: number;
/** 渲染标签 th 还是 td */
tag: 'td' | 'th';
/** 单元格类型 */
type: 'content' | 'item' | 'label';
}
const props = withDefaults(defineProps<Props>(), {
bordered: false,
colon: true,
content: null,
contentStyle: undefined,
itemClass: undefined,
label: null,
labelStyle: undefined,
size: 'middle',
span: 1,
});
const BORDERED_PADDING: Record<DescriptionsSize, string> = {
large: 'px-6 py-4',
middle: 'px-4 py-2.5',
small: 'px-3 py-2',
};
const PLAIN_PADDING: Record<DescriptionsSize, string> = {
large: 'pb-6',
middle: 'pb-4',
small: 'pb-2',
};
// 冒号通过伪元素追加,避免标签为渲染函数时无法拼接
const COLON_CLASS = "after:content-[':']";
const hasLabel = computed(
() => props.label !== null && props.label !== undefined,
);
const hasContent = computed(
() => props.content !== null && props.content !== undefined,
);
// 数字 0 会被 VbenRenderContent 当作 falsy 隐藏,这里转为字符串保证展示;
// 同时将 null 归一为 undefined,匹配 VbenRenderContent 的 content 类型
const displayLabel = computed(() => {
if (props.label === null || props.label === undefined) return undefined;
return typeof props.label === 'number' ? String(props.label) : props.label;
});
const displayContent = computed(() => {
if (props.content === null || props.content === undefined) return undefined;
return typeof props.content === 'number'
? String(props.content)
: props.content;
});
const cellClass = computed(() => {
if (props.bordered) {
return cn(
'border border-border align-top break-words',
BORDERED_PADDING[props.size],
props.type === 'label'
? 'bg-muted/50 text-start font-normal text-foreground'
: 'text-foreground',
props.itemClass,
);
}
return cn('align-top', PLAIN_PADDING[props.size], props.itemClass);
});
const labelClass = computed(() =>
cn('mr-2 shrink-0 text-muted-foreground', props.colon && COLON_CLASS),
);
</script>
<template>
<component :is="tag" :class="cellClass" :colspan="span">
<!-- 边框模式:每个单元格仅承载 label 或 content -->
<template v-if="bordered">
<span v-if="hasLabel" :style="labelStyle">
<VbenRenderContent :content="displayLabel" />
</span>
<span v-if="hasContent" :style="contentStyle">
<VbenRenderContent :content="displayContent" />
</span>
</template>
<!-- 非边框模式:label + content 容器 -->
<div v-else class="flex">
<span v-if="hasLabel" :class="labelClass" :style="labelStyle">
<VbenRenderContent :content="displayLabel" />
</span>
<span
v-if="hasContent"
class="break-words text-foreground"
:style="contentStyle"
>
<VbenRenderContent :content="displayContent" />
</span>
</div>
</component>
</template>

View File

@@ -0,0 +1,57 @@
<script lang="ts">
import type { PropType } from 'vue';
import type { DescriptionsItemSpan, DescriptionsRenderNode } from './types';
import { defineComponent } from 'vue';
import { DESCRIPTIONS_ITEM_NAME } from './use-descriptions';
/**
* 子节点用法的标记组件,本身不渲染任何内容。
* 其 props 与默认插槽会被父级 VbenDescriptions 收集为列表项。
*/
const VbenDescriptionsItem = defineComponent({
name: DESCRIPTIONS_ITEM_NAME,
props: {
content: {
default: undefined,
type: [
String,
Number,
Function,
Object,
] as PropType<DescriptionsRenderNode>,
},
contentStyle: {
default: undefined,
type: Object,
},
label: {
default: undefined,
type: [
String,
Number,
Function,
Object,
] as PropType<DescriptionsRenderNode>,
},
labelStyle: {
default: undefined,
type: Object,
},
span: {
default: undefined,
type: [Number, String, Object] as PropType<DescriptionsItemSpan>,
},
},
setup() {
return () => null;
},
});
// 额外标记,便于在 vnode 中稳健识别
(VbenDescriptionsItem as Record<string, any>).__isDescriptionsItem = true;
export default VbenDescriptionsItem;
</script>

View File

@@ -0,0 +1,112 @@
<script setup lang="ts">
import type { CSSProperties } from 'vue';
import type { DescriptionsSize, InternalDescriptionsItem } from './types';
import DescriptionsCell from './descriptions-cell.vue';
interface Props {
bordered?: boolean;
colon?: boolean;
contentStyle?: CSSProperties;
labelStyle?: CSSProperties;
row: InternalDescriptionsItem[];
size?: DescriptionsSize;
vertical?: boolean;
}
withDefaults(defineProps<Props>(), {
bordered: false,
colon: true,
contentStyle: undefined,
labelStyle: undefined,
size: 'middle',
vertical: false,
});
function mergeStyle(
base?: CSSProperties,
override?: CSSProperties,
): CSSProperties | undefined {
if (!base && !override) return undefined;
return { ...base, ...override };
}
</script>
<template>
<!-- 垂直布局:标签独占一行,内容独占一行 -->
<template v-if="vertical">
<tr>
<DescriptionsCell
v-for="(item, index) in row"
:key="`label-${item.key ?? index}`"
tag="th"
type="label"
:span="item.span ?? 1"
:bordered="bordered"
:colon="colon"
:size="size"
:label="item.label ?? null"
:item-class="item.class"
:label-style="mergeStyle(labelStyle, item.labelStyle)"
/>
</tr>
<tr>
<DescriptionsCell
v-for="(item, index) in row"
:key="`content-${item.key ?? index}`"
tag="td"
type="content"
:span="item.span ?? 1"
:bordered="bordered"
:size="size"
:content="item.content ?? null"
:item-class="item.class"
:content-style="mergeStyle(contentStyle, item.contentStyle)"
/>
</tr>
</template>
<!-- 水平 + 边框:每项拆分为 label(th) 与 content(td) -->
<tr v-else-if="bordered">
<template v-for="(item, index) in row" :key="item.key ?? index">
<DescriptionsCell
tag="th"
type="label"
:span="1"
:bordered="true"
:size="size"
:label="item.label ?? null"
:item-class="item.class"
:label-style="mergeStyle(labelStyle, item.labelStyle)"
/>
<DescriptionsCell
tag="td"
type="content"
:span="(item.span ?? 1) * 2 - 1"
:bordered="true"
:size="size"
:content="item.content ?? null"
:content-style="mergeStyle(contentStyle, item.contentStyle)"
/>
</template>
</tr>
<!-- 水平 + 非边框:每项一个单元格,label 与 content 同列 -->
<tr v-else>
<DescriptionsCell
v-for="(item, index) in row"
:key="item.key ?? index"
tag="td"
type="item"
:span="item.span ?? 1"
:colon="colon"
:size="size"
:label="item.label ?? null"
:content="item.content ?? null"
:item-class="item.class"
:label-style="mergeStyle(labelStyle, item.labelStyle)"
:content-style="mergeStyle(contentStyle, item.contentStyle)"
/>
</tr>
</template>

View File

@@ -0,0 +1,91 @@
<script setup lang="ts">
import type { VNode } from 'vue';
import type { DescriptionsItemType, DescriptionsProps } from './types';
import { computed, useSlots } from 'vue';
import { cn } from '@vben-core/shared/utils';
import DescriptionsRow from './descriptions-row.vue';
import {
calcRows,
normalizeItems,
parseItemsFromSlot,
resolveColumn,
useScreens,
} from './use-descriptions';
defineOptions({ name: 'VbenDescriptions' });
const props = withDefaults(defineProps<DescriptionsProps>(), {
bordered: false,
class: undefined,
colon: true,
column: undefined,
contentStyle: undefined,
extra: undefined,
items: undefined,
labelStyle: undefined,
layout: 'horizontal',
size: 'middle',
title: undefined,
});
const slots = useSlots();
const screens = useScreens();
// 优先使用 items;否则从默认插槽中解析 VbenDescriptionsItem
const resolvedItems = computed<DescriptionsItemType[]>(() => {
if (props.items && props.items.length > 0) return props.items;
const nodes = (slots.default?.() ?? []) as VNode[];
return parseItemsFromSlot(nodes);
});
const mergedColumn = computed(() => resolveColumn(props.column, screens.value));
const mergedItems = computed(() =>
normalizeItems(resolvedItems.value, screens.value),
);
const rows = computed(() => calcRows(mergedItems.value, mergedColumn.value));
const hasHeader = computed(
() => !!props.title || !!props.extra || !!slots.title || !!slots.extra,
);
const tableClass = computed(() =>
cn(
'w-full table-auto border-collapse text-sm',
// 非边框模式下,去掉最后一行的底部间距
!props.bordered && '[&>tbody>tr:last-child>td]:pb-0',
),
);
</script>
<template>
<div :class="cn('w-full', props.class)">
<div v-if="hasHeader" class="mb-5 flex items-center justify-between gap-4">
<div class="text-base font-semibold text-foreground">
<slot name="title">{{ title }}</slot>
</div>
<div class="text-foreground">
<slot name="extra">{{ extra }}</slot>
</div>
</div>
<table :class="tableClass">
<tbody>
<DescriptionsRow
v-for="(row, index) in rows"
:key="index"
:row="row"
:vertical="layout === 'vertical'"
:bordered="bordered"
:colon="colon"
:size="size"
:label-style="labelStyle"
:content-style="contentStyle"
/>
</tbody>
</table>
</div>
</template>

View File

@@ -0,0 +1,4 @@
export { default as VbenDescriptionsItem } from './descriptions-item.vue';
export { default as VbenDescriptions } from './descriptions.vue';
export * from './types';

View File

@@ -0,0 +1,93 @@
import type { Component, CSSProperties } from 'vue';
/** 响应式断点,与 antdv-next 保持一致 */
export type DescriptionsBreakpoint =
| 'lg'
| 'md'
| 'sm'
| 'xl'
| 'xs'
| 'xxl'
| 'xxxl';
/** 当前命中的断点集合 */
export type ScreenMap = Partial<Record<DescriptionsBreakpoint, boolean>>;
export type DescriptionsLayout = 'horizontal' | 'vertical';
export type DescriptionsSize = 'large' | 'middle' | 'small';
/** 列数,可为固定数字或按断点配置 */
export type DescriptionsColumn =
| number
| Partial<Record<DescriptionsBreakpoint, number>>;
/** 单项跨列,支持固定数字、'filled'(占满当前行剩余)或按断点配置 */
export type DescriptionsItemSpan =
| 'filled'
| number
| Partial<Record<DescriptionsBreakpoint, number>>;
/** 可渲染内容:字符串/数字/渲染函数/组件 */
export type DescriptionsRenderNode = (() => any) | Component | number | string;
export interface DescriptionsItemType {
/** 内容 */
content?: DescriptionsRenderNode;
/** 内容样式 */
contentStyle?: CSSProperties;
/** 唯一 key */
key?: number | string;
/** 标签 */
label?: DescriptionsRenderNode;
/** 标签样式 */
labelStyle?: CSSProperties;
/** 跨列 */
span?: DescriptionsItemSpan;
}
export interface DescriptionsProps {
/** 是否展示边框 */
bordered?: boolean;
class?: any;
/** 是否显示冒号(仅非 bordered 的水平布局生效) */
colon?: boolean;
/** 一行的列数 */
column?: DescriptionsColumn;
/** 统一的内容样式 */
contentStyle?: CSSProperties;
/** 操作区域,位于标题右侧 */
extra?: string;
/** 数据驱动的列表项;不传则读取默认插槽中的 VbenDescriptionsItem */
items?: DescriptionsItemType[];
/** 统一的标签样式 */
labelStyle?: CSSProperties;
/** 布局方式 */
layout?: DescriptionsLayout;
/** 尺寸 */
size?: DescriptionsSize;
/** 标题 */
title?: string;
}
export interface DescriptionsItemProps {
content?: DescriptionsRenderNode;
contentStyle?: CSSProperties;
label?: DescriptionsRenderNode;
labelStyle?: CSSProperties;
span?: DescriptionsItemSpan;
}
/** 归一化后的内部项,span 已解析为数字 */
export interface InternalDescriptionsItem {
_index?: number;
class?: string;
content?: DescriptionsRenderNode;
contentStyle?: CSSProperties;
filled?: boolean;
key?: number | string;
label?: DescriptionsRenderNode;
labelStyle?: CSSProperties;
span?: number;
style?: CSSProperties;
}

View File

@@ -0,0 +1,216 @@
import type { VNode } from 'vue';
import type {
DescriptionsBreakpoint,
DescriptionsColumn,
DescriptionsItemType,
InternalDescriptionsItem,
ScreenMap,
} from './types';
import { Comment, computed, Fragment } from 'vue';
import { useBreakpoints } from '@vueuse/core';
/** 默认列数映射 */
export const DEFAULT_COLUMN_MAP: Record<DescriptionsBreakpoint, number> = {
lg: 3,
md: 3,
sm: 2,
xl: 3,
xs: 1,
xxl: 3,
xxxl: 4,
};
/** 由大到小的断点顺序,matchScreen 按此顺序取第一个命中的值 */
const RESPONSIVE_ARRAY: DescriptionsBreakpoint[] = [
'xxxl',
'xxl',
'xl',
'lg',
'md',
'sm',
'xs',
];
/** 断点像素值 */
const BREAKPOINT_PX = {
sm: 576,
md: 768,
lg: 992,
xl: 1200,
xxl: 1600,
xxxl: 2000,
};
/**
* 在给定的断点配置中,按由大到小的顺序取第一个命中的值
*/
export function matchScreen(
screens: ScreenMap,
screenSizes?: Partial<Record<DescriptionsBreakpoint, number>>,
): number | undefined {
if (!screenSizes) return undefined;
for (const breakpoint of RESPONSIVE_ARRAY) {
if (screens[breakpoint] && screenSizes[breakpoint] !== undefined) {
return screenSizes[breakpoint];
}
}
return undefined;
}
/**
* 监听视口宽度,返回当前命中的断点集合
*/
export function useScreens() {
const breakpoints = useBreakpoints(BREAKPOINT_PX);
return computed<ScreenMap>(() => ({
lg: breakpoints.lg.value,
md: breakpoints.md.value,
sm: breakpoints.sm.value,
xl: breakpoints.xl.value,
xs: !breakpoints.sm.value,
xxl: breakpoints.xxl.value,
xxxl: breakpoints.xxxl.value,
}));
}
/**
* 计算最终列数:固定数字直接返回,否则按断点解析
*/
export function resolveColumn(
column: DescriptionsColumn | undefined,
screens: ScreenMap,
): number {
if (typeof column === 'number') return column;
return matchScreen(screens, { ...DEFAULT_COLUMN_MAP, ...column }) ?? 3;
}
/**
* 归一化列表项:将 span 解析为数字,'filled' 标记为 filled
*/
export function normalizeItems(
items: DescriptionsItemType[],
screens: ScreenMap,
): InternalDescriptionsItem[] {
return items.map((item, index) => {
const { span, ...rest } = item;
if (span === 'filled') {
return { ...rest, _index: index, filled: true };
}
return {
...rest,
_index: index,
span: typeof span === 'number' ? span : matchScreen(screens, span),
};
});
}
/**
* 行装箱算法:根据列数与各项 span 将列表项拆分为多行,
* 并补齐每行最后一项以占满列数。移植自 antdv-next useRow。
*/
export function calcRows(
items: InternalDescriptionsItem[],
column: number,
): InternalDescriptionsItem[][] {
let rows: InternalDescriptionsItem[][] = [];
let tmpRow: InternalDescriptionsItem[] = [];
let count = 0;
items.filter(Boolean).forEach((item) => {
const { filled, ...rest } = item;
// filled:占满当前行剩余,并立即换行
if (filled) {
tmpRow.push(rest);
rows.push(tmpRow);
tmpRow = [];
count = 0;
return;
}
const restSpan = column - count;
count += item.span || 1;
if (count >= column) {
// 超出列数时,将当前项 span 收敛为剩余列数,避免溢出
tmpRow.push(count > column ? { ...rest, span: restSpan } : rest);
rows.push(tmpRow);
tmpRow = [];
count = 0;
} else {
tmpRow.push(rest);
}
});
if (tmpRow.length > 0) rows.push(tmpRow);
// 补齐:若一行总 span 不足列数,扩展最后一项
rows = rows.map((row) => {
const total = row.reduce((acc, item) => acc + (item.span || 1), 0);
if (total < column) {
const last = row[row.length - 1];
if (last) {
last.span = column - (total - (last.span || 1));
}
}
return row;
});
return rows;
}
/** 标记组件类型为 DescriptionsItem,便于从插槽 vnode 中识别 */
export const DESCRIPTIONS_ITEM_NAME = 'VbenDescriptionsItem';
function isItemVNode(node: VNode): boolean {
const type = node.type as any;
return (
!!type &&
(type.__isDescriptionsItem === true || type.name === DESCRIPTIONS_ITEM_NAME)
);
}
function flattenVNodes(nodes: VNode[]): VNode[] {
const result: VNode[] = [];
for (const node of nodes) {
if (node.type === Fragment && Array.isArray(node.children)) {
result.push(...flattenVNodes(node.children as VNode[]));
} else if (node.type !== Comment) {
result.push(node);
}
}
return result;
}
/**
* 从默认插槽的 vnode 中解析出列表项,支持
* <VbenDescriptionsItem label="..." :span="2">content</VbenDescriptionsItem> 写法
*/
export function parseItemsFromSlot(nodes: VNode[]): DescriptionsItemType[] {
return flattenVNodes(nodes)
.filter((node) => isItemVNode(node))
.map((node) => {
const props = (node.props ?? {}) as Record<string, any>;
const children = (node.children ?? {}) as Record<string, any>;
const labelSlot =
typeof children.label === 'function' ? children.label : undefined;
const contentDefaultSlot =
typeof children.default === 'function' ? children.default : undefined;
const contentSlot =
typeof children.content === 'function'
? children.content
: contentDefaultSlot;
return {
class: props.class,
content: contentSlot ?? props.content,
contentStyle: props.contentStyle ?? props['content-style'],
key: node.key ?? undefined,
label: labelSlot ?? props.label,
labelStyle: props.labelStyle ?? props['label-style'],
span: props.span,
style: props.style,
} as DescriptionsItemType;
});
}

View File

@@ -6,6 +6,7 @@ export * from './checkbox';
export * from './collapsible';
export * from './context-menu';
export * from './count-to-animator';
export * from './descriptions';
export * from './dropdown-menu';
export * from './expandable-arrow';
export * from './full-screen';
@@ -21,4 +22,5 @@ export * from './segmented';
export * from './select';
export * from './spine-text';
export * from './spinner';
export * from './table-action';
export * from './tooltip';

View File

@@ -3,7 +3,7 @@ import type { PinInputProps } from './types';
import { computed, onBeforeUnmount, ref, useId, watch } from 'vue';
import { PinInput, PinInputGroup, PinInputInput } from '../../ui';
import { PinInput, PinInputGroup, PinInputSlot } from '../../ui';
import { VbenButton } from '../button';
defineOptions({
@@ -101,7 +101,7 @@ const pinType = 'text' as const;
>
<div class="relative flex w-full">
<PinInputGroup class="mr-2">
<PinInputInput
<PinInputSlot
v-for="(item, index) in codeLength"
:key="item"
:index="index"

View File

@@ -115,7 +115,7 @@ function handleScroll(event: Event) {
></div>
<ScrollBar
v-if="horizontal"
:class="scrollBarClass"
:class="cn(scrollBarClass)"
orientation="horizontal"
/>
</ScrollArea>

View File

@@ -45,7 +45,7 @@ function activeClass(tab: string): string[] {
<Tabs v-model="activeTab" :default-value="getDefaultValue">
<TabsList
:style="tabsStyle"
class="bg-accent outline-heavy! relative grid w-full outline! outline-2!"
class="bg-accent outline-heavy! relative grid w-full outline-2!"
>
<TabsIndicator :style="tabsIndicatorStyle" />
<template v-for="tab in tabs" :key="tab.value">

View File

@@ -0,0 +1,116 @@
<script setup lang="ts">
import type { ActionItem } from './types';
import { computed, ref } from 'vue';
import { useSimpleLocale } from '@vben-core/composables';
import { cn } from '@vben-core/shared/utils';
import {
DropdownMenuItem,
Popover,
PopoverContent,
PopoverTrigger,
} from '../../ui';
import { VbenButton } from '../button';
import { VbenIcon } from '../icon';
const props = defineProps<{ action: ActionItem }>();
const emit = defineEmits<{ confirm: [] }>();
const { $t } = useSimpleLocale();
const open = ref(false);
const itemClass = computed(() =>
cn(
'cursor-pointer gap-2',
props.action.danger && 'text-destructive focus:text-destructive',
),
);
/**
* 阻止 reka-ui 事件的默认行为,用于:
* - @select:阻止点击菜单项后自动关闭菜单,以便弹出气泡确认框;
* - @open-auto-focus:阻止弹层抢占焦点(避免与菜单的焦点陷阱冲突);
* - @focus-outside:阻止因菜单夺回焦点而被误判为「焦点移出」从而关闭弹层。
*/
function preventDefault(event: Event) {
event.preventDefault();
}
function onClick() {
if (props.action.disabled) return;
props.action.onClick?.();
}
function onConfirm() {
open.value = false;
const pc = props.action.popConfirm;
if (pc?.confirm) {
pc.confirm();
} else {
props.action.onClick?.();
}
// 确认后关闭整个下拉菜单
emit('confirm');
}
function onCancel() {
open.value = false;
}
</script>
<template>
<!--
气泡确认:菜单项同时作为 Popover 触发器。
通过双重 as-child(DropdownMenuItem + PopoverTrigger 均合并到同一个叶子元素),
使该元素既是菜单项又是弹层触发器;@select 阻止点击后菜单自动关闭。
-->
<Popover v-if="action.popConfirm" v-model:open="open">
<PopoverTrigger as-child>
<DropdownMenuItem
as-child
:class="itemClass"
:disabled="action.disabled"
@select="preventDefault"
>
<div>
<VbenIcon v-if="action.icon" :icon="action.icon" class="size-4" />
{{ action.text }}
</div>
</DropdownMenuItem>
</PopoverTrigger>
<PopoverContent
class="z-popup w-60"
side="left"
@focus-outside="preventDefault"
@open-auto-focus="preventDefault"
>
<div class="text-foreground mb-3 text-sm">
{{ action.popConfirm.title ?? $t('confirmTitle') }}
</div>
<div class="flex justify-end gap-2">
<VbenButton size="sm" variant="outline" @click="onCancel">
{{ action.popConfirm.cancelText ?? $t('cancel') }}
</VbenButton>
<VbenButton
:variant="action.danger ? 'destructive' : 'default'"
size="sm"
@click="onConfirm"
>
{{ action.popConfirm.okText ?? $t('confirm') }}
</VbenButton>
</div>
</PopoverContent>
</Popover>
<!-- 普通下拉项 -->
<DropdownMenuItem
v-else
:class="itemClass"
:disabled="action.disabled"
@click="onClick"
>
<VbenIcon v-if="action.icon" :icon="action.icon" class="size-4" />
{{ action.text }}
</DropdownMenuItem>
</template>

View File

@@ -0,0 +1,97 @@
<script setup lang="ts">
import type { ActionItem } from './types';
import { computed, ref } from 'vue';
import { cn } from '@vben-core/shared/utils';
import { Popover, PopoverContent, PopoverTrigger } from '../../ui';
import { VbenButton } from '../button';
import { VbenIcon } from '../icon';
const props = defineProps<{ action: ActionItem }>();
const open = ref(false);
const buttonClass = computed(() =>
cn(
'gap-1',
props.action.danger && 'text-destructive hover:text-destructive',
props.action.class,
),
);
const variant = computed(() => props.action.variant ?? 'link');
const size = computed(() => props.action.size ?? 'default');
function onClick() {
if (props.action.disabled || props.action.loading) return;
props.action.onClick?.();
}
function onConfirm() {
open.value = false;
const pc = props.action.popConfirm;
if (pc?.confirm) {
pc.confirm();
} else {
props.action.onClick?.();
}
}
function onCancel() {
open.value = false;
}
</script>
<template>
<!-- 气泡确认 -->
<Popover v-if="action.popConfirm" v-model:open="open">
<PopoverTrigger as-child>
<VbenButton
:class="buttonClass"
:disabled="action.disabled"
:loading="action.loading"
:size="size"
class="p-2"
:variant="variant"
>
<VbenIcon :icon="action.icon" v-if="action.icon" class="size-4" />
<span v-if="action.text">{{ action.text }}</span>
</VbenButton>
</PopoverTrigger>
<PopoverContent class="z-popup w-60" side="top">
<div class="text-foreground mb-3 text-sm">
{{ action.popConfirm.title ?? 'Are you sure?' }}
</div>
<div class="flex justify-end gap-2">
<VbenButton size="default" variant="outline" @click="onCancel">
{{ action.popConfirm.cancelText ?? 'Cancel' }}
</VbenButton>
<VbenButton
:variant="action.danger ? 'destructive' : 'default'"
size="default"
class="p-2"
@click="onConfirm"
>
{{ action.popConfirm.okText ?? 'OK' }}
</VbenButton>
</div>
</PopoverContent>
</Popover>
<!-- 普通按钮 -->
<VbenButton
v-else
:class="buttonClass"
:disabled="action.disabled"
:loading="action.loading"
:size="size"
class="p-2"
:variant="variant"
@click="onClick"
>
<VbenIcon :icon="action.icon" v-if="action.icon" class="size-4" />
<span v-if="action.text">{{ action.text }}</span>
</VbenButton>
</template>

View File

@@ -0,0 +1,3 @@
export { default as VbenTableAction } from './table-action.vue';
export type * from './types';

View File

@@ -0,0 +1,216 @@
<script setup lang="ts">
import type { ActionItem, TableActionProps } from './types';
import { computed, ref } from 'vue';
import { Ellipsis } from '@vben-core/icons';
import { cn } from '@vben-core/shared/utils';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuSeparator,
DropdownMenuTrigger,
Separator,
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '../../ui';
import { VbenButton } from '../button';
import { VbenIcon } from '../icon';
import ActionDropdownItemComp from './action-dropdown-item.vue';
import ActionItemComp from './action-item.vue';
defineOptions({ name: 'VbenTableAction' });
const props = withDefaults(defineProps<TableActionProps>(), {
actions: () => [],
align: 'end',
class: undefined,
divider: false,
dropdownActions: () => [],
hasPermission: undefined,
moreText: undefined,
});
function checkVisible(item: ActionItem): boolean {
// 权限
if (item.auth && props.hasPermission && !props.hasPermission(item.auth)) {
return false;
}
// ifShow
if (typeof item.ifShow === 'boolean') return item.ifShow;
if (typeof item.ifShow === 'function') return item.ifShow();
return true;
}
const visibleActions = computed(() =>
(props.actions ?? []).filter((item) => checkVisible(item)),
);
const visibleDropdownActions = computed(() =>
(props.dropdownActions ?? []).filter((item) => checkVisible(item)),
);
const alignClass = computed(
() =>
({ center: 'justify-center', end: 'justify-end', start: 'justify-start' })[
props.align
],
);
// 缓存根节点类名,避免每次渲染都执行 cn()(内部 tailwind-merge 解析开销较大)
const wrapperClass = computed(() =>
cn('flex items-center gap-1', alignClass.value, props.class),
);
function tooltipSide(action: ActionItem) {
return typeof action.tooltip === 'object'
? (action.tooltip.side ?? 'top')
: 'top';
}
function tooltipContent(action: ActionItem) {
return typeof action.tooltip === 'object'
? action.tooltip.content
: action.tooltip;
}
/**
* 预计算每个主操作的渲染视图模型:
* - 普通按钮在本组件内直接渲染,不再为每个操作多包一层子组件,
* 表格大量行时可显著减少组件实例数;
* - 仅 popConfirm 操作仍交由子组件维护独立弹层状态;
* - 类名等在此一次性计算并缓存,避免模板每次渲染都执行 cn()。
*/
const renderedActions = computed(() => {
const list = visibleActions.value;
return list.map((action, index) => {
const hasTooltip = !!action.tooltip && !action.popConfirm;
return {
action,
buttonClass: cn(
'gap-1 p-2',
action.danger && 'text-destructive hover:text-destructive',
action.class,
),
hasTooltip,
isConfirm: !!action.popConfirm,
key: action.key ?? index,
showDivider: props.divider && index < list.length - 1,
size: action.size ?? 'default',
tooltipContent: hasTooltip ? tooltipContent(action) : undefined,
tooltipSide: hasTooltip ? tooltipSide(action) : 'top',
variant: action.variant ?? 'link',
};
});
});
const dropdownOpen = ref(false);
function onActionClick(action: ActionItem) {
if (action.disabled || action.loading) return;
action.onClick?.();
}
/**
* 当与气泡确认(Popover)交互时,避免误关闭整个下拉菜单。
* Popover 内容被 Portal 渲染到菜单之外,默认会被判定为「点击外部」而关闭菜单。
*/
function onContentInteractOutside(event: Event) {
const target = (event as CustomEvent).detail?.originalEvent?.target as
| HTMLElement
| null
| undefined;
if (target?.closest('[data-slot="popover-content"]')) {
event.preventDefault();
}
}
</script>
<template>
<div :class="wrapperClass">
<!-- 所有主操作共享同一个 TooltipProvider,避免每个 tooltip 各建一个 provider -->
<TooltipProvider v-if="renderedActions.length > 0" :delay-duration="0">
<template v-for="item in renderedActions" :key="item.key">
<!-- 气泡确认:需独立弹层状态,交由子组件维护 -->
<ActionItemComp v-if="item.isConfirm" :action="item.action" />
<!-- 带提示的普通按钮 -->
<Tooltip v-else-if="item.hasTooltip">
<TooltipTrigger as-child tabindex="-1">
<VbenButton
:class="item.buttonClass"
:disabled="item.action.disabled"
:loading="item.action.loading"
:size="item.size"
:variant="item.variant"
@click="onActionClick(item.action)"
>
<VbenIcon
v-if="item.action.icon"
:icon="item.action.icon"
class="size-4"
/>
<span v-if="item.action.text">{{ item.action.text }}</span>
</VbenButton>
</TooltipTrigger>
<TooltipContent
:side="item.tooltipSide"
class="side-content bg-accent text-popover-foreground rounded-md"
>
{{ item.tooltipContent }}
</TooltipContent>
</Tooltip>
<!-- 普通按钮 -->
<VbenButton
v-else
:class="item.buttonClass"
:disabled="item.action.disabled"
:loading="item.action.loading"
:size="item.size"
:variant="item.variant"
@click="onActionClick(item.action)"
>
<VbenIcon
v-if="item.action.icon"
:icon="item.action.icon"
class="size-4"
/>
<span v-if="item.action.text">{{ item.action.text }}</span>
</VbenButton>
<Separator v-if="item.showDivider" orientation="vertical" class="h-4" />
</template>
</TooltipProvider>
<DropdownMenu
v-if="visibleDropdownActions.length > 0"
v-model:open="dropdownOpen"
>
<DropdownMenuTrigger as-child>
<VbenButton class="gap-1 p-2" variant="link">
<Ellipsis class="size-4" />
<span v-if="moreText">{{ moreText }}</span>
</VbenButton>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
@interact-outside="onContentInteractOutside"
>
<template
v-for="(item, index) in visibleDropdownActions"
:key="item.key ?? index"
>
<ActionDropdownItemComp
:action="item"
@confirm="dropdownOpen = false"
/>
<DropdownMenuSeparator
v-if="divider && index < visibleDropdownActions.length - 1"
/>
</template>
</DropdownMenuContent>
</DropdownMenu>
</div>
</template>

View File

@@ -0,0 +1,75 @@
import type { ButtonVariants } from '../../ui';
import { VbenIcon } from '../icon';
/** 权限码:单个或多个,配合注入的 hasPermission 判断 */
export type TableActionAuth = string | string[];
/** 操作按钮提示 */
export interface TableActionTooltip {
content: string;
side?: 'bottom' | 'left' | 'right' | 'top';
}
/** 气泡确认框配置 */
export interface TableActionPopConfirm {
/** 取消按钮文案 */
cancelText?: string;
/** 确认回调;未提供时回退到 action.onClick */
confirm?: () => void;
/** 确认按钮文案 */
okText?: string;
/** 提示标题 */
title?: string;
}
export interface ActionItem {
/** 权限码,配合注入的 hasPermission 过滤 */
auth?: TableActionAuth;
/** 自定义类名 */
class?: any;
/** 危险操作(红色文字) */
danger?: boolean;
/** 是否禁用 */
disabled?: boolean;
/** 图标组件 */
icon?: typeof VbenIcon.icon;
/** 是否显示:布尔或返回布尔的函数 */
ifShow?: (() => boolean) | boolean;
/** 唯一标识,点击回调可据此区分 */
key?: number | string;
/** 加载状态 */
loading?: boolean;
/** 点击回调 */
onClick?: () => void;
/** 气泡确认框 */
popConfirm?: TableActionPopConfirm;
/** 尺寸 */
size?: ButtonVariants['size'];
/** 文本 */
text?: string;
/** 提示:字符串或配置对象 */
tooltip?: string | TableActionTooltip;
/** 按钮样式变体 */
variant?: ButtonVariants['variant'];
}
export interface TableActionProps {
/** 主操作按钮 */
actions?: ActionItem[];
/** 对齐方式 */
align?: 'center' | 'end' | 'start';
/** 自定义类名 */
class?: any;
/** 按钮之间是否显示分割线 */
divider?: boolean;
/** “更多”下拉中的操作 */
dropdownActions?: ActionItem[];
/**
* 权限判断函数,返回 false 则隐藏对应 auth 的操作。
* 核心组件不依赖业务,由使用方注入(如 useAccess().hasAccessByCodes)。
*/
hasPermission?: (auth?: TableActionAuth) => boolean;
/** “更多”按钮文案(提供时显示在图标右侧) */
moreText?: string;
}

View File

@@ -1,7 +1,7 @@
<script setup lang="ts">
import { cn } from '@vben-core/shared/utils';
import { CircleHelp } from 'lucide-vue-next';
import { CircleHelp } from '@lucide/vue';
import Tooltip from './tooltip.vue';