refactor api
This commit is contained in:
@@ -1,119 +0,0 @@
|
||||
import axios, {type AxiosInstance, type AxiosResponse, type InternalAxiosRequestConfig} from "axios";
|
||||
import {ApiResponse} from "../types";
|
||||
|
||||
export type ErrorCallback = (response: ApiResponse<any>) => void;
|
||||
export type RequestInterceptor = (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig;
|
||||
export interface ResponseObserverPayload {
|
||||
config?: InternalAxiosRequestConfig;
|
||||
status?: number;
|
||||
response?: AxiosResponse;
|
||||
error?: any;
|
||||
serverResponse?: ApiResponse<any>;
|
||||
}
|
||||
export type ResponseObserver = (payload: ResponseObserverPayload) => void;
|
||||
|
||||
let globalErrorCallback: ErrorCallback | null = null;
|
||||
let globalRequestInterceptor: RequestInterceptor | null = null;
|
||||
let globalResponseObserver: ResponseObserver | null = null;
|
||||
|
||||
export const setGlobalErrorCallback = (callback: ErrorCallback) => {
|
||||
globalErrorCallback = callback;
|
||||
};
|
||||
|
||||
export const setGlobalRequestInterceptor = (callback: RequestInterceptor | null) => {
|
||||
globalRequestInterceptor = callback;
|
||||
};
|
||||
|
||||
export const setGlobalResponseObserver = (callback: ResponseObserver | null) => {
|
||||
globalResponseObserver = callback;
|
||||
};
|
||||
|
||||
const notifyResponseObserver = (payload: ResponseObserverPayload) => {
|
||||
if (!globalResponseObserver) {
|
||||
return;
|
||||
}
|
||||
globalResponseObserver(payload);
|
||||
};
|
||||
|
||||
const applyDefaultInterceptors = (instance: AxiosInstance) => {
|
||||
instance.defaults.withCredentials = true;
|
||||
instance.interceptors.request.use((config) => {
|
||||
if (globalRequestInterceptor) {
|
||||
return globalRequestInterceptor(config);
|
||||
}
|
||||
return config;
|
||||
});
|
||||
instance.interceptors.response.use((axiosResp: any) => {
|
||||
if (!axiosResp.config.responseType) {
|
||||
// 服务端返回
|
||||
const serverResp = axiosResp.data as ApiResponse<any>;
|
||||
if (serverResp.code < 40000) {
|
||||
notifyResponseObserver({
|
||||
config: axiosResp?.config,
|
||||
status: axiosResp?.status,
|
||||
response: axiosResp,
|
||||
serverResponse: serverResp
|
||||
});
|
||||
// 200 或 300 HTTP 状态段视为成功
|
||||
return serverResp.data;
|
||||
} else {
|
||||
notifyResponseObserver({
|
||||
config: axiosResp?.config,
|
||||
status: axiosResp?.status,
|
||||
response: axiosResp,
|
||||
serverResponse: serverResp,
|
||||
error: serverResp.message
|
||||
});
|
||||
if (globalErrorCallback) {
|
||||
globalErrorCallback(serverResp);
|
||||
}
|
||||
// 由调用方处理
|
||||
return Promise.reject(serverResp.message);
|
||||
}
|
||||
}
|
||||
notifyResponseObserver({
|
||||
config: axiosResp?.config,
|
||||
status: axiosResp?.status,
|
||||
response: axiosResp
|
||||
});
|
||||
return axiosResp.data;
|
||||
}, (error: any) => {
|
||||
notifyResponseObserver({
|
||||
config: error?.config,
|
||||
status: error?.response?.status,
|
||||
response: error?.response,
|
||||
error
|
||||
});
|
||||
// 请求错误
|
||||
if (error) {
|
||||
if (error.response && error.response.status) {
|
||||
throw error;
|
||||
}
|
||||
if (error.request) {
|
||||
if (error.message && error.message.startsWith("timeout")) {
|
||||
throw new Error("time out");
|
||||
} else {
|
||||
throw new Error(error.message || "request error");
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
};
|
||||
|
||||
const axiosInstance = axios.create();
|
||||
applyDefaultInterceptors(axiosInstance);
|
||||
|
||||
export const createServiceAxios = (baseURL?: string) => {
|
||||
const instance = axios.create({ baseURL });
|
||||
applyDefaultInterceptors(instance);
|
||||
return instance;
|
||||
};
|
||||
|
||||
export default {
|
||||
axios: axiosInstance,
|
||||
setGlobalErrorCallback,
|
||||
setGlobalRequestInterceptor,
|
||||
setGlobalResponseObserver,
|
||||
createServiceAxios
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import Toolkit from "./Toolkit";
|
||||
|
||||
export enum PopupType {
|
||||
TEXT,
|
||||
IMG,
|
||||
HTML,
|
||||
EL
|
||||
}
|
||||
|
||||
export type PopupConfig = {
|
||||
type: PopupType,
|
||||
value?: string | HTMLElement;
|
||||
canShow?: () => boolean;
|
||||
beforeShow?: (type: PopupType, value: string | HTMLElement) => Promise<void>;
|
||||
afterHidden?: (type: PopupType, value: string | HTMLElement) => Promise<void>;
|
||||
}
|
||||
|
||||
export const POPUP_ID = "tui-popup";
|
||||
export const POPUP_CONTENT_ID = "tui-popup-content";
|
||||
|
||||
export function getPopup() {
|
||||
return document.getElementById(POPUP_ID);
|
||||
}
|
||||
|
||||
export function getPopupContent() {
|
||||
return document.getElementById(POPUP_CONTENT_ID);
|
||||
}
|
||||
|
||||
export function clearPopup(popup: HTMLElement) {
|
||||
popup.replaceChildren();
|
||||
}
|
||||
|
||||
export function movePopup(popup: HTMLElement, x: number, y: number) {
|
||||
const offsetX = 20;
|
||||
const offsetY = 32;
|
||||
popup.style.left = `${x + offsetX}px`;
|
||||
popup.style.top = `${y + offsetY}px`;
|
||||
|
||||
const popupRect = popup.getBoundingClientRect();
|
||||
if (window.innerWidth < popupRect.right + offsetX) {
|
||||
popup.style.left = `${Math.max(0, window.innerWidth - popupRect.width - offsetX)}px`;
|
||||
}
|
||||
if (window.innerHeight < popupRect.bottom) {
|
||||
popup.style.top = `${Math.max(0, y - popupRect.height - 6)}px`;
|
||||
}
|
||||
}
|
||||
|
||||
export function showPopup(popup: HTMLElement) {
|
||||
popup.style.visibility = "visible";
|
||||
}
|
||||
|
||||
export function hidePopup(popup: HTMLElement) {
|
||||
popup.style.visibility = "hidden";
|
||||
popup.style.left = "0px";
|
||||
popup.style.top = "0px";
|
||||
}
|
||||
|
||||
export function appendPopupValue(popup: HTMLElement, type: PopupType, value: string | HTMLElement) {
|
||||
let popupChild: HTMLElement;
|
||||
switch (type) {
|
||||
case PopupType.TEXT:
|
||||
popupChild = document.createElement("div");
|
||||
popupChild.className = "text";
|
||||
popupChild.textContent = value as string;
|
||||
popup.appendChild(popupChild);
|
||||
break;
|
||||
case PopupType.IMG:
|
||||
popupChild = document.createElement("img");
|
||||
(popupChild as HTMLImageElement).src = value as string;
|
||||
popup.appendChild(popupChild);
|
||||
break;
|
||||
case PopupType.HTML:
|
||||
popup.appendChild(Toolkit.toDOM(value as string));
|
||||
break;
|
||||
case PopupType.EL:
|
||||
if (value instanceof HTMLElement) {
|
||||
value.style.display = "block";
|
||||
popup.appendChild(value);
|
||||
break;
|
||||
}
|
||||
throw new Error("Vue 指令错误:v-popup:el 的值不是 HTML 元素");
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
import {ref, Ref} from "vue";
|
||||
import {Setting} from "../types";
|
||||
import {CommonAPI} from "../api";
|
||||
|
||||
export default class SettingMapper {
|
||||
|
||||
private static instance: SettingMapper;
|
||||
|
||||
private moduleMap = new Map<string, Map<string, Ref<Setting>>>();
|
||||
|
||||
public static async loadSetting(map: Record<string, string[]>): Promise<void> {
|
||||
const result = await CommonAPI.settingMap(map);
|
||||
this.appendSettingMap(result);
|
||||
}
|
||||
|
||||
public static appendSettingMap(result: Map<string, Map<string, Setting>>): void {
|
||||
for (const [module, settingMap] of result) {
|
||||
for (const [key, setting] of settingMap) {
|
||||
this.setValue(module, key, setting);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static createModule(module: string): Map<string, Ref<Setting>> {
|
||||
const instance = this.getInstance();
|
||||
const moduleVal = instance.moduleMap.get(module);
|
||||
if (moduleVal) {
|
||||
return moduleVal;
|
||||
}
|
||||
const created = new Map<string, Ref<Setting>>();
|
||||
instance.moduleMap.set(module, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
public static getModule(module: string): Map<string, Ref<Setting>> | undefined {
|
||||
return this.getInstance().moduleMap.get(module);
|
||||
}
|
||||
|
||||
public static hasModule(module: string): boolean {
|
||||
return this.getInstance().moduleMap.has(module);
|
||||
}
|
||||
|
||||
public static deleteModule(module: string): boolean {
|
||||
return this.getInstance().moduleMap.delete(module);
|
||||
}
|
||||
|
||||
public static setModule(module: string, moduleVal: Map<string, Ref<Setting>>): void {
|
||||
this.getInstance().moduleMap.set(module, moduleVal);
|
||||
}
|
||||
|
||||
public static is(module: string, key: string): boolean {
|
||||
const setting = this.getValueRef(module, key).value;
|
||||
return !!setting.value && setting.value === "true";
|
||||
}
|
||||
|
||||
public static not(module: string, key: string): boolean {
|
||||
return !this.is(module, key);
|
||||
}
|
||||
|
||||
public static getValue(module: string, key: string): Setting {
|
||||
return this.getValueRef(module, key).value;
|
||||
}
|
||||
|
||||
public static setValue(module: string, key: string, setting: Setting): void {
|
||||
const moduleVal = this.createModule(module);
|
||||
const settingRef = moduleVal.get(key);
|
||||
if (settingRef) {
|
||||
settingRef.value = setting;
|
||||
return;
|
||||
}
|
||||
moduleVal.set(key, ref(setting));
|
||||
}
|
||||
|
||||
public static setValueRef(module: string, key: string, settingRef: Ref<Setting>): void {
|
||||
const moduleVal = this.createModule(module);
|
||||
moduleVal.set(key, settingRef);
|
||||
}
|
||||
|
||||
public static hasValue(module: string, key: string): boolean {
|
||||
return !!this.getModule(module)?.has(key);
|
||||
}
|
||||
|
||||
public static deleteValue(module: string, key: string): boolean {
|
||||
return !!this.getModule(module)?.delete(key);
|
||||
}
|
||||
|
||||
public static getValueRef(module: string, key: string): Ref<Setting> {
|
||||
const moduleVal = this.getModule(module);
|
||||
if (!moduleVal) {
|
||||
throw new Error(`Setting module not found: ${module}`);
|
||||
}
|
||||
const valueRef = moduleVal.get(key);
|
||||
if (!valueRef) {
|
||||
throw new Error(`Setting key not found: ${module}.${key}`);
|
||||
}
|
||||
return valueRef;
|
||||
}
|
||||
|
||||
public static getInstance(): SettingMapper {
|
||||
if (SettingMapper.instance) {
|
||||
return SettingMapper.instance;
|
||||
}
|
||||
return SettingMapper.instance = new SettingMapper();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { AppContext } from "vue";
|
||||
|
||||
type MessageType = "info" | "success" | "warning" | "error";
|
||||
|
||||
type MessageHandler = (content: string) => unknown | Promise<unknown>;
|
||||
|
||||
type MessageApi = {
|
||||
[type in MessageType]?: MessageHandler;
|
||||
};
|
||||
|
||||
export const showTDesignMessage = async (
|
||||
appContext: AppContext | undefined,
|
||||
type: MessageType,
|
||||
content: string
|
||||
) => {
|
||||
const handler = (appContext?.config.globalProperties.$message as MessageApi | undefined)?.[type];
|
||||
if (handler) {
|
||||
await handler(content);
|
||||
return;
|
||||
}
|
||||
if ("error" === type) {
|
||||
console.error(content);
|
||||
return;
|
||||
}
|
||||
console.warn(content);
|
||||
};
|
||||
|
||||
|
||||
@@ -56,6 +56,13 @@ export default class Time {
|
||||
return `${Text.pad(d.getHours())}:${Text.pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** Unix 时间戳转带秒时间,兼容旧业务项目调用。 */
|
||||
public static toLongTime(unix?: number): string {
|
||||
if (!unix) return "";
|
||||
const d = new Date(unix);
|
||||
return `${Text.pad(d.getHours())}:${Text.pad(d.getMinutes())}:${Text.pad(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
public static toShortTime(unix?: number): string {
|
||||
if (!unix) return "";
|
||||
const d = new Date(unix);
|
||||
@@ -72,6 +79,12 @@ export default class Time {
|
||||
return `${this.toDate(unix)} ${this.toTime(unix)}`;
|
||||
}
|
||||
|
||||
/** Unix 时间戳转带秒日期和时间,兼容旧业务项目调用。 */
|
||||
public static toLongDateTime(unix?: number): string {
|
||||
if (!unix) return "";
|
||||
return `${this.toDate(unix)} ${this.toLongTime(unix)}`;
|
||||
}
|
||||
|
||||
public static toPassedDate(unix?: number): string {
|
||||
return this.toPassedDateTime(unix, false);
|
||||
}
|
||||
|
||||
+15
-25
@@ -1,5 +1,5 @@
|
||||
import type { App } from "vue";
|
||||
import { InstallRecord, UserLevelType } from "../types";
|
||||
import type { InstallRecord } from "../types";
|
||||
|
||||
export default class Toolkit {
|
||||
|
||||
@@ -301,27 +301,6 @@ export default class Toolkit {
|
||||
return debounced as ((...args: Parameters<T>) => void) & { cancel(): void };
|
||||
}
|
||||
|
||||
public static toUserLevel(exp?: number): UserLevelType {
|
||||
exp = exp ?? 0;
|
||||
const levels = [0, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096];
|
||||
for (let i = 1; i < levels.length; i++) {
|
||||
if (exp < levels[i]) {
|
||||
return {
|
||||
exp,
|
||||
value: i - 1,
|
||||
percent: (exp - levels[i - 1]) / (levels[i] - levels[i - 1]),
|
||||
nextLevelUp: i === levels.length - 1 ? 4096 : levels[i]
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
exp,
|
||||
value: 8,
|
||||
percent: 1,
|
||||
nextLevelUp: 4096
|
||||
};
|
||||
}
|
||||
|
||||
public static toFormData(root?: object): FormData {
|
||||
const form = new FormData();
|
||||
if (!root) {
|
||||
@@ -422,11 +401,22 @@ export default class Toolkit {
|
||||
}, interval);
|
||||
}
|
||||
|
||||
public static formatJson(jsonStr?: string): string {
|
||||
if (!jsonStr) {
|
||||
public static formatJson(jsonValue?: string | object): string {
|
||||
if (jsonValue === undefined || jsonValue === null) {
|
||||
return "";
|
||||
}
|
||||
return JSON.stringify(JSON.parse(jsonStr), null, 4);
|
||||
if (typeof jsonValue === "string") {
|
||||
const value = jsonValue.trim();
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(value), null, 4);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return JSON.stringify(jsonValue, null, 4);
|
||||
}
|
||||
|
||||
public static downloadBlob(blob: Blob, fileName: string): void {
|
||||
|
||||
@@ -1,226 +0,0 @@
|
||||
import type { Directive, DirectiveBinding, EffectScope } from "vue";
|
||||
import { effectScope, watch } from "vue";
|
||||
import { AccessMatchMode, useUserStore } from "../../store";
|
||||
|
||||
/** 访问控制类型 */
|
||||
export type AccessControlType = "permission" | "role";
|
||||
/** 指令结果生效方式 */
|
||||
export type AccessEffectMode = "if" | "show";
|
||||
|
||||
/** 自定义回调参数 */
|
||||
export type AccessDirectiveCallbackPayload = {
|
||||
type: AccessControlType;
|
||||
granted: boolean;
|
||||
valueList: string[];
|
||||
mode: AccessMatchMode;
|
||||
el: HTMLElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 访问控制指令配置
|
||||
* `value` 支持单个值或值数组
|
||||
* 数组默认按 `or` 逻辑处理,需要 `and` 时显式传 `mode`
|
||||
* `callback` 存在时优先执行回调,不再使用 `effect`
|
||||
*/
|
||||
export type AccessDirectiveConfig = {
|
||||
value: string | string[];
|
||||
mode?: AccessMatchMode;
|
||||
effect?: AccessEffectMode;
|
||||
reverse?: boolean;
|
||||
display?: string;
|
||||
callback?: (payload: AccessDirectiveCallbackPayload) => void;
|
||||
}
|
||||
|
||||
type AccessDirectiveValue = string | string[] | AccessDirectiveConfig;
|
||||
|
||||
type AccessDirectiveState = {
|
||||
scope: EffectScope;
|
||||
placeholder: Comment | null;
|
||||
display: string;
|
||||
config: AccessDirectiveConfig;
|
||||
lastGranted?: boolean;
|
||||
}
|
||||
|
||||
type AccessMatcher = (store: ReturnType<typeof useUserStore>, valueList: string[], mode: AccessMatchMode) => boolean;
|
||||
|
||||
const ACCESS_STATE_KEY = "__vAccessState";
|
||||
|
||||
/** 过滤空字符串并统一裁剪空白 */
|
||||
function normalizeValueList(value: string | string[]): string[] {
|
||||
return (Array.isArray(value) ? value : [value])
|
||||
.map(item => item?.trim())
|
||||
.filter((item): item is string => !!item);
|
||||
}
|
||||
|
||||
/** 统一把指令值转成标准配置 */
|
||||
function normalizeConfig(value: AccessDirectiveValue): AccessDirectiveConfig {
|
||||
if (typeof value === "string" || Array.isArray(value)) {
|
||||
return {
|
||||
value,
|
||||
mode: "or",
|
||||
effect: "if",
|
||||
reverse: false
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
value: value?.value || [],
|
||||
mode: value?.mode || "or",
|
||||
effect: value?.effect || "if",
|
||||
reverse: !!value?.reverse,
|
||||
display: value?.display,
|
||||
callback: value?.callback
|
||||
};
|
||||
}
|
||||
|
||||
/** 恢复被 `if` 模式替换掉的真实元素 */
|
||||
function restoreElement(el: HTMLElement, state: AccessDirectiveState): void {
|
||||
if (state.placeholder?.parentNode) {
|
||||
state.placeholder.parentNode.replaceChild(el, state.placeholder);
|
||||
}
|
||||
state.placeholder = null;
|
||||
}
|
||||
|
||||
/** `if` 模式:无权限时直接移出 DOM */
|
||||
function applyIfEffect(el: HTMLElement, state: AccessDirectiveState, granted: boolean): void {
|
||||
if (granted) {
|
||||
restoreElement(el, state);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.placeholder && el.parentNode) {
|
||||
state.placeholder = document.createComment("v-access");
|
||||
el.parentNode.replaceChild(state.placeholder, el);
|
||||
}
|
||||
}
|
||||
|
||||
/** `show` 模式:保留 DOM,仅切换 display */
|
||||
function applyShowEffect(el: HTMLElement, state: AccessDirectiveState, granted: boolean): void {
|
||||
restoreElement(el, state);
|
||||
el.style.display = granted ? state.display : "none";
|
||||
}
|
||||
|
||||
/** 自定义模式:交给调用方自己处理样式或行为 */
|
||||
function applyCustomCallback(
|
||||
el: HTMLElement,
|
||||
state: AccessDirectiveState,
|
||||
granted: boolean,
|
||||
type: AccessControlType,
|
||||
valueList: string[],
|
||||
mode: AccessMatchMode
|
||||
): void {
|
||||
restoreElement(el, state);
|
||||
if (state.lastGranted === granted) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.config.callback?.({
|
||||
type,
|
||||
granted,
|
||||
valueList,
|
||||
mode,
|
||||
el
|
||||
});
|
||||
}
|
||||
|
||||
/** 根据当前登录用户状态刷新指令效果 */
|
||||
function updateAccess(
|
||||
el: HTMLElement,
|
||||
state: AccessDirectiveState,
|
||||
type: AccessControlType,
|
||||
matcher: AccessMatcher
|
||||
): void {
|
||||
const store = useUserStore();
|
||||
const config = state.config;
|
||||
const mode = config.mode || "or";
|
||||
const valueList = normalizeValueList(config.value);
|
||||
const granted = config.reverse ? !matcher(store, valueList, mode) : matcher(store, valueList, mode);
|
||||
|
||||
if (config.callback) {
|
||||
applyCustomCallback(el, state, granted, type, valueList, mode);
|
||||
} else if (config.effect === "show") {
|
||||
applyShowEffect(el, state, granted);
|
||||
} else {
|
||||
applyIfEffect(el, state, granted);
|
||||
}
|
||||
|
||||
state.lastGranted = granted;
|
||||
}
|
||||
|
||||
function getState(el: HTMLElement): AccessDirectiveState | undefined {
|
||||
return (el as HTMLElement & { [ACCESS_STATE_KEY]?: AccessDirectiveState })[ACCESS_STATE_KEY];
|
||||
}
|
||||
|
||||
function setState(el: HTMLElement, state: AccessDirectiveState): void {
|
||||
(el as HTMLElement & { [ACCESS_STATE_KEY]?: AccessDirectiveState })[ACCESS_STATE_KEY] = state;
|
||||
}
|
||||
|
||||
function clearState(el: HTMLElement): void {
|
||||
delete (el as HTMLElement & { [ACCESS_STATE_KEY]?: AccessDirectiveState })[ACCESS_STATE_KEY];
|
||||
}
|
||||
|
||||
/** 卸载时清掉占位注释,避免遗留无用节点 */
|
||||
function clearPlaceholder(state: AccessDirectiveState): void {
|
||||
if (state.placeholder?.parentNode) {
|
||||
state.placeholder.parentNode.removeChild(state.placeholder);
|
||||
}
|
||||
state.placeholder = null;
|
||||
}
|
||||
|
||||
/** 创建角色/权限通用指令 */
|
||||
function createAccessDirective(type: AccessControlType, matcher: AccessMatcher): Directive<HTMLElement, AccessDirectiveValue> {
|
||||
return {
|
||||
mounted(el: HTMLElement, binding: DirectiveBinding<AccessDirectiveValue>) {
|
||||
const state: AccessDirectiveState = {
|
||||
scope: effectScope(),
|
||||
placeholder: null,
|
||||
display: el.style.display,
|
||||
config: normalizeConfig(binding.value)
|
||||
};
|
||||
|
||||
setState(el, state);
|
||||
|
||||
state.scope.run(() => {
|
||||
const store = useUserStore();
|
||||
watch(
|
||||
() => {
|
||||
return type === "permission" ? store.getPermissionList().join("|") : store.getRoleList().join("|");
|
||||
},
|
||||
() => updateAccess(el, state, type, matcher),
|
||||
{ immediate: true }
|
||||
);
|
||||
});
|
||||
},
|
||||
updated(el: HTMLElement, binding: DirectiveBinding<AccessDirectiveValue>) {
|
||||
const state = getState(el);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.config = normalizeConfig(binding.value);
|
||||
updateAccess(el, state, type, matcher);
|
||||
},
|
||||
unmounted(el: HTMLElement) {
|
||||
const state = getState(el);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.scope.stop();
|
||||
clearPlaceholder(state);
|
||||
clearState(el);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** 权限指令:`v-can` */
|
||||
export const VCan = createAccessDirective("permission", (store, valueList, mode) => {
|
||||
return store.hasPermissions(valueList, mode);
|
||||
});
|
||||
|
||||
/** 角色指令:`v-role` */
|
||||
export const VRole = createAccessDirective("role", (store, valueList, mode) => {
|
||||
return store.hasRoles(valueList, mode);
|
||||
});
|
||||
|
||||
export default VCan;
|
||||
+126
-99
@@ -1,115 +1,142 @@
|
||||
import type { Directive, DirectiveBinding } from "vue";
|
||||
import Toolkit from "../Toolkit";
|
||||
|
||||
export type PopupType = "TEXT" | "IMG" | "HTML" | "ELEMENT";
|
||||
|
||||
/** */
|
||||
export type PopupConfig = {
|
||||
|
||||
type: PopupType,
|
||||
value?: string | HTMLElement;
|
||||
canShow?: () => boolean;
|
||||
beforeShow?: (type: PopupType, value: string | HTMLElement) => Promise<void>;
|
||||
afterHidden?: (type: PopupType, value: string | HTMLElement) => Promise<void>;
|
||||
}
|
||||
import { appendPopupValue, clearPopup, getPopup, getPopupContent, hidePopup, movePopup, PopupType, showPopup, type PopupConfig } from "../Popup";
|
||||
|
||||
// Popup 弹出提示 DOM 节点,全局唯一
|
||||
let popup: HTMLElement | null;
|
||||
let popupContent: HTMLElement | null;
|
||||
|
||||
const VPopup: Directive = {
|
||||
type PopupBindingValue = string | PopupConfig;
|
||||
|
||||
mounted(el: HTMLElement, binding: DirectiveBinding<PopupConfig>) {
|
||||
// 转配置
|
||||
let config: PopupConfig;
|
||||
if (binding.arg && binding.arg === "config") {
|
||||
config = binding.value as PopupConfig;
|
||||
} else {
|
||||
config = {
|
||||
type: "TEXT",
|
||||
value: binding.value as any as string,
|
||||
canShow: () => true
|
||||
};
|
||||
}
|
||||
// Popup 节点
|
||||
if (!popup) {
|
||||
popup = document.getElementById("tui-popup");
|
||||
}
|
||||
let isShowing = false;
|
||||
// 显示
|
||||
el.addEventListener("mouseenter", async e => {
|
||||
if (!config.value) {
|
||||
console.warn("not found popup value", config);
|
||||
return;
|
||||
}
|
||||
if (config.beforeShow) {
|
||||
await config.beforeShow(config.type, config.value);
|
||||
}
|
||||
if (config.canShow && config.canShow() && popup) {
|
||||
let el: HTMLElement | null = null;
|
||||
if (!config) {
|
||||
el = document.createElement("div");
|
||||
el.className = "text";
|
||||
el.textContent = config as string;
|
||||
popup.appendChild(el);
|
||||
type PopupState = {
|
||||
config: PopupConfig;
|
||||
isShowing: boolean;
|
||||
onMouseEnter: (e: MouseEvent) => Promise<void>;
|
||||
onMouseMove: (e: MouseEvent) => void;
|
||||
onMouseLeave: () => Promise<void>;
|
||||
};
|
||||
|
||||
const popupStates = new WeakMap<HTMLElement, PopupState>();
|
||||
|
||||
function getPopupElements() {
|
||||
if (!popup) {
|
||||
popup = getPopup();
|
||||
}
|
||||
if (!popupContent) {
|
||||
popupContent = getPopupContent();
|
||||
}
|
||||
return {
|
||||
popup,
|
||||
popupContent
|
||||
};
|
||||
}
|
||||
|
||||
function getConfig(binding: DirectiveBinding<PopupBindingValue>): PopupConfig {
|
||||
if (binding.arg === "config") {
|
||||
const config = binding.value as PopupConfig;
|
||||
return {
|
||||
...config,
|
||||
type: config.type ?? PopupType.TEXT,
|
||||
canShow: config.canShow ?? (() => true)
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: PopupType.TEXT,
|
||||
value: binding.value as string,
|
||||
canShow: () => true
|
||||
};
|
||||
}
|
||||
|
||||
function refreshPopupContent(config: PopupConfig) {
|
||||
const popupElements = getPopupElements();
|
||||
if (!config.value || !popupElements.popupContent) {
|
||||
return false;
|
||||
}
|
||||
clearPopup(popupElements.popupContent);
|
||||
appendPopupValue(popupElements.popupContent, config.type, config.value);
|
||||
return true;
|
||||
}
|
||||
|
||||
function hidePopupContent(state: PopupState) {
|
||||
const popupElements = getPopupElements();
|
||||
state.isShowing = false;
|
||||
if (popupElements.popup) {
|
||||
hidePopup(popupElements.popup);
|
||||
}
|
||||
// 内容和定位分离,避免直接清空根节点破坏 teleport
|
||||
if (popupElements.popupContent) {
|
||||
clearPopup(popupElements.popupContent);
|
||||
}
|
||||
}
|
||||
|
||||
const VPopup: Directive<HTMLElement, PopupBindingValue> = {
|
||||
|
||||
mounted(el, binding) {
|
||||
const state: PopupState = {
|
||||
config: getConfig(binding),
|
||||
isShowing: false,
|
||||
onMouseEnter: async e => {
|
||||
const popupElements = getPopupElements();
|
||||
let config = state.config;
|
||||
if (!config.value) {
|
||||
return;
|
||||
}
|
||||
switch (config.type) {
|
||||
case "TEXT":
|
||||
// 文本
|
||||
el = document.createElement("div");
|
||||
el.className = "text";
|
||||
el.textContent = config.value as string;
|
||||
popup.appendChild(el);
|
||||
break;
|
||||
case "IMG":
|
||||
// 图片
|
||||
el = document.createElement("img");
|
||||
(el as HTMLImageElement).src = config.value as string;
|
||||
popup.appendChild(el);
|
||||
break;
|
||||
case "HTML":
|
||||
// HTML 字符串
|
||||
popup.appendChild(Toolkit.toDOM(config.value as string));
|
||||
break;
|
||||
case "ELEMENT":
|
||||
// DOM 节点
|
||||
if (config.value instanceof HTMLElement) {
|
||||
const valueEl = config.value as HTMLElement;
|
||||
valueEl.style.display = "block";
|
||||
popup.appendChild(valueEl);
|
||||
break;
|
||||
} else {
|
||||
console.error(config);
|
||||
throw new Error("Vue 指令错误:v-popup:el 的值不是 HTML 元素");
|
||||
}
|
||||
if (config.beforeShow) {
|
||||
await config.beforeShow(config.type, config.value);
|
||||
}
|
||||
popup.style.left = (e.x + 20) + "px";
|
||||
popup.style.top = (e.y + 14) + "px";
|
||||
popup.style.visibility = "visible";
|
||||
isShowing = true;
|
||||
}
|
||||
}, false);
|
||||
// 移动
|
||||
el.addEventListener("mousemove", async (e) => {
|
||||
if (config.canShow && config.canShow() && isShowing && popup) {
|
||||
popup.style.left = (e.x + 20) + "px";
|
||||
popup.style.top = (e.y + 14) + "px";
|
||||
}
|
||||
}, false);
|
||||
// 隐藏
|
||||
el.addEventListener("mouseleave", async () => {
|
||||
if (popup) {
|
||||
popup.style.visibility = "hidden";
|
||||
popup.innerText = "";
|
||||
popup.style.left = "0px";
|
||||
popup.style.top = "0px";
|
||||
|
||||
// 隐藏后事件
|
||||
config = state.config;
|
||||
if (config.canShow?.() && popupElements.popup && refreshPopupContent(config)) {
|
||||
movePopup(popupElements.popup, e.x, e.y);
|
||||
showPopup(popupElements.popup);
|
||||
state.isShowing = true;
|
||||
}
|
||||
},
|
||||
onMouseMove: e => {
|
||||
const popupElements = getPopupElements();
|
||||
if (state.config.canShow?.() && state.isShowing && popupElements.popup) {
|
||||
movePopup(popupElements.popup, e.x, e.y);
|
||||
}
|
||||
},
|
||||
onMouseLeave: async () => {
|
||||
const config = state.config;
|
||||
hidePopupContent(state);
|
||||
if (config.afterHidden && config.value) {
|
||||
await config.afterHidden(config.type, config.value);
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
};
|
||||
popupStates.set(el, state);
|
||||
el.addEventListener("mouseenter", state.onMouseEnter, false);
|
||||
el.addEventListener("mousemove", state.onMouseMove, false);
|
||||
el.addEventListener("mouseleave", state.onMouseLeave, false);
|
||||
},
|
||||
|
||||
updated(el, binding) {
|
||||
const state = popupStates.get(el);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
state.config = getConfig(binding);
|
||||
if (!state.isShowing) {
|
||||
return;
|
||||
}
|
||||
if (!state.config.canShow?.() || !refreshPopupContent(state.config)) {
|
||||
hidePopupContent(state);
|
||||
}
|
||||
},
|
||||
|
||||
unmounted(el) {
|
||||
const state = popupStates.get(el);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
el.removeEventListener("mouseenter", state.onMouseEnter, false);
|
||||
el.removeEventListener("mousemove", state.onMouseMove, false);
|
||||
el.removeEventListener("mouseleave", state.onMouseLeave, false);
|
||||
hidePopupContent(state);
|
||||
popupStates.delete(el);
|
||||
}
|
||||
};
|
||||
|
||||
export default VPopup;
|
||||
export { PopupType };
|
||||
export type { PopupConfig };
|
||||
|
||||
+1
-5
@@ -2,7 +2,6 @@ export { default as Cooker } from "./Cooker";
|
||||
export { default as Events } from "./Events";
|
||||
export { default as IOSize } from "./IOSize";
|
||||
export { default as Markdown } from "./Markdown";
|
||||
export { default as Network } from "./Network";
|
||||
export { default as Prismjs } from "./Prismjs";
|
||||
export { default as Resizer } from "./Resizer";
|
||||
export { default as Scroller } from "./Scroller";
|
||||
@@ -11,15 +10,12 @@ export { default as Text } from "./Text";
|
||||
export { default as Time } from "./Time";
|
||||
export { default as Toolkit } from "./Toolkit";
|
||||
export { default as IconMapper } from "./IconMapper";
|
||||
export { default as SettingMapper } from "./SettingMapper";
|
||||
export { showTDesignMessage } from "./TDesignMessage";
|
||||
|
||||
export { default as VCan } from "./directives/Access";
|
||||
export { default as VDraggable } from "./directives/Draggable";
|
||||
export { default as VPopup } from "./directives/Popup";
|
||||
|
||||
export * from "./MethodLocker";
|
||||
export * from "./Network";
|
||||
export * from "./Prismjs";
|
||||
export * from "./directives/Access";
|
||||
export * from "./directives/Draggable";
|
||||
export * from "./directives/Popup";
|
||||
|
||||
Reference in New Issue
Block a user