chore(mobile-h5): add existing H5 app sources to the monorepo
Track the weighbridge mobile-h5 codebase (excluding node_modules, dist, and local .env) so subsequent adaptation tasks can evolve it in-repo. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
f8f9c0ceff
commit
a4b13fa2bc
91 files changed
+15791
No files matched your search
@@ -0,0 +1,78 @@
|
||||
import { showToast } from 'vant'
|
||||
|
||||
/**
|
||||
* hex颜色转rgb颜色
|
||||
* @param str 颜色值字符串
|
||||
* @returns 返回处理后的颜色值
|
||||
*/
|
||||
export function hexToRgb(str: any) {
|
||||
let hexs: any = ''
|
||||
const reg = /^#?[0-9A-Fa-f]{6}$/
|
||||
if (!reg.test(str)) {
|
||||
showToast({ type: 'fail', message: '输入错误的hex' })
|
||||
return
|
||||
}
|
||||
str = str.replace('#', '')
|
||||
|
||||
hexs = str.match(/../g)
|
||||
|
||||
for (let i = 0; i < 3; i++) hexs[i] = parseInt(hexs[i], 16)
|
||||
return hexs
|
||||
}
|
||||
|
||||
/**
|
||||
* rgb颜色转Hex颜色
|
||||
* @param r 代表红色
|
||||
* @param g 代表绿色
|
||||
* @param b 代表蓝色
|
||||
* @returns 返回处理后的颜色值
|
||||
*/
|
||||
export function rgbToHex(r: any, g: any, b: any) {
|
||||
const reg = /^\d{1,3}$/
|
||||
if (!reg.test(r) || !reg.test(g) || !reg.test(b)) {
|
||||
showToast({ type: 'fail', message: '输入错误的rgb颜色值' })
|
||||
return
|
||||
}
|
||||
const hexs = [r.toString(16), g.toString(16), b.toString(16)]
|
||||
|
||||
for (let i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`
|
||||
|
||||
return `#${hexs.join('')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 加深颜色值
|
||||
* @param color 颜色值字符串
|
||||
* @param level 加深的程度,限0-1之间
|
||||
* @returns 返回处理后的颜色值
|
||||
*/
|
||||
export function getDarkColor(color: string, level: number) {
|
||||
const reg = /^#?[0-9A-Fa-f]{6}$/
|
||||
if (!reg.test(color)) {
|
||||
showToast({ type: 'fail', message: '输入错误的hex颜色值' })
|
||||
return
|
||||
}
|
||||
const rgb = hexToRgb(color)
|
||||
for (let i = 0; i < 3; i++) rgb[i] = Math.round(20.5 * level + rgb[i] * (1 - level))
|
||||
return rgbToHex(rgb[0], rgb[1], rgb[2])
|
||||
}
|
||||
|
||||
/**
|
||||
* 变浅颜色值
|
||||
* @param color 颜色值字符串
|
||||
* @param level 加深的程度,限0-1之间
|
||||
* @returns 返回处理后的颜色值
|
||||
*/
|
||||
export function getLightColor(color: string, level: number) {
|
||||
const reg = /^#?[0-9A-Fa-f]{6}$/
|
||||
if (!reg.test(color)) {
|
||||
showToast({ type: 'fail', message: '输入错误的hex颜色值' })
|
||||
return
|
||||
}
|
||||
const rgb = hexToRgb(color)
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
rgb[i] = Math.round(255 * level + rgb[i] * (1 - level))
|
||||
}
|
||||
return rgbToHex(rgb[0], rgb[1], rgb[2])
|
||||
}
|
||||
Executable
+109
@@ -0,0 +1,109 @@
|
||||
export function getCssVariable(str: string) {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(str)
|
||||
}
|
||||
|
||||
// 将hex颜色转成rgb 例如(#F55442, 1)
|
||||
export function hexToRgba(
|
||||
hex: string,
|
||||
opacity: number
|
||||
): { red: number; green: number; blue: number; rgba: string } {
|
||||
// 移除可能存在的 # 前缀并转换为大写
|
||||
hex = hex.replace(/^#/, '').toUpperCase()
|
||||
|
||||
// 如果是缩写形式(如 FFF),转换为完整形式
|
||||
if (hex.length === 3) {
|
||||
hex = hex
|
||||
.split('')
|
||||
.map((char) => char.repeat(2))
|
||||
.join('')
|
||||
}
|
||||
|
||||
// 验证 hex 格式
|
||||
if (!/^[0-9A-F]{6}$/.test(hex)) {
|
||||
throw new Error('Invalid hex color format')
|
||||
}
|
||||
|
||||
// 解析 RGB 值
|
||||
const [red, green, blue] = hex.match(/\w\w/g)!.map((x) => parseInt(x, 16))
|
||||
|
||||
// 确保 opacity 在有效范围内
|
||||
opacity = Math.max(0, Math.min(1, opacity))
|
||||
|
||||
// 构建 RGBA 字符串
|
||||
const rgba = `rgba(${red}, ${green}, ${blue}, ${opacity.toFixed(2)})`
|
||||
|
||||
return { red, green, blue, rgba }
|
||||
}
|
||||
|
||||
// 将rgb颜色转成hex 例如(24,12,255)
|
||||
export function rgbToHex(r: any, g: any, b: any) {
|
||||
const hex = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
|
||||
return hex
|
||||
}
|
||||
|
||||
// 颜色混合
|
||||
export function colourBlend(c1: string, c2: string, ratio: any) {
|
||||
ratio = Math.max(Math.min(Number(ratio), 1), 0)
|
||||
const r1 = parseInt(c1.substring(1, 3), 16)
|
||||
const g1 = parseInt(c1.substring(3, 5), 16)
|
||||
const b1 = parseInt(c1.substring(5, 7), 16)
|
||||
const r2 = parseInt(c2.substring(1, 3), 16)
|
||||
const g2 = parseInt(c2.substring(3, 5), 16)
|
||||
const b2 = parseInt(c2.substring(5, 7), 16)
|
||||
let r: any = Math.round(r1 * (1 - ratio) + r2 * ratio)
|
||||
let g: any = Math.round(g1 * (1 - ratio) + g2 * ratio)
|
||||
let b: any = Math.round(b1 * (1 - ratio) + b2 * ratio)
|
||||
r = ('0' + (r || 0).toString(16)).slice(-2)
|
||||
g = ('0' + (g || 0).toString(16)).slice(-2)
|
||||
b = ('0' + (b || 0).toString(16)).slice(-2)
|
||||
return '#' + r + g + b
|
||||
}
|
||||
|
||||
export const getCssVar = (name: string) => {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(name)
|
||||
}
|
||||
|
||||
// 处理 Element Plus 主题颜色
|
||||
export function handleElementThemeColor(theme: string, isDark: boolean = false): void {
|
||||
document.documentElement.style.setProperty('--el-color-primary', theme)
|
||||
for (let i = 1; i <= 9; i++) {
|
||||
document.documentElement.style.setProperty(
|
||||
`--el-color-primary-light-${i}`,
|
||||
`${getLightColor(theme, i / 10, isDark)}`
|
||||
)
|
||||
}
|
||||
for (let i = 1; i <= 9; i++) {
|
||||
document.documentElement.style.setProperty(
|
||||
`--el-color-primary-dark-${i}`,
|
||||
`${getDarkColor(theme, i / 10)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// hex颜色转rgb颜色
|
||||
export function hexToRgb(str: string): number[] {
|
||||
str = str.replace('#', '')
|
||||
const hexs = str.match(/../g)
|
||||
if (!hexs) {
|
||||
throw new Error('Invalid hex color')
|
||||
}
|
||||
return hexs.map((hex) => parseInt(hex, 16))
|
||||
}
|
||||
|
||||
// 变浅颜色值
|
||||
export function getLightColor(color: string, level: number, isDark: boolean = false): string {
|
||||
if (isDark) {
|
||||
return getDarkColor(color, level)
|
||||
} else {
|
||||
const rgb = hexToRgb(color)
|
||||
const newRgb = rgb.map((value) => Math.floor((255 - value) * level + value))
|
||||
return rgbToHex(newRgb[0], newRgb[1], newRgb[2])
|
||||
}
|
||||
}
|
||||
|
||||
// 变深颜色值
|
||||
export function getDarkColor(color: string, level: number): string {
|
||||
const rgb = hexToRgb(color)
|
||||
const newRgb = rgb.map((value) => Math.floor(value * (1 - level)))
|
||||
return rgbToHex(newRgb[0], newRgb[1], newRgb[2])
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// ANSI 转义码生成网站 https://patorjk.com/software/taag/#p=display&f=Big&t=ABB%0A
|
||||
const asciiArt = `
|
||||
\x1b[32m✨ 你好!欢迎使用 Art Design Pro!
|
||||
\x1b[0m
|
||||
\x1b[36m💡 如果您觉得项目对您有帮助,请点击下面的链接为我点个 ★Star 支持一下!祝您使用愉快!
|
||||
\x1b[0m
|
||||
\x1b[33m🌟 GitHub: https://github.com/Daymychen/art-design-pro
|
||||
\x1b[0m
|
||||
\x1b[31m✨ 技术支持(QQ群): 821834289,如果你有任何问题,请加入QQ群,我们会在第一时间为你解答!
|
||||
\x1b[0m
|
||||
|
||||
\x1b[36m _ _______ _________ ______ ________ ______ _____ ______ ____ _____ _______ _______ ___
|
||||
\x1b[36m / \\ |_ __ \\ | _ _ | |_ _ \`.|_ __ |.' ____ \\ |_ _|.' ___ ||_ \\|_ _| |_ __ \\|_ __ \\ .' \`.
|
||||
\x1b[36m / _ \\ | |__) ||_/ | | \\_| | | \`. \\ | |_ \\_|| (___ \\_| | | / .' \\_| | \\ | | | |__) | | |__) | / .-. \\
|
||||
\x1b[36m / ___ \\ | __ / | | | | | | | _| _ _.____\`. | | | | ____ | |\\ \\| | | ___/ | __ / | | | |
|
||||
\x1b[36m _/ / \\ \\_ _| | \\ \\_ _| |_ _| |_.' /_| |__/ || \\____) | _| |_\\ \`.___] |_| |_\\ |_ _| |_ _| | \\ \\_\\ \`-' /
|
||||
\x1b[36m|____| |____||____| |___||_____| |______.'|________| \\______.'|_____|\\\`._____.'|_____|\____| |_____| |____| |___|\\\`.___.'
|
||||
\x1b[0m
|
||||
`
|
||||
|
||||
console.log(asciiArt)
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
ECharts 配置项参考地址
|
||||
|
||||
地址:https://echarts.apache.org/examples/zh/editor.html?c=line-simple
|
||||
|
||||
示例编辑:可以在这里方便快捷的配置
|
||||
|
||||
完整代码:配置后的所有代码
|
||||
|
||||
配置项:根据需求选择配置项配置
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
// 默认配置
|
||||
|
||||
const defaultOpstions = {
|
||||
grid: {
|
||||
left: '0',
|
||||
right: '4%',
|
||||
bottom: '0%',
|
||||
top: '0',
|
||||
containLabel: true
|
||||
},
|
||||
tooltip: {},
|
||||
yAxis: {
|
||||
axisLabel: {
|
||||
show: true,
|
||||
color: '#8c8c8c'
|
||||
},
|
||||
axisTick: {
|
||||
show: false
|
||||
},
|
||||
axisLine: {
|
||||
show: true,
|
||||
lineStyle: {
|
||||
color: '#e8e8e8',
|
||||
width: 1,
|
||||
type: 'solid'
|
||||
}
|
||||
}
|
||||
},
|
||||
xAxis: {
|
||||
axisLine: {
|
||||
show: true,
|
||||
lineStyle: {
|
||||
color: '#e8e8e8',
|
||||
width: 1,
|
||||
type: 'solid'
|
||||
}
|
||||
},
|
||||
splitLine: {
|
||||
show: true,
|
||||
lineStyle: {
|
||||
color: '#e8e8e8',
|
||||
width: 0,
|
||||
type: 'solid'
|
||||
}
|
||||
},
|
||||
axisLabel: {
|
||||
show: true,
|
||||
color: 'rgba(255,255,255, 0.6)'
|
||||
},
|
||||
axisTick: {
|
||||
show: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { defaultOpstions }
|
||||
Executable
+117
@@ -0,0 +1,117 @@
|
||||
// src/utils/echarts/useECharts.ts
|
||||
import { unref, Ref, nextTick } from 'vue'
|
||||
import echarts from '@/plugins/echarts'
|
||||
import { defaultOpstions } from './defaultOpstions'
|
||||
|
||||
// ECharts 类型定义(如果 echarts 未安装)
|
||||
type EChartsOption = any
|
||||
type EChartsInstance = {
|
||||
setOption: (option: any) => void
|
||||
resize: () => void
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
export function useECharts(
|
||||
elRef: Ref<HTMLDivElement>,
|
||||
theme: 'light' | 'dark' | 'default' = 'light'
|
||||
) {
|
||||
let chartInstance: EChartsInstance | null = null
|
||||
let resizeHandler: () => void
|
||||
|
||||
// 初始化echarts
|
||||
function initCharts() {
|
||||
const el = unref(elRef)
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
chartInstance = echarts.init ? echarts.init(el, theme) : null
|
||||
addResize()
|
||||
}
|
||||
|
||||
// 配置
|
||||
function setOptions(options: EChartsOption | any) {
|
||||
// 默认配置
|
||||
if (!options.grid) {
|
||||
options.grid = defaultOpstions.grid
|
||||
}
|
||||
|
||||
if (!options.tooltip) {
|
||||
options.tooltip = defaultOpstions.tooltip
|
||||
}
|
||||
|
||||
if (options.yAxis) {
|
||||
const { axisLine, axisTick } = defaultOpstions.yAxis
|
||||
|
||||
if (!options.yAxis.axisLine) {
|
||||
options.yAxis.axisLine = axisLine
|
||||
}
|
||||
if (!options.yAxis.axisTick) {
|
||||
options.yAxis.axisTick = axisTick
|
||||
}
|
||||
}
|
||||
|
||||
if (options.xAxis) {
|
||||
const { axisLine, splitLine, axisTick } = defaultOpstions.xAxis
|
||||
|
||||
if (!options.xAxis.axisLine) {
|
||||
options.xAxis.axisLine = axisLine
|
||||
}
|
||||
if (!options.xAxis.splitLine) {
|
||||
options.xAxis.splitLine = splitLine
|
||||
}
|
||||
if (!options.xAxis.axisTick) {
|
||||
options.xAxis.axisTick = axisTick
|
||||
}
|
||||
}
|
||||
|
||||
if (unref(elRef).offsetHeight === 0) {
|
||||
setTimeout(() => {
|
||||
setOptions(options)
|
||||
}, 30)
|
||||
return
|
||||
}
|
||||
|
||||
nextTick(() => {
|
||||
setTimeout(() => {
|
||||
if (!chartInstance) {
|
||||
initCharts()
|
||||
if (!chartInstance) return
|
||||
}
|
||||
chartInstance.setOption(options)
|
||||
}, 30)
|
||||
})
|
||||
}
|
||||
|
||||
// 监听窗口大小变化
|
||||
function addResize() {
|
||||
resizeHandler = () => {
|
||||
resize()
|
||||
}
|
||||
window.addEventListener('resize', resizeHandler)
|
||||
}
|
||||
|
||||
// 移除监听
|
||||
function removeResize() {
|
||||
if (resizeHandler) {
|
||||
window.removeEventListener('resize', resizeHandler)
|
||||
}
|
||||
}
|
||||
|
||||
// 暴露 resize 方法
|
||||
function resize() {
|
||||
if (chartInstance) {
|
||||
chartInstance.resize()
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化时创建图表
|
||||
initCharts()
|
||||
|
||||
return {
|
||||
setOptions,
|
||||
addResize,
|
||||
removeResize,
|
||||
resize,
|
||||
echarts
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* 表情
|
||||
* 用于在消息提示的时候显示对应的表情
|
||||
*
|
||||
* 用法
|
||||
* ElMessage.success(`${EmojiText[200]} 图片上传成功`)
|
||||
* ElMessage.error(`${EmojiText[400]} 图片上传失败`)
|
||||
* ElMessage.error(`${EmojiText[500]} 图片上传失败`)
|
||||
*/
|
||||
|
||||
// macos 用户 按 shift + 6 可以唤出更多表情……
|
||||
const EmojiText: { [key: string]: string } = {
|
||||
'0': 'O_O', // 空
|
||||
'200': '^_^', // 成功
|
||||
'400': 'T_T', // 错误请求
|
||||
'500': 'X_X' // 服务器内部错误,无法完成请求
|
||||
}
|
||||
|
||||
// const EmojiIcon = ['🟢', '🔴', '🟡 ', '🚀', '✨', '💡', '🛠️', '🔥', '🎉', '🌟', '🌈']
|
||||
|
||||
export default EmojiText
|
||||
Executable
+174
@@ -0,0 +1,174 @@
|
||||
import axios, { InternalAxiosRequestConfig, AxiosRequestConfig, AxiosResponse } from 'axios'
|
||||
import { showToast } from 'vant'
|
||||
import { useUserStore } from '@/store/modules/user'
|
||||
|
||||
const getBaseURL = () => {
|
||||
if (import.meta.env.DEV) {
|
||||
return '/api'
|
||||
}
|
||||
return import.meta.env.VITE_API_URL || '/api'
|
||||
}
|
||||
|
||||
const axiosInstance = axios.create({
|
||||
timeout: 15000,
|
||||
baseURL: getBaseURL(),
|
||||
withCredentials: true,
|
||||
transformRequest: [
|
||||
(data) => {
|
||||
if (data && typeof data === 'object' && !(data instanceof FormData)) {
|
||||
return JSON.stringify(data)
|
||||
}
|
||||
return data
|
||||
}
|
||||
],
|
||||
validateStatus: (status) => status >= 200 && status < 300,
|
||||
headers: {
|
||||
get: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
|
||||
post: { 'Content-Type': 'application/json;charset=utf-8' }
|
||||
},
|
||||
transformResponse: [
|
||||
(data, headers) => {
|
||||
// 如果 data 是 undefined 或 null,直接返回
|
||||
if (data === undefined || data === null) {
|
||||
return data
|
||||
}
|
||||
|
||||
const contentType = headers['content-type']
|
||||
if (contentType && contentType.includes('application/json')) {
|
||||
try {
|
||||
// 如果 data 是字符串,尝试解析
|
||||
if (typeof data === 'string') {
|
||||
return JSON.parse(data)
|
||||
}
|
||||
// 如果已经是对象,直接返回
|
||||
return data
|
||||
} catch (error) {
|
||||
console.error('JSON parse error:', error, 'data:', data)
|
||||
return data
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
// 请求拦截器
|
||||
axiosInstance.interceptors.request.use(
|
||||
(config: InternalAxiosRequestConfig) => {
|
||||
const userStore = useUserStore()
|
||||
if (userStore.accessToken) {
|
||||
config.headers.Authorization = `Bearer ${userStore.accessToken}`
|
||||
}
|
||||
|
||||
// 对于有 body 的请求(POST, PUT, PATCH),确保 Content-Type 正确
|
||||
const method = config.method?.toUpperCase()
|
||||
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
|
||||
if (config.data && typeof config.data === 'object' && !(config.data instanceof FormData)) {
|
||||
// 如果 data 是对象,确保 Content-Type 是 application/json
|
||||
config.headers['Content-Type'] = 'application/json;charset=utf-8'
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// 响应拦截器
|
||||
axiosInstance.interceptors.response.use(
|
||||
(response: AxiosResponse) => {
|
||||
// 如果 response.data 是 undefined,直接返回
|
||||
if (!response.data) {
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 如果响应数据没有 code 字段,说明后端直接返回数据,直接返回
|
||||
if (typeof response.data !== 'object' || !('code' in response.data)) {
|
||||
return response.data
|
||||
}
|
||||
|
||||
const { code, message } = response.data
|
||||
|
||||
// 成功响应
|
||||
if (code === 200 || code === 0) {
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 401 未授权,清除 token 并跳转登录
|
||||
if (code === 401) {
|
||||
const userStore = useUserStore()
|
||||
userStore.logOut()
|
||||
showToast({
|
||||
type: 'fail',
|
||||
message: message || '登录已过期,请重新登录'
|
||||
})
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login'
|
||||
}, 1500)
|
||||
return Promise.reject(new Error(message || 'Unauthorized'))
|
||||
}
|
||||
|
||||
// 其他错误
|
||||
showToast({
|
||||
type: 'fail',
|
||||
message: message || '请求失败'
|
||||
})
|
||||
return Promise.reject(new Error(message || 'Request failed'))
|
||||
},
|
||||
(error) => {
|
||||
if (error.response) {
|
||||
const { status, data } = error.response
|
||||
if (status === 401) {
|
||||
const userStore = useUserStore()
|
||||
userStore.logOut()
|
||||
showToast({
|
||||
type: 'fail',
|
||||
message: '登录已过期,请重新登录'
|
||||
})
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login'
|
||||
}, 1500)
|
||||
} else {
|
||||
showToast({
|
||||
type: 'fail',
|
||||
message: data?.message || `请求失败: ${status}`
|
||||
})
|
||||
}
|
||||
} else if (error.request) {
|
||||
showToast({
|
||||
type: 'fail',
|
||||
message: '网络错误,请检查网络连接'
|
||||
})
|
||||
} else {
|
||||
showToast({
|
||||
type: 'fail',
|
||||
message: error.message || '请求失败'
|
||||
})
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// API 方法封装
|
||||
const api = {
|
||||
get<T = any>(config: AxiosRequestConfig): Promise<T> {
|
||||
return axiosInstance.request({ ...config, method: 'GET' })
|
||||
},
|
||||
post<T = any>(config: AxiosRequestConfig): Promise<T> {
|
||||
return axiosInstance.request({ ...config, method: 'POST' })
|
||||
},
|
||||
put<T = any>(config: AxiosRequestConfig): Promise<T> {
|
||||
return axiosInstance.request({ ...config, method: 'PUT' })
|
||||
},
|
||||
patch<T = any>(config: AxiosRequestConfig): Promise<T> {
|
||||
return axiosInstance.request({ ...config, method: 'PATCH' })
|
||||
},
|
||||
del<T = any>(config: AxiosRequestConfig): Promise<T> {
|
||||
return axiosInstance.request({ ...config, method: 'DELETE' })
|
||||
}
|
||||
}
|
||||
|
||||
export default api
|
||||
export { axiosInstance }
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
export enum ApiStatus {
|
||||
success = 200
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// 提取 iconfont 图标
|
||||
|
||||
export interface IconfontType {
|
||||
className: string
|
||||
unicode?: string
|
||||
}
|
||||
|
||||
interface StyleSheetError {
|
||||
sheet: CSSStyleSheet
|
||||
error: unknown
|
||||
}
|
||||
|
||||
function extractIconFromRule(rule: CSSRule): IconfontType | null {
|
||||
if (!(rule instanceof CSSStyleRule)) return null
|
||||
|
||||
const { selectorText, style } = rule
|
||||
if (!selectorText?.startsWith('.iconsys-') || !selectorText.includes('::before')) return null
|
||||
|
||||
const className = selectorText.substring(1).replace('::before', '')
|
||||
const content = style.getPropertyValue('content')
|
||||
if (!content) return null
|
||||
|
||||
const unicode = content.replace(/['"\\]/g, '')
|
||||
return {
|
||||
className,
|
||||
unicode: unicode ? `&#x${getUnicode(unicode)};` : undefined
|
||||
}
|
||||
}
|
||||
|
||||
const processedErrors = new Set<StyleSheetError>()
|
||||
|
||||
export function extractIconClasses(): IconfontType[] {
|
||||
const iconInfos: IconfontType[] = []
|
||||
|
||||
try {
|
||||
Array.from(document.styleSheets).forEach((sheet) => {
|
||||
try {
|
||||
const rules = Array.from(sheet.cssRules || sheet.rules)
|
||||
rules.forEach((rule) => {
|
||||
const iconInfo = extractIconFromRule(rule)
|
||||
if (iconInfo) {
|
||||
iconInfos.push(iconInfo)
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
const styleSheetError: StyleSheetError = { sheet, error }
|
||||
if (!processedErrors.has(styleSheetError)) {
|
||||
console.warn('Cannot read cssRules from stylesheet:', {
|
||||
error,
|
||||
sheetHref: sheet.href
|
||||
})
|
||||
processedErrors.add(styleSheetError)
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to process stylesheets:', error)
|
||||
}
|
||||
|
||||
return iconInfos
|
||||
}
|
||||
|
||||
export function getUnicode(charCode: string): string {
|
||||
if (!charCode) return ''
|
||||
return charCode.charCodeAt(0).toString(16).padStart(4, '0')
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { MenuListType } from '@/types/menu'
|
||||
import { router } from '@/router'
|
||||
|
||||
// 打开外部链接
|
||||
export const openExternalLink = (link: string) => {
|
||||
window.open(link, '_blank')
|
||||
}
|
||||
|
||||
/**
|
||||
* 菜单跳转
|
||||
* @param item 菜单项
|
||||
* @param jumpToFirst 是否跳转到第一个子菜单
|
||||
* @returns
|
||||
*/
|
||||
export const handleMenuJump = (item: MenuListType, jumpToFirst: boolean = false) => {
|
||||
// 处理外部链接
|
||||
const link = item.meta?.link || item.meta?.isLink
|
||||
const isIframe = item.meta?.isIframe
|
||||
if (link && !isIframe) {
|
||||
return openExternalLink(link)
|
||||
}
|
||||
|
||||
// 如果不需要跳转到第一个子菜单,或者没有子菜单,直接跳转当前路径
|
||||
if (!jumpToFirst || !item.children?.length) {
|
||||
return router.push(item.path)
|
||||
}
|
||||
|
||||
// 获取第一个可见的子菜单,如果没有则取第一个子菜单
|
||||
const firstChild = item.children.find((child: MenuListType) => !child.meta?.isHide) || item.children[0]
|
||||
|
||||
// 如果第一个子菜单是外部链接则打开新窗口
|
||||
const childLink = firstChild.meta?.link || firstChild.meta?.isLink
|
||||
if (childLink) {
|
||||
return openExternalLink(childLink)
|
||||
}
|
||||
|
||||
// 跳转到子菜单路径
|
||||
router.push(firstChild.path)
|
||||
}
|
||||
|
||||
// ... existing code ...
|
||||
@@ -0,0 +1,22 @@
|
||||
export const WEB_LINKS = {
|
||||
// Github 主页
|
||||
GITHUB_HOME: 'https://github.com/Daymychen',
|
||||
|
||||
// 项目 Github 主页
|
||||
GITHUB: 'https://github.com/Daymychen/art-design-pro',
|
||||
|
||||
// 个人博客
|
||||
BLOG: 'https://www.lingchen.kim',
|
||||
|
||||
// 项目文档
|
||||
DOCS: 'https://www.lingchen.kim/art-design-pro/docs',
|
||||
|
||||
// 项目社区
|
||||
COMMUNITY: 'https://www.lingchen.kim/art-design-pro/docs/guide/community/communicate.html',
|
||||
|
||||
// 个人 Bilibili 主页
|
||||
BILIBILI: 'https://space.bilibili.com/425500936?spm_id_from=333.1007.0.0',
|
||||
|
||||
// 项目介绍
|
||||
INTRODUCE: 'https://www.lingchen.kim/art-design-pro/docs/guide/introduce.html'
|
||||
}
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
import { $t } from '@/language'
|
||||
import { MenuListType } from '@/types/menu'
|
||||
|
||||
// 创建递归函数处理嵌套路由
|
||||
/**
|
||||
* 处理路由配置,转换为菜单数据结构
|
||||
* @param route 路由配置对象
|
||||
* @param parentPath 父级路径
|
||||
* @returns 处理后的菜单项
|
||||
*/
|
||||
export const processRoute = (route: MenuListType, parentPath = ''): MenuListType => {
|
||||
// 构建完整路径
|
||||
const currentPath = route.path
|
||||
? route.meta?.isIframe
|
||||
? route.path // isIframe 为 true 时直接使用原始路径
|
||||
: parentPath
|
||||
? `${parentPath}/${route.path}`.replace(/\/+/g, '/') // 规范化路径,避免多余的斜杠
|
||||
: route.path
|
||||
: ''
|
||||
|
||||
return {
|
||||
...(route.id && { id: route.id }), // 如果有 id 则包含
|
||||
name: route.name,
|
||||
path: currentPath,
|
||||
component: route.component,
|
||||
meta: route.meta ?? {}, // 使用空值合并运算符
|
||||
children: Array.isArray(route.children)
|
||||
? route.children.map((child: MenuListType) => processRoute(child, currentPath))
|
||||
: []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存 iframe 路由到 sessionStorage 中
|
||||
* @param list iframe 路由列表
|
||||
*/
|
||||
export const saveIframeRoutes = (list: MenuListType[]): void => {
|
||||
if (list.length > 0) {
|
||||
sessionStorage.setItem('iframeRoutes', JSON.stringify(list))
|
||||
}
|
||||
}
|
||||
|
||||
// 获取 iframe 路由
|
||||
export const getIframeRoutes = () => {
|
||||
return JSON.parse(sessionStorage.getItem('iframeRoutes') || '[]')
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化菜单标题
|
||||
* @param title 菜单标题,可以是 i18n 的 key,也可以是字符串,比如:'用户列表'
|
||||
* @returns 格式化后的菜单标题
|
||||
*/
|
||||
export const formatMenuTitle = (title: string) => {
|
||||
return title.startsWith('menus.') ? $t(title) : title
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* 全局事件总线,用于全局事件的发布与订阅
|
||||
* 用法:
|
||||
* mittBus.on('event', callback)
|
||||
* mittBus.emit('event', data)
|
||||
*/
|
||||
import mitt from 'mitt'
|
||||
const mittBus = mitt()
|
||||
export default mittBus
|
||||
@@ -0,0 +1,167 @@
|
||||
import { showToast } from 'vant'
|
||||
import { router } from '@/router'
|
||||
import { useUserStore } from '@/store/modules/user'
|
||||
import { useSettingStore } from '@/store/modules/setting'
|
||||
import { useWorktabStore } from '@/store/modules/worktab'
|
||||
|
||||
// 初始化本地数据
|
||||
export function initState() {
|
||||
if (validateStorageData() || isLocalStorageEmpty()) {
|
||||
const userStore = useUserStore()
|
||||
const worktabStore = useWorktabStore()
|
||||
const settingStore = useSettingStore()
|
||||
|
||||
userStore.initState()
|
||||
worktabStore.initState()
|
||||
settingStore.initState()
|
||||
}
|
||||
}
|
||||
|
||||
// 获取系统存储数据
|
||||
export function getSysStorage() {
|
||||
const version = getSysVersion() || import.meta.env.VITE_VERSION
|
||||
return localStorage.getItem(`sys-v${version}`) as any
|
||||
}
|
||||
|
||||
// 获取系统版本
|
||||
export function getSysVersion() {
|
||||
return localStorage.getItem('version')
|
||||
}
|
||||
|
||||
// 验证本地存储数据的类型
|
||||
function validate(obj: any, schema: any, path: string = ''): boolean {
|
||||
// 如果 obj 不存在或为 null,且不是根对象,则跳过验证(允许可选字段)
|
||||
if (!obj && path !== '') {
|
||||
return true
|
||||
}
|
||||
|
||||
// 如果 obj 不是对象,验证失败
|
||||
if (obj && typeof obj !== 'object') {
|
||||
return false
|
||||
}
|
||||
|
||||
return Object.keys(schema).every((key) => {
|
||||
const fullPath = path ? `${path}.${key}` : key
|
||||
const expectedType = schema[key]
|
||||
const value = obj?.[key]
|
||||
const actualType = typeof value
|
||||
|
||||
// 如果字段不存在或为 undefined,且是嵌套对象,允许跳过(可选字段)
|
||||
if (value === undefined || value === null) {
|
||||
if (typeof expectedType === 'object' && !Array.isArray(expectedType)) {
|
||||
return true // 允许嵌套对象为 undefined
|
||||
}
|
||||
// 对于基本类型,如果值为 undefined,也允许(可选字段)
|
||||
return true
|
||||
}
|
||||
|
||||
if (typeof expectedType === 'object' && !Array.isArray(expectedType)) {
|
||||
return validate(value, expectedType, fullPath)
|
||||
} else if (actualType !== expectedType) {
|
||||
console.error(
|
||||
`检测到本地数据异常 path:[/utils/storage.ts] ${fullPath} 数据类型应为 ${expectedType},实际为 ${actualType}`
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// 显示错误消息并处理登出逻辑
|
||||
function handleError() {
|
||||
showToast({
|
||||
type: 'fail',
|
||||
message: '系统检测到本地数据异常,请重新登录系统恢复使用!',
|
||||
duration: 5000
|
||||
})
|
||||
|
||||
logOut()
|
||||
}
|
||||
|
||||
function logOut() {
|
||||
setTimeout(() => {
|
||||
localStorage.clear()
|
||||
useUserStore().logOut()
|
||||
router.push('/login')
|
||||
initState()
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
// 验证本地存储数据并处理异常
|
||||
export function validateStorageData() {
|
||||
if (location.href.includes('/login')) return true
|
||||
|
||||
const schema = {
|
||||
user: {
|
||||
info: 'object',
|
||||
isLogin: 'boolean',
|
||||
language: 'string',
|
||||
worktab: {
|
||||
// current 是 Partial 类型,所有字段都是可选的
|
||||
current: {},
|
||||
opened: 'object'
|
||||
},
|
||||
setting: {
|
||||
systemThemeType: 'string',
|
||||
systemThemeMode: 'string',
|
||||
menuThemeType: 'string',
|
||||
boxBorderMode: 'boolean',
|
||||
uniqueOpened: 'boolean',
|
||||
systemThemeColor: 'string',
|
||||
showMenuButton: 'boolean',
|
||||
showRefreshButton: 'boolean',
|
||||
showCrumbs: 'boolean',
|
||||
autoClose: 'boolean',
|
||||
showWorkTab: 'boolean',
|
||||
showLanguage: 'boolean',
|
||||
showNprogress: 'boolean',
|
||||
colorWeak: 'boolean',
|
||||
showSettingGuide: 'boolean',
|
||||
refresh: 'boolean'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const data = getLocalStorageData()
|
||||
// 模拟本地数据类型错误
|
||||
// data.user.language = 2024
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
logOut()
|
||||
return false
|
||||
}
|
||||
|
||||
if (!validate(data, schema)) {
|
||||
throw new Error('本地存储数据结构异常')
|
||||
}
|
||||
|
||||
return true
|
||||
} catch {
|
||||
handleError()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 获取本地存储数据
|
||||
function getLocalStorageData() {
|
||||
return JSON.parse(getSysStorage() || '{}')
|
||||
}
|
||||
|
||||
// 本地存储是否为空
|
||||
function isLocalStorageEmpty() {
|
||||
return Object.keys(getLocalStorageData()).length === 0
|
||||
}
|
||||
|
||||
// 将 vuex 中的数据保存到 localStorage 中(在即将离开页面(刷新或关闭)时执行)
|
||||
export function saveUserData() {
|
||||
const isiOS = /iPhone|iPad|iPod/i.test(navigator.userAgent)
|
||||
const eventType = isiOS ? 'pagehide' : 'beforeunload'
|
||||
|
||||
window.addEventListener(eventType, () => {
|
||||
if (getSysVersion()) {
|
||||
useUserStore().saveUserData()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 标签页容器高度以及顶部距离配置
|
||||
* @param {Object} tab-default - 默认标签页样式配置
|
||||
* @param {number} openTop - 标签页打开时的顶部填充高度
|
||||
* @param {number} closeTop - 标签页关闭时的顶部填充高度
|
||||
* @param {number} openHeight - 标签页打开时的总高度
|
||||
* @param {number} closeHeight - 标签页关闭时的总高度
|
||||
*/
|
||||
export const TAB_CONFIG = {
|
||||
'tab-default': {
|
||||
openTop: 70,
|
||||
closeTop: 60,
|
||||
openHeight: 85,
|
||||
closeHeight: 75
|
||||
},
|
||||
'tab-card': {
|
||||
openTop: 122,
|
||||
closeTop: 78,
|
||||
openHeight: 139,
|
||||
closeHeight: 95
|
||||
},
|
||||
'tab-google': {
|
||||
openTop: 122,
|
||||
closeTop: 78,
|
||||
openHeight: 139,
|
||||
closeHeight: 95
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前 tab 样式配置,设置默认值
|
||||
export const getTabConfig = (style: string) => {
|
||||
return TAB_CONFIG[style as keyof typeof TAB_CONFIG] || TAB_CONFIG['tab-card'] // 默认使用 tab-card 配置
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useCommon } from '@/composables/useCommon'
|
||||
import { useTheme } from '@/composables/useTheme'
|
||||
import { SystemThemeEnum } from '@/enums/appEnum'
|
||||
import { useSettingStore } from '@/store/modules/setting'
|
||||
const { LIGHT, DARK } = SystemThemeEnum
|
||||
|
||||
/**
|
||||
* 主题切换动画
|
||||
* @param e 鼠标点击事件
|
||||
*/
|
||||
export const themeAnimation = (e: any) => {
|
||||
const x = e.clientX
|
||||
const y = e.clientY
|
||||
// 计算鼠标点击位置距离视窗的最大圆半径
|
||||
const endRadius = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y))
|
||||
|
||||
// 设置CSS变量
|
||||
document.documentElement.style.setProperty('--x', x + 'px')
|
||||
document.documentElement.style.setProperty('--y', y + 'px')
|
||||
document.documentElement.style.setProperty('--r', endRadius + 'px')
|
||||
|
||||
if (document.startViewTransition) {
|
||||
document.startViewTransition(() => toggleTheme())
|
||||
} else {
|
||||
toggleTheme()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换主题
|
||||
*/
|
||||
const toggleTheme = () => {
|
||||
useTheme().switchThemeStyles(useSettingStore().systemThemeType === LIGHT ? DARK : LIGHT)
|
||||
useCommon().refresh()
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { upgradeLogList } from '@/mock/upgradeLog'
|
||||
import { showNotify } from 'vant'
|
||||
import { useUserStore } from '@/store/modules/user'
|
||||
|
||||
// 系统升级
|
||||
export function systemUpgrade() {
|
||||
const version = import.meta.env.VITE_VERSION
|
||||
// 跳过版本为1.0.0的提示
|
||||
if (version === '1.0.0') return
|
||||
|
||||
setTimeout(() => {
|
||||
const { title: content, requireReLogin } = upgradeLogList.value[0]
|
||||
// 系统升级公告
|
||||
const message = [
|
||||
`<p style="color: var(--art-gray-text-800) !important; padding-bottom: 5px;">`,
|
||||
`系统已升级到 ${version} 版本,此次更新带来了以下改进:`,
|
||||
`</p>`,
|
||||
content,
|
||||
requireReLogin
|
||||
? `<p style="color: var(--main-color); padding-top: 5px;">升级完成,请重新登录后继续使用。</p>`
|
||||
: ''
|
||||
].join('')
|
||||
|
||||
const oldSysKey = Object.keys(localStorage).find(
|
||||
(key) => key.startsWith('sys-v') && key !== `sys-v${version}`
|
||||
)
|
||||
|
||||
if (oldSysKey) {
|
||||
showNotify({
|
||||
type: 'success',
|
||||
message: message,
|
||||
duration: 0
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
// 更新版本号
|
||||
localStorage.setItem('version', version)
|
||||
// 删除旧版本号
|
||||
localStorage.removeItem(oldSysKey)
|
||||
// 需要重新登录
|
||||
if (requireReLogin) {
|
||||
useUserStore().logOut()
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
Executable
+293
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
* 常用 JavaScript 函数片段
|
||||
* author chen tao
|
||||
* date 2020-10-6
|
||||
*/
|
||||
|
||||
/* 数组相关函数 */
|
||||
|
||||
// 数组去重
|
||||
export function noRepeat<T>(arr: T[]): T[] {
|
||||
return [...new Set(arr)]
|
||||
}
|
||||
|
||||
// 查找数组最大值
|
||||
export function arrayMax(arr: number[]): number {
|
||||
if (!arr.length) throw new Error('Array is empty')
|
||||
return Math.max(...arr)
|
||||
}
|
||||
|
||||
// 查找数组最小值
|
||||
export function arrayMin(arr: number[]): number {
|
||||
if (!arr.length) throw new Error('Array is empty')
|
||||
return Math.min(...arr)
|
||||
}
|
||||
|
||||
// 数组分割
|
||||
export function chunk<T>(arr: T[], size: number = 1): T[][] {
|
||||
if (size <= 0) return [arr.slice()]
|
||||
return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
|
||||
arr.slice(i * size, i * size + size)
|
||||
)
|
||||
}
|
||||
|
||||
// 检查元素出现次数
|
||||
export function countOccurrences<T>(arr: T[], value: T): number {
|
||||
return arr.reduce((count, current) => (current === value ? count + 1 : count), 0)
|
||||
}
|
||||
|
||||
// 扁平化数组
|
||||
export function flatten<T>(arr: any[], depth: number = Infinity): T[] {
|
||||
return arr.flat(depth)
|
||||
}
|
||||
|
||||
// 返回两个数组的差集
|
||||
export function difference<T>(arrA: T[], arrB: T[]): T[] {
|
||||
const setB = new Set(arrB)
|
||||
return arrA.filter((item) => !setB.has(item))
|
||||
}
|
||||
|
||||
// 返回两个数组的交集
|
||||
export function intersection<T>(arr1: T[], arr2: T[]): T[] {
|
||||
const set2 = new Set(arr2)
|
||||
return arr1.filter((item) => set2.has(item))
|
||||
}
|
||||
|
||||
// 从右删除 n 个元素
|
||||
export function dropRight<T>(arr: T[], n: number = 0): T[] {
|
||||
return arr.slice(0, Math.max(0, arr.length - n))
|
||||
}
|
||||
|
||||
// 返回间隔 nth 的元素
|
||||
export function everyNth<T>(arr: T[], nth: number): T[] {
|
||||
if (nth <= 0) return []
|
||||
return arr.filter((_, i) => i % nth === nth - 1)
|
||||
}
|
||||
|
||||
// 返回第 n 个元素
|
||||
export function nthElement<T>(arr: T[], n: number = 0): T | undefined {
|
||||
const index = n >= 0 ? n : arr.length + n
|
||||
return arr[index]
|
||||
}
|
||||
|
||||
// 数组乱序
|
||||
export function shuffle<T>(arr: T[]): T[] {
|
||||
const array = [...arr] // 创建新数组避免修改原数组
|
||||
for (let i = array.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1))
|
||||
;[array[i], array[j]] = [array[j], array[i]]
|
||||
}
|
||||
return array
|
||||
}
|
||||
|
||||
/* 浏览器对象 BOM */
|
||||
|
||||
// 当前网页地址
|
||||
export function currentURL(): string {
|
||||
return window.location.href
|
||||
}
|
||||
|
||||
// 获取滚动条位置
|
||||
export function getScrollPosition(el: HTMLElement | Window = window): { x: number; y: number } {
|
||||
return el === window
|
||||
? {
|
||||
x: window.scrollX || document.documentElement.scrollLeft,
|
||||
y: window.scrollY || document.documentElement.scrollTop
|
||||
}
|
||||
: {
|
||||
x: (el as HTMLElement).scrollLeft,
|
||||
y: (el as HTMLElement).scrollTop
|
||||
}
|
||||
}
|
||||
|
||||
// 获取 URL 参数
|
||||
export function getURLParameters(url: string): Record<string, string> {
|
||||
return Object.fromEntries(new URLSearchParams(url.split('?')[1]).entries())
|
||||
}
|
||||
|
||||
// 兼容非 HTTPS 等环境:使用 execCommand 复制
|
||||
function fallbackCopy(str: string): boolean {
|
||||
try {
|
||||
const textarea = document.createElement('textarea')
|
||||
textarea.value = str
|
||||
textarea.style.position = 'fixed'
|
||||
textarea.style.left = '-9999px'
|
||||
textarea.setAttribute('readonly', '')
|
||||
document.body.appendChild(textarea)
|
||||
textarea.select()
|
||||
const ok = document.execCommand('copy')
|
||||
document.body.removeChild(textarea)
|
||||
return ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 复制文本(同步,优先 clipboard API,不可用时回退 execCommand)
|
||||
export function copy(str: string): boolean {
|
||||
try {
|
||||
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
||||
navigator.clipboard.writeText(str)
|
||||
return true
|
||||
}
|
||||
return fallbackCopy(str)
|
||||
} catch (err) {
|
||||
console.error('Copy failed:', err)
|
||||
return fallbackCopy(str)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步复制到剪贴板,生产环境安全:优先 clipboard API,不可用时回退 execCommand。
|
||||
*/
|
||||
export async function copyToClipboard(str: string): Promise<boolean> {
|
||||
try {
|
||||
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
||||
await navigator.clipboard.writeText(str)
|
||||
return true
|
||||
}
|
||||
return fallbackCopy(str)
|
||||
} catch {
|
||||
return fallbackCopy(str)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从图片 URL 拉取图片并复制到剪贴板(需支持 ClipboardItem,通常为 HTTPS 环境)。
|
||||
*/
|
||||
export async function copyImageFromUrl(imageUrl: string): Promise<boolean> {
|
||||
try {
|
||||
if (!navigator.clipboard || typeof navigator.clipboard.write !== 'function') return false
|
||||
const res = await fetch(imageUrl, { mode: 'cors' })
|
||||
if (!res.ok) return false
|
||||
const blob = await res.blob()
|
||||
const type = blob.type || 'image/png'
|
||||
await navigator.clipboard.write([new ClipboardItem({ [type]: blob })])
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Blob 图片写入剪贴板(用于 html2canvas 等生成的图片)。
|
||||
*/
|
||||
export async function copyImageBlobToClipboard(blob: Blob): Promise<boolean> {
|
||||
try {
|
||||
if (!navigator.clipboard || typeof navigator.clipboard.write !== 'function') return false
|
||||
const type = blob.type || 'image/png'
|
||||
await navigator.clipboard.write([new ClipboardItem({ [type]: blob })])
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 检测设备类型
|
||||
export function detectDeviceType(): 'Mobile' | 'Desktop' {
|
||||
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
|
||||
? 'Mobile'
|
||||
: 'Desktop'
|
||||
}
|
||||
|
||||
/* Cookie 操作 */
|
||||
|
||||
// 设置 Cookie
|
||||
export function setCookie(key: string, value: string, expireDays: number): void {
|
||||
const date = new Date()
|
||||
date.setDate(date.getDate() + expireDays)
|
||||
document.cookie = `${key}=${encodeURIComponent(value)}${
|
||||
expireDays ? `;expires=${date.toUTCString()}` : ''
|
||||
}`
|
||||
}
|
||||
|
||||
// 删除 Cookie
|
||||
export function delCookie(name: string): void {
|
||||
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT`
|
||||
}
|
||||
|
||||
// 获取 Cookie
|
||||
export function getCookie(name: string): string | null {
|
||||
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`))
|
||||
return match ? decodeURIComponent(match[1]) : null
|
||||
}
|
||||
|
||||
/* 日期相关 */
|
||||
|
||||
// 时间戳转时间
|
||||
export function timestampToTime(timestamp: number = Date.now(), isMs: boolean = true): string {
|
||||
const date = new Date(isMs ? timestamp : timestamp * 1000)
|
||||
return date.toISOString().replace('T', ' ').slice(0, 19)
|
||||
}
|
||||
|
||||
/* DOM 操作 */
|
||||
|
||||
let scrollTop = 0
|
||||
|
||||
export function preventScroll(): void {
|
||||
scrollTop = window.scrollY
|
||||
Object.assign(document.body.style, {
|
||||
position: 'fixed',
|
||||
width: '100%',
|
||||
top: `-${scrollTop}px`,
|
||||
overflowY: 'hidden'
|
||||
})
|
||||
}
|
||||
|
||||
export function recoverScroll(): void {
|
||||
Object.assign(document.body.style, {
|
||||
position: '',
|
||||
width: '',
|
||||
top: '',
|
||||
overflowY: ''
|
||||
})
|
||||
window.scrollTo(0, scrollTop)
|
||||
}
|
||||
|
||||
// 判断是否到达页面底部
|
||||
export function bottomVisible(): boolean {
|
||||
return window.innerHeight + window.scrollY >= document.documentElement.scrollHeight
|
||||
}
|
||||
|
||||
// 判断元素是否在可视区域
|
||||
export function elementIsVisibleInViewport(
|
||||
el: HTMLElement,
|
||||
partiallyVisible: boolean = false
|
||||
): boolean {
|
||||
const { top, left, bottom, right } = el.getBoundingClientRect()
|
||||
const { innerHeight, innerWidth } = window
|
||||
|
||||
return partiallyVisible
|
||||
? top + el.offsetHeight > 0 &&
|
||||
top < innerHeight &&
|
||||
left + el.offsetWidth > 0 &&
|
||||
left < innerWidth
|
||||
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth
|
||||
}
|
||||
|
||||
// 获取元素样式
|
||||
export function getStyle(el: HTMLElement, ruleName: string): string {
|
||||
return window.getComputedStyle(el)[ruleName as any]
|
||||
}
|
||||
|
||||
/* 数字操作 */
|
||||
|
||||
export function commafy(num: number): string {
|
||||
return num.toLocaleString('en-US')
|
||||
}
|
||||
|
||||
export function randomNum(min: number, max?: number): number {
|
||||
if (max === undefined) return Math.floor(Math.random() * min)
|
||||
return Math.floor(Math.random() * (max - min + 1)) + min
|
||||
}
|
||||
|
||||
/* 字符串操作 */
|
||||
|
||||
export function removeHtmlTags(str: string = ''): string {
|
||||
return str.replace(/<[^>]*>/g, '')
|
||||
}
|
||||
|
||||
// 判断是不是iframe
|
||||
export function isIframe(url: string) {
|
||||
return url.includes('/outside/iframe')
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useWorktabStore } from '@/store/modules/worktab'
|
||||
import { RouteLocationNormalized } from 'vue-router'
|
||||
import { getIframeRoutes } from './menu'
|
||||
import { isIframe } from './utils'
|
||||
import { useSettingStore } from '@/store/modules/setting'
|
||||
import { HOME_PAGE } from '@/router'
|
||||
|
||||
/**
|
||||
* 根据当前路由信息设置工作标签页(worktab)
|
||||
* @param to 当前路由对象
|
||||
*/
|
||||
export const setWorktab = (to: RouteLocationNormalized): void => {
|
||||
const worktabStore = useWorktabStore()
|
||||
const { meta, path, name, params, query } = to
|
||||
if (!meta.isHideTab) {
|
||||
// 如果是 iframe 页面,则特殊处理工作标签页
|
||||
if (isIframe(path)) {
|
||||
const iframeRoute = getIframeRoutes().find((route: any) => route.path === to.path)
|
||||
|
||||
if (iframeRoute?.meta) {
|
||||
worktabStore.openTab({
|
||||
title: iframeRoute.meta.title,
|
||||
path,
|
||||
name: name as string,
|
||||
keepAlive: meta.keepAlive as boolean,
|
||||
params,
|
||||
query
|
||||
})
|
||||
}
|
||||
} else if (useSettingStore().showWorkTab || path === HOME_PAGE) {
|
||||
worktabStore.openTab({
|
||||
title: meta.title as string,
|
||||
path,
|
||||
name: name as string,
|
||||
keepAlive: meta.keepAlive as boolean,
|
||||
params,
|
||||
query
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user