update: 升级vben5.5.9到5.7.0

This commit is contained in:
2026-09-22 17:09:46 +08:00
parent 345e4a31f8
commit 802f72cd9e
766 changed files with 28468 additions and 15447 deletions
@@ -1,7 +1,8 @@
<script lang="ts" setup>
import type { Component } from 'vue';
import type { AnyPromiseFunction } from '@vben/types';
import type {
ApiComponentProps,
ApiComponentOptionsItem as OptionsItem,
} from './types';
import { computed, nextTick, ref, unref, useAttrs, watch } from 'vue';
@@ -11,70 +12,13 @@ import { cloneDeep, get, isEqual, isFunction } from '@vben-core/shared/utils';
import { objectOmit } from '@vueuse/core';
type OptionsItem = {
[name: string]: any;
children?: OptionsItem[];
disabled?: boolean;
label?: string;
value?: string;
};
interface Props {
/** 组件 */
component: Component;
/** 是否将value从数字转为string */
numberToString?: boolean;
/** 获取options数据的函数 */
api?: (arg?: any) => Promise<OptionsItem[] | Record<string, any>>;
/** 传递给api的参数 */
params?: Record<string, any>;
/** 从api返回的结果中提取options数组的字段名 */
resultField?: string;
/** label字段名 */
labelField?: string;
/** children字段名,需要层级数据的组件可用 */
childrenField?: string;
/** value字段名 */
valueField?: string;
/** 组件接收options数据的属性名 */
optionsPropName?: string;
/** 是否立即调用api */
immediate?: boolean;
/** 每次`visibleEvent`事件发生时都重新请求数据 */
alwaysLoad?: boolean;
/** 在api请求之前的回调函数 */
beforeFetch?: AnyPromiseFunction<any, any>;
/** 在api请求之后的回调函数 */
afterFetch?: AnyPromiseFunction<any, any>;
/** 直接传入选项数据,也作为api返回空数据时的后备数据 */
options?: OptionsItem[];
/** 组件的插槽名称,用来显示一个"加载中"的图标 */
loadingSlot?: string;
/** 触发api请求的事件名 */
visibleEvent?: string;
/** 组件的v-model属性名,默认为modelValue。部分组件可能为value */
modelPropName?: string;
/**
* 自动选择
* - `first`:自动选择第一个选项
* - `last`:自动选择最后一个选项
* - `one`: 当请求的结果只有一个选项时,自动选择该选项
* - 函数:自定义选择逻辑,函数的参数为请求的结果数组,返回值为选择的选项
* - false:不自动选择(默认)
*/
autoSelect?:
| 'first'
| 'last'
| 'one'
| ((item: OptionsItem[]) => OptionsItem)
| false;
}
defineOptions({ name: 'ApiComponent', inheritAttrs: false });
const props = withDefaults(defineProps<Props>(), {
const props = withDefaults(defineProps<ApiComponentProps>(), {
labelField: 'label',
valueField: 'value',
labelFn: undefined,
disabledField: 'disabled',
childrenField: '',
optionsPropName: 'options',
resultField: '',
@@ -85,6 +29,7 @@ const props = withDefaults(defineProps<Props>(), {
alwaysLoad: false,
loadingSlot: '',
beforeFetch: undefined,
shouldFetch: undefined,
afterFetch: undefined,
modelPropName: 'modelValue',
api: undefined,
@@ -108,27 +53,39 @@ const isFirstLoaded = ref(false);
const hasPendingRequest = ref(false);
const getOptions = computed(() => {
const { labelField, valueField, childrenField, numberToString } = props;
const {
labelField,
labelFn,
valueField,
disabledField,
childrenField,
numberToString,
} = props;
const refOptionsData = unref(refOptions);
function transformData(data: OptionsItem[]): OptionsItem[] {
function transformData(data: OptionsItem[] = []): OptionsItem[] {
return data.map((item) => {
const value = get(item, valueField);
const children = childrenField ? get(item, childrenField) : item.children;
return {
...objectOmit(item, [labelField, valueField, childrenField]),
label: get(item, labelField),
...objectOmit(item, [
labelField,
valueField,
disabledField,
...(childrenField ? [childrenField] : []),
]),
label: labelFn ? labelFn(item) : get(item, labelField),
value: numberToString ? `${value}` : value,
...(childrenField && item[childrenField]
? { children: transformData(item[childrenField]) }
disabled: get(item, disabledField),
...(Array.isArray(children) && children.length > 0
? { children: transformData(children) }
: {}),
};
});
}
const data: OptionsItem[] = transformData(refOptionsData);
const data = transformData(unref(refOptions));
return data.length > 0 ? data : props.options;
return data.length > 0 ? data : transformData(props.options);
});
const bindProps = computed(() => {
@@ -148,7 +105,7 @@ const bindProps = computed(() => {
});
async function fetchApi() {
const { api, beforeFetch, afterFetch, resultField } = props;
const { api, beforeFetch, shouldFetch, afterFetch, resultField } = props;
if (!api || !isFunction(api)) {
return;
@@ -167,6 +124,14 @@ async function fetchApi() {
if (beforeFetch && isFunction(beforeFetch)) {
finalParams = (await beforeFetch(cloneDeep(finalParams))) || finalParams;
}
// 判断是否需要控制执行中断
if (
shouldFetch &&
isFunction(shouldFetch) &&
!(await shouldFetch(finalParams))
) {
return;
}
let res = await api(finalParams);
if (afterFetch && isFunction(afterFetch)) {
res = (await afterFetch(res)) || res;
@@ -264,7 +229,7 @@ defineExpose({
/** 获取当前值 */
getValue: () => unref(modelValue),
/** 获取被包装的组件实例 */
getComponentRef: <T = any,>() => componentRef.value as T,
getComponentRef: <T = any>() => componentRef.value as T,
/** 更新Api参数 */
updateParam(newParams: Record<string, any>) {
innerParams.value = newParams;
@@ -1 +1,7 @@
export { default as ApiComponent } from './api-component.vue';
export type {
ApiComponentLabelFn,
ApiComponentOptionsItem,
ApiComponentProps,
ApiComponentSharedProps,
} from './types';
@@ -0,0 +1,72 @@
import type { Component } from 'vue';
import type { AnyPromiseFunction } from '@vben/types';
export type ApiComponentOptionsItem = {
[name: string]: any;
children?: ApiComponentOptionsItem[];
disabled?: boolean;
label?: string;
value?: number | string;
};
export type ApiComponentLabelFn = (item: ApiComponentOptionsItem) => string;
export interface ApiComponentProps {
/** 组件 */
component: Component;
/** 是否将value从数字转为string */
numberToString?: boolean;
/** 获取options数据的函数 */
api?: (arg?: any) => Promise<ApiComponentOptionsItem[] | Record<string, any>>;
/** 传递给api的参数 */
params?: Record<string, any>;
/** 从api返回的结果中提取options数组的字段名 */
resultField?: string;
/** label字段名 */
labelField?: string;
/** 通过选项数据自定义label */
labelFn?: ApiComponentLabelFn;
/** children字段名,需要层级数据的组件可用 */
childrenField?: string;
/** value字段名 */
valueField?: string;
/** disabled字段名 */
disabledField?: string;
/** 组件接收options数据的属性名 */
optionsPropName?: string;
/** 是否立即调用api */
immediate?: boolean;
/** 每次`visibleEvent`事件发生时都重新请求数据 */
alwaysLoad?: boolean;
/** 在api请求之前的回调函数 */
beforeFetch?: AnyPromiseFunction<any, any>;
/** 在api请求之前的判断是否允许请求的回调函数 */
shouldFetch?: AnyPromiseFunction<any, boolean>;
/** 在api请求之后的回调函数 */
afterFetch?: AnyPromiseFunction<any, any>;
/** 直接传入选项数据,也作为api返回空数据时的后备数据 */
options?: ApiComponentOptionsItem[];
/** 组件的插槽名称,用来显示一个"加载中"的图标 */
loadingSlot?: string;
/** 触发api请求的事件名 */
visibleEvent?: string;
/** 组件的v-model属性名,默认为modelValue。部分组件可能为value */
modelPropName?: string;
/**
* 自动选择
* - `first`:自动选择第一个选项
* - `last`:自动选择最后一个选项
* - `one`: 当请求的结果只有一个选项时,自动选择该选项
* - 函数:自定义选择逻辑,函数的参数为请求的结果数组,返回值为选择的选项
* - false:不自动选择(默认)
*/
autoSelect?:
| 'first'
| 'last'
| 'one'
| ((item: ApiComponentOptionsItem[]) => ApiComponentOptionsItem)
| false;
}
export type ApiComponentSharedProps = Omit<ApiComponentProps, 'component'>;
@@ -152,7 +152,7 @@ function handleConfirm() {
top: `${point.y - POINT_OFFSET}px`,
left: `${point.x - POINT_OFFSET}px`,
}"
class="bg-primary text-primary-50 border-primary-50 absolute z-20 flex h-5 w-5 cursor-default items-center justify-center rounded-full border-2"
class="absolute z-20 flex-center size-5 cursor-default rounded-full border-2 border-primary-50 bg-primary text-primary-50"
role="button"
tabindex="0"
>
@@ -163,11 +163,11 @@ function handleConfirm() {
v-if="hintImage"
:alt="$t('ui.captcha.alt')"
:src="hintImage"
class="border-border h-10 w-full rounded border"
class="h-10 w-full rounded-sm border border-border"
/>
<div
v-else-if="hintText"
class="border-border flex-center h-10 w-full rounded border"
class="flex-center h-10 w-full rounded-sm border border-border"
>
{{ `${$t('ui.captcha.clickInOrder')}` + `【${hintText}】` }}
</div>
@@ -64,7 +64,9 @@ function handleClick(e: MouseEvent) {
</div>
</CardTitle>
</CardHeader>
<CardContent class="relative mt-2 flex w-full overflow-hidden rounded p-0">
<CardContent
class="relative mt-2 flex w-full overflow-hidden rounded-sm p-0"
>
<img
v-show="captchaImage"
:alt="$t('ui.captcha.alt')"
@@ -50,9 +50,11 @@ defineExpose({
});
const wrapperRef = useTemplateRef<HTMLDivElement>('wrapperRef');
const barRef = useTemplateRef<typeof SliderCaptchaBar>('barRef');
const contentRef = useTemplateRef<typeof SliderCaptchaContent>('contentRef');
const actionRef = useTemplateRef<typeof SliderCaptchaAction>('actionRef');
const barRef = useTemplateRef<InstanceType<typeof SliderCaptchaBar>>('barRef');
const contentRef =
useTemplateRef<InstanceType<typeof SliderCaptchaContent>>('contentRef');
const actionRef =
useTemplateRef<InstanceType<typeof SliderCaptchaAction>>('actionRef');
watch(
() => state.isPassing,
@@ -83,20 +85,19 @@ function handleDragStart(e: MouseEvent | TouchEvent) {
if (state.isPassing) {
return;
}
if (!actionRef.value) return;
const actionEl = actionRef.value;
const actionStyle = actionEl?.getStyle();
if (!actionEl || !actionStyle) return;
emit('start', e);
state.moveDistance =
getEventPageX(e) -
Number.parseInt(
actionRef.value.getStyle().left.replace('px', '') || '0',
10,
);
Number.parseInt(actionStyle.left.replace('px', '') || '0', 10);
state.startTime = Date.now();
state.isMoving = true;
}
function getOffset(actionEl: HTMLDivElement) {
function getOffset(actionEl?: HTMLDivElement | null) {
const wrapperWidth = wrapperRef.value?.offsetWidth ?? 220;
const actionWidth = actionEl?.offsetWidth ?? 40;
const offset = wrapperWidth - actionWidth - 6;
@@ -109,7 +110,9 @@ function handleDragMoving(e: MouseEvent | TouchEvent) {
const actionEl = unref(actionRef);
const barEl = unref(barRef);
if (!actionEl || !barEl) return;
const { actionWidth, offset, wrapperWidth } = getOffset(actionEl.getEl());
const actionNode = actionEl.getEl();
if (!actionNode) return;
const { actionWidth, offset, wrapperWidth } = getOffset(actionNode);
const moveX = getEventPageX(e) - moveDistance;
emit('move', {
@@ -138,14 +141,18 @@ function handleDragOver(e: MouseEvent | TouchEvent) {
const barEl = unref(barRef);
if (!actionEl || !barEl) return;
const moveX = getEventPageX(e) - moveDistance;
const { actionWidth, offset, wrapperWidth } = getOffset(actionEl.getEl());
const actionNode = actionEl.getEl();
if (!actionNode) return;
const { actionWidth, offset, wrapperWidth } = getOffset(actionNode);
if (moveX < offset) {
if (props.isSlot) {
setTimeout(() => {
if (modelValue.value) {
const contentEl = unref(contentRef);
if (contentEl) {
contentEl.getEl().style.width = `${Number.parseInt(barEl.getEl().style.width)}px`;
const contentNode = contentEl?.getEl();
const barNode = barEl.getEl();
if (contentNode && barNode) {
contentNode.style.width = `${Number.parseInt(barNode.style.width || '0', 10)}px`;
}
} else {
resume();
@@ -185,7 +192,10 @@ function resume() {
const contentEl = unref(contentRef);
if (!actionEl || !barEl || !contentEl) return;
contentEl.getEl().style.width = '100%';
const contentNode = contentEl.getEl();
if (!contentNode) return;
contentNode.style.width = '100%';
state.toLeft = true;
useTimeoutFn(() => {
state.toLeft = false;
@@ -200,7 +210,7 @@ function resume() {
ref="wrapperRef"
:class="
cn(
'border-border bg-background-deep relative flex h-10 w-full items-center overflow-hidden rounded-md border text-center',
'relative flex h-10 w-full items-center overflow-hidden rounded-md border border-border bg-muted text-center',
props.class,
)
"
@@ -48,14 +48,14 @@ defineExpose({
<div
ref="actionRef"
:class="{
'transition-width !left-0 duration-300': toLeft,
'transition-width left-0! duration-300': toLeft,
'rounded-md': isDragging,
}"
:style="style"
class="bg-background dark:bg-accent absolute left-0 top-0 flex h-full cursor-move items-center justify-center px-3.5 shadow-md"
class="absolute top-0 left-0 flex-center z-10 h-full cursor-move border-r border-border bg-background px-3.5 shadow-md dark:bg-accent"
name="captcha-action"
>
<Slot :is-passing="isPassing" class="text-foreground/60 size-4">
<Slot :is-passing="isPassing" class="size-4 text-foreground/60">
<slot name="icon">
<ChevronsRight v-if="!isPassing" />
<Check v-else />
@@ -33,8 +33,8 @@ defineExpose({
<template>
<div
ref="barRef"
:class="toLeft && 'transition-width !w-0 duration-300'"
:class="toLeft && 'transition-width w-0! duration-300'"
:style="style"
class="bg-success absolute h-full"
class="absolute h-full bg-success"
></div>
</template>
@@ -3,8 +3,6 @@ import type { CSSProperties } from 'vue';
import { computed, useTemplateRef } from 'vue';
import { VbenSpineText } from '@vben-core/shadcn-ui';
const props = defineProps<{
contentStyle: CSSProperties;
isPassing: boolean;
@@ -32,22 +30,14 @@ defineExpose({
<template>
<div
ref="contentRef"
:class="{
[$style.success]: isPassing,
}"
:style="style"
class="absolute top-0 flex size-full select-none items-center justify-center text-xs"
class="absolute top-0 flex-center size-full select-none text-xs"
:class="isPassing ? 'font-medium text-foreground' : 'text-muted-foreground'"
>
<slot name="text">
<VbenSpineText class="flex h-full items-center">
<span class="flex h-full items-center">
{{ isPassing ? successText : text }}
</VbenSpineText>
</span>
</slot>
</div>
</template>
<style module>
.success {
-webkit-text-fill-color: hsl(0deg 0% 98%);
}
</style>
@@ -84,12 +84,12 @@ function handleDragBarMove(data: SliderRotateVerifyPassingData) {
state.dragging = true;
const { imageSize, maxDegree } = props;
const { moveX } = data;
const denominator = imageSize!;
const denominator = imageSize;
if (denominator === 0) {
return;
}
const currentRotate = Math.ceil(
(moveX / denominator) * 1.5 * maxDegree! * unref(getFactorRef),
(moveX / denominator) * 1.5 * maxDegree * unref(getFactorRef),
);
state.currentRotate = currentRotate;
setImgRotate(state.randomRotate - currentRotate);
@@ -98,7 +98,7 @@ function handleDragBarMove(data: SliderRotateVerifyPassingData) {
function handleImgOnLoad() {
const { maxDegree, minDegree } = props;
const ranRotate = Math.floor(
minDegree! + Math.random() * (maxDegree! - minDegree!),
minDegree + Math.random() * (maxDegree - minDegree),
); // 生成随机角度
state.randomRotate = ranRotate;
setImgRotate(ranRotate);
@@ -167,7 +167,7 @@ defineExpose({
<div class="relative flex flex-col items-center">
<div
:style="getImgWrapStyleRef"
class="border-border relative cursor-pointer overflow-hidden rounded-full border shadow-md"
class="relative cursor-pointer overflow-hidden rounded-full border border-border shadow-md"
>
<img
:class="imgCls"
@@ -35,12 +35,12 @@ const emit = defineEmits<{
}>();
const PI: number = Math.PI;
enum CanvasOpr {
// eslint-disable-next-line no-unused-vars
Clip = 'clip',
// eslint-disable-next-line no-unused-vars
Fill = 'fill',
}
const canvasOpr = {
clip: 'clip',
fill: 'fill',
} as const;
type CanvasOpr = (typeof canvasOpr)[keyof typeof canvasOpr];
const modalValue = defineModel<boolean>({ default: false });
@@ -189,8 +189,8 @@ function draw(ctx1: CanvasRenderingContext2D, ctx2: CanvasRenderingContext2D) {
3 * circleRadius,
canvasHeight - (squareLength + 2 * circleRadius),
);
drawPiece(ctx1, state.pieceX, state.pieceY, CanvasOpr.Fill);
drawPiece(ctx2, state.pieceX, state.pieceY, CanvasOpr.Clip);
drawPiece(ctx1, state.pieceX, state.pieceY, canvasOpr.fill);
drawPiece(ctx2, state.pieceX, state.pieceY, canvasOpr.clip);
}
// 绘制拼图切块
@@ -233,7 +233,7 @@ function drawPiece(
ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)';
ctx.stroke();
opr === CanvasOpr.Clip ? ctx.clip() : ctx.fill();
opr === canvasOpr.clip ? ctx.clip() : ctx.fill();
ctx.globalCompositeOperation = 'destination-over';
}
@@ -261,7 +261,7 @@ onMounted(() => {
<template>
<div class="relative flex flex-col items-center">
<div
class="border-border relative flex cursor-pointer overflow-hidden border shadow-md"
class="relative flex cursor-pointer overflow-hidden border border-border shadow-md"
>
<canvas
ref="puzzleCanvasRef"
@@ -278,7 +278,7 @@ onMounted(() => {
@click="resume"
></canvas>
<div
class="h-15 absolute bottom-3 left-0 z-10 block w-full text-center text-xs leading-[30px] text-white"
class="absolute bottom-3 left-0 z-10 block h-15 w-full text-center text-xs leading-[30px] text-white"
>
<div
v-if="state.showTip"
@@ -54,8 +54,7 @@ export interface PointSelectionCaptchaCardProps {
width?: number | string;
}
export interface PointSelectionCaptchaProps
extends PointSelectionCaptchaCardProps {
export interface PointSelectionCaptchaProps extends PointSelectionCaptchaCardProps {
/**
* 是否展示确定按钮
* @default false
@@ -1,7 +1,7 @@
<script lang="ts" setup>
import type { ColPageProps } from './types';
import { computed, nextTick, onMounted, ref, unref, useSlots, watch } from 'vue';
import { computed, ref, useSlots } from 'vue';
import {
ResizableHandle,
@@ -18,34 +18,12 @@ defineOptions({
const props = withDefaults(defineProps<ColPageProps>(), {
leftWidth: 30,
leftCollapsed: false,
rightWidth: 70,
resizable: true,
});
const emit = defineEmits<{
'update:leftWidth': [width: number];
'update:leftCollapsed': [collapsed: boolean];
}>();
const delegatedProps = computed(() => {
const {
leftWidth: _leftWidth,
leftMinWidth: _leftMinWidth,
leftMaxWidth: _leftMaxWidth,
leftCollapsedWidth: _leftCollapsedWidth,
leftCollapsible: _leftCollapsible,
leftCollapsed: _leftCollapsed,
rightWidth: _rightWidth,
rightMinWidth: _rightMinWidth,
rightMaxWidth: _rightMaxWidth,
rightCollapsedWidth: _rightCollapsedWidth,
rightCollapsible: _rightCollapsible,
resizable: _resizable,
splitLine: _splitLine,
splitHandle: _splitHandle,
...delegated
} = props;
const { leftWidth: _, ...delegated } = props;
return delegated;
});
@@ -63,32 +41,6 @@ const delegatedSlots = computed(() => {
});
const leftPanelRef = ref<InstanceType<typeof ResizablePanel>>();
/** 自身操作引起的回写,避免与外部 v-model 互相触发 */
const suppressExternalSync = ref(false);
const leftDefaultSize = computed(() =>
props.leftCollapsed
? (props.leftCollapsedWidth ?? 0)
: props.leftWidth,
);
const rightDefaultSize = computed(() =>
props.leftCollapsed
? 100 - (props.leftCollapsedWidth ?? 0)
: props.rightWidth,
);
function isLeftCollapsed() {
return !!unref(leftPanelRef.value?.isCollapsed);
}
function runAsSelfApply(apply: () => void) {
suppressExternalSync.value = true;
apply();
void nextTick(() => {
suppressExternalSync.value = false;
});
}
function expandLeft() {
leftPanelRef.value?.expand();
@@ -98,56 +50,6 @@ function collapseLeft() {
leftPanelRef.value?.collapse();
}
function applyCollapsed(collapsed: boolean) {
const panel = leftPanelRef.value;
if (!panel) return;
if (collapsed) {
panel.collapse();
return;
}
panel.expand();
void nextTick(() => panel.resize(props.leftWidth));
}
function onLeftCollapse() {
runAsSelfApply(() => emit('update:leftCollapsed', true));
}
function onLeftExpand() {
runAsSelfApply(() => emit('update:leftCollapsed', false));
}
/** 收起过程中的尺寸不写入展开宽度 */
function onLeftResize(size: number) {
const collapsedSize = props.leftCollapsedWidth ?? 0;
if (isLeftCollapsed() || size <= collapsedSize + 0.51) return;
if (Math.abs(size - props.leftWidth) < 0.15) return;
runAsSelfApply(() => emit('update:leftWidth', size));
}
watch(
() => props.leftCollapsed,
(collapsed) => {
if (suppressExternalSync.value) return;
applyCollapsed(collapsed);
},
);
watch(
() => props.leftWidth,
(width) => {
if (suppressExternalSync.value || isLeftCollapsed()) return;
const current = leftPanelRef.value?.getSize();
if (current == null || Math.abs(current - width) < 0.3) return;
leftPanelRef.value?.resize(width);
},
);
onMounted(() => {
if (!props.leftCollapsed) return;
void nextTick(() => applyCollapsed(true));
});
defineExpose({
expandLeft,
collapseLeft,
@@ -166,16 +68,12 @@ defineExpose({
<ResizablePanelGroup class="w-full" direction="horizontal">
<ResizablePanel
id="col-page-left"
ref="leftPanelRef"
:collapsed-size="leftCollapsedWidth"
:collapsible="leftCollapsible"
:default-size="leftDefaultSize"
:default-size="leftWidth"
:max-size="leftMaxWidth"
:min-size="leftMinWidth"
@collapse="onLeftCollapse"
@expand="onLeftExpand"
@resize="onLeftResize"
>
<template #default="slotProps">
<slot
@@ -194,10 +92,9 @@ defineExpose({
:with-handle="splitHandle"
/>
<ResizablePanel
id="col-page-right"
:collapsed-size="rightCollapsedWidth"
:collapsible="rightCollapsible"
:default-size="rightDefaultSize"
:default-size="rightWidth"
:max-size="rightMaxWidth"
:min-size="rightMinWidth"
>
@@ -2,7 +2,7 @@ import type { PageProps } from '../page/types';
export interface ColPageProps extends PageProps {
/**
* 左侧宽度(百分比 1-100)。配合 `update:leftWidth` 可做受控/持久化。
* 左侧宽度
* @default 30
*/
leftWidth?: number;
@@ -10,10 +10,6 @@ export interface ColPageProps extends PageProps {
leftMaxWidth?: number;
leftCollapsedWidth?: number;
leftCollapsible?: boolean;
/**
* 左侧是否收起。配合 `update:leftCollapsed` 可做受控/持久化。
*/
leftCollapsed?: boolean;
/**
* 右侧宽度
* @default 70
@@ -0,0 +1,981 @@
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue';
// 定义组件参数
const props = defineProps<{
/** 裁剪比例 格式如 '1:1', '16:9', '3:4' 等(非必填) */
aspectRatio?: string;
/** 容器高度(默认400) */
height?: number;
/** 图片地址 */
img: string;
/** 容器宽度(默认500) */
width?: number;
}>();
const CROPPER_CONSTANTS = {
MIN_WIDTH: 60 as const,
MIN_HEIGHT: 60 as const,
DEFAULT_WIDTH: 500 as const,
DEFAULT_HEIGHT: 400 as const,
PADDING_RATIO: 0.1 as const,
MAX_PADDING: 50 as const,
} as const;
type Point = [number, number]; // [clientX, clientY]
type Dimension = [number, number, number, number]; // [top, right, bottom, left]
// 拖拽点类型
type DragAction =
| 'bottom'
| 'bottom-left'
| 'bottom-right'
| 'left'
| 'move'
| 'right'
| 'top'
| 'top-left'
| 'top-right';
// DOM 引用
const containerRef = ref<HTMLDivElement | null>(null);
const bgImageRef = ref<HTMLImageElement | null>(null);
// const maskRef = ref<HTMLDivElement | null>(null);
const maskViewRef = ref<HTMLDivElement | null>(null);
const cropperRef = ref<HTMLDivElement | null>(null);
// const cropperViewRef = ref<HTMLDivElement | null>(null);
// 响应式数据
const isCropperVisible = ref<boolean>(false);
const validAspectRatio = ref<null | number>(null); // 有效比例值(null表示无固定比例)
const containerWidth = ref<number>(
props.width ?? CROPPER_CONSTANTS.DEFAULT_WIDTH,
);
const containerHeight = ref<number>(
props.height ?? CROPPER_CONSTANTS.DEFAULT_HEIGHT,
);
// 裁剪区域尺寸(top, right, bottom, left)
const currentDimension = ref<Dimension>([50, 50, 50, 50]);
const initDimension = ref<Dimension>([50, 50, 50, 50]);
// 拖拽状态
const dragging = ref<boolean>(false);
const startPoint = ref<Point>([0, 0]);
const startDimension = ref<Dimension>([0, 0, 0, 0]);
const direction = ref<Dimension>([0, 0, 0, 0]);
const moving = ref<boolean>(false);
/**
* 计算图片的适配尺寸,保证完整显示且不超过最大宽高限制
*/
const calculateImageFitSize = () => {
if (!bgImageRef.value) return;
// 获取图片原始尺寸
const imgWidth = bgImageRef.value.naturalWidth;
const imgHeight = bgImageRef.value.naturalHeight;
if (imgWidth === 0 || imgHeight === 0) return;
// 计算缩放比例(使用传入的width/height,默认500/400)
const widthRatio =
(props.width ?? CROPPER_CONSTANTS.DEFAULT_WIDTH) / imgWidth;
const heightRatio =
(props.height ?? CROPPER_CONSTANTS.DEFAULT_HEIGHT) / imgHeight;
const scaleRatio = Math.min(widthRatio, heightRatio, 1); // 不放大图片,只缩小
// 计算适配后的容器尺寸
const fitWidth = Math.floor(imgWidth * scaleRatio);
const fitHeight = Math.floor(imgHeight * scaleRatio);
containerWidth.value = fitWidth;
containerHeight.value = fitHeight;
// 重置裁剪框初始尺寸(基于新的容器尺寸)
const padding = Math.min(
CROPPER_CONSTANTS.MAX_PADDING,
Math.floor(fitWidth * CROPPER_CONSTANTS.PADDING_RATIO),
Math.floor(fitHeight * CROPPER_CONSTANTS.PADDING_RATIO),
);
initDimension.value = [padding, padding, padding, padding];
currentDimension.value = [padding, padding, padding, padding];
};
/**
* 验证并解析比例字符串
* @returns {number|null} 比例值 (width/height),解析失败返回null
*/
const parseAndValidateAspectRatio = (): null | number => {
// 如果未传入比例参数,直接返回null
if (!props.aspectRatio) {
return null;
}
// 验证比例格式
const ratioRegex = /^[1-9]\d*:[1-9]\d*$/;
if (!ratioRegex.test(props.aspectRatio)) {
console.warn('裁剪比例格式错误,应为 "数字:数字" 格式,如 "16:9"');
return null;
}
// 解析比例
const [width, height] = props.aspectRatio.split(':').map(Number);
// 验证解析结果有效性
if (Number.isNaN(width) || Number.isNaN(height) || !width || !height) {
console.warn('裁剪比例解析失败,宽高必须为正整数');
return null;
}
return width / height;
};
/**
* 设置裁剪区域尺寸
* @param {Dimension} dimension - [top, right, bottom, left]
*/
const setDimension = (dimension: Dimension) => {
currentDimension.value = [...dimension];
if (maskViewRef.value) {
maskViewRef.value.style.clipPath = `inset(${dimension[0]}px ${dimension[1]}px ${dimension[2]}px ${dimension[3]}px)`;
}
};
/**
* 调整裁剪区域至指定比例
*/
const adjustCropperToAspectRatio = () => {
if (!cropperRef.value) return;
// 验证并解析比例
validAspectRatio.value = parseAndValidateAspectRatio();
// 如果无有效比例,使用初始尺寸,不强制固定比例
if (validAspectRatio.value === null) {
setDimension(initDimension.value);
return;
}
// 有有效比例,按比例调整裁剪框
const ratio = validAspectRatio.value;
const containerWidthVal = containerWidth.value;
const containerHeightVal = containerHeight.value;
// 根据比例计算裁剪框尺寸
let newHeight: number, newWidth: number;
// 先按宽度优先计算
newWidth = containerWidthVal;
newHeight = newWidth / ratio;
// 如果高度超出容器,按高度优先计算
if (newHeight > containerHeightVal) {
newHeight = containerHeightVal;
newWidth = newHeight * ratio;
}
// 居中显示
const leftRight = (containerWidthVal - newWidth) / 2;
const topBottom = (containerHeightVal - newHeight) / 2;
const newDimension: Dimension = [topBottom, leftRight, topBottom, leftRight];
setDimension(newDimension);
};
/**
* 创建裁剪器
*/
const createCropper = () => {
// 计算图片适配尺寸
calculateImageFitSize();
isCropperVisible.value = true;
adjustCropperToAspectRatio();
};
/**
* 处理鼠标按下事件
* @param {MouseEvent} e - 鼠标事件
* @param {DragAction} action - 操作类型
*/
const handleMouseDown = (e: MouseEvent, action: DragAction) => {
dragging.value = true;
startPoint.value = [e.clientX, e.clientY];
startDimension.value = [...currentDimension.value];
direction.value = [0, 0, 0, 0];
moving.value = false;
// 处理移动
if (action === 'move') {
direction.value[0] = 1;
direction.value[2] = -1;
direction.value[3] = 1;
direction.value[1] = -1;
moving.value = true;
return;
}
// 处理拖拽方向
switch (action) {
case 'bottom': {
direction.value[2] = -1;
break;
}
case 'bottom-left': {
direction.value[2] = -1;
direction.value[3] = 1;
break;
}
case 'bottom-right': {
direction.value[2] = -1;
direction.value[1] = -1;
break;
}
case 'left': {
direction.value[3] = 1;
break;
}
case 'right': {
direction.value[1] = -1;
break;
}
case 'top': {
direction.value[0] = 1;
break;
}
case 'top-left': {
direction.value[0] = 1;
direction.value[3] = 1;
break;
}
case 'top-right': {
direction.value[0] = 1;
direction.value[1] = -1;
break;
}
}
};
/**
* 处理鼠标移动事件
* @param {MouseEvent} e - 鼠标事件
*/
const handleMouseMove = (e: MouseEvent) => {
if (!dragging.value || !cropperRef.value) return;
const { clientX, clientY } = e;
const diffX = clientX - startPoint.value[0];
const diffY = clientY - startPoint.value[1];
// 处理移动裁剪框
if (moving.value) {
handleMoveCropBox(diffX, diffY);
return;
}
// 无有效比例
if (validAspectRatio.value === null) {
handleFreeAspectResize(diffX, diffY);
} else {
handleFixedAspectResize(diffX, diffY);
}
};
const handleMoveCropBox = (diffX: number, diffY: number) => {
const newDimension = [...startDimension.value] as Dimension;
// 计算临时偏移后的位置
const tempTop = startDimension.value[0] + diffY;
const tempLeft = startDimension.value[3] + diffX;
// 计算裁剪框的固定尺寸
const cropWidth =
containerWidth.value - startDimension.value[3] - startDimension.value[1];
const cropHeight =
containerHeight.value - startDimension.value[0] - startDimension.value[2];
// 边界限制:确保裁剪框完全在容器内,且尺寸不变
// 顶部边界:top >= 0,且 bottom = 容器高度 - top - 裁剪高度 >= 0
newDimension[0] = Math.max(
0,
Math.min(tempTop, containerHeight.value - cropHeight),
);
// 底部边界:bottom = 容器高度 - top - 裁剪高度(由top推导,无需额外计算)
newDimension[2] = containerHeight.value - newDimension[0] - cropHeight;
// 左侧边界:left >= 0,且 right = 容器宽度 - left - 裁剪宽度 >= 0
newDimension[3] = Math.max(
0,
Math.min(tempLeft, containerWidth.value - cropWidth),
);
// 右侧边界:right = 容器宽度 - left - 裁剪宽度(由left推导,无需额外计算)
newDimension[1] = containerWidth.value - newDimension[3] - cropWidth;
// 强制保证尺寸不变(兜底)
const finalWidth = containerWidth.value - newDimension[3] - newDimension[1];
const finalHeight = containerHeight.value - newDimension[0] - newDimension[2];
if (finalWidth !== cropWidth) {
newDimension[1] = containerWidth.value - newDimension[3] - cropWidth;
}
if (finalHeight !== cropHeight) {
newDimension[2] = containerHeight.value - newDimension[0] - cropHeight;
}
// 更新裁剪区域(仅位置变化,尺寸/比例完全不变)
setDimension(newDimension);
};
const handleFreeAspectResize = (diffX: number, diffY: number) => {
const cropperWidth = containerWidth.value;
const cropperHeight = containerHeight.value;
const currentDimensionNew: Dimension = [0, 0, 0, 0];
// 计算新的尺寸,确保不小于最小值
currentDimensionNew[0] = Math.min(
Math.max(startDimension.value[0] + direction.value[0] * diffY, 0),
cropperHeight - CROPPER_CONSTANTS.MIN_HEIGHT,
);
currentDimensionNew[1] = Math.min(
Math.max(startDimension.value[1] + direction.value[1] * diffX, 0),
cropperWidth - CROPPER_CONSTANTS.MIN_WIDTH,
);
currentDimensionNew[2] = Math.min(
Math.max(startDimension.value[2] + direction.value[2] * diffY, 0),
cropperHeight - CROPPER_CONSTANTS.MIN_HEIGHT,
);
currentDimensionNew[3] = Math.min(
Math.max(startDimension.value[3] + direction.value[3] * diffX, 0),
cropperWidth - CROPPER_CONSTANTS.MIN_WIDTH,
);
// 确保裁剪区域宽度和高度不小于最小值
const newWidth =
cropperWidth - currentDimensionNew[3] - currentDimensionNew[1];
const newHeight =
cropperHeight - currentDimensionNew[0] - currentDimensionNew[2];
if (newWidth < CROPPER_CONSTANTS.MIN_WIDTH) {
if (direction.value[3] === 1) {
currentDimensionNew[3] =
cropperWidth - currentDimensionNew[1] - CROPPER_CONSTANTS.MIN_WIDTH;
} else {
currentDimensionNew[1] =
cropperWidth - currentDimensionNew[3] - CROPPER_CONSTANTS.MIN_WIDTH;
}
}
if (newHeight < CROPPER_CONSTANTS.MIN_HEIGHT) {
if (direction.value[0] === 1) {
currentDimensionNew[0] =
cropperHeight - currentDimensionNew[2] - CROPPER_CONSTANTS.MIN_HEIGHT;
} else {
currentDimensionNew[2] =
cropperHeight - currentDimensionNew[0] - CROPPER_CONSTANTS.MIN_HEIGHT;
}
}
setDimension(currentDimensionNew);
};
const handleFixedAspectResize = (diffX: number, diffY: number) => {
if (validAspectRatio.value === null) return;
const cropperWidth = containerWidth.value;
const cropperHeight = containerHeight.value;
// 有有效比例 - 固定比例裁剪
const ratio = validAspectRatio.value;
const currentWidth =
cropperWidth - startDimension.value[3] - startDimension.value[1];
const currentHeight =
cropperHeight - startDimension.value[0] - startDimension.value[2];
let newHeight: number, newWidth: number;
let widthChange = 0;
let heightChange = 0;
// 计算宽度/高度变化量
if (direction.value[3] === 1) widthChange = -diffX;
else if (direction.value[1] === -1) widthChange = diffX;
if (direction.value[0] === 1) heightChange = -diffY;
else if (direction.value[2] === -1) heightChange = diffY;
const isCornerDrag =
(direction.value[3] === 1 || direction.value[1] === -1) &&
(direction.value[0] === 1 || direction.value[2] === -1);
// 计算新尺寸
if (isCornerDrag) {
if (Math.abs(widthChange) > Math.abs(heightChange)) {
newWidth = Math.max(
CROPPER_CONSTANTS.MIN_WIDTH,
currentWidth + widthChange,
);
newHeight = newWidth / ratio;
} else {
newHeight = Math.max(
CROPPER_CONSTANTS.MIN_HEIGHT,
currentHeight + heightChange,
);
newWidth = newHeight * ratio;
}
} else {
if (direction.value[3] === 1 || direction.value[1] === -1) {
newWidth = Math.max(
CROPPER_CONSTANTS.MIN_WIDTH,
currentWidth + widthChange,
);
newHeight = newWidth / ratio;
} else {
newHeight = Math.max(
CROPPER_CONSTANTS.MIN_HEIGHT,
currentHeight + heightChange,
);
newWidth = newHeight * ratio;
}
}
// 限制最大尺寸
const maxWidth = cropperWidth;
const maxHeight = cropperHeight;
if (newWidth > maxWidth) {
newWidth = maxWidth;
newHeight = newWidth / ratio;
}
if (newHeight > maxHeight) {
newHeight = maxHeight;
newWidth = newHeight * ratio;
}
// 计算新的位置
let newLeft = startDimension.value[3];
let newTop = startDimension.value[0];
let newRight = startDimension.value[1];
let newBottom = startDimension.value[2];
// 根据拖拽方向调整位置
if (direction.value[3] === 1) {
newLeft = cropperWidth - newWidth - startDimension.value[1];
} else if (direction.value[1] === -1) {
newRight = cropperWidth - newWidth - startDimension.value[3];
} else if (!isCornerDrag) {
// 居中调整
const currentHorizontalCenter = startDimension.value[3] + currentWidth / 2;
newLeft = Math.max(
0,
Math.min(cropperWidth - newWidth, currentHorizontalCenter - newWidth / 2),
);
newRight = cropperWidth - newWidth - newLeft;
}
if (direction.value[0] === 1) {
newTop = cropperHeight - newHeight - startDimension.value[2];
} else if (direction.value[2] === -1) {
newBottom = cropperHeight - newHeight - startDimension.value[0];
} else if (!isCornerDrag) {
// 居中调整
const currentVerticalCenter = startDimension.value[0] + currentHeight / 2;
newTop = Math.max(
0,
Math.min(
cropperHeight - newHeight,
currentVerticalCenter - newHeight / 2,
),
);
newBottom = cropperHeight - newHeight - newTop;
}
// 边界检查
newLeft = Math.max(0, newLeft);
newTop = Math.max(0, newTop);
newRight = Math.max(0, newRight);
newBottom = Math.max(0, newBottom);
const newDimension: Dimension = [newTop, newRight, newBottom, newLeft];
setDimension(newDimension);
};
/**
* 处理鼠标抬起事件
*/
const handleMouseUp = () => {
dragging.value = false;
moving.value = false;
direction.value = [0, 0, 0, 0];
};
/**
* 处理图片加载完成
*/
const handleImageLoad = () => {
createCropper();
};
/**
* 裁剪图片
* @param {'image/jpeg' | 'image/png'} format - 输出图片格式
* @param {number} quality - 压缩质量(0-1)
* @param {'blob' | 'base64'} outputType - 输出类型
* @param {number} targetWidth - 目标宽度(可选,不传则为原始裁剪宽度)
* @param {number} targetHeight - 目标高度(可选,不传则为原始裁剪高度)
*/
const getCropImage = async (
format: 'image/jpeg' | 'image/png' = 'image/png',
quality: number = 0.92,
outputType: 'base64' | 'blob' = 'blob',
targetWidth?: number,
targetHeight?: number,
): Promise<Blob | string | undefined> => {
if (!props.img || !bgImageRef.value || !containerRef.value) return;
// 质量参数边界修正:强制限制在 0-1 区间,防止传入非法值报错
const validQuality = Math.max(0, Math.min(1, quality));
// 创建临时图片对象获取原始尺寸
const tempImg = new Image();
// 跨域图片处理:仅对非同源的网络图片设置跨域匿名
if (props.img.startsWith('http://') || props.img.startsWith('https://')) {
try {
const url = new URL(props.img);
if (url.origin !== location.origin) {
tempImg.crossOrigin = 'anonymous';
}
} catch {
// Invalid URL,跳过跨域配置,不中断执行
}
}
// 等待临时图片加载完成
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
tempImg.removeEventListener('load', handleLoad);
tempImg.removeEventListener('error', handleError);
reject(new Error('图片加载超时,超时时间10秒'));
}, 10_000);
const handleLoad = () => {
clearTimeout(timeout);
tempImg.removeEventListener('load', handleLoad);
tempImg.removeEventListener('error', handleError);
resolve();
};
const handleError = (err: ErrorEvent) => {
clearTimeout(timeout);
tempImg.removeEventListener('load', handleLoad);
tempImg.removeEventListener('error', handleError);
reject(new Error(`图片加载失败: ${err.message}`));
};
tempImg.addEventListener('load', handleLoad);
tempImg.addEventListener('error', handleError);
tempImg.src = props.img;
});
const containerRect = containerRef.value.getBoundingClientRect();
const imgRect = bgImageRef.value.getBoundingClientRect();
// 1. 计算图片在容器内的渲染参数
const containerWidth = containerRect.width;
const containerHeight = containerRect.height;
const renderedImgWidth = imgRect.width;
const renderedImgHeight = imgRect.height;
const imgOffsetX = (containerWidth - renderedImgWidth) / 2;
const imgOffsetY = (containerHeight - renderedImgHeight) / 2;
// 2. 计算裁剪框在容器内的实际坐标
const [cropTop, cropRight, cropBottom, cropLeft] = currentDimension.value;
const cropBoxWidth = containerWidth - cropLeft - cropRight;
const cropBoxHeight = containerHeight - cropTop - cropBottom;
// 3. 将裁剪框坐标转换为图片上的坐标(考虑图片偏移)
const cropOnImgX = cropLeft - imgOffsetX;
const cropOnImgY = cropTop - imgOffsetY;
// 4. 计算渲染图片到原始图片的缩放比例(保留原始像素)
const scaleX = tempImg.width / renderedImgWidth;
const scaleY = tempImg.height / renderedImgHeight;
// 5. 映射到原始图片的裁剪区域(精确到原始像素,防止越界)
const originalCropX = Math.max(0, Math.floor(cropOnImgX * scaleX));
const originalCropY = Math.max(0, Math.floor(cropOnImgY * scaleY));
const originalCropWidth = Math.min(
Math.floor(cropBoxWidth * scaleX),
tempImg.width - originalCropX,
);
const originalCropHeight = Math.min(
Math.floor(cropBoxHeight * scaleY),
tempImg.height - originalCropY,
);
// 边界校验:裁剪尺寸非法则返回
if (originalCropWidth <= 0 || originalCropHeight <= 0) return;
// 6. 处理高清屏适配(解决Retina屏模糊)
const dpr = window.devicePixelRatio || 1;
// 最终画布尺寸(优先使用传入的目标尺寸,无则用原始裁剪尺寸)
const finalWidth = targetWidth ? Math.max(1, targetWidth) : originalCropWidth;
const finalHeight = targetHeight
? Math.max(1, targetHeight)
: originalCropHeight;
// 创建画布并获取绘制上下文
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
// 画布物理尺寸(乘以设备像素比,保证高清无模糊)
canvas.width = finalWidth * dpr;
canvas.height = finalHeight * dpr;
// 画布显示尺寸(视觉尺寸,和最终展示一致)
canvas.style.width = `${finalWidth}px`;
canvas.style.height = `${finalHeight}px`;
// 缩放画布上下文,适配高清屏DPR
ctx.scale(dpr, dpr);
// 7. 绘制裁剪后的图片(使用原始像素绘制,保证清晰度)
ctx.drawImage(
tempImg,
originalCropX, // 原始图片裁剪起始X(精确像素)
originalCropY, // 原始图片裁剪起始Y(精确像素)
originalCropWidth, // 原始图片裁剪宽度(精确像素)
originalCropHeight, // 原始图片裁剪高度(精确像素)
0, // 画布绘制起始X
0, // 画布绘制起始Y
finalWidth, // 画布绘制宽度(目标尺寸)
finalHeight, // 画布绘制高度(目标尺寸)
);
try {
return outputType === 'base64'
? canvas.toDataURL(format, validQuality)
: new Promise<Blob>((resolve) => {
canvas.toBlob(
(blob) => {
// 兜底:如果blob生成失败,返回空Blob(防止null)
resolve(blob || new Blob([], { type: format }));
},
format,
validQuality,
);
});
} catch (error) {
console.error('图片导出失败:', error);
}
};
// 监听比例变化,重新调整裁剪框
watch(() => props.aspectRatio, adjustCropperToAspectRatio);
// 监听width/height变化,重新计算尺寸
watch([() => props.width, () => props.height], () => {
calculateImageFitSize();
adjustCropperToAspectRatio();
});
// 组件挂载时注册全局事件
onMounted(() => {
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
// 如果图片已经加载完成,手动触发创建裁剪器
if (
bgImageRef.value &&
bgImageRef.value.complete &&
bgImageRef.value.naturalWidth > 0
) {
createCropper();
}
});
// 组件卸载时清理
onUnmounted(() => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
});
defineExpose({ getCropImage });
</script>
<template>
<div
:style="{
width: `${width || CROPPER_CONSTANTS.DEFAULT_WIDTH}px`,
height: `${height || CROPPER_CONSTANTS.DEFAULT_HEIGHT}px`,
}"
class="cropper-action-wrapper"
>
<div
ref="containerRef"
class="cropper-container"
:style="{
width: `${containerWidth}px`,
height: `${containerHeight}px`,
}"
>
<!-- 原图展示 - 自适应尺寸 -->
<img
ref="bgImageRef"
class="cropper-image"
:src="img"
@load="handleImageLoad"
:style="{
maxWidth: '100%',
maxHeight: '100%',
objectFit: 'contain',
}"
alt="裁剪原图"
/>
<!-- 遮罩层 -->
<div
class="cropper-mask"
:style="{
display: isCropperVisible ? 'block' : 'none',
width: '100%',
height: '100%',
}"
>
<div
ref="maskViewRef"
class="cropper-mask-view"
:style="{
backgroundImage: `url(${img})`,
backgroundSize: 'contain',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
clipPath: `inset(${currentDimension[0]}px ${currentDimension[1]}px ${currentDimension[2]}px ${currentDimension[3]}px)`,
width: '100%',
height: '100%',
}"
></div>
</div>
<!-- 裁剪框 -->
<div
ref="cropperRef"
class="cropper-box"
:style="{
display: isCropperVisible ? 'block' : 'none',
width: '100%',
height: '100%',
}"
>
<div
class="cropper-view"
:style="{
inset: `${currentDimension[0]}px ${currentDimension[1]}px ${currentDimension[2]}px ${currentDimension[3]}px`,
}"
>
<!-- 裁剪框辅助线-->
<span class="cropper-dashed-h"></span>
<span class="cropper-dashed-v"></span>
<!-- 裁剪框拖拽区域 -->
<span
class="cropper-move-area"
@mousedown="handleMouseDown($event, 'move')"
></span>
<!-- 边框线 -->
<span class="cropper-line-e"></span>
<span class="cropper-line-n"></span>
<span class="cropper-line-w"></span>
<span class="cropper-line-s"></span>
<!-- 边角拖拽点 -->
<span
class="cropper-point cropper-point-ne"
@mousedown="handleMouseDown($event, 'top-right')"
>
<span class="cropper-point-inner"></span>
</span>
<span
class="cropper-point cropper-point-nw"
@mousedown="handleMouseDown($event, 'top-left')"
>
<span class="cropper-point-inner"></span>
</span>
<span
class="cropper-point cropper-point-sw"
@mousedown="handleMouseDown($event, 'bottom-left')"
>
<span class="cropper-point-inner"></span>
</span>
<span
class="cropper-point cropper-point-se"
@mousedown="handleMouseDown($event, 'bottom-right')"
>
<span class="cropper-point-inner"></span>
</span>
<!-- 边中点拖拽点 -->
<span
class="cropper-point cropper-point-e"
@mousedown="handleMouseDown($event, 'right')"
>
<span class="cropper-point-inner"></span>
</span>
<span
class="cropper-point cropper-point-n"
@mousedown="handleMouseDown($event, 'top')"
>
<span class="cropper-point-inner"></span>
</span>
<span
class="cropper-point cropper-point-w"
@mousedown="handleMouseDown($event, 'left')"
>
<span class="cropper-point-inner"></span>
</span>
<span
class="cropper-point cropper-point-s"
@mousedown="handleMouseDown($event, 'bottom')"
>
<span class="cropper-point-inner"></span>
</span>
</div>
</div>
</div>
</div>
</template>
<style scoped>
@reference "@vben/tailwind-config/theme";
.cropper-action-wrapper {
@apply box-border flex items-center justify-center;
background-color: transparent;
/* 马赛克背景 */
background-image:
linear-gradient(45deg, #ccc 25%, transparent 25%),
linear-gradient(-45deg, #ccc 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #ccc 75%),
linear-gradient(-45deg, transparent 75%, #ccc 75%);
background-position:
0 0,
0 10px,
10px -10px,
-10px 0;
background-size: 20px 20px;
}
.cropper-container {
@apply relative;
}
.cropper-image {
@apply block;
}
/* 遮罩层 */
.cropper-mask {
@apply absolute top-0 left-0 bg-black/50;
}
.cropper-mask-view {
@apply absolute top-0 left-0;
}
/* 裁剪框 */
.cropper-box {
@apply absolute top-0 left-0 z-10;
}
.cropper-view {
@apply absolute top-0 right-0 bottom-0 left-0 outline-1 outline-blue-500 select-none;
}
/* 裁剪框辅助线 */
.cropper-dashed-h {
@apply absolute top-1/3 left-0 block h-1/3 w-full border-t border-b border-dashed border-gray-200/50;
}
.cropper-dashed-v {
@apply absolute top-0 left-1/3 block h-full w-1/3 border-r border-l border-dashed border-gray-200/50;
}
/* 裁剪框拖拽区域 */
.cropper-move-area {
@apply absolute top-0 left-0 block h-full w-full cursor-move bg-white/10;
}
/* 边框拖拽线 */
.cropper-line-e,
.cropper-line-n,
.cropper-line-w,
.cropper-line-s {
@apply absolute block bg-blue-500/10;
}
.cropper-line-e {
@apply top-0 -right-0.75 h-full w-1;
}
.cropper-line-n {
@apply -top-0.75 left-0 h-1 w-full;
}
.cropper-line-w {
@apply top-0 -left-0.75 h-full w-1;
}
.cropper-line-s {
@apply -bottom-0.75 left-0 h-1 w-full;
}
/* 拖拽点 */
.cropper-point {
@apply absolute flex h-2 w-2 items-center justify-center bg-blue-500;
}
.cropper-point-inner {
@apply block h-1.5 w-1.5 bg-white;
}
/* 边角拖拽点位置和光标 */
.cropper-point-ne {
@apply -top-1.25 -right-1.25 cursor-ne-resize;
}
.cropper-point-nw {
@apply -top-1.25 -left-1.25 cursor-nw-resize;
}
.cropper-point-sw {
@apply -bottom-1.25 -left-1.25 cursor-sw-resize;
}
.cropper-point-se {
@apply -right-1.25 -bottom-1.25 cursor-se-resize;
}
/* 边中点拖拽点位置和光标 */
.cropper-point-e {
@apply top-1/2 -right-1.25 -mt-1 cursor-e-resize;
}
.cropper-point-n {
@apply -top-1.25 left-1/2 -ml-1 cursor-n-resize;
}
.cropper-point-w {
@apply top-1/2 -left-1.25 -mt-1 cursor-w-resize;
}
.cropper-point-s {
@apply -bottom-1.25 left-1/2 -ml-1 cursor-s-resize;
}
</style>
@@ -0,0 +1 @@
export { default as VCropper } from './cropper.vue';
@@ -205,7 +205,7 @@ function handleExpand() {
<div
ref="ellipsis"
:class="{
'!cursor-pointer': expand,
'cursor-pointer!': expand,
['block truncate']: line === 1,
[$style.ellipsisMultiLine]: line > 1,
}"
@@ -1,5 +1,5 @@
<script setup lang="ts">
import type { VNode } from 'vue';
import type { IconPickerProps } from './types';
import { computed, ref, useAttrs, watch, watchEffect } from 'vue';
@@ -28,28 +28,7 @@ import { objectOmit, refDebounced, watchDebounced } from '@vueuse/core';
import { fetchIconsData } from './icons';
interface Props {
pageSize?: number;
/** 图标集的名字 */
prefix?: string;
/** 是否自动请求API以获得图标集的数据.提供prefix时有效 */
autoFetchApi?: boolean;
/**
* 图标列表
*/
icons?: string[];
/** Input组件 */
inputComponent?: VNode;
/** 图标插槽名,预览图标将被渲染到此插槽中 */
iconSlot?: string;
/** input组件的值属性名称 */
modelValueProp?: string;
/** 图标样式 */
iconClass?: string;
type?: 'icon' | 'input';
}
const props = withDefaults(defineProps<Props>(), {
const props = withDefaults(defineProps<IconPickerProps>(), {
prefix: 'ant-design',
pageSize: 36,
icons: () => [],
@@ -71,17 +50,10 @@ const modelValue = defineModel({ default: '', type: String });
const visible = ref(false);
const currentSelect = ref('');
const currentPage = ref(1);
const keyword = ref('');
const keywordDebounce = refDebounced(keyword, 300);
const innerIcons = ref<string[]>([]);
/* 当检索关键词变化时,重置分页 */
watch(keywordDebounce, () => {
currentPage.value = 1;
setCurrentPage(1);
});
watchDebounced(
() => props.prefix,
async (prefix) => {
@@ -122,7 +94,7 @@ const showList = computed(() => {
);
});
const { paginationList, total, setCurrentPage } = usePagination(
const { paginationList, total, setCurrentPage, currentPage } = usePagination(
showList,
props.pageSize,
);
@@ -145,7 +117,6 @@ const handleClick = (icon: string) => {
};
const handlePageChange = (page: number) => {
currentPage.value = page;
setCurrentPage(page);
};
@@ -176,6 +147,9 @@ const searchInputProps = computed(() => {
function updateCurrentSelect(v: string) {
currentSelect.value = v;
if (props.modelValueProp === 'modelValue') {
modelValue.value = v;
}
const eventKey = `onUpdate:${props.modelValueProp}`;
if (attrs[eventKey] && isFunction(attrs[eventKey])) {
attrs[eventKey](v);
@@ -227,7 +201,7 @@ defineExpose({ toggleOpenState, open, close });
/>
<VbenIcon
:icon="currentSelect || Grip"
class="absolute right-1 top-1 size-6"
class="absolute top-1 right-1 size-6"
aria-hidden="true"
/>
</div>
@@ -254,7 +228,7 @@ defineExpose({ toggleOpenState, open, close });
</div>
<template v-if="paginationList.length > 0">
<div class="grid max-h-[360px] w-full grid-cols-6 justify-items-center">
<div class="grid max-h-90 w-full grid-cols-6 justify-items-center">
<VbenIconButton
v-for="(item, index) in paginationList"
:key="index"
@@ -317,7 +291,7 @@ defineExpose({ toggleOpenState, open, close });
</template>
<template v-else>
<div class="flex-col-center text-muted-foreground min-h-[150px] w-full">
<div class="flex-col-center min-h-37.5 w-full text-muted-foreground">
<EmptyIcon class="size-10" />
<div class="mt-1 text-sm">{{ $t('common.noData') }}</div>
</div>
@@ -1 +1,2 @@
export { default as IconPicker } from './icon-picker.vue';
export type { IconPickerProps } from './types';
@@ -0,0 +1,22 @@
import type { VNode } from 'vue';
export interface IconPickerProps {
pageSize?: number;
/** 图标集的名字 */
prefix?: string;
/** 是否自动请求API以获得图标集的数据.提供prefix时有效 */
autoFetchApi?: boolean;
/**
* 图标列表
*/
icons?: string[];
/** Input组件 */
inputComponent?: VNode;
/** 图标插槽名,预览图标将被渲染到此插槽中 */
iconSlot?: string;
/** input组件的值属性名称 */
modelValueProp?: string;
/** 图标样式 */
iconClass?: string;
type?: 'icon' | 'input';
}
@@ -2,6 +2,7 @@ export * from './api-component';
export * from './captcha';
export * from './col-page';
export * from './count-to';
export * from './cropper';
export * from './ellipsis-text';
export * from './icon-picker';
export * from './json-viewer';
@@ -9,6 +10,7 @@ export * from './loading';
export * from './page';
export * from './resize';
export * from './tippy';
export * from './tree';
export * from '@vben-core/form-ui';
export * from '@vben-core/popup-ui';
@@ -19,16 +21,22 @@ export {
VbenButtonGroup,
VbenCheckbox,
VbenCheckButtonGroup,
VbenCollapsibleParams,
VbenContextMenu,
VbenCountToAnimator,
VbenFullScreen,
VbenIconButton,
VbenInputPassword,
VbenLoading,
VbenLogo,
VbenPinInput,
VbenSelect,
VbenSpinner,
VbenTree,
} from '@vben-core/shadcn-ui';
export type { FlattenedItem } from '@vben-core/shadcn-ui';
export type {
CollapsibleParamSchema,
CollapsibleParamsProps,
FlattenedItem,
} from '@vben-core/shadcn-ui';
export { globalShareState } from '@vben-core/shared/global-state';
@@ -10,15 +10,12 @@ import type {
JsonViewerValue,
} from './types';
import { computed, useAttrs } from 'vue';
// @ts-ignore
import VueJsonViewer from 'vue-json-viewer';
import { computed, ref, useAttrs } from 'vue';
import VueJsonPretty from 'vue-json-pretty';
import 'vue-json-pretty/lib/styles.css';
import { $t } from '@vben/locales';
import { isBoolean } from '@vben-core/shared/utils';
// @ts-ignore
import JsonBigint from 'json-bigint';
defineOptions({ name: 'JsonViewer' });
@@ -45,30 +42,29 @@ const emit = defineEmits<{
const attrs: SetupContext['attrs'] = useAttrs();
function handleClick(event: MouseEvent) {
if (
event.target instanceof HTMLElement &&
event.target.classList.contains('jv-item')
) {
const pathNode = event.target.closest('.jv-push');
if (!pathNode || !pathNode.hasAttribute('path')) {
return;
const copiedPath = ref<null | string>(null);
const copyConfig = computed(() => {
return {
copiedText: $t('ui.jsonViewer.copied'),
copyText: $t('ui.jsonViewer.copy'),
timeout: 2000,
};
});
function handleCopy(node: any, defaultCopy: () => void) {
defaultCopy();
copiedPath.value = node.path;
emit('copied', {
action: 'copy',
text: JSON.stringify(node.content),
trigger: node.el ?? document.body,
});
setTimeout(() => {
if (copiedPath.value === node.path) {
copiedPath.value = null;
}
const param: JsonViewerValue = {
path: '',
value: '',
depth: 0,
el: event.target,
};
param.path = pathNode.getAttribute('path') || '';
param.depth = Number(pathNode.getAttribute('depth')) || 0;
param.value = event.target.textContent || undefined;
param.value = JSON.parse(param.value);
emit('valueClick', param);
}
emit('click', event);
}, copyConfig.value.timeout ?? 2000);
}
// 支持显示 bigint 数据,如较长的订单号
@@ -86,30 +82,46 @@ const jsonData = computed<Record<string, any>>(() => {
});
const bindProps = computed<Recordable<any>>(() => {
const copyable = {
copyText: $t('ui.jsonViewer.copy'),
copiedText: $t('ui.jsonViewer.copied'),
timeout: 2000,
...(isBoolean(props.copyable) ? {} : props.copyable),
};
const prettyTheme =
props.theme === 'dark' || props.theme === 'dark-json-theme'
? 'dark'
: 'light';
return {
...props,
...attrs,
value: jsonData.value,
onCopied: (event: JsonViewerAction) => emit('copied', event),
onKeyclick: (key: string) => emit('keyClick', key),
onClick: (event: MouseEvent) => handleClick(event),
copyable: props.copyable ? copyable : false,
data: jsonData.value,
deep: props.expanded ? Infinity : props.expandDepth,
showDoubleQuotes: props.showDoubleQuotes,
showLine: props.boxed,
showLength: true,
showIcon: true,
theme: prettyTheme,
collapsedNodeLength: props.previewMode ? 0 : Infinity,
renderNodeActions: !!props.copyable,
};
});
</script>
<template>
<VueJsonViewer v-bind="bindProps">
<template #copy="slotProps">
<slot name="copy" v-bind="slotProps"></slot>
</template>
</VueJsonViewer>
<div :class="[props.theme, { boxed: props.boxed }]" class="vben-json-viewer">
<VueJsonPretty v-bind="bindProps">
<template #renderNodeActions="{ node, defaultActions }">
<slot name="copy" :node="node" :default-actions="defaultActions">
<span
v-if="props.copyable"
class="vben-json-copy-btn"
:class="[{ 'is-copied': copiedPath === node.path }]"
@click.stop="handleCopy(node, defaultActions.copy)"
>
{{
copiedPath === node.path
? copyConfig.copiedText
: copyConfig.copyText
}}
</span>
</slot>
</template>
</VueJsonPretty>
</div>
</template>
<style lang="scss">
@use './style.scss';
@@ -1,98 +1,91 @@
.default-json-theme {
.vben-json-viewer {
font-family: Consolas, Menlo, Courier, monospace;
font-size: 14px;
color: hsl(var(--foreground));
white-space: nowrap;
background: hsl(var(--background));
&.jv-container.boxed {
&.boxed {
padding: 10px;
border: 1px solid hsl(var(--border));
border-radius: 4px;
}
.jv-ellipsis {
display: inline-block;
padding: 0 4px 2px;
font-size: 0.9em;
line-height: 0.9;
vertical-align: 2px;
.vjs-key {
color: hsl(var(--heavy-foreground));
}
.vjs-value-null,
.vjs-value-undefined {
color: hsl(var(--secondary-foreground));
}
.vjs-value-boolean {
color: hsl(var(--red-400));
}
.vjs-value-number {
color: hsl(var(--info-foreground));
}
.vjs-value-string {
color: hsl(var(--primary));
overflow-wrap: break-word;
white-space: normal;
}
.vjs-tree-brackets {
color: hsl(var(--heavy-foreground));
}
.vjs-comment {
color: hsl(var(--secondary-foreground));
}
.vjs-tree-node {
&.is-highlight {
background-color: hsl(var(--accent));
}
}
.vjs-carets {
cursor: pointer;
&:hover {
color: hsl(var(--primary));
}
}
.vjs-indent-unit {
&.has-line {
border-left: 1px solid hsl(var(--border));
}
}
.vben-json-copy-btn {
display: inline-block;
padding: 0 6px;
margin-left: 8px;
font-size: 12px;
line-height: 20px;
color: hsl(var(--primary));
cursor: pointer;
user-select: none;
background-color: hsl(var(--secondary));
border-radius: 3px;
}
opacity: 0;
transition: opacity 0.2s;
.jv-button {
color: hsl(var(--primary));
}
.jv-key {
color: hsl(var(--heavy-foreground));
}
.jv-item {
&.jv-array {
color: hsl(var(--heavy-foreground));
&:hover {
background-color: hsl(var(--accent));
}
&.jv-boolean {
color: hsl(var(--red-400));
}
&.jv-function {
color: hsl(var(--destructive-foreground));
}
&.jv-number {
color: hsl(var(--info-foreground));
}
&.jv-number-float {
color: hsl(var(--info-foreground));
}
&.jv-number-integer {
color: hsl(var(--info-foreground));
}
&.jv-object {
color: hsl(var(--accent-darker));
}
&.jv-undefined {
color: hsl(var(--secondary-foreground));
}
&.jv-string {
color: hsl(var(--primary));
overflow-wrap: break-word;
white-space: normal;
&.is-copied {
color: hsl(var(--success-foreground, var(--primary)));
opacity: 1;
}
}
&.jv-container .jv-code {
padding: 10px;
&.boxed:not(.open) {
padding-bottom: 20px;
margin-bottom: 10px;
}
&.open {
padding-bottom: 10px;
}
.jv-toggle {
&::before {
padding: 0 2px;
border-radius: 2px;
}
&:hover {
&::before {
background: hsl(var(--accent-foreground));
}
}
}
.vjs-tree-node:hover .vben-json-copy-btn {
opacity: 1;
}
}
@@ -16,6 +16,7 @@ const {
autoContentHeight = false,
contentPaddingClass,
heightOffset = 0,
footerFixed = false,
} = defineProps<PageProps>();
const headerHeight = ref(0);
@@ -28,7 +29,7 @@ const footerRef = useTemplateRef<HTMLDivElement>('footerRef');
const contentStyle = computed<StyleValue>(() => {
if (autoContentHeight) {
return {
height: `calc(var(${CSS_VARIABLE_LAYOUT_CONTENT_HEIGHT}) - ${headerHeight.value}px - ${typeof heightOffset === 'number' ? `${heightOffset}px` : heightOffset})`,
height: `calc(var(${CSS_VARIABLE_LAYOUT_CONTENT_HEIGHT}) - ${headerHeight.value}px - ${footerHeight.value}px - ${typeof heightOffset === 'number' ? `${heightOffset}px` : heightOffset})`,
overflowY: shouldAutoHeight.value ? 'auto' : 'unset',
};
}
@@ -39,9 +40,12 @@ async function calcContentHeight() {
if (!autoContentHeight) {
return;
}
shouldAutoHeight.value = false;
await nextTick();
headerHeight.value = headerRef.value?.offsetHeight || 0;
footerHeight.value = footerRef.value?.offsetHeight || 0;
footerHeight.value = footerFixed ? 0 : footerRef.value?.offsetHeight || 0;
setTimeout(() => {
shouldAutoHeight.value = true;
}, 30);
@@ -53,7 +57,7 @@ onMounted(() => {
</script>
<template>
<div class="relative">
<div class="relative flex min-h-full flex-col">
<div
v-if="
description ||
@@ -65,7 +69,7 @@ onMounted(() => {
ref="headerRef"
:class="
cn(
'bg-card border-border relative flex items-end border-b px-6 py-4',
'relative flex items-end border-b border-border bg-card px-6 py-4',
headerClass,
)
"
@@ -95,16 +99,10 @@ onMounted(() => {
>
<slot></slot>
</div>
<div
v-if="$slots.footer"
ref="footerRef"
:class="
cn(
'bg-card align-center absolute bottom-0 left-0 right-0 flex px-6 py-4',
footerClass,
)
"
:class="cn('align-center flex bg-card px-6 py-4', footerClass)"
>
<slot name="footer"></slot>
</div>
@@ -18,4 +18,10 @@ export interface PageProps {
* @default 0
*/
heightOffset?: number;
/**
* Whether the footer is position: fixed.
* When true, footer height is excluded from content height calculation.
* @default false
*/
footerFixed?: boolean;
}
@@ -264,13 +264,64 @@ const currentStick = ref<null | string>(null);
const parentElement = ref<HTMLElement | null>(null);
const width = computed(() => parentWidth.value! - left.value! - right.value!);
function getPointerPosition(
ev: Partial<{
pageX: number;
pageY: number;
touches: ArrayLike<{ pageX: number; pageY: number }>;
}>,
): null | { pointerX: number; pointerY: number } {
const touch = ev.touches?.[0];
const pointerX = ev.pageX ?? touch?.pageX;
const pointerY = ev.pageY ?? touch?.pageY;
const height = computed(() => parentHeight.value! - top.value! - bottom.value!);
if (
pointerX === null ||
pointerX === undefined ||
pointerY === null ||
pointerY === undefined
) {
return null;
}
return { pointerX, pointerY };
}
const width = computed(() => {
const currentParentWidth = parentWidth.value;
const currentLeft = left.value;
const currentRight = right.value;
if (
currentParentWidth === null ||
currentLeft === null ||
currentRight === null
) {
return 0;
}
return currentParentWidth - currentLeft - currentRight;
});
const height = computed(() => {
const currentParentHeight = parentHeight.value;
const currentTop = top.value;
const currentBottom = bottom.value;
if (
currentParentHeight === null ||
currentTop === null ||
currentBottom === null
) {
return 0;
}
return currentParentHeight - currentTop - currentBottom;
});
const rect = computed(() => ({
left: Math.round(left.value!),
top: Math.round(top.value!),
left: Math.round(left.value ?? 0),
top: Math.round(top.value ?? 0),
width: Math.round(width.value),
height: Math.round(height.value),
}));
@@ -348,36 +399,48 @@ const rectCorrectionByAspectRatio = (rect: {
newTop: number;
}) => {
let { newLeft, newRight, newTop, newBottom } = rect;
// const { parentWidth, parentHeight, currentStick, aspectFactor, dimensionsBeforeMove } = this;
const currentParentWidth = parentWidth.value;
const currentParentHeight = parentHeight.value;
const stick = currentStick.value;
const factor = aspectFactor.value;
let newWidth = parentWidth.value! - newLeft - newRight;
let newHeight = parentHeight.value! - newTop - newBottom;
if (
currentParentWidth === null ||
currentParentHeight === null ||
!stick ||
factor === null
) {
return { newLeft, newRight, newTop, newBottom };
}
if (currentStick.value![1] === 'm') {
let newWidth = currentParentWidth - newLeft - newRight;
let newHeight = currentParentHeight - newTop - newBottom;
if (stick[1] === 'm') {
const deltaHeight = newHeight - dimensionsBeforeMove.value.height;
newLeft -= (deltaHeight * aspectFactor.value!) / 2;
newRight -= (deltaHeight * aspectFactor.value!) / 2;
} else if (currentStick.value![0] === 'm') {
newLeft -= (deltaHeight * factor) / 2;
newRight -= (deltaHeight * factor) / 2;
} else if (stick[0] === 'm') {
const deltaWidth = newWidth - dimensionsBeforeMove.value.width;
newTop -= deltaWidth / aspectFactor.value! / 2;
newBottom -= deltaWidth / aspectFactor.value! / 2;
} else if (newWidth / newHeight > aspectFactor.value!) {
newWidth = aspectFactor.value! * newHeight;
newTop -= deltaWidth / factor / 2;
newBottom -= deltaWidth / factor / 2;
} else if (newWidth / newHeight > factor) {
newWidth = factor * newHeight;
if (currentStick.value![1] === 'l') {
newLeft = parentWidth.value! - newRight - newWidth;
if (stick[1] === 'l') {
newLeft = currentParentWidth - newRight - newWidth;
} else {
newRight = parentWidth.value! - newLeft - newWidth;
newRight = currentParentWidth - newLeft - newWidth;
}
} else {
newHeight = newWidth / aspectFactor.value!;
newHeight = newWidth / factor;
if (currentStick.value![0] === 't') {
newTop = parentHeight.value! - newBottom - newHeight;
if (stick[0] === 't') {
newTop = currentParentHeight - newBottom - newHeight;
} else {
newBottom = parentHeight.value! - newTop - newHeight;
newBottom = currentParentHeight - newTop - newHeight;
}
}
@@ -385,11 +448,17 @@ const rectCorrectionByAspectRatio = (rect: {
};
const stickMove = (delta: { x: number; y: number }) => {
const stick = currentStick.value;
if (!stick) {
return;
}
let newTop = dimensionsBeforeMove.value.top;
let newBottom = dimensionsBeforeMove.value.bottom;
let newLeft = dimensionsBeforeMove.value.left;
let newRight = dimensionsBeforeMove.value.right;
switch (currentStick.value![0]) {
switch (stick[0]) {
case 'b': {
newBottom = dimensionsBeforeMove.value.bottom + delta.y;
@@ -419,7 +488,7 @@ const stickMove = (delta: { x: number; y: number }) => {
}
}
switch (currentStick.value![1]) {
switch (stick[1]) {
case 'l': {
newLeft = dimensionsBeforeMove.value.left - delta.x;
@@ -512,89 +581,121 @@ const calcDragLimitation = () => {
};
const calcResizeLimits = () => {
// const { aspectFactor, width, height, bottom, top, left, right } = this;
const parentLim = parentLimitation.value ? 0 : null;
const currentAspectFactor = aspectFactor.value;
const currentLeft = left.value;
const currentRight = right.value;
const currentTop = top.value;
const currentBottom = bottom.value;
const stick = currentStick.value;
if (aspectRatio.value) {
if (minw.value / minh.value > (aspectFactor.value as number)) {
minh.value = minw.value / (aspectFactor.value as number);
if (
currentLeft === null ||
currentRight === null ||
currentTop === null ||
currentBottom === null
) {
return {
left: { min: parentLim, max: parentLim },
right: { min: parentLim, max: parentLim },
top: { min: parentLim, max: parentLim },
bottom: { min: parentLim, max: parentLim },
};
}
let minWidth = minw.value;
let minHeight = minh.value;
if (aspectRatio.value && currentAspectFactor) {
if (minWidth / minHeight > currentAspectFactor) {
minHeight = minWidth / currentAspectFactor;
} else {
minw.value = ((aspectFactor.value as number) * minh.value) as number;
minWidth = currentAspectFactor * minHeight;
}
}
const limits = {
left: {
min: parentLim,
max: (left.value as number) + (width.value - minw.value),
max: currentLeft + (width.value - minWidth),
},
right: {
min: parentLim,
max: (right.value as number) + (width.value - minw.value),
max: currentRight + (width.value - minWidth),
},
top: {
min: parentLim,
max: (top.value as number) + (height.value - minh.value),
max: currentTop + (height.value - minHeight),
},
bottom: {
min: parentLim,
max: (bottom.value as number) + (height.value - minh.value),
max: currentBottom + (height.value - minHeight),
},
};
if (aspectRatio.value) {
if (aspectRatio.value && currentAspectFactor) {
const aspectLimits = {
left: {
min:
left.value! -
Math.min(top.value!, bottom.value!) * aspectFactor.value! * 2,
currentLeft -
Math.min(currentTop, currentBottom) * currentAspectFactor * 2,
max:
left.value! +
((height.value - minh.value!) / 2) * aspectFactor.value! * 2,
currentLeft +
((height.value - minHeight) / 2) * currentAspectFactor * 2,
},
right: {
min:
right.value! -
Math.min(top.value!, bottom.value!) * aspectFactor.value! * 2,
currentRight -
Math.min(currentTop, currentBottom) * currentAspectFactor * 2,
max:
right.value! +
((height.value - minh.value!) / 2) * aspectFactor.value! * 2,
currentRight +
((height.value - minHeight) / 2) * currentAspectFactor * 2,
},
top: {
min:
top.value! -
(Math.min(left.value!, right.value!) / aspectFactor.value!) * 2,
currentTop -
(Math.min(currentLeft, currentRight) / currentAspectFactor) * 2,
max:
top.value! +
((width.value - minw.value) / 2 / aspectFactor.value!) * 2,
currentTop + ((width.value - minWidth) / 2 / currentAspectFactor) * 2,
},
bottom: {
min:
bottom.value! -
(Math.min(left.value!, right.value!) / aspectFactor.value!) * 2,
currentBottom -
(Math.min(currentLeft, currentRight) / currentAspectFactor) * 2,
max:
bottom.value! +
((width.value - minw.value) / 2 / aspectFactor.value!) * 2,
currentBottom +
((width.value - minWidth) / 2 / currentAspectFactor) * 2,
},
};
if (currentStick.value![0] === 'm') {
if (stick?.[0] === 'm') {
limits.left = {
min: Math.max(limits.left.min!, aspectLimits.left.min),
min: Math.max(
limits.left.min ?? aspectLimits.left.min,
aspectLimits.left.min,
),
max: Math.min(limits.left.max, aspectLimits.left.max),
};
limits.right = {
min: Math.max(limits.right.min!, aspectLimits.right.min),
min: Math.max(
limits.right.min ?? aspectLimits.right.min,
aspectLimits.right.min,
),
max: Math.min(limits.right.max, aspectLimits.right.max),
};
} else if (currentStick.value![1] === 'm') {
} else if (stick?.[1] === 'm') {
limits.top = {
min: Math.max(limits.top.min!, aspectLimits.top.min),
min: Math.max(
limits.top.min ?? aspectLimits.top.min,
aspectLimits.top.min,
),
max: Math.min(limits.top.max, aspectLimits.top.max),
};
limits.bottom = {
min: Math.max(limits.bottom.min!, aspectLimits.bottom.min),
min: Math.max(
limits.bottom.min ?? aspectLimits.bottom.min,
aspectLimits.bottom.min,
),
max: Math.min(limits.bottom.max, aspectLimits.bottom.max),
};
}
@@ -604,9 +705,9 @@ const calcResizeLimits = () => {
};
const positionStyle = computed(() => ({
top: `${top.value}px`,
left: `${left.value}px`,
zIndex: zIndex.value!,
top: `${top.value ?? 0}px`,
left: `${left.value ?? 0}px`,
zIndex: zIndex.value ?? 'auto',
}));
const sizeStyle = computed(() => ({
@@ -618,13 +719,11 @@ const stickStyles = computed(() => (stick: string) => {
const stickStyle = {
width: `${stickSize.value / parentScaleX.value}px`,
height: `${stickSize.value / parentScaleY.value}px`,
[styleMapping.y[stick[0] as 'b' | 'm' | 't'] as 'height' | 'width']:
`${stickSize.value / parentScaleX.value / -2}px`,
[styleMapping.x[stick[1] as 'l' | 'm' | 'r'] as 'height' | 'width']:
`${stickSize.value / parentScaleX.value / -2}px`,
};
stickStyle[
styleMapping.y[stick[0] as 'b' | 'm' | 't'] as 'height' | 'width'
] = `${stickSize.value / parentScaleX.value / -2}px`;
stickStyle[
styleMapping.x[stick[1] as 'l' | 'm' | 'r'] as 'height' | 'width'
] = `${stickSize.value / parentScaleX.value / -2}px`;
return stickStyle;
});
@@ -719,12 +818,15 @@ const stickDown = (
return;
}
const pointerPosition = getPointerPosition(ev);
if (!pointerPosition) {
return;
}
stickDrag.value = true;
const pointerX = ev.pageX === undefined ? ev.touches[0].pageX : ev.pageX;
const pointerY = ev.pageY === undefined ? ev.touches[0].pageY : ev.pageY;
saveDimensionsBeforeMove({ pointerX, pointerY });
saveDimensionsBeforeMove(pointerPosition);
currentStick.value = stick;
@@ -738,13 +840,19 @@ const move = (ev: MouseEvent & TouchEvent) => {
ev.stopPropagation();
// touches 兼容性代码
const pageX = ev.pageX === undefined ? ev.touches![0]!.pageX : ev.pageX;
const pageY = ev.pageY === undefined ? ev.touches![0]!.pageY : ev.pageY;
const pointerPosition = getPointerPosition(ev);
if (!pointerPosition) {
return;
}
const delta = {
x: (dimensionsBeforeMove.value.pointerX - pageX) / parentScaleX.value,
y: (dimensionsBeforeMove.value.pointerY - pageY) / parentScaleY.value,
x:
(dimensionsBeforeMove.value.pointerX - pointerPosition.pointerX) /
parentScaleX.value,
y:
(dimensionsBeforeMove.value.pointerY - pointerPosition.pointerY) /
parentScaleY.value,
};
if (stickDrag.value) {
@@ -812,12 +920,17 @@ onMounted(() => {
left.value = x.value;
top.value = y.value;
right.value = (parentWidth.value -
(w.value === 'auto' ? container.value!.scrollWidth : (w.value as number)) -
left.value) as number;
bottom.value = (parentHeight.value -
(h.value === 'auto' ? container.value!.scrollHeight : (h.value as number)) -
top.value) as number;
const containerElement = container.value;
const contentWidth =
w.value === 'auto'
? (containerElement?.scrollWidth ?? 0)
: (w.value as number);
const contentHeight =
h.value === 'auto'
? (containerElement?.scrollHeight ?? 0)
: (h.value as number);
right.value = (parentWidth.value ?? 0) - contentWidth - (left.value ?? 0);
bottom.value = (parentHeight.value ?? 0) - contentHeight - (top.value ?? 0);
addEvents(domEvents.value);
@@ -841,13 +954,14 @@ onMounted(() => {
);
}
});
onBeforeUnmount(() => {
removeEvents(domEvents.value);
});
const bodyDown = (ev: MouseEvent & TouchEvent) => {
const { target, button } = ev;
const targetElement = target instanceof HTMLElement ? target : null;
const uid = getCurrentInstance()?.uid.toString();
if (!preventActiveBehavior.value) {
active.value = true;
@@ -865,17 +979,13 @@ const bodyDown = (ev: MouseEvent & TouchEvent) => {
if (
dragHandle.value &&
(target! as HTMLElement).dataset.dragHandle !==
getCurrentInstance()?.uid.toString()
targetElement &&
targetElement.dataset.dragHandle !== uid
) {
return;
}
if (
dragCancel.value &&
(target! as HTMLElement).dataset.dragCancel ===
getCurrentInstance()?.uid.toString()
) {
if (dragCancel.value && targetElement?.dataset.dragCancel === uid) {
return;
}
@@ -887,14 +997,17 @@ const bodyDown = (ev: MouseEvent & TouchEvent) => {
ev.preventDefault();
}
const pointerPosition = getPointerPosition(ev);
if (!pointerPosition) {
return;
}
if (isDraggable.value) {
bodyDrag.value = true;
}
const pointerX = ev.pageX === undefined ? ev.touches[0]!.pageX : ev.pageX;
const pointerY = ev.pageY === undefined ? ev.touches[0]!.pageY : ev.pageY;
saveDimensionsBeforeMove({ pointerX, pointerY });
saveDimensionsBeforeMove(pointerPosition);
if (parentLimitation.value) {
limits.value = calcDragLimitation();
@@ -923,8 +1036,10 @@ watch(
watch(
() => z.value,
(val) => {
if ((val as number) >= 0 || val === 'auto') {
zIndex.value = val as number;
if (typeof val === 'number' && val >= 0) {
zIndex.value = val;
} else if (val === 'auto') {
zIndex.value = null;
}
},
{ immediate: true },
@@ -933,13 +1048,22 @@ watch(
watch(
() => x.value,
(newVal, oldVal) => {
if (stickDrag.value || bodyDrag.value || newVal === left.value) {
const currentLeft = left.value;
const currentTop = top.value;
if (
stickDrag.value ||
bodyDrag.value ||
currentLeft === null ||
currentTop === null ||
newVal === currentLeft
) {
return;
}
const delta = oldVal - newVal;
bodyDown({ pageX: left.value!, pageY: top.value! } as MouseEvent &
bodyDown({ pageX: currentLeft, pageY: currentTop } as MouseEvent &
TouchEvent);
bodyMove({ x: delta, y: 0 });
@@ -952,13 +1076,22 @@ watch(
watch(
() => y.value,
(newVal, oldVal) => {
if (stickDrag.value || bodyDrag.value || newVal === top.value) {
const currentLeft = left.value;
const currentTop = top.value;
if (
stickDrag.value ||
bodyDrag.value ||
currentLeft === null ||
currentTop === null ||
newVal === currentTop
) {
return;
}
const delta = oldVal - newVal;
bodyDown({ pageX: left.value, pageY: top.value } as MouseEvent &
bodyDown({ pageX: currentLeft, pageY: currentTop } as MouseEvent &
TouchEvent);
bodyMove({ x: 0, y: delta });
@@ -971,16 +1104,23 @@ watch(
watch(
() => w.value,
(newVal, oldVal) => {
const currentRight = right.value;
const currentTop = top.value;
if (stickDrag.value || bodyDrag.value || newVal === width.value) {
return;
}
if (currentRight === null || currentTop === null) {
return;
}
const stick = 'mr';
const delta = (oldVal as number) - (newVal as number);
stickDown(
stick,
{ pageX: right.value, pageY: top.value! + height.value / 2 },
{ pageX: currentRight, pageY: currentTop + height.value / 2 },
true,
);
stickMove({ x: delta, y: 0 });
@@ -994,16 +1134,23 @@ watch(
watch(
() => h.value,
(newVal, oldVal) => {
const currentLeft = left.value;
const currentBottom = bottom.value;
if (stickDrag.value || bodyDrag.value || newVal === height.value) {
return;
}
if (currentLeft === null || currentBottom === null) {
return;
}
const stick = 'bm';
const delta = (oldVal as number) - (newVal as number);
stickDown(
stick,
{ pageX: left.value! + width.value / 2, pageY: bottom.value },
{ pageX: currentLeft + width.value / 2, pageY: currentBottom },
true,
);
stickMove({ x: 0, y: delta });
@@ -1017,7 +1164,7 @@ watch(
watch(
() => parentW.value,
(val) => {
right.value = val - width.value - left.value!;
right.value = val - width.value - (left.value ?? 0);
parentWidth.value = val;
},
);
@@ -1025,7 +1172,7 @@ watch(
watch(
() => parentH.value,
(val) => {
bottom.value = val - height.value - top.value!;
bottom.value = val - height.value - (top.value ?? 0);
parentHeight.value = val;
},
);
@@ -0,0 +1 @@
export { default as Tree } from './tree.vue';
@@ -0,0 +1,25 @@
<script setup lang="ts">
import type { TreeProps } from '@vben-core/shadcn-ui';
import { Inbox } from '@vben/icons';
import { $t } from '@vben/locales';
import { treePropsDefaults, VbenTree } from '@vben-core/shadcn-ui';
const props = withDefaults(defineProps<TreeProps>(), treePropsDefaults());
</script>
<template>
<VbenTree v-if="props.treeData?.length > 0" v-bind="props">
<template v-for="(_, key) in $slots" :key="key" #[key]="slotProps">
<slot :name="key" v-bind="slotProps"> </slot>
</template>
</VbenTree>
<div
v-else
class="flex-col-center cursor-pointer rounded-lg border p-10 text-sm font-medium text-muted-foreground"
>
<Inbox class="size-10" />
<div class="mt-1">{{ $t('common.noData') }}</div>
</div>
</template>