This commit is contained in:
lucienteng
2024-08-23 11:53:59 +08:00
commit 8881708e2b
210 changed files with 23515 additions and 0 deletions

141
src/utils/auth.ts Normal file
View File

@@ -0,0 +1,141 @@
import Cookies from "js-cookie";
import { useUserStoreHook } from "@/store/modules/user";
import { storageLocal, isString, isIncludeAllChildren } from "@pureadmin/utils";
export interface DataInfo<T> {
/** token */
accessToken: string;
/** `accessToken`的过期时间(时间戳) */
expires: T;
/** 用于调用刷新accessToken的接口时所需的token */
refreshToken: string;
/** 头像 */
avatar?: string;
/** 用户名 */
username?: string;
/** 昵称 */
nickname?: string;
/** 当前登录用户的角色 */
roles?: Array<string>;
/** 当前登录用户的按钮级别权限 */
permissions?: Array<string>;
}
export const userKey = "user-info";
export const TokenKey = "authorized-token";
/**
* 通过`multiple-tabs`是否在`cookie`中,判断用户是否已经登录系统,
* 从而支持多标签页打开已经登录的系统后无需再登录。
* 浏览器完全关闭后`multiple-tabs`将自动从`cookie`中销毁,
* 再次打开浏览器需要重新登录系统
* */
export const multipleTabsKey = "multiple-tabs";
/** 获取`token` */
export function getToken(): DataInfo<number> {
// 此处与`TokenKey`相同,此写法解决初始化时`Cookies`中不存在`TokenKey`报错
return Cookies.get(TokenKey)
? JSON.parse(Cookies.get(TokenKey))
: storageLocal().getItem(userKey);
}
/**
* @description 设置`token`以及一些必要信息并采用无感刷新`token`方案
* 无感刷新:后端返回`accessToken`(访问接口使用的`token`)、`refreshToken`(用于调用刷新`accessToken`的接口时所需的`token``refreshToken`的过期时间比如30天应大于`accessToken`的过期时间比如2小时、`expires``accessToken`的过期时间)
* 将`accessToken`、`expires`、`refreshToken`这三条信息放在key值为authorized-token的cookie里过期自动销毁
* 将`avatar`、`username`、`nickname`、`roles`、`permissions`、`refreshToken`、`expires`这七条信息放在key值为`user-info`的localStorage里利用`multipleTabsKey`当浏览器完全关闭后自动销毁)
*/
export function setToken(data: DataInfo<Date>) {
let expires = 0;
const { accessToken, refreshToken } = data;
const { isRemembered, loginDay } = useUserStoreHook();
expires = new Date(data.expires).getTime(); // 如果后端直接设置时间戳将此处代码改为expires = data.expires然后把上面的DataInfo<Date>改成DataInfo<number>即可
const cookieString = JSON.stringify({ accessToken, expires, refreshToken });
expires > 0
? Cookies.set(TokenKey, cookieString, {
expires: (expires - Date.now()) / 86400000
})
: Cookies.set(TokenKey, cookieString);
Cookies.set(
multipleTabsKey,
"true",
isRemembered
? {
expires: loginDay
}
: {}
);
function setUserKey({ avatar, username, nickname, roles, permissions }) {
useUserStoreHook().SET_AVATAR(avatar);
useUserStoreHook().SET_USERNAME(username);
useUserStoreHook().SET_NICKNAME(nickname);
useUserStoreHook().SET_ROLES(roles);
useUserStoreHook().SET_PERMS(permissions);
storageLocal().setItem(userKey, {
refreshToken,
expires,
avatar,
username,
nickname,
roles,
permissions
});
}
if (data.username && data.roles) {
const { username, roles } = data;
setUserKey({
avatar: data?.avatar ?? "",
username,
nickname: data?.nickname ?? "",
roles,
permissions: data?.permissions ?? []
});
} else {
const avatar =
storageLocal().getItem<DataInfo<number>>(userKey)?.avatar ?? "";
const username =
storageLocal().getItem<DataInfo<number>>(userKey)?.username ?? "";
const nickname =
storageLocal().getItem<DataInfo<number>>(userKey)?.nickname ?? "";
const roles =
storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [];
const permissions =
storageLocal().getItem<DataInfo<number>>(userKey)?.permissions ?? [];
setUserKey({
avatar,
username,
nickname,
roles,
permissions
});
}
}
/** 删除`token`以及key值为`user-info`的localStorage信息 */
export function removeToken() {
Cookies.remove(TokenKey);
Cookies.remove(multipleTabsKey);
storageLocal().removeItem(userKey);
}
/** 格式化tokenjwt格式 */
export const formatToken = (token: string): string => {
return "Bearer " + token;
};
/** 是否有按钮级别的权限(根据登录接口返回的`permissions`字段进行判断)*/
export const hasPerms = (value: string | Array<string>): boolean => {
if (!value) return false;
const allPerms = "*:*:*";
const { permissions } = useUserStoreHook();
if (!permissions) return false;
if (permissions.length === 1 && permissions[0] === allPerms) return true;
const isAuths = isString(value)
? permissions.includes(value)
: isIncludeAllChildren(value, permissions);
return isAuths ? true : false;
};

View File

@@ -0,0 +1,7 @@
// 如果项目出现 `global is not defined` 报错,可能是您引入某个库的问题,比如 aws-sdk-js https://github.com/aws/aws-sdk-js
// 解决办法就是将该文件引入 src/main.ts 即可 import "@/utils/globalPolyfills";
if (typeof (window as any).global === "undefined") {
(window as any).global = window;
}
export {};

194
src/utils/http/index.ts Normal file
View File

@@ -0,0 +1,194 @@
import Axios, {
type AxiosInstance,
type AxiosRequestConfig,
type CustomParamsSerializer
} from "axios";
import type {
PureHttpError,
RequestMethods,
PureHttpResponse,
PureHttpRequestConfig
} from "./types.d";
import { stringify } from "qs";
import NProgress from "../progress";
import { getToken, formatToken } from "@/utils/auth";
import { useUserStoreHook } from "@/store/modules/user";
// 相关配置请参考www.axios-js.com/zh-cn/docs/#axios-request-config-1
const defaultConfig: AxiosRequestConfig = {
// 请求超时时间
timeout: 10000,
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
},
// 数组格式参数序列化https://github.com/axios/axios/issues/5142
paramsSerializer: {
serialize: stringify as unknown as CustomParamsSerializer
}
};
class PureHttp {
constructor() {
this.httpInterceptorsRequest();
this.httpInterceptorsResponse();
}
/** `token`过期后,暂存待执行的请求 */
private static requests = [];
/** 防止重复刷新`token` */
private static isRefreshing = false;
/** 初始化配置对象 */
private static initConfig: PureHttpRequestConfig = {};
/** 保存当前`Axios`实例对象 */
private static axiosInstance: AxiosInstance = Axios.create(defaultConfig);
/** 重连原始请求 */
private static retryOriginalRequest(config: PureHttpRequestConfig) {
return new Promise(resolve => {
PureHttp.requests.push((token: string) => {
config.headers["Authorization"] = formatToken(token);
resolve(config);
});
});
}
/** 请求拦截 */
private httpInterceptorsRequest(): void {
PureHttp.axiosInstance.interceptors.request.use(
async (config: PureHttpRequestConfig): Promise<any> => {
// 开启进度条动画
NProgress.start();
// 优先判断post/get等方法是否传入回调否则执行初始化设置等回调
if (typeof config.beforeRequestCallback === "function") {
config.beforeRequestCallback(config);
return config;
}
if (PureHttp.initConfig.beforeRequestCallback) {
PureHttp.initConfig.beforeRequestCallback(config);
return config;
}
/** 请求白名单,放置一些不需要`token`的接口(通过设置请求白名单,防止`token`过期后再请求造成的死循环问题) */
const whiteList = ["/refresh-token", "/login"];
return whiteList.some(url => config.url.endsWith(url))
? config
: new Promise(resolve => {
const data = getToken();
if (data) {
const now = new Date().getTime();
const expired = parseInt(data.expires) - now <= 0;
if (expired) {
if (!PureHttp.isRefreshing) {
PureHttp.isRefreshing = true;
// token过期刷新
useUserStoreHook()
.handRefreshToken({ refreshToken: data.refreshToken })
.then(res => {
const token = res.data.accessToken;
config.headers["Authorization"] = formatToken(token);
PureHttp.requests.forEach(cb => cb(token));
PureHttp.requests = [];
})
.finally(() => {
PureHttp.isRefreshing = false;
});
}
resolve(PureHttp.retryOriginalRequest(config));
} else {
config.headers["Authorization"] = formatToken(
data.accessToken
);
resolve(config);
}
} else {
resolve(config);
}
});
},
error => {
return Promise.reject(error);
}
);
}
/** 响应拦截 */
private httpInterceptorsResponse(): void {
const instance = PureHttp.axiosInstance;
instance.interceptors.response.use(
(response: PureHttpResponse) => {
const $config = response.config;
// 关闭进度条动画
NProgress.done();
// 优先判断post/get等方法是否传入回调否则执行初始化设置等回调
if (typeof $config.beforeResponseCallback === "function") {
$config.beforeResponseCallback(response);
return response.data;
}
if (PureHttp.initConfig.beforeResponseCallback) {
PureHttp.initConfig.beforeResponseCallback(response);
return response.data;
}
return response.data;
},
(error: PureHttpError) => {
const $error = error;
$error.isCancelRequest = Axios.isCancel($error);
// 关闭进度条动画
NProgress.done();
// 所有的响应异常 区分来源为取消请求/非取消请求
return Promise.reject($error);
}
);
}
/** 通用请求工具函数 */
public request<T>(
method: RequestMethods,
url: string,
param?: AxiosRequestConfig,
axiosConfig?: PureHttpRequestConfig
): Promise<T> {
const config = {
method,
url,
...param,
...axiosConfig
} as PureHttpRequestConfig;
// 单独处理自定义请求/响应回调
return new Promise((resolve, reject) => {
PureHttp.axiosInstance
.request(config)
.then((response: undefined) => {
resolve(response);
})
.catch(error => {
reject(error);
});
});
}
/** 单独抽离的`post`工具函数 */
public post<T, P>(
url: string,
params?: AxiosRequestConfig<P>,
config?: PureHttpRequestConfig
): Promise<T> {
return this.request<T>("post", url, params, config);
}
/** 单独抽离的`get`工具函数 */
public get<T, P>(
url: string,
params?: AxiosRequestConfig<P>,
config?: PureHttpRequestConfig
): Promise<T> {
return this.request<T>("get", url, params, config);
}
}
export const http = new PureHttp();

47
src/utils/http/types.d.ts vendored Normal file
View File

@@ -0,0 +1,47 @@
import type {
Method,
AxiosError,
AxiosResponse,
AxiosRequestConfig
} from "axios";
export type resultType = {
accessToken?: string;
};
export type RequestMethods = Extract<
Method,
"get" | "post" | "put" | "delete" | "patch" | "option" | "head"
>;
export interface PureHttpError extends AxiosError {
isCancelRequest?: boolean;
}
export interface PureHttpResponse extends AxiosResponse {
config: PureHttpRequestConfig;
}
export interface PureHttpRequestConfig extends AxiosRequestConfig {
beforeRequestCallback?: (request: PureHttpRequestConfig) => void;
beforeResponseCallback?: (response: PureHttpResponse) => void;
}
export default class PureHttp {
request<T>(
method: RequestMethods,
url: string,
param?: AxiosRequestConfig,
axiosConfig?: PureHttpRequestConfig
): Promise<T>;
post<T, P>(
url: string,
params?: P,
config?: PureHttpRequestConfig
): Promise<T>;
get<T, P>(
url: string,
params?: P,
config?: PureHttpRequestConfig
): Promise<T>;
}

View File

@@ -0,0 +1,109 @@
import forage from "localforage";
import type { LocalForage, ProxyStorage, ExpiresData } from "./types.d";
class StorageProxy implements ProxyStorage {
protected storage: LocalForage;
constructor(storageModel) {
this.storage = storageModel;
this.storage.config({
// 首选IndexedDB作为第一驱动不支持IndexedDB会自动降级到localStorageWebSQL被弃用详情看https://developer.chrome.com/blog/deprecating-web-sql
driver: [this.storage.INDEXEDDB, this.storage.LOCALSTORAGE],
name: "pure-admin"
});
}
/**
* @description 将对应键名的数据保存到离线仓库
* @param k 键名
* @param v 键值
* @param m 缓存时间(单位`分`,默认`0`分钟,永久缓存)
*/
public async setItem<T>(k: string, v: T, m = 0): Promise<T> {
return new Promise((resolve, reject) => {
this.storage
.setItem(k, {
data: v,
expires: m ? new Date().getTime() + m * 60 * 1000 : 0
})
.then(value => {
resolve(value.data);
})
.catch(err => {
reject(err);
});
});
}
/**
* @description 从离线仓库中获取对应键名的值
* @param k 键名
*/
public async getItem<T>(k: string): Promise<T> {
return new Promise((resolve, reject) => {
this.storage
.getItem(k)
.then((value: ExpiresData<T>) => {
value && (value.expires > new Date().getTime() || value.expires === 0)
? resolve(value.data)
: resolve(null);
})
.catch(err => {
reject(err);
});
});
}
/**
* @description 从离线仓库中删除对应键名的值
* @param k 键名
*/
public async removeItem(k: string) {
return new Promise<void>((resolve, reject) => {
this.storage
.removeItem(k)
.then(() => {
resolve();
})
.catch(err => {
reject(err);
});
});
}
/**
* @description 从离线仓库中删除所有的键名,重置数据库
*/
public async clear() {
return new Promise<void>((resolve, reject) => {
this.storage
.clear()
.then(() => {
resolve();
})
.catch(err => {
reject(err);
});
});
}
/**
* @description 获取数据仓库中所有的key
*/
public async keys() {
return new Promise<string[]>((resolve, reject) => {
this.storage
.keys()
.then(keys => {
resolve(keys);
})
.catch(err => {
reject(err);
});
});
}
}
/**
* 二次封装 [localforage](https://localforage.docschina.org/) 支持设置过期时间,提供完整的类型提示
*/
export const localForage = () => new StorageProxy(forage);

166
src/utils/localforage/types.d.ts vendored Normal file
View File

@@ -0,0 +1,166 @@
// https://github.com/localForage/localForage/blob/master/typings/localforage.d.ts
interface LocalForageDbInstanceOptions {
name?: string;
storeName?: string;
}
interface LocalForageOptions extends LocalForageDbInstanceOptions {
driver?: string | string[];
size?: number;
version?: number;
description?: string;
}
interface LocalForageDbMethodsCore {
getItem<T>(
key: string,
callback?: (err: any, value: T | null) => void
): Promise<T | null>;
setItem<T>(
key: string,
value: T,
callback?: (err: any, value: T) => void
): Promise<T>;
removeItem(key: string, callback?: (err: any) => void): Promise<void>;
clear(callback?: (err: any) => void): Promise<void>;
length(callback?: (err: any, numberOfKeys: number) => void): Promise<number>;
key(
keyIndex: number,
callback?: (err: any, key: string) => void
): Promise<string>;
keys(callback?: (err: any, keys: string[]) => void): Promise<string[]>;
iterate<T, U>(
iteratee: (value: T, key: string, iterationNumber: number) => U,
callback?: (err: any, result: U) => void
): Promise<U>;
}
interface LocalForageDropInstanceFn {
(
dbInstanceOptions?: LocalForageDbInstanceOptions,
callback?: (err: any) => void
): Promise<void>;
}
interface LocalForageDriverMethodsOptional {
dropInstance?: LocalForageDropInstanceFn;
}
// duplicating LocalForageDriverMethodsOptional to preserve TS v2.0 support,
// since Partial<> isn't supported there
interface LocalForageDbMethodsOptional {
dropInstance: LocalForageDropInstanceFn;
}
interface LocalForageDriverDbMethods
extends LocalForageDbMethodsCore,
LocalForageDriverMethodsOptional {}
interface LocalForageDriverSupportFunc {
(): Promise<boolean>;
}
interface LocalForageDriver extends LocalForageDriverDbMethods {
_driver: string;
_initStorage(options: LocalForageOptions): void;
_support?: boolean | LocalForageDriverSupportFunc;
}
interface LocalForageSerializer {
serialize<T>(
value: T | ArrayBuffer | Blob,
callback: (value: string, error: any) => void
): void;
deserialize<T>(value: string): T | ArrayBuffer | Blob;
stringToBuffer(serializedString: string): ArrayBuffer;
bufferToString(buffer: ArrayBuffer): string;
}
interface LocalForageDbMethods
extends LocalForageDbMethodsCore,
LocalForageDbMethodsOptional {}
export interface LocalForage extends LocalForageDbMethods {
LOCALSTORAGE: string;
WEBSQL: string;
INDEXEDDB: string;
/**
* Set and persist localForage options. This must be called before any other calls to localForage are made, but can be called after localForage is loaded.
* If you set any config values with this method they will persist after driver changes, so you can call config() then setDriver()
* @param {LocalForageOptions} options?
*/
config(options: LocalForageOptions): boolean;
config(options: string): any;
config(): LocalForageOptions;
/**
* Create a new instance of localForage to point to a different store.
* All the configuration options used by config are supported.
* @param {LocalForageOptions} options
*/
createInstance(options: LocalForageOptions): LocalForage;
driver(): string;
/**
* Force usage of a particular driver or drivers, if available.
* @param {string} driver
*/
setDriver(
driver: string | string[],
callback?: () => void,
errorCallback?: (error: any) => void
): Promise<void>;
defineDriver(
driver: LocalForageDriver,
callback?: () => void,
errorCallback?: (error: any) => void
): Promise<void>;
/**
* Return a particular driver
* @param {string} driver
*/
getDriver(driver: string): Promise<LocalForageDriver>;
getSerializer(
callback?: (serializer: LocalForageSerializer) => void
): Promise<LocalForageSerializer>;
supports(driverName: string): boolean;
ready(callback?: (error: any) => void): Promise<void>;
}
// Customize
export interface ProxyStorage {
setItem<T>(k: string, v: T, m: number): Promise<T>;
getItem<T>(k: string): Promise<T>;
removeItem(k: string): Promise<void>;
clear(): Promise<void>;
}
export interface ExpiresData<T> {
data: T;
expires: number;
}

85
src/utils/message.ts Normal file
View File

@@ -0,0 +1,85 @@
import type { VNode } from "vue";
import { isFunction } from "@pureadmin/utils";
import { type MessageHandler, ElMessage } from "element-plus";
type messageStyle = "el" | "antd";
type messageTypes = "info" | "success" | "warning" | "error";
interface MessageParams {
/** 消息类型,可选 `info` 、`success` 、`warning` 、`error` ,默认 `info` */
type?: messageTypes;
/** 自定义图标,该属性会覆盖 `type` 的图标 */
icon?: any;
/** 是否将 `message` 属性作为 `HTML` 片段处理,默认 `false` */
dangerouslyUseHTMLString?: boolean;
/** 消息风格,可选 `el` 、`antd` ,默认 `antd` */
customClass?: messageStyle;
/** 显示时间,单位为毫秒。设为 `0` 则不会自动关闭,`element-plus` 默认是 `3000` ,平台改成默认 `2000` */
duration?: number;
/** 是否显示关闭按钮,默认值 `false` */
showClose?: boolean;
/** 文字是否居中,默认值 `false` */
center?: boolean;
/** `Message` 距离窗口顶部的偏移量,默认 `20` */
offset?: number;
/** 设置组件的根元素,默认 `document.body` */
appendTo?: string | HTMLElement;
/** 合并内容相同的消息,不支持 `VNode` 类型的消息,默认值 `false` */
grouping?: boolean;
/** 关闭时的回调函数, 参数为被关闭的 `message` 实例 */
onClose?: Function | null;
}
/** 用法非常简单,参考 src/views/components/message/index.vue 文件 */
/**
* `Message` 消息提示函数
*/
const message = (
message: string | VNode | (() => VNode),
params?: MessageParams
): MessageHandler => {
if (!params) {
return ElMessage({
message,
customClass: "pure-message"
});
} else {
const {
icon,
type = "info",
dangerouslyUseHTMLString = false,
customClass = "antd",
duration = 2000,
showClose = false,
center = false,
offset = 20,
appendTo = document.body,
grouping = false,
onClose
} = params;
return ElMessage({
message,
type,
icon,
dangerouslyUseHTMLString,
duration,
showClose,
center,
offset,
appendTo,
grouping,
// 全局搜 pure-message 即可知道该类的样式位置
customClass: customClass === "antd" ? "pure-message" : "",
onClose: () => (isFunction(onClose) ? onClose() : null)
});
}
};
/**
* 关闭所有 `Message` 消息提示函数
*/
const closeAllMessage = (): void => ElMessage.closeAll();
export { message, closeAllMessage };

13
src/utils/mitt.ts Normal file
View File

@@ -0,0 +1,13 @@
import type { Emitter } from "mitt";
import mitt from "mitt";
/** 全局公共事件需要在此处添加类型 */
type Events = {
openPanel: string;
tagViewsChange: string;
tagViewsShowModel: string;
logoChange: boolean;
changLayoutRoute: string;
};
export const emitter: Emitter<Events> = mitt<Events>();

View File

@@ -0,0 +1,28 @@
import { useEventListener } from "@vueuse/core";
/** 是否为`img`标签 */
function isImgElement(element) {
return typeof HTMLImageElement !== "undefined"
? element instanceof HTMLImageElement
: element.tagName.toLowerCase() === "img";
}
// 在 src/main.ts 引入并调用即可 import { addPreventDefault } from "@/utils/preventDefault"; addPreventDefault();
export const addPreventDefault = () => {
// 阻止通过键盘F12快捷键打开浏览器开发者工具面板
useEventListener(
window.document,
"keydown",
ev => ev.key === "F12" && ev.preventDefault()
);
// 阻止浏览器默认的右键菜单弹出(不会影响自定义右键事件)
useEventListener(window.document, "contextmenu", ev => ev.preventDefault());
// 阻止页面元素选中
useEventListener(window.document, "selectstart", ev => ev.preventDefault());
// 浏览器中图片通常默认是可拖动的,并且可以在新标签页或窗口中打开,或者将其拖动到其他应用程序中,此处将其禁用,使其默认不可拖动
useEventListener(
window.document,
"dragstart",
ev => isImgElement(ev?.target) && ev.preventDefault()
);
};

213
src/utils/print.ts Normal file
View File

@@ -0,0 +1,213 @@
interface PrintFunction {
extendOptions: Function;
getStyle: Function;
setDomHeight: Function;
toPrint: Function;
}
const Print = function (dom, options?: object): PrintFunction {
options = options || {};
// @ts-expect-error
if (!(this instanceof Print)) return new Print(dom, options);
this.conf = {
styleStr: "",
// Elements that need to dynamically get and set the height
setDomHeightArr: [],
// Callback before printing
printBeforeFn: null,
// Callback after printing
printDoneCallBack: null
};
for (const key in this.conf) {
if (key && options.hasOwnProperty(key)) {
this.conf[key] = options[key];
}
}
if (typeof dom === "string") {
this.dom = document.querySelector(dom);
} else {
this.dom = this.isDOM(dom) ? dom : dom.$el;
}
if (this.conf.setDomHeightArr && this.conf.setDomHeightArr.length) {
this.setDomHeight(this.conf.setDomHeightArr);
}
this.init();
};
Print.prototype = {
/**
* init
*/
init: function (): void {
const content = this.getStyle() + this.getHtml();
this.writeIframe(content);
},
/**
* Configuration property extension
* @param {Object} obj
* @param {Object} obj2
*/
extendOptions: function <T>(obj, obj2: T): T {
for (const k in obj2) {
obj[k] = obj2[k];
}
return obj;
},
/**
Copy all styles of the original page
*/
getStyle: function (): string {
let str = "";
const styles: NodeListOf<Element> = document.querySelectorAll("style,link");
for (let i = 0; i < styles.length; i++) {
str += styles[i].outerHTML;
}
str += `<style>.no-print{display:none;}${this.conf.styleStr}</style>`;
return str;
},
// form assignment
getHtml: function (): Element {
const inputs = document.querySelectorAll("input");
const selects = document.querySelectorAll("select");
const textareas = document.querySelectorAll("textarea");
const canvass = document.querySelectorAll("canvas");
for (let k = 0; k < inputs.length; k++) {
if (inputs[k].type == "checkbox" || inputs[k].type == "radio") {
if (inputs[k].checked == true) {
inputs[k].setAttribute("checked", "checked");
} else {
inputs[k].removeAttribute("checked");
}
} else if (inputs[k].type == "text") {
inputs[k].setAttribute("value", inputs[k].value);
} else {
inputs[k].setAttribute("value", inputs[k].value);
}
}
for (let k2 = 0; k2 < textareas.length; k2++) {
if (textareas[k2].type == "textarea") {
textareas[k2].innerHTML = textareas[k2].value;
}
}
for (let k3 = 0; k3 < selects.length; k3++) {
if (selects[k3].type == "select-one") {
const child = selects[k3].children;
for (const i in child) {
if (child[i].tagName == "OPTION") {
if ((child[i] as any).selected == true) {
child[i].setAttribute("selected", "selected");
} else {
child[i].removeAttribute("selected");
}
}
}
}
}
for (let k4 = 0; k4 < canvass.length; k4++) {
const imageURL = canvass[k4].toDataURL("image/png");
const img = document.createElement("img");
img.src = imageURL;
img.setAttribute("style", "max-width: 100%;");
img.className = "isNeedRemove";
canvass[k4].parentNode.insertBefore(img, canvass[k4].nextElementSibling);
}
return this.dom.outerHTML;
},
/**
create iframe
*/
writeIframe: function (content) {
let w: Document | Window;
let doc: Document;
const iframe: HTMLIFrameElement = document.createElement("iframe");
const f: HTMLIFrameElement = document.body.appendChild(iframe);
iframe.id = "myIframe";
iframe.setAttribute(
"style",
"position:absolute;width:0;height:0;top:-10px;left:-10px;"
);
w = f.contentWindow || f.contentDocument;
doc = f.contentDocument || f.contentWindow.document;
doc.open();
doc.write(content);
doc.close();
const removes = document.querySelectorAll(".isNeedRemove");
for (let k = 0; k < removes.length; k++) {
removes[k].parentNode.removeChild(removes[k]);
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
const _this = this;
iframe.onload = function (): void {
// Before popping, callback
if (_this.conf.printBeforeFn) {
_this.conf.printBeforeFn({ doc });
}
_this.toPrint(w);
setTimeout(function () {
document.body.removeChild(iframe);
// After popup, callback
if (_this.conf.printDoneCallBack) {
_this.conf.printDoneCallBack();
}
}, 100);
};
},
/**
Print
*/
toPrint: function (frameWindow): void {
try {
setTimeout(function () {
frameWindow.focus();
try {
if (!frameWindow.document.execCommand("print", false, null)) {
frameWindow.print();
}
} catch (e) {
frameWindow.print();
}
frameWindow.close();
}, 10);
} catch (err) {
console.error(err);
}
},
isDOM:
typeof HTMLElement === "object"
? function (obj) {
return obj instanceof HTMLElement;
}
: function (obj) {
return (
obj &&
typeof obj === "object" &&
obj.nodeType === 1 &&
typeof obj.nodeName === "string"
);
},
/**
* Set the height of the specified dom element by getting the existing height of the dom element and setting
* @param {Array} arr
*/
setDomHeight(arr) {
if (arr && arr.length) {
arr.forEach(name => {
const domArr = document.querySelectorAll(name);
domArr.forEach(dom => {
dom.style.height = dom.offsetHeight + "px";
});
});
}
}
};
export default Print;

View File

@@ -0,0 +1,17 @@
import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({
// 动画方式
easing: "ease",
// 递增进度条的速度
speed: 500,
// 是否显示加载ico
showSpinner: false,
// 自动递增间隔
trickleSpeed: 200,
// 初始化时的最小百分比
minimum: 0.3
});
export default NProgress;

39
src/utils/propTypes.ts Normal file
View File

@@ -0,0 +1,39 @@
import type { CSSProperties, VNodeChild } from "vue";
import {
createTypes,
toValidableType,
type VueTypesInterface,
type VueTypeValidableDef
} from "vue-types";
export type VueNode = VNodeChild | JSX.Element;
type PropTypes = VueTypesInterface & {
readonly style: VueTypeValidableDef<CSSProperties>;
readonly VNodeChild: VueTypeValidableDef<VueNode>;
};
const newPropTypes = createTypes({
func: undefined,
bool: undefined,
string: undefined,
number: undefined,
object: undefined,
integer: undefined
}) as PropTypes;
// 从 vue-types v5.0 开始extend()方法已经废弃当前已改为官方推荐的ES6+方法 https://dwightjack.github.io/vue-types/advanced/extending-vue-types.html#the-extend-method
export default class propTypes extends newPropTypes {
// a native-like validator that supports the `.validable` method
static get style() {
return toValidableType("style", {
type: [String, Object]
});
}
static get VNodeChild() {
return toValidableType("VNodeChild", {
type: undefined
});
}
}

42
src/utils/responsive.ts Normal file
View File

@@ -0,0 +1,42 @@
// 响应式storage
import type { App } from "vue";
import Storage from "responsive-storage";
import { routerArrays } from "@/layout/types";
import { responsiveStorageNameSpace } from "@/config";
export const injectResponsiveStorage = (app: App, config: PlatformConfigs) => {
const nameSpace = responsiveStorageNameSpace();
const configObj = Object.assign(
{
// layout模式以及主题
layout: Storage.getData("layout", nameSpace) ?? {
layout: config.Layout ?? "vertical",
theme: config.Theme ?? "light",
darkMode: config.DarkMode ?? false,
sidebarStatus: config.SidebarStatus ?? true,
epThemeColor: config.EpThemeColor ?? "#409EFF",
themeColor: config.Theme ?? "light", // 主题色对应系统配置中的主题色与theme不同的是它不会受到浅色、深色整体风格切换的影响只会在手动点击主题色时改变
overallStyle: config.OverallStyle ?? "light" // 整体风格浅色light、深色dark、自动system
},
// 系统配置-界面显示
configure: Storage.getData("configure", nameSpace) ?? {
grey: config.Grey ?? false,
weak: config.Weak ?? false,
hideTabs: config.HideTabs ?? false,
hideFooter: config.HideFooter ?? true,
showLogo: config.ShowLogo ?? true,
showModel: config.ShowModel ?? "smart",
multiTagsCache: config.MultiTagsCache ?? false,
stretch: config.Stretch ?? false
}
},
config.MultiTagsCache
? {
// 默认显示顶级菜单tag
tags: Storage.getData("tags", nameSpace) ?? routerArrays
}
: {}
);
app.use(Storage, { nameSpace, memory: configObj });
};

59
src/utils/sso.ts Normal file
View File

@@ -0,0 +1,59 @@
import { removeToken, setToken, type DataInfo } from "./auth";
import { subBefore, getQueryMap } from "@pureadmin/utils";
/**
* 简版前端单点登录,根据实际业务自行编写,平台启动后本地可以跳后面这个链接进行测试 http://localhost:8848/#/permission/page/index?username=sso&roles=admin&accessToken=eyJhbGciOiJIUzUxMiJ9.admin
* 划重点:
* 判断是否为单点登录,不为则直接返回不再进行任何逻辑处理,下面是单点登录后的逻辑处理
* 1.清空本地旧信息;
* 2.获取url中的重要参数信息然后通过 setToken 保存在本地;
* 3.删除不需要显示在 url 的参数
* 4.使用 window.location.replace 跳转正确页面
*/
(function () {
// 获取 url 中的参数
const params = getQueryMap(location.href) as DataInfo<Date>;
const must = ["username", "roles", "accessToken"];
const mustLength = must.length;
if (Object.keys(params).length !== mustLength) return;
// url 参数满足 must 里的全部值,才判定为单点登录,避免非单点登录时刷新页面无限循环
let sso = [];
let start = 0;
while (start < mustLength) {
if (Object.keys(params).includes(must[start]) && sso.length <= mustLength) {
sso.push(must[start]);
} else {
sso = [];
}
start++;
}
if (sso.length === mustLength) {
// 判定为单点登录
// 清空本地旧信息
removeToken();
// 保存新信息到本地
setToken(params);
// 删除不需要显示在 url 的参数
delete params.roles;
delete params.accessToken;
const newUrl = `${location.origin}${location.pathname}${subBefore(
location.hash,
"?"
)}?${JSON.stringify(params)
.replace(/["{}]/g, "")
.replace(/:/g, "=")
.replace(/,/g, "&")}`;
// 替换历史记录项
window.location.replace(newUrl);
} else {
return;
}
})();

188
src/utils/tree.ts Normal file
View File

@@ -0,0 +1,188 @@
/**
* @description 提取菜单树中的每一项uniqueId
* @param tree 树
* @returns 每一项uniqueId组成的数组
*/
export const extractPathList = (tree: any[]): any => {
if (!Array.isArray(tree)) {
console.warn("tree must be an array");
return [];
}
if (!tree || tree.length === 0) return [];
const expandedPaths: Array<number | string> = [];
for (const node of tree) {
const hasChildren = node.children && node.children.length > 0;
if (hasChildren) {
extractPathList(node.children);
}
expandedPaths.push(node.uniqueId);
}
return expandedPaths;
};
/**
* @description 如果父级下children的length为1删除children并自动组建唯一uniqueId
* @param tree 树
* @param pathList 每一项的id组成的数组
* @returns 组件唯一uniqueId后的树
*/
export const deleteChildren = (tree: any[], pathList = []): any => {
if (!Array.isArray(tree)) {
console.warn("menuTree must be an array");
return [];
}
if (!tree || tree.length === 0) return [];
for (const [key, node] of tree.entries()) {
if (node.children && node.children.length === 1) delete node.children;
node.id = key;
node.parentId = pathList.length ? pathList[pathList.length - 1] : null;
node.pathList = [...pathList, node.id];
node.uniqueId =
node.pathList.length > 1 ? node.pathList.join("-") : node.pathList[0];
const hasChildren = node.children && node.children.length > 0;
if (hasChildren) {
deleteChildren(node.children, node.pathList);
}
}
return tree;
};
/**
* @description 创建层级关系
* @param tree 树
* @param pathList 每一项的id组成的数组
* @returns 创建层级关系后的树
*/
export const buildHierarchyTree = (tree: any[], pathList = []): any => {
if (!Array.isArray(tree)) {
console.warn("tree must be an array");
return [];
}
if (!tree || tree.length === 0) return [];
for (const [key, node] of tree.entries()) {
node.id = key;
node.parentId = pathList.length ? pathList[pathList.length - 1] : null;
node.pathList = [...pathList, node.id];
const hasChildren = node.children && node.children.length > 0;
if (hasChildren) {
buildHierarchyTree(node.children, node.pathList);
}
}
return tree;
};
/**
* @description 广度优先遍历根据唯一uniqueId找当前节点信息
* @param tree 树
* @param uniqueId 唯一uniqueId
* @returns 当前节点信息
*/
export const getNodeByUniqueId = (
tree: any[],
uniqueId: number | string
): any => {
if (!Array.isArray(tree)) {
console.warn("menuTree must be an array");
return [];
}
if (!tree || tree.length === 0) return [];
const item = tree.find(node => node.uniqueId === uniqueId);
if (item) return item;
const childrenList = tree
.filter(node => node.children)
.map(i => i.children)
.flat(1) as unknown;
return getNodeByUniqueId(childrenList as any[], uniqueId);
};
/**
* @description 向当前唯一uniqueId节点中追加字段
* @param tree 树
* @param uniqueId 唯一uniqueId
* @param fields 需要追加的字段
* @returns 追加字段后的树
*/
export const appendFieldByUniqueId = (
tree: any[],
uniqueId: number | string,
fields: object
): any => {
if (!Array.isArray(tree)) {
console.warn("menuTree must be an array");
return [];
}
if (!tree || tree.length === 0) return [];
for (const node of tree) {
const hasChildren = node.children && node.children.length > 0;
if (
node.uniqueId === uniqueId &&
Object.prototype.toString.call(fields) === "[object Object]"
)
Object.assign(node, fields);
if (hasChildren) {
appendFieldByUniqueId(node.children, uniqueId, fields);
}
}
return tree;
};
/**
* @description 构造树型结构数据
* @param data 数据源
* @param id id字段 默认id
* @param parentId 父节点字段默认parentId
* @param children 子节点字段默认children
* @returns 追加字段后的树
*/
export const handleTree = (
data: any[],
id?: string,
parentId?: string,
children?: string
): any => {
if (!Array.isArray(data)) {
console.warn("data must be an array");
return [];
}
const config = {
id: id || "id",
parentId: parentId || "parentId",
childrenList: children || "children"
};
const childrenListMap: any = {};
const nodeIds: any = {};
const tree = [];
for (const d of data) {
const parentId = d[config.parentId];
if (childrenListMap[parentId] == null) {
childrenListMap[parentId] = [];
}
nodeIds[d[config.id]] = d;
childrenListMap[parentId].push(d);
}
for (const d of data) {
const parentId = d[config.parentId];
if (nodeIds[parentId] == null) {
tree.push(d);
}
}
for (const t of tree) {
adaptToChildrenList(t);
}
function adaptToChildrenList(o: Record<string, any>) {
if (childrenListMap[o[config.id]] !== null) {
o[config.childrenList] = childrenListMap[o[config.id]];
}
if (o[config.childrenList]) {
for (const c of o[config.childrenList]) {
adaptToChildrenList(c);
}
}
}
return tree;
};