This commit is contained in:
xingyu4j
2026-01-26 10:13:23 +08:00
62 changed files with 5078 additions and 3451 deletions

View File

@@ -18,9 +18,9 @@
font-size: var(--font-size-base, 16px);
font-variation-settings: normal;
font-synthesis-weight: none;
line-height: 1.15;
text-size-adjust: 100%;
font-synthesis-weight: none;
scroll-behavior: smooth;
text-rendering: optimizelegibility;
-webkit-tap-highlight-color: transparent;

View File

@@ -96,9 +96,6 @@
"devDependencies": {
"@types/crypto-js": "catalog:",
"@types/lodash.clonedeep": "catalog:",
"@types/lodash.get": "catalog:",
"@types/lodash.isequal": "catalog:",
"@types/lodash.set": "catalog:",
"@types/nprogress": "catalog:"
}
}

View File

@@ -116,11 +116,11 @@ describe('getElementVisibleRect', () => {
} as HTMLElement;
expect(getElementVisibleRect(element)).toEqual({
bottom: 800,
bottom: 0,
height: 0,
left: 1100,
right: 1000,
top: 900,
left: 0,
right: 0,
top: 0,
width: 0,
});
});

View File

@@ -41,6 +41,18 @@ export function getElementVisibleRect(
const left = Math.max(rect.left, 0);
const right = Math.min(rect.right, viewWidth);
// 如果元素完全不可见,则返回一个空的矩形
if (top >= viewHeight || bottom <= 0 || left >= viewWidth || right <= 0) {
return {
bottom: 0,
height: 0,
left: 0,
right: 0,
top: 0,
width: 0,
};
}
return {
bottom,
height: Math.max(0, bottom - top),

View File

@@ -29,9 +29,9 @@ describe('useSortable', () => {
await initializeSortable();
// Import sortablejs to access the mocked create function
const Sortable = await import(
'sortablejs/modular/sortable.complete.esm.js'
);
const Sortable =
// @ts-expect-error - This is a dynamic import
await import('sortablejs/modular/sortable.complete.esm.js');
// Verify that Sortable.create was called with the correct parameters
expect(Sortable.default.create).toHaveBeenCalledTimes(1);

View File

@@ -2,33 +2,17 @@ import type { Preferences } from './types';
import { preferencesManager } from './preferences';
// 偏好设置(带有层级关系)
const preferences: Preferences =
preferencesManager.getPreferences.apply(preferencesManager);
// 更新偏好设置
const updatePreferences =
preferencesManager.updatePreferences.bind(preferencesManager);
// 重置偏好设置
const resetPreferences =
preferencesManager.resetPreferences.bind(preferencesManager);
const clearPreferencesCache =
preferencesManager.clearCache.bind(preferencesManager);
// 初始化偏好设置
const initPreferences =
preferencesManager.initPreferences.bind(preferencesManager);
export {
clearPreferencesCache,
initPreferences,
preferences,
preferencesManager,
resetPreferences,
export const {
getPreferences,
updatePreferences,
};
resetPreferences,
clearCache,
initPreferences,
} = preferencesManager;
export const preferences: Preferences = getPreferences();
export { preferencesManager };
export * from './constants';
export type * from './types';

View File

@@ -16,168 +16,168 @@ import {
import { defaultPreferences } from './config';
import { updateCSSVariables } from './update-css-variables';
const STORAGE_KEY = 'preferences';
const STORAGE_KEY_LOCALE = `${STORAGE_KEY}-locale`;
const STORAGE_KEY_THEME = `${STORAGE_KEY}-theme`;
const STORAGE_KEYS = {
MAIN: 'preferences',
LOCALE: 'preferences-locale',
THEME: 'preferences-theme',
} as const;
class PreferenceManager {
private cache: null | StorageManager = null;
// private flattenedState: Flatten<Preferences>;
private cache: StorageManager;
private debouncedSave: (preference: Preferences) => void;
private initialPreferences: Preferences = defaultPreferences;
private isInitialized: boolean = false;
private savePreferences: (preference: Preferences) => void;
private state: Preferences = reactive<Preferences>({
...this.loadPreferences(),
});
private isInitialized = false;
private state: Preferences;
constructor() {
this.cache = new StorageManager();
// 避免频繁的操作缓存
this.savePreferences = useDebounceFn(
(preference: Preferences) => this._savePreferences(preference),
this.state = reactive<Preferences>(
this.loadFromCache() || { ...defaultPreferences },
);
this.debouncedSave = useDebounceFn(
(preference) => this.saveToCache(preference),
150,
);
}
clearCache() {
[STORAGE_KEY, STORAGE_KEY_LOCALE, STORAGE_KEY_THEME].forEach((key) => {
this.cache?.removeItem(key);
});
}
public getInitialPreferences() {
return this.initialPreferences;
}
public getPreferences() {
return readonly(this.state);
}
/**
* 清除所有缓存的偏好设置
*/
clearCache = () => {
Object.values(STORAGE_KEYS).forEach((key) => this.cache.removeItem(key));
};
/**
* 覆盖偏好设置
* overrides 要覆盖的偏好设置
* namespace 命名空间
* 获取初始化偏好设置
*/
public async initPreferences({ namespace, overrides }: InitialOptions) {
// 是否初始化过
getInitialPreferences = () => {
return this.initialPreferences;
};
/**
* 获取当前偏好设置(只读)
*/
getPreferences = () => {
return readonly(this.state);
};
/**
* 初始化偏好设置
* @param options - 初始化配置项
* @param options.namespace - 命名空间,用于隔离不同应用的配置
* @param options.overrides - 要覆盖的偏好设置
*/
initPreferences = async ({ namespace, overrides }: InitialOptions) => {
// 防止重复初始化
if (this.isInitialized) {
return;
}
// 初始化存储管理器
// 使用命名空间初始化存储管理器
this.cache = new StorageManager({ prefix: namespace });
// 合并初始偏好设置
this.initialPreferences = merge({}, overrides, defaultPreferences);
// 加载并合并当前存储的偏好设置
// 加载缓存的偏好设置并与初始配置合并
const cachedPreferences = this.loadFromCache() || {};
const mergedPreference = merge(
{},
// overrides,
this.loadCachedPreferences() || {},
cachedPreferences,
this.initialPreferences,
);
// 更新偏好设置
this.updatePreferences(mergedPreference);
// 设置监听器
this.setupWatcher();
// 初始化平台标识
this.initPlatform();
// 标记为已初始化
this.isInitialized = true;
}
};
/**
* 重置偏好设置
* 偏好设置将被重置为初始值,并从 localStorage 中移除。
*
* @example
* 假设 initialPreferences 为 { theme: 'light', language: 'en' }
* 当前 state 为 { theme: 'dark', language: 'fr' }
* this.resetPreferences();
* 调用后state 将被重置为 { theme: 'light', language: 'en' }
* 并且 localStorage 中的对应项将被移除
* 重置偏好设置到初始状态
*/
resetPreferences() {
resetPreferences = () => {
// 将状态重置为初始偏好设置
Object.assign(this.state, this.initialPreferences);
// 保存重置后的偏好设置
this.savePreferences(this.state);
// 从存储中移除偏好设置项
[STORAGE_KEY, STORAGE_KEY_THEME, STORAGE_KEY_LOCALE].forEach((key) => {
this.cache?.removeItem(key);
});
this.updatePreferences(this.state);
}
// 保存偏好设置至缓存
this.saveToCache(this.state);
// 直接触发 UI 更新
this.handleUpdates(this.state);
};
/**
* 更新偏好设置
* @param updates - 要更新的偏好设置
*/
public updatePreferences(updates: DeepPartial<Preferences>) {
updatePreferences = (updates: DeepPartial<Preferences>) => {
// 深度合并更新内容和当前状态
const mergedState = merge({}, updates, markRaw(this.state));
Object.assign(this.state, mergedState);
// 根据更新的值执行相应的操作
// 根据更新的值执行更新
this.handleUpdates(updates);
this.savePreferences(this.state);
}
// 保存到缓存
this.debouncedSave(this.state);
};
/**
* 保存偏好设置
* @param {Preferences} preference - 需要保存的偏好设置
*/
private _savePreferences(preference: Preferences) {
this.cache?.setItem(STORAGE_KEY, preference);
this.cache?.setItem(STORAGE_KEY_LOCALE, preference.app.locale);
this.cache?.setItem(STORAGE_KEY_THEME, preference.theme.mode);
}
/**
* 处理更新的键值
* 根据更新的键值执行相应的操作。
* @param {DeepPartial<Preferences>} updates - 部分更新的偏好设置
* 处理更新
* @param updates - 更新的偏好设置
*/
private handleUpdates(updates: DeepPartial<Preferences>) {
const themeUpdates = updates.theme || {};
const appUpdates = updates.app || {};
const { theme, app } = updates;
if (
(themeUpdates && Object.keys(themeUpdates).length > 0) ||
Reflect.has(themeUpdates, 'fontSize')
theme &&
(Object.keys(theme).length > 0 || Reflect.has(theme, 'fontSize'))
) {
updateCSSVariables(this.state);
}
if (
Reflect.has(appUpdates, 'colorGrayMode') ||
Reflect.has(appUpdates, 'colorWeakMode')
app &&
(Reflect.has(app, 'colorGrayMode') || Reflect.has(app, 'colorWeakMode'))
) {
this.updateColorMode(this.state);
}
}
/**
* 初始化平台标识
*/
private initPlatform() {
const dom = document.documentElement;
dom.dataset.platform = isMacOs() ? 'macOs' : 'window';
document.documentElement.dataset.platform = isMacOs() ? 'macOs' : 'window';
}
/**
* 从缓存加载偏好设置。如果缓存中没有找到对应的偏好设置,则返回默认偏好设置。
* 从缓存加载偏好设置
* @returns 缓存的偏好设置,如果不存在则返回 null
*/
private loadCachedPreferences() {
return this.cache?.getItem<Preferences>(STORAGE_KEY);
private loadFromCache(): null | Preferences {
return this.cache.getItem<Preferences>(STORAGE_KEYS.MAIN);
}
/**
* 加载偏好设置
* @returns {Preferences} 加载的偏好设置
* 保存偏好设置到缓存
* @param preference - 要保存的偏好设置
*/
private loadPreferences(): Preferences {
return this.loadCachedPreferences() || { ...defaultPreferences };
private saveToCache(preference: Preferences) {
this.cache.setItem(STORAGE_KEYS.MAIN, preference);
this.cache.setItem(STORAGE_KEYS.LOCALE, preference.app.locale);
this.cache.setItem(STORAGE_KEYS.THEME, preference.theme.mode);
}
/**
* 监听状态和系统偏好设置的变化
* 监听状态和系统偏好设置的变化
*/
private setupWatcher() {
if (this.isInitialized) {
@@ -187,6 +187,7 @@ class PreferenceManager {
// 监听断点,判断是否移动端
const breakpoints = useBreakpoints(breakpointsTailwind);
const isMobile = breakpoints.smaller('md');
watch(
() => isMobile.value,
(val) => {
@@ -201,12 +202,13 @@ class PreferenceManager {
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', ({ matches: isDark }) => {
// 如果偏好设置中主题模式为auto跟随系统更新
// 仅在自动模式下跟随系统主题
if (this.state.theme.mode === 'auto') {
// 先应用实际的主题
this.updatePreferences({
theme: { mode: isDark ? 'dark' : 'light' },
});
// 恢复为auto模式
// 恢复为 auto 模式,保持跟随系统的状态
this.updatePreferences({
theme: { mode: 'auto' },
});
@@ -216,19 +218,17 @@ class PreferenceManager {
/**
* 更新页面颜色模式(灰色、色弱)
* @param preference
* @param preference - 偏好设置
*/
private updateColorMode(preference: Preferences) {
if (preference.app) {
const { colorGrayMode, colorWeakMode } = preference.app;
const dom = document.documentElement;
const COLOR_WEAK = 'invert-mode';
const COLOR_GRAY = 'grayscale-mode';
dom.classList.toggle(COLOR_WEAK, colorWeakMode);
dom.classList.toggle(COLOR_GRAY, colorGrayMode);
}
const { colorGrayMode, colorWeakMode } = preference.app;
const dom = document.documentElement;
dom.classList.toggle('invert-mode', colorWeakMode);
dom.classList.toggle('grayscale-mode', colorGrayMode);
}
}
const preferencesManager = new PreferenceManager();
export { PreferenceManager, preferencesManager };

View File

@@ -136,7 +136,7 @@ function usePreferences() {
});
/**
* @zh_CN 登录注册页面布局是否为
* @zh_CN 登录注册页面布局是否为
*/
const authPanelRight = computed(() => {
return appPreferences.value.authPageLayout === 'panel-right';

View File

@@ -53,7 +53,11 @@ const wrapperClass = computed(() => {
provideFormRenderProps(props);
const { isCalculated, keepFormItemIndex, wrapperRef } = useExpandable(props);
const {
isCalculated,
keepFormItemIndex,
wrapperRef: _wrapperRef,
} = useExpandable(props);
const shapes = computed(() => {
const resultShapes: FormShape[] = [];
@@ -170,7 +174,7 @@ const computedSchema = computed(
<template>
<component :is="formComponent" v-bind="formComponentProps">
<div ref="wrapperRef" :class="wrapperClass">
<div ref="_wrapperRef" :class="wrapperClass">
<template v-for="cSchema in computedSchema" :key="cSchema.fieldName">
<!-- <div v-if="$slots[cSchema.fieldName]" :class="cSchema.formItemClass">
<slot :definition="cSchema" :name="cSchema.fieldName"> </slot>

View File

@@ -352,9 +352,9 @@ export interface ActionButtonOptions extends VbenButtonProps {
export interface VbenFormProps<
T extends BaseFormComponentType = BaseFormComponentType,
> extends Omit<
FormRenderProps<T>,
'componentBindEventMap' | 'componentMap' | 'form'
> {
FormRenderProps<T>,
'componentBindEventMap' | 'componentMap' | 'form'
> {
/**
* 操作按钮是否反转(提交按钮前置)
*/

View File

@@ -26,7 +26,8 @@ interface Props {
const props = withDefaults(defineProps<Props>(), {});
const { contentElement, overlayStyle } = useLayoutContentStyle();
const { contentElement: _contentElement, overlayStyle } =
useLayoutContentStyle();
const style = computed((): CSSProperties => {
const {
@@ -55,7 +56,11 @@ const style = computed((): CSSProperties => {
</script>
<template>
<main ref="contentElement" :style="style" class="relative bg-background-deep">
<main
ref="_contentElement"
:style="style"
class="relative bg-background-deep"
>
<Slot :style="overlayStyle">
<slot name="overlay"></slot>
</Slot>

View File

@@ -1,7 +1,7 @@
<script setup lang="ts">
import type { CSSProperties } from 'vue';
import { computed, shallowRef, useSlots, watchEffect } from 'vue';
import { computed, useSlots, watchEffect } from 'vue';
import { VbenScrollbar } from '@vben-core/shadcn-ui';
@@ -114,7 +114,7 @@ const extraVisible = defineModel<boolean>('extraVisible');
const isLocked = useScrollLock(document.body);
const slots = useSlots();
const asideRef = shallowRef<HTMLDivElement | null>();
// const asideRef = shallowRef<HTMLDivElement | null>();
const hiddenSideStyle = computed((): CSSProperties => calcMenuWidthStyle(true));
@@ -290,7 +290,6 @@ function handleMouseleave() {
/>
<div
v-if="isSidebarMixed"
ref="asideRef"
:class="{
'border-l': extraVisible,
}"

View File

@@ -403,13 +403,10 @@ watch(
);
{
const mouseMove = () => {
mouseY.value > headerWrapperHeight.value
? (headerIsHidden.value = true)
: (headerIsHidden.value = false);
};
const HEADER_TRIGGER_DISTANCE = 12;
watch(
[() => props.headerMode, () => mouseY.value],
[() => props.headerMode, () => mouseY.value, () => headerIsHidden.value],
() => {
if (!isHeaderAutoMode.value || isMixedNav.value || isFullContent.value) {
if (props.headerMode !== 'auto-scroll') {
@@ -417,8 +414,12 @@ watch(
}
return;
}
headerIsHidden.value = true;
mouseMove();
const isInTriggerZone = mouseY.value <= HEADER_TRIGGER_DISTANCE;
const isInHeaderZone =
!headerIsHidden.value && mouseY.value <= headerWrapperHeight.value;
headerIsHidden.value = !(isInTriggerZone || isInHeaderZone);
},
{
immediate: true,

View File

@@ -351,14 +351,14 @@ function getActivePaths() {
role="menu"
>
<template v-if="mode === 'horizontal' && getSlot.showSlotMore">
<template v-for="item in getSlot.slotDefault" :key="item.key">
<template v-for="(item, index) in getSlot.slotDefault" :key="index">
<component :is="item" />
</template>
<SubMenu is-sub-menu-more path="sub-menu-more">
<template #title>
<Ellipsis class="size-4" />
</template>
<template v-for="item in getSlot.slotMore" :key="item.key">
<template v-for="(item, index) in getSlot.slotMore" :key="index">
<component :is="item" />
</template>
</SubMenu>

View File

@@ -54,7 +54,7 @@ const components = globalShareState.getComponents();
const id = useId();
provide('DISMISSABLE_DRAWER_ID', id);
const wrapperRef = ref<HTMLElement>();
// const wrapperRef = ref<HTMLElement>();
const { $t } = useSimpleLocale();
const { isMobile } = useIsMobile();
@@ -281,7 +281,6 @@ const getForceMount = computed(() => {
</VisuallyHidden>
</template>
<div
ref="wrapperRef"
:class="
cn('relative flex-1 overflow-y-auto p-3', contentClass, {
'pointer-events-none': showLoading || submitting,

View File

@@ -50,10 +50,10 @@ const props = withDefaults(defineProps<Props>(), {
const components = globalShareState.getComponents();
const contentRef = ref();
const wrapperRef = ref<HTMLElement>();
// const wrapperRef = ref<HTMLElement>();
const dialogRef = ref();
const headerRef = ref();
const footerRef = ref();
// const footerRef = ref();
const id = useId();
@@ -306,7 +306,6 @@ function handleClosed() {
</VisuallyHidden>
</DialogHeader>
<div
ref="wrapperRef"
:class="
cn('relative min-h-40 flex-1 overflow-y-auto p-3', contentClass, {
'pointer-events-none': showLoading || submitting,
@@ -327,7 +326,6 @@ function handleClosed() {
<DialogFooter
v-if="showFooter"
ref="footerRef"
:class="
cn(
'flex-row items-center justify-end p-2',

View File

@@ -41,6 +41,7 @@ export function useVbenModal<TParentModalProps extends ModalProps = ModalProps>(
// 不能用 Object.assign,会丢失 api 的原型函数
Object.setPrototypeOf(extendedApi, api);
},
consumed: false,
options,
async reCreateModal() {
isModalReady.value = false;
@@ -73,7 +74,13 @@ export function useVbenModal<TParentModalProps extends ModalProps = ModalProps>(
return [Modal, extendedApi as ExtendedModalApi] as const;
}
const injectData = inject<any>(USER_MODAL_INJECT_KEY, {});
let injectData = inject<any>(USER_MODAL_INJECT_KEY, {});
// 这个数据已经被使用了说明这个弹窗是嵌套的弹窗不应该merge上层的配置
if (injectData.consumed) {
injectData = {};
} else {
injectData.consumed = true;
}
const mergedOptions = {
...DEFAULT_MODAL_PROPS,

View File

@@ -27,8 +27,10 @@ export type CustomRenderType = (() => Component | string) | string;
export type ValueType = boolean | number | string;
export interface VbenButtonGroupProps
extends Pick<VbenButtonProps, 'disabled'> {
export interface VbenButtonGroupProps extends Pick<
VbenButtonProps,
'disabled'
> {
/** 单选模式下允许清除选中 */
allowClear?: boolean;
/** 值改变前的回调 */

View File

@@ -73,6 +73,7 @@ function handleClick(menu: IContextMenuItem) {
>
<template v-for="menu in menusView" :key="menu.key">
<ContextMenuItem
v-if="!menu.hidden"
:class="itemClass"
:disabled="menu.disabled"
:inset="menu.inset || !menu.icon"

View File

@@ -10,6 +10,10 @@ interface IContextMenuItem {
* @param data
*/
handler?: (data: any) => void;
/**
* @zh_CN 是否隐藏
*/
hidden?: boolean;
/**
* @zh_CN 图标
*/

View File

@@ -27,7 +27,7 @@ function handleItemClick(value: string) {
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuGroup>
<template v-for="menu in menus" :key="menu.key">
<template v-for="menu in menus" :key="menu.value">
<DropdownMenuItem
:class="
menu.value === modelValue

View File

@@ -32,19 +32,19 @@ const props = withDefaults(defineProps<Props>(), {
// const startTime = ref(0);
const showSpinner = ref(false);
const renderSpinner = ref(false);
const timer = ref<ReturnType<typeof setTimeout>>();
let timer: ReturnType<typeof setTimeout> | undefined;
watch(
() => props.spinning,
(show) => {
if (!show) {
showSpinner.value = false;
clearTimeout(timer.value);
timer && clearTimeout(timer);
return;
}
// startTime.value = performance.now();
timer.value = setTimeout(() => {
timer = setTimeout(() => {
// const loadingTime = performance.now() - startTime.value;
showSpinner.value = true;

View File

@@ -3,7 +3,7 @@ import type { TabDefinition } from '@vben-core/typings';
import type { TabConfig, TabsProps } from '../../types';
import { computed, ref } from 'vue';
import { computed } from 'vue';
import { Pin, X } from '@vben-core/icons';
import { VbenContextMenu, VbenIcon } from '@vben-core/shadcn-ui';
@@ -28,8 +28,8 @@ const emit = defineEmits<{
}>();
const active = defineModel<string>('active');
const contentRef = ref();
const tabRef = ref();
// const contentRef = ref();
// const tabRef = ref();
const style = computed(() => {
const { gap } = props;
@@ -73,7 +73,6 @@ function onMouseDown(e: MouseEvent, tab: TabConfig) {
<template>
<div
ref="contentRef"
:class="contentClass"
:style="style"
class="tabs-chrome !flex h-full w-max overflow-y-hidden pr-6"
@@ -82,7 +81,6 @@ function onMouseDown(e: MouseEvent, tab: TabConfig) {
<div
v-for="(tab, i) in tabsView"
:key="tab.key"
ref="tabRef"
:class="[
{
'is-active': tab.key === active,

View File

@@ -29,7 +29,7 @@ const forward = useForwardPropsEmits(props, emit);
const {
handleScrollAt,
handleWheel,
scrollbarRef,
scrollbarRef: _scrollbarRef,
scrollDirection,
scrollIsAtLeft,
scrollIsAtRight,
@@ -69,7 +69,7 @@ useTabsDrag(props, emit);
class="size-full flex-1 overflow-hidden"
>
<VbenScrollbar
ref="scrollbarRef"
ref="_scrollbarRef"
:shadow-bottom="false"
:shadow-top="false"
class="h-full"

View File

@@ -54,8 +54,7 @@ export interface PointSelectionCaptchaCardProps {
width?: number | string;
}
export interface PointSelectionCaptchaProps
extends PointSelectionCaptchaCardProps {
export interface PointSelectionCaptchaProps extends PointSelectionCaptchaCardProps {
/**
* 是否展示确定按钮
* @default false

View File

@@ -0,0 +1,979 @@
<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/jpeg',
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>
.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 left-0 top-0 bg-black/50;
}
.cropper-mask-view {
@apply absolute left-0 top-0;
}
/* 裁剪框 */
.cropper-box {
@apply absolute left-0 top-0 z-10;
}
.cropper-view {
@apply absolute bottom-0 left-0 right-0 top-0 select-none outline outline-1 outline-blue-500;
}
/* 裁剪框辅助线 */
.cropper-dashed-h {
@apply absolute left-0 top-1/3 block h-1/3 w-full border-b border-t border-dashed border-gray-200/50;
}
.cropper-dashed-v {
@apply absolute left-1/3 top-0 block h-full w-1/3 border-l border-r border-dashed border-gray-200/50;
}
/* 裁剪框拖拽区域 */
.cropper-move-area {
@apply absolute left-0 top-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 right-[-3px] top-0 h-full w-1;
}
.cropper-line-n {
@apply left-0 top-[-3px] h-1 w-full;
}
.cropper-line-w {
@apply left-[-3px] top-0 h-full w-1;
}
.cropper-line-s {
@apply bottom-[-3px] 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 right-[-5px] top-[-5px] cursor-ne-resize;
}
.cropper-point-nw {
@apply left-[-5px] top-[-5px] cursor-nw-resize;
}
.cropper-point-sw {
@apply bottom-[-5px] left-[-5px] cursor-sw-resize;
}
.cropper-point-se {
@apply bottom-[-5px] right-[-5px] cursor-se-resize;
}
/* 边中点拖拽点位置和光标 */
.cropper-point-e {
@apply right-[-5px] top-1/2 -mt-1 cursor-e-resize;
}
.cropper-point-n {
@apply left-1/2 top-[-5px] -ml-1 cursor-n-resize;
}
.cropper-point-w {
@apply left-[-5px] top-1/2 -mt-1 cursor-w-resize;
}
.cropper-point-s {
@apply bottom-[-5px] left-1/2 -ml-1 cursor-s-resize;
}
</style>

View File

@@ -0,0 +1 @@
export { default as VCropper } from './cropper.vue';

View File

@@ -7,6 +7,7 @@ export * from './col-page';
export * from './content-wrap';
export * from './count-to';
export * from './doc-alert';
export * from './cropper';
export * from './ellipsis-text';
export * from './icon-picker';
export * from './iframe';
@@ -26,6 +27,7 @@ export {
VbenButtonGroup,
VbenCheckbox,
VbenCheckButtonGroup,
VbenContextMenu,
VbenCountToAnimator,
VbenFullScreen,
VbenInputPassword,

View File

@@ -14,7 +14,7 @@ import {
updatePreferences,
usePreferences,
} from '@vben/preferences';
import { useAccessStore } from '@vben/stores';
import { useAccessStore, useTabbarStore, useTimezoneStore } from '@vben/stores';
import { cloneDeep, mapTree } from '@vben/utils';
import { VbenAdminLayout } from '@vben-core/layout-ui';
@@ -52,6 +52,7 @@ const {
theme,
} = usePreferences();
const accessStore = useAccessStore();
const timezoneStore = useTimezoneStore();
const { refresh } = useRefresh();
const sidebarTheme = computed(() => {
@@ -187,9 +188,19 @@ watch(
},
);
const tabbarStore = useTabbarStore();
function refreshAll() {
tabbarStore.cachedTabs.clear();
refresh();
}
// 语言更新后,刷新页面
// i18n.global.locale会在preference.app.locale变更之后才会更新因此watchpreference.app.locale是不合适的刷新页面时可能语言配置尚未完全加载完成
watch(i18n.global.locale, refresh, { flush: 'post' });
watch(i18n.global.locale, refreshAll, { flush: 'post' });
// 时区更新后,刷新页面
watch(() => timezoneStore.timezone, refreshAll, { flush: 'post' });
const slots: SetupContext['slots'] = useSlots();
const headerSlots = computed(() => {
@@ -351,8 +362,6 @@ const headerSlots = computed(() => {
<VbenLogo
v-if="preferences.logo.enable"
:fit="preferences.logo.fit"
:src="preferences.logo.source"
:src-dark="preferences.logo.sourceDark"
:text="preferences.app.name"
:theme="theme"
>

View File

@@ -19,7 +19,7 @@ import { computed, ref } from 'vue';
import { Copy, Pin, PinOff, RotateCw } from '@vben/icons';
import { $t, loadLocaleMessages } from '@vben/locales';
import {
clearPreferencesCache,
clearCache,
preferences,
resetPreferences,
usePreferences,
@@ -228,7 +228,7 @@ async function handleCopy() {
async function handleClearCache() {
resetPreferences();
clearPreferencesCache();
clearCache();
emit('clearPreferencesAndLogout');
}
@@ -488,6 +488,6 @@ async function handleReset() {
:deep(.sticky-tabs-header [role='tablist']) {
position: sticky;
top: -12px;
z-index: 10;
z-index: 9999;
}
</style>

View File

@@ -106,7 +106,8 @@ function useEcharts(chartRef: Ref<EchartsUIType>) {
return;
}
useTimeoutFn(() => {
if (!chartInstance) {
if (!chartInstance || chartInstance?.getDom() !== el) {
chartInstance?.dispose();
const instance = initCharts();
if (!instance) return;
}
@@ -118,6 +119,36 @@ function useEcharts(chartRef: Ref<EchartsUIType>) {
});
};
const updateDate = (
option: EChartsOption,
notMerge = false, // false = 合并保留动画true = 完全替换
lazyUpdate = false, // true 时不立即重绘,适合短时间内多次调用
): Promise<echarts.ECharts | null> => {
return new Promise((resolve) => {
nextTick(() => {
if (!chartInstance) {
// 还没初始化 → 当作首次渲染
renderEcharts(option).then(resolve);
return;
}
// 合并你原有的全局配置(比如 backgroundColor
const finalOption = {
...option,
...getOptions.value,
};
chartInstance.setOption(finalOption, {
notMerge,
lazyUpdate,
// silent: true, // 如果追求极致性能可开启(关闭所有事件)
});
resolve(chartInstance);
});
});
};
function resize() {
const el = getChartEl();
if (isElHidden(el)) {
@@ -153,6 +184,7 @@ function useEcharts(chartRef: Ref<EchartsUIType>) {
return {
renderEcharts,
resize,
updateDate,
getChartInstance: () => chartInstance,
};
}

View File

@@ -315,6 +315,7 @@ async function init() {
'[Vben Vxe Table]: The formConfig in the grid is not supported, please use the `formOptions` props',
);
}
// @ts-ignore
props.api?.setState?.({ gridOptions: defaultGridOptions });
// form 由 vben-form 代替所以需要保证query相关事件可以拿到参数
extendProxyOptions(props.api, defaultGridOptions, () =>

View File

@@ -8,7 +8,9 @@
"alreadyExists": "{0} `{1}` already exists",
"startWith": "{0} must start with `{1}`",
"invalidURL": "Please input a valid URL",
"mobile": "Please input a valid {0}"
"mobile": "Please input a valid {0}",
"sizeLimit": "The file size cannot exceed {0}MB",
"previewWarning": "Unable to open the file, there is no available URL or preview address"
},
"actionTitle": {
"copy": "Copy {0}",
@@ -42,7 +44,8 @@
},
"placeholder": {
"input": "Please enter",
"select": "Please select"
"select": "Please select",
"upload": "Click to upload"
},
"captcha": {
"title": "Please complete the security verification",
@@ -69,6 +72,13 @@
"copy": "Copy",
"copied": "Copied"
},
"crop": {
"title": "Image Cropping",
"titleTip": "Cropping Ratio {0}",
"confirm": "Crop",
"cancel": "Cancel cropping",
"errorTip": "Cropping error"
},
"fallback": {
"pageNotFound": "Oops! Page Not Found",
"pageNotFoundDesc": "Sorry, we couldn't find the page you were looking for.",

View File

@@ -8,7 +8,9 @@
"alreadyExists": "{0} `{1}` 已存在",
"startWith": "{0}必须以 {1} 开头",
"invalidURL": "请输入有效的链接",
"mobile": "请输入正确的{0}"
"mobile": "请输入正确的{0}",
"sizeLimit": "文件大小不能超过 {0}MB",
"previewWarning": "无法打开文件没有可用的URL或预览地址"
},
"actionTitle": {
"copy": "复制{0}",
@@ -42,7 +44,8 @@
},
"placeholder": {
"input": "请输入",
"select": "请选择"
"select": "请选择",
"upload": "点击上传"
},
"captcha": {
"title": "请完成安全验证",
@@ -69,6 +72,13 @@
"copy": "复制",
"copied": "已复制"
},
"crop": {
"title": "图片裁剪",
"titleTip": "裁剪比例 {0}",
"confirm": "裁剪",
"cancel": "取消裁剪",
"errorTip": "裁剪错误"
},
"fallback": {
"pageNotFound": "哎呀!未找到页面",
"pageNotFoundDesc": "抱歉,我们无法找到您要找的页面。",