This commit is contained in:
gjd
2025-06-16 09:58:35 +08:00
648 changed files with 27087 additions and 5714 deletions

View File

@@ -140,6 +140,63 @@ export function urlToBase64(url: string, mineType?: string): Promise<string> {
});
}
/**
* 将 Base64 字符串转换为文件对象
* @param base64 - Base64 字符串
* @param fileName - 文件名
* @returns File 对象
*/
export function base64ToFile(base64: string, fileName: string): File {
// 输入验证
if (!base64 || typeof base64 !== 'string') {
throw new Error('base64 参数必须是非空字符串');
}
// 将 base64 按照逗号进行分割,将前缀与后续内容分隔开
const data = base64.split(',');
if (data.length !== 2 || !data[0] || !data[1]) {
throw new Error('无效的 base64 格式');
}
// 利用正则表达式从前缀中获取类型信息image/png、image/jpeg、image/webp等
const typeMatch = data[0].match(/:(.*?);/);
if (!typeMatch || !typeMatch[1]) {
throw new Error('无法解析 base64 类型信息');
}
const type = typeMatch[1];
// 从类型信息中获取具体的文件格式后缀png、jpeg、webp
const typeParts = type.split('/');
if (typeParts.length !== 2 || !typeParts[1]) {
throw new Error('无效的 MIME 类型格式');
}
const suffix = typeParts[1];
try {
// 使用 atob() 对 base64 数据进行解码,结果是一个文件数据流以字符串的格式输出
const bstr = window.atob(data[1]);
// 获取解码结果字符串的长度
const n = bstr.length;
// 根据解码结果字符串的长度创建一个等长的整型数字数组
const u8arr = new Uint8Array(n);
// 优化的 Uint8Array 填充逻辑
for (let i = 0; i < n; i++) {
// 使用 charCodeAt() 获取字符对应的字节值Base64 解码后的字符串是字节级别的)
// eslint-disable-next-line unicorn/prefer-code-point
u8arr[i] = bstr.charCodeAt(i);
}
// 返回 File 文件对象
return new File([u8arr], `${fileName}.${suffix}`, { type });
} catch (error) {
throw new Error(
`Base64 解码失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
}
}
/**
* 通用下载触发函数
* @param href - 文件下载的 URL

View File

@@ -0,0 +1,194 @@
import { isEmpty, isString, isUndefined } from './inference';
/**
* 将一个整数转换为分数保留传入的小数
* @param num
* @param digit
*/
export function formatToFractionDigit(
num: number | string | undefined,
digit: number = 2,
): string {
if (isUndefined(num)) return '0.00';
const parsedNumber = isString(num) ? Number.parseFloat(num) : num;
return (parsedNumber / 100).toFixed(digit);
}
/**
* 将一个整数转换为分数保留两位小数
* @param num
*/
export function formatToFraction(num: number | string | undefined): string {
return formatToFractionDigit(num, 2);
}
/**
* 将一个数转换为 1.00 这样
* 数据呈现的时候使用
*
* @param num 整数
*/
export function floatToFixed2(num: number | string | undefined): string {
let str = '0.00';
if (isUndefined(num)) return str;
const f = formatToFraction(num);
const decimalPart = f.toString().split('.')[1];
const len = decimalPart ? decimalPart.length : 0;
switch (len) {
case 0: {
str = `${f.toString()}.00`;
break;
}
case 1: {
str = `${f.toString()}0`;
break;
}
case 2: {
str = f.toString();
break;
}
}
return str;
}
/**
* 将一个分数转换为整数
* @param num
*/
export function convertToInteger(num: number | string | undefined): number {
if (isUndefined(num)) return 0;
const parsedNumber = isString(num) ? Number.parseFloat(num) : num;
return Math.round(parsedNumber * 100);
}
/**
* 元转分
*/
export function yuanToFen(amount: number | string): number {
return convertToInteger(amount);
}
/**
* 分转元
*/
export function fenToYuan(price: number | string): string {
return formatToFraction(price);
}
/**
* 计算环比
*
* @param value 当前数值
* @param reference 对比数值
*/
export function calculateRelativeRate(
value?: number,
reference?: number,
): number {
// 防止除0
if (!reference || reference === 0) return 0;
return Number.parseFloat(
((100 * ((value || 0) - reference)) / reference).toFixed(0),
);
}
// ========== ERP 专属方法 ==========
const ERP_COUNT_DIGIT = 3;
const ERP_PRICE_DIGIT = 2;
/**
* 【ERP】格式化 Input 数字
*
* 例如说:库存数量
*
* @param num 数量
* @package
* @return 格式化后的数量
*/
export function erpNumberFormatter(
num: number | string | undefined,
digit: number,
) {
if (num === null || num === undefined) {
return '';
}
if (typeof num === 'string') {
num = Number.parseFloat(num);
}
// 如果非 number则直接返回空串
if (Number.isNaN(num)) {
return '';
}
return num.toFixed(digit);
}
/**
* 【ERP】格式化数量保留三位小数
*
* 例如说:库存数量
*
* @param num 数量
* @return 格式化后的数量
*/
export function erpCountInputFormatter(num: number | string | undefined) {
return erpNumberFormatter(num, ERP_COUNT_DIGIT);
}
/**
* 【ERP】格式化数量保留三位小数
*
* @param cellValue 数量
* @return 格式化后的数量
*/
export function erpCountTableColumnFormatter(cellValue: any) {
return erpNumberFormatter(cellValue, ERP_COUNT_DIGIT);
}
/**
* 【ERP】格式化金额保留二位小数
*
* 例如说:库存数量
*
* @param num 数量
* @return 格式化后的数量
*/
export function erpPriceInputFormatter(num: number | string | undefined) {
return erpNumberFormatter(num, ERP_PRICE_DIGIT);
}
/**
* 【ERP】格式化金额保留二位小数
*
* @param cellValue 数量
* @return 格式化后的数量
*/
export function erpPriceTableColumnFormatter(cellValue: any) {
return erpNumberFormatter(cellValue, ERP_PRICE_DIGIT);
}
/**
* 【ERP】价格计算四舍五入保留两位小数
*
* @param price 价格
* @param count 数量
* @return 总价格。如果有任一为空,则返回 undefined
*/
export function erpPriceMultiply(price: number, count: number) {
if (isEmpty(price) || isEmpty(count)) return undefined;
return Number.parseFloat((price * count).toFixed(ERP_PRICE_DIGIT));
}
/**
* 【ERP】百分比计算四舍五入保留两位小数
*
* 如果 total 为 0则返回 0
*
* @param value 当前值
* @param total 总值
*/
export function erpCalculatePercentage(value: number, total: number) {
if (total === 0) return 0;
return ((value / total) * 100).toFixed(2);
}

View File

@@ -3,6 +3,7 @@ export * from './date';
export * from './diff';
export * from './dom';
export * from './download';
export * from './formatNumber';
export * from './inference';
export * from './letter';
export * from './merge';

View File

@@ -164,4 +164,48 @@ function handleTree(
return tree;
}
export { filterTree, handleTree, mapTree, traverseTreeValues };
/**
* 获取节点的完整结构
* @param tree 树数据
* @param nodeId 节点 id
*/
function treeToString(tree: any[], nodeId: number | string) {
if (tree === undefined || !Array.isArray(tree) || tree.length === 0) {
console.warn('tree must be an array');
return '';
}
// 校验是否是一级节点
const node = tree.find((item) => item.id === nodeId);
if (node !== undefined) {
return node.name;
}
let str = '';
function performAThoroughValidation(arr: any[]) {
if (arr === undefined || !Array.isArray(arr) || arr.length === 0) {
return false;
}
for (const item of arr) {
if (item.id === nodeId) {
str += ` / ${item.name}`;
return true;
} else if (item.children !== undefined && item.children.length > 0) {
str += ` / ${item.name}`;
if (performAThoroughValidation(item.children)) {
return true;
}
}
}
return false;
}
for (const item of tree) {
str = `${item.name}`;
if (performAThoroughValidation(item.children)) {
break;
}
}
return str;
}
export { filterTree, handleTree, mapTree, traverseTreeValues, treeToString };

View File

@@ -122,6 +122,7 @@ async function onBtnClick(value: ValueType) {
v-bind="btnDefaultProps"
:variant="innerValue.includes(btn.value) ? 'default' : 'outline'"
@click="onBtnClick(btn.value)"
type="button"
>
<div class="icon-wrapper" v-if="props.showIcon">
<slot

View File

@@ -0,0 +1,39 @@
<script lang="ts" setup>
import type { DocAlertProps } from './types';
import { isDocAlertEnable } from '@vben/hooks';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { cn, openWindow } from '@vben-core/shared/utils';
defineOptions({
name: 'DocAlert',
});
const props = defineProps<DocAlertProps>();
function goToUrl() {
openWindow(props.url);
}
</script>
<template>
<!-- Alert Component -->
<!-- TODO @xingyu是不是左右边距 + 和搜索的对齐会好看一丢丢的 -->
<div
role="alert"
v-if="isDocAlertEnable()"
:class="
cn(
'border-primary bg-primary/10 relative m-1 flex w-full items-center gap-5 rounded-md border p-1',
)
"
>
<span class="grid shrink-0 place-items-center">
<VbenIcon icon="mdi:information-outline" class="text-primary size-5" />
</span>
<div class="text-primary w-full font-sans text-sm leading-none">
{{ title }}文档地址
<a class="hover:text-primary" @click="goToUrl">{{ url }}</a>
</div>
</div>
</template>

View File

@@ -0,0 +1,2 @@
export { default as DocAlert } from './doc-alert.vue';
export * from './types';

View File

@@ -0,0 +1,4 @@
export interface DocAlertProps {
title: string;
url: string;
}

View File

@@ -2,6 +2,7 @@ export * from './api-component';
export * from './captcha';
export * from './col-page';
export * from './count-to';
export * from './doc-alert';
export * from './ellipsis-text';
export * from './icon-picker';
export * from './json-viewer';

View File

@@ -63,7 +63,7 @@ onMounted(() => {
ref="docRef"
:class="
cn(
'bg-card border-border relative flex items-end rounded-md border-b p-4',
'bg-card border-border relative flex items-start rounded-md border-b p-1',
)
"
>

View File

@@ -8,19 +8,40 @@ import { isFunction } from '@vben/utils';
import { useElementHover } from '@vueuse/core';
interface HoverDelayOptions {
/** 鼠标进入延迟时间 */
enterDelay?: (() => number) | number;
/** 鼠标离开延迟时间 */
leaveDelay?: (() => number) | number;
}
const DEFAULT_LEAVE_DELAY = 500; // 鼠标离开延迟时间,默认为 500ms
const DEFAULT_ENTER_DELAY = 0; // 鼠标进入延迟时间,默认为 0立即响应
/**
* 监测鼠标是否在元素内部,如果在元素内部则返回 true否则返回 false
* @param refElement 所有需要检测的元素。如果提供了一个数组,那么鼠标在任何一个元素内部都会返回 true
* @param delay 延迟更新状态的时间
* @param delay 延迟更新状态的时间,可以是数字或包含进入/离开延迟的配置对象
* @returns 返回一个数组,第一个元素是一个 ref表示鼠标是否在元素内部第二个元素是一个控制器可以通过 enable 和 disable 方法来控制监听器的启用和禁用
*/
export function useHoverToggle(
refElement: Arrayable<MaybeElementRef>,
delay: (() => number) | number = 500,
delay: (() => number) | HoverDelayOptions | number = DEFAULT_LEAVE_DELAY,
) {
// 兼容旧版本API
const normalizedOptions: HoverDelayOptions =
typeof delay === 'number' || isFunction(delay)
? { enterDelay: DEFAULT_ENTER_DELAY, leaveDelay: delay }
: {
enterDelay: DEFAULT_ENTER_DELAY,
leaveDelay: DEFAULT_LEAVE_DELAY,
...delay,
};
const isHovers: Array<Ref<boolean>> = [];
const value = ref(false);
const timer = ref<ReturnType<typeof setTimeout> | undefined>();
const enterTimer = ref<ReturnType<typeof setTimeout> | undefined>();
const leaveTimer = ref<ReturnType<typeof setTimeout> | undefined>();
const refs = Array.isArray(refElement) ? refElement : [refElement];
refs.forEach((refEle) => {
const eleRef = computed(() => {
@@ -32,15 +53,47 @@ export function useHoverToggle(
});
const isOutsideAll = computed(() => isHovers.every((v) => !v.value));
function clearTimers() {
if (enterTimer.value) {
clearTimeout(enterTimer.value);
enterTimer.value = undefined;
}
if (leaveTimer.value) {
clearTimeout(leaveTimer.value);
leaveTimer.value = undefined;
}
}
function setValueDelay(val: boolean) {
timer.value && clearTimeout(timer.value);
timer.value = setTimeout(
() => {
value.value = val;
timer.value = undefined;
},
isFunction(delay) ? delay() : delay,
);
clearTimers();
if (val) {
// 鼠标进入
const enterDelay = normalizedOptions.enterDelay ?? DEFAULT_ENTER_DELAY;
const delayTime = isFunction(enterDelay) ? enterDelay() : enterDelay;
if (delayTime <= 0) {
value.value = true;
} else {
enterTimer.value = setTimeout(() => {
value.value = true;
enterTimer.value = undefined;
}, delayTime);
}
} else {
// 鼠标离开
const leaveDelay = normalizedOptions.leaveDelay ?? DEFAULT_LEAVE_DELAY;
const delayTime = isFunction(leaveDelay) ? leaveDelay() : leaveDelay;
if (delayTime <= 0) {
value.value = false;
} else {
leaveTimer.value = setTimeout(() => {
value.value = false;
leaveTimer.value = undefined;
}, delayTime);
}
}
}
const watcher = watch(
@@ -61,7 +114,7 @@ export function useHoverToggle(
};
onUnmounted(() => {
timer.value && clearTimeout(timer.value);
clearTimers();
});
return [value, controller] as [typeof value, typeof controller];

View File

@@ -26,14 +26,14 @@ function getDefaultState(): VxeGridProps {
};
}
export class VxeGridApi {
export class VxeGridApi<T extends Record<string, any> = any> {
public formApi = {} as ExtendedFormApi;
// private prevState: null | VxeGridProps = null;
public grid = {} as VxeGridInstance;
public state: null | VxeGridProps = null;
public grid = {} as VxeGridInstance<T>;
public state: null | VxeGridProps<T> = null;
public store: Store<VxeGridProps>;
public store: Store<VxeGridProps<T>>;
private isMounted = false;
@@ -99,8 +99,8 @@ export class VxeGridApi {
setState(
stateOrFn:
| ((prev: VxeGridProps) => Partial<VxeGridProps>)
| Partial<VxeGridProps>,
| ((prev: VxeGridProps<T>) => Partial<VxeGridProps<T>>)
| Partial<VxeGridProps<T>>,
) {
if (isFunction(stateOrFn)) {
this.store.setState((prev) => {

View File

@@ -9,7 +9,7 @@ import type { Ref } from 'vue';
import type { ClassType, DeepPartial } from '@vben/types';
import type { VbenFormProps } from '@vben-core/form-ui';
import type { BaseFormComponentType, VbenFormProps } from '@vben-core/form-ui';
import type { VxeGridApi } from './api';
@@ -35,7 +35,11 @@ export interface SeparatorOptions {
show?: boolean;
backgroundColor?: string;
}
export interface VxeGridProps {
export interface VxeGridProps<
T extends Record<string, any> = any,
D extends BaseFormComponentType = BaseFormComponentType,
> {
/**
* 标题
*/
@@ -55,15 +59,15 @@ export interface VxeGridProps {
/**
* vxe-grid 配置
*/
gridOptions?: DeepPartial<VxeTableGridOptions>;
gridOptions?: DeepPartial<VxeTableGridOptions<T>>;
/**
* vxe-grid 事件
*/
gridEvents?: DeepPartial<VxeGridListeners>;
gridEvents?: DeepPartial<VxeGridListeners<T>>;
/**
* 表单配置
*/
formOptions?: VbenFormProps;
formOptions?: VbenFormProps<D>;
/**
* 显示搜索表单
*/
@@ -74,9 +78,12 @@ export interface VxeGridProps {
separator?: boolean | SeparatorOptions;
}
export type ExtendedVxeGridApi = VxeGridApi & {
useStore: <T = NoInfer<VxeGridProps>>(
selector?: (state: NoInfer<VxeGridProps>) => T,
export type ExtendedVxeGridApi<
D extends Record<string, any> = any,
F extends BaseFormComponentType = BaseFormComponentType,
> = VxeGridApi<D> & {
useStore: <T = NoInfer<VxeGridProps<D, F>>>(
selector?: (state: NoInfer<VxeGridProps<any, any>>) => T,
) => Readonly<Ref<T>>;
};

View File

@@ -1,3 +1,5 @@
import type { BaseFormComponentType } from '@vben-core/form-ui';
import type { ExtendedVxeGridApi, VxeGridProps } from './types';
import { defineComponent, h, onBeforeUnmount } from 'vue';
@@ -7,16 +9,19 @@ import { useStore } from '@vben-core/shared/store';
import { VxeGridApi } from './api';
import VxeGrid from './use-vxe-grid.vue';
export function useVbenVxeGrid(options: VxeGridProps) {
export function useVbenVxeGrid<
T extends Record<string, any> = any,
D extends BaseFormComponentType = BaseFormComponentType,
>(options: VxeGridProps<T, D>) {
// const IS_REACTIVE = isReactive(options);
const api = new VxeGridApi(options);
const extendedApi: ExtendedVxeGridApi = api as ExtendedVxeGridApi;
const extendedApi: ExtendedVxeGridApi<T, D> = api as ExtendedVxeGridApi<T, D>;
extendedApi.useStore = (selector) => {
return useStore(api.store, selector);
};
const Grid = defineComponent(
(props: VxeGridProps, { attrs, slots }) => {
(props: VxeGridProps<T>, { attrs, slots }) => {
onBeforeUnmount(() => {
api.unmount();
});

View File

@@ -1,6 +1,8 @@
import type { RequestClient } from '../request-client';
import type { RequestClientConfig } from '../types';
import { isUndefined } from '@vben/utils';
class FileUploader {
private client: RequestClient;
@@ -18,10 +20,10 @@ class FileUploader {
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, item);
!isUndefined(item) && formData.append(`${key}[${index}]`, item);
});
} else {
formData.append(key, value);
!isUndefined(value) && formData.append(key, value);
}
});

View File

@@ -9,6 +9,7 @@ export function getPopupContainer(node?: HTMLElement): HTMLElement {
);
}
// TODO @xingyu这个需要 pr 给 vben 官方么?体感上,这个是全局性的哈;
/**
* VxeTable专用弹窗层
* 解决问题: https://gitee.com/dapppp/ruoyi-plus-vben5/issues/IB1DM3