功能:更新消息中心和 YumiNail 模块
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
export const ACCOUNT_REGEX = /^[A-Za-z0-9]+$/
|
||||
const ACCOUNT_SANITIZE_REGEX = /[^A-Za-z0-9]/g
|
||||
|
||||
export const ACCOUNT_RULE_MESSAGE = '账号只能包含字母和数字'
|
||||
|
||||
export const sanitizeAccountInput = (value: string) => (value || '').replace(ACCOUNT_SANITIZE_REGEX, '')
|
||||
@@ -0,0 +1,51 @@
|
||||
import { ElLoading, type LoadingInstance } from 'element-plus'
|
||||
|
||||
export interface GlobalLoadingOptions {
|
||||
text?: string
|
||||
lock?: boolean
|
||||
}
|
||||
|
||||
let activeLoadingCount = 0
|
||||
let loadingInstance: LoadingInstance | null = null
|
||||
|
||||
const openGlobalLoading = (options?: GlobalLoadingOptions) => {
|
||||
activeLoadingCount += 1
|
||||
|
||||
if (typeof window === 'undefined' || loadingInstance) {
|
||||
return
|
||||
}
|
||||
|
||||
loadingInstance = ElLoading.service({
|
||||
lock: options?.lock ?? true,
|
||||
text: options?.text ?? '\u52a0\u8f7d\u4e2d',
|
||||
background: 'rgba(255, 255, 255, 0.72)'
|
||||
})
|
||||
}
|
||||
|
||||
const closeGlobalLoading = () => {
|
||||
activeLoadingCount = Math.max(0, activeLoadingCount - 1)
|
||||
|
||||
if (activeLoadingCount > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
loadingInstance?.close()
|
||||
loadingInstance = null
|
||||
}
|
||||
|
||||
export const runWithGlobalLoading = async <T>(
|
||||
task: (() => Promise<T>) | Promise<T>,
|
||||
options?: GlobalLoadingOptions
|
||||
) => {
|
||||
openGlobalLoading(options)
|
||||
|
||||
try {
|
||||
if (typeof task === 'function') {
|
||||
return await task()
|
||||
}
|
||||
|
||||
return await task
|
||||
} finally {
|
||||
closeGlobalLoading()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import {
|
||||
clearAdminSessionStorage,
|
||||
getAdminAccessToken,
|
||||
isBootstrapAdminUser,
|
||||
loadCachedAdminUserInfo,
|
||||
} from '@/utils/admin-session'
|
||||
import {
|
||||
clearStoredPermissions,
|
||||
fetchUserPermissionsStrict,
|
||||
getStoredUserPermissions,
|
||||
} from '@/utils/permission'
|
||||
|
||||
export type AuthBootstrapState = 'pending' | 'ready' | 'invalid'
|
||||
|
||||
const adminBootstrapState = ref<AuthBootstrapState>('pending')
|
||||
let bootstrapPromise: Promise<AuthBootstrapState> | null = null
|
||||
|
||||
const ADMIN_PERMISSION_ROUTE_MAP: Array<{ code: string; path: string }> = [
|
||||
{ code: 'dashboard:view', path: '/admin/dashboard' },
|
||||
{ code: 'shop:view', path: '/admin/shops' },
|
||||
{ code: 'product:view', path: '/admin/products' },
|
||||
{ code: 'coupon:view', path: '/admin/coupons' },
|
||||
{ code: 'order:view', path: '/admin/orders' },
|
||||
{ code: 'user:view', path: '/admin/users' },
|
||||
{ code: 'tag:view', path: '/admin/tags' },
|
||||
{ code: 'permission:view', path: '/admin/permissions' },
|
||||
{ code: 'nail_artist:view', path: '/admin/nail-artists' },
|
||||
]
|
||||
|
||||
export const useAdminBootstrapState = () => computed(() => adminBootstrapState.value)
|
||||
|
||||
export const invalidateAdminBootstrap = () => {
|
||||
adminBootstrapState.value = 'pending'
|
||||
bootstrapPromise = null
|
||||
}
|
||||
|
||||
export const clearAdminBootstrapSession = () => {
|
||||
clearAdminSessionStorage()
|
||||
clearStoredPermissions()
|
||||
adminBootstrapState.value = 'invalid'
|
||||
bootstrapPromise = null
|
||||
}
|
||||
|
||||
export const getAdminBootstrapSnapshot = () => {
|
||||
const userInfo = loadCachedAdminUserInfo()
|
||||
return {
|
||||
token: getAdminAccessToken(),
|
||||
userInfo,
|
||||
isBootstrapAdmin: isBootstrapAdminUser(userInfo),
|
||||
permissions: getStoredUserPermissions() || [],
|
||||
}
|
||||
}
|
||||
|
||||
export const hasAdminPermission = (permissionCode?: string) => {
|
||||
if (!permissionCode) {
|
||||
return true
|
||||
}
|
||||
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
if (snapshot.isBootstrapAdmin) {
|
||||
return false
|
||||
}
|
||||
|
||||
return snapshot.permissions.includes(permissionCode)
|
||||
}
|
||||
|
||||
export const resolveAdminLandingPath = () => {
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
if (snapshot.isBootstrapAdmin) {
|
||||
return '/admin/shops'
|
||||
}
|
||||
|
||||
const matchedRoute = ADMIN_PERMISSION_ROUTE_MAP.find(item => snapshot.permissions.includes(item.code))
|
||||
return matchedRoute?.path || '/admin'
|
||||
}
|
||||
|
||||
export const canAccessAdminRoute = (path: string, permissionCode?: string) => {
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
if (snapshot.isBootstrapAdmin) {
|
||||
return path === '/admin' || path === '/admin/shops'
|
||||
}
|
||||
|
||||
return hasAdminPermission(permissionCode)
|
||||
}
|
||||
|
||||
export const ensureAdminAuthBootstrap = async (force = false): Promise<AuthBootstrapState> => {
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
if (!snapshot.token || !snapshot.userInfo) {
|
||||
clearAdminBootstrapSession()
|
||||
return 'invalid'
|
||||
}
|
||||
|
||||
if (snapshot.isBootstrapAdmin) {
|
||||
clearStoredPermissions()
|
||||
adminBootstrapState.value = 'ready'
|
||||
bootstrapPromise = null
|
||||
return 'ready'
|
||||
}
|
||||
|
||||
const cachedPermissions = getStoredUserPermissions()
|
||||
if (!force && cachedPermissions) {
|
||||
adminBootstrapState.value = 'ready'
|
||||
return 'ready'
|
||||
}
|
||||
|
||||
if (!force && bootstrapPromise) {
|
||||
return bootstrapPromise
|
||||
}
|
||||
|
||||
adminBootstrapState.value = 'pending'
|
||||
bootstrapPromise = (async () => {
|
||||
try {
|
||||
await fetchUserPermissionsStrict()
|
||||
adminBootstrapState.value = 'ready'
|
||||
return 'ready' as AuthBootstrapState
|
||||
} catch (error) {
|
||||
console.error('Failed to bootstrap admin permissions:', error)
|
||||
clearAdminBootstrapSession()
|
||||
return 'invalid' as AuthBootstrapState
|
||||
} finally {
|
||||
bootstrapPromise = null
|
||||
}
|
||||
})()
|
||||
|
||||
return bootstrapPromise
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { IdType } from '@/utils/id'
|
||||
|
||||
export interface AdminCachedUserInfo {
|
||||
id?: IdType
|
||||
type?: number
|
||||
account?: string
|
||||
nickname?: string
|
||||
avatar?: string
|
||||
shopId?: IdType
|
||||
shopName?: string
|
||||
shopIds?: IdType[]
|
||||
shopNames?: string[]
|
||||
}
|
||||
|
||||
export const getAdminAccessToken = () =>
|
||||
localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')
|
||||
|
||||
export const getAdminRefreshToken = () =>
|
||||
localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken')
|
||||
|
||||
export const loadCachedAdminUserInfo = (): AdminCachedUserInfo | null => {
|
||||
const raw = localStorage.getItem('adminUserInfo')
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw) as AdminCachedUserInfo
|
||||
} catch (error) {
|
||||
console.error('Failed to parse cached admin user info:', error)
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const isBootstrapAdminUser = (userInfo?: AdminCachedUserInfo | null) =>
|
||||
userInfo?.type === 4 && !userInfo?.shopId
|
||||
|
||||
export const clearAdminSessionStorage = () => {
|
||||
localStorage.removeItem('adminAccessToken')
|
||||
localStorage.removeItem('adminRefreshToken')
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
localStorage.removeItem('userPermissions')
|
||||
sessionStorage.removeItem('adminAccessToken')
|
||||
sessionStorage.removeItem('adminRefreshToken')
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { cartApi } from '@/api/cart'
|
||||
import { toOptionalIdString } from '@/utils/id'
|
||||
|
||||
export const fetchCartProductIdSet = async () => {
|
||||
try {
|
||||
const response = await cartApi.getCartList() as unknown as Array<{ productId?: string | number }>
|
||||
return new Set(
|
||||
(Array.isArray(response) ? response : [])
|
||||
.map(item => toOptionalIdString(item && item.productId))
|
||||
.filter((id): id is string => Boolean(id))
|
||||
)
|
||||
} catch (error) {
|
||||
return new Set<string>()
|
||||
}
|
||||
}
|
||||
|
||||
export const hasCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
|
||||
const normalizedId = toOptionalIdString(productId)
|
||||
return Boolean(normalizedId && cartProductIdSet.has(normalizedId))
|
||||
}
|
||||
|
||||
export const withAddedCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
|
||||
const next = new Set(cartProductIdSet || [])
|
||||
const normalizedId = toOptionalIdString(productId)
|
||||
if (normalizedId) {
|
||||
next.add(normalizedId)
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import type { AxiosProgressEvent } from 'axios'
|
||||
|
||||
export interface ChunkUploadSession {
|
||||
uploadId: string
|
||||
chunkSize: number
|
||||
totalChunks: number
|
||||
uploadedChunks: number[]
|
||||
}
|
||||
|
||||
export interface ChunkUploadInitRequest {
|
||||
fileName: string
|
||||
fileSize: number
|
||||
contentType: string
|
||||
fileFingerprint: string
|
||||
scene: string
|
||||
}
|
||||
|
||||
export interface ChunkUploadApi<TResponse> {
|
||||
initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession>
|
||||
uploadChunk: (
|
||||
payload: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
|
||||
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
|
||||
) => Promise<unknown>
|
||||
completeUpload: (uploadId: string) => Promise<TResponse>
|
||||
cancelUpload?: (uploadId: string) => Promise<unknown>
|
||||
}
|
||||
|
||||
export interface ChunkUploadOptions<TResponse> {
|
||||
file: File
|
||||
scene: string
|
||||
api: ChunkUploadApi<TResponse>
|
||||
preprocessFile?: (file: File) => Promise<File>
|
||||
onProgress?: (percent: number) => void
|
||||
}
|
||||
|
||||
export interface ChunkUploadResult<TResponse> {
|
||||
response: TResponse
|
||||
uploadId: string
|
||||
processedFile: File
|
||||
}
|
||||
|
||||
export interface ChunkUploadTask<TResponse> {
|
||||
promise: Promise<ChunkUploadResult<TResponse>>
|
||||
cancel: () => void
|
||||
getUploadId: () => string
|
||||
}
|
||||
|
||||
const computeFileFingerprint = async (file: File) => {
|
||||
const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}`
|
||||
if (!window.crypto?.subtle) {
|
||||
return btoa(unescape(encodeURIComponent(fingerprintSeed)))
|
||||
}
|
||||
const buffer = new TextEncoder().encode(fingerprintSeed)
|
||||
const hashBuffer = await window.crypto.subtle.digest('SHA-256', buffer)
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer))
|
||||
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
const getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => {
|
||||
const start = chunkIndex * chunkSize
|
||||
const end = Math.min(start + chunkSize, fileSize)
|
||||
return Math.max(end - start, 0)
|
||||
}
|
||||
|
||||
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => {
|
||||
return uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
|
||||
}
|
||||
|
||||
export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => {
|
||||
const abortController = new AbortController()
|
||||
let uploadId = ''
|
||||
let cancelled = false
|
||||
const cleanupCancelledSession = async () => {
|
||||
if (uploadId && options.api.cancelUpload) {
|
||||
await options.api.cancelUpload(uploadId).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const promise = (async () => {
|
||||
const processedFile = options.preprocessFile ? await options.preprocessFile(options.file) : options.file
|
||||
const fileFingerprint = await computeFileFingerprint(processedFile)
|
||||
const session = await options.api.initUpload({
|
||||
fileName: processedFile.name,
|
||||
fileSize: processedFile.size,
|
||||
contentType: processedFile.type || 'application/octet-stream',
|
||||
fileFingerprint,
|
||||
scene: options.scene
|
||||
})
|
||||
|
||||
uploadId = session.uploadId
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
const uploadedChunkSet = new Set(session.uploadedChunks || [])
|
||||
let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet))
|
||||
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100))
|
||||
|
||||
for (let chunkIndex = 0; chunkIndex < session.totalChunks; chunkIndex++) {
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
if (uploadedChunkSet.has(chunkIndex)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const start = chunkIndex * session.chunkSize
|
||||
const end = Math.min(start + session.chunkSize, processedFile.size)
|
||||
const chunk = processedFile.slice(start, end)
|
||||
const chunkBytes = end - start
|
||||
|
||||
await options.api.uploadChunk(
|
||||
{
|
||||
uploadId: session.uploadId,
|
||||
chunkIndex,
|
||||
totalChunks: session.totalChunks,
|
||||
chunk
|
||||
},
|
||||
{
|
||||
signal: abortController.signal,
|
||||
onUploadProgress: (event) => {
|
||||
const loaded = Math.min(event.loaded || 0, chunkBytes)
|
||||
const percent = ((uploadedBytes + loaded) / Math.max(processedFile.size, 1)) * 100
|
||||
options.onProgress?.(Math.min(percent, 99.9))
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
uploadedChunkSet.add(chunkIndex)
|
||||
uploadedBytes += chunkBytes
|
||||
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9))
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
const response = await options.api.completeUpload(session.uploadId)
|
||||
options.onProgress?.(100)
|
||||
return {
|
||||
response,
|
||||
uploadId: session.uploadId,
|
||||
processedFile
|
||||
}
|
||||
})()
|
||||
|
||||
return {
|
||||
promise,
|
||||
cancel: () => {
|
||||
cancelled = true
|
||||
abortController.abort()
|
||||
if (uploadId && options.api.cancelUpload) {
|
||||
void options.api.cancelUpload(uploadId).catch(() => undefined)
|
||||
}
|
||||
},
|
||||
getUploadId: () => uploadId
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
export type DraftStorageMode = 'local' | 'session'
|
||||
|
||||
export interface DraftRecord<T> {
|
||||
savedAt: number
|
||||
payload: T
|
||||
}
|
||||
|
||||
const getStorage = (mode: DraftStorageMode) => (mode === 'session' ? window.sessionStorage : window.localStorage)
|
||||
|
||||
export const buildDraftStorageKey = (...parts: Array<string | number | undefined | null>) => {
|
||||
const normalizedParts = parts
|
||||
.filter((part): part is string | number => part !== undefined && part !== null && String(part).trim().length > 0)
|
||||
.map(part => String(part).trim())
|
||||
return `yuminail:draft:${normalizedParts.join(':')}`
|
||||
}
|
||||
|
||||
export const saveDraftRecord = <T>(key: string, payload: T, mode: DraftStorageMode = 'local') => {
|
||||
const record: DraftRecord<T> = {
|
||||
savedAt: Date.now(),
|
||||
payload
|
||||
}
|
||||
getStorage(mode).setItem(key, JSON.stringify(record))
|
||||
return record
|
||||
}
|
||||
|
||||
export const loadDraftRecord = <T>(key: string, mode: DraftStorageMode = 'local') => {
|
||||
const rawValue = getStorage(mode).getItem(key)
|
||||
if (!rawValue) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(rawValue) as DraftRecord<T>
|
||||
} catch {
|
||||
getStorage(mode).removeItem(key)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const clearDraftRecord = (key: string, mode: DraftStorageMode = 'local') => {
|
||||
getStorage(mode).removeItem(key)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export type IdType = string | number
|
||||
|
||||
export const isEmptyId = (value: unknown): value is undefined | null | '' => {
|
||||
return value === undefined || value === null || `${value}`.trim() === ''
|
||||
}
|
||||
|
||||
export const toIdString = (value: IdType) => String(value)
|
||||
|
||||
// 前端统一把雪花 ID 视为字符串语义处理,避免任何 Number 转换带来的精度污染。
|
||||
export const toOptionalIdString = (value: unknown) => {
|
||||
if (isEmptyId(value)) {
|
||||
return undefined
|
||||
}
|
||||
return String(value).trim()
|
||||
}
|
||||
|
||||
// 比较 ID 时统一做字符串归一化,兼容接口返回 string / number 两种情况。
|
||||
export const sameId = (left: unknown, right: unknown) => {
|
||||
const leftId = toOptionalIdString(left)
|
||||
const rightId = toOptionalIdString(right)
|
||||
return leftId !== undefined && leftId === rightId
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
const DEFAULT_MAX_IMAGE_SIZE = 5 * 1024 * 1024
|
||||
const AUTO_COMPRESS_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])
|
||||
|
||||
export interface ImageCompressionResult {
|
||||
file: File
|
||||
originalSize: number
|
||||
finalSize: number
|
||||
compressed: boolean
|
||||
converted: boolean
|
||||
skippedReason?: string
|
||||
}
|
||||
|
||||
const QUALITY_STEPS = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52]
|
||||
const SCALE_STEPS = [1, 0.9, 0.8, 0.7, 0.6, 0.5]
|
||||
|
||||
const loadImageElement = (file: File) => {
|
||||
return new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const image = new Image()
|
||||
const objectUrl = URL.createObjectURL(file)
|
||||
|
||||
image.onload = () => {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
resolve(image)
|
||||
}
|
||||
|
||||
image.onerror = () => {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
reject(new Error('图片读取失败'))
|
||||
}
|
||||
|
||||
image.src = objectUrl
|
||||
})
|
||||
}
|
||||
|
||||
const canvasToBlob = (canvas: HTMLCanvasElement, type: string, quality?: number) => {
|
||||
return new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (!blob) {
|
||||
reject(new Error('图片压缩失败'))
|
||||
return
|
||||
}
|
||||
resolve(blob)
|
||||
},
|
||||
type,
|
||||
quality
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const getOutputExtension = (type: string) => {
|
||||
if (type === 'image/png') {
|
||||
return '.png'
|
||||
}
|
||||
if (type === 'image/webp') {
|
||||
return '.webp'
|
||||
}
|
||||
return '.jpg'
|
||||
}
|
||||
|
||||
const buildOutputName = (fileName: string, type: string) => {
|
||||
const extension = getOutputExtension(type)
|
||||
const dotIndex = fileName.lastIndexOf('.')
|
||||
const baseName = dotIndex > -1 ? fileName.slice(0, dotIndex) : fileName
|
||||
return `${baseName}${extension}`
|
||||
}
|
||||
|
||||
const drawImageToCanvas = (image: HTMLImageElement, width: number, height: number, mimeType: string) => {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) {
|
||||
throw new Error('无法初始化图片压缩画布')
|
||||
}
|
||||
|
||||
if (mimeType !== 'image/png') {
|
||||
context.fillStyle = '#ffffff'
|
||||
context.fillRect(0, 0, width, height)
|
||||
}
|
||||
|
||||
context.drawImage(image, 0, 0, width, height)
|
||||
return canvas
|
||||
}
|
||||
|
||||
const toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => {
|
||||
return new File([blob], buildOutputName(sourceFile.name, mimeType), {
|
||||
type: mimeType,
|
||||
lastModified: sourceFile.lastModified
|
||||
})
|
||||
}
|
||||
|
||||
const getPreferredMimeTypes = (file: File) => {
|
||||
if (file.type === 'image/png') {
|
||||
return ['image/png', 'image/jpeg']
|
||||
}
|
||||
if (file.type === 'image/webp') {
|
||||
return ['image/webp', 'image/jpeg']
|
||||
}
|
||||
return ['image/jpeg']
|
||||
}
|
||||
|
||||
export const formatFileSize = (bytes: number) => {
|
||||
if (bytes >= 1024 * 1024) {
|
||||
return `${(bytes / 1024 / 1024).toFixed(2)}MB`
|
||||
}
|
||||
return `${(bytes / 1024).toFixed(0)}KB`
|
||||
}
|
||||
|
||||
export const compressImageIfNeeded = async (
|
||||
file: File,
|
||||
maxSize = DEFAULT_MAX_IMAGE_SIZE
|
||||
): Promise<ImageCompressionResult> => {
|
||||
if (!file.type.startsWith('image/')) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false,
|
||||
skippedReason: '仅支持图片文件上传'
|
||||
}
|
||||
}
|
||||
|
||||
if (file.size <= maxSize) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false
|
||||
}
|
||||
}
|
||||
|
||||
if (!AUTO_COMPRESS_TYPES.has(file.type)) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false,
|
||||
skippedReason: '当前图片格式暂不支持自动压缩,请手动处理后重试'
|
||||
}
|
||||
}
|
||||
|
||||
const image = await loadImageElement(file)
|
||||
const preferredMimeTypes = getPreferredMimeTypes(file)
|
||||
let bestBlob: Blob | null = null
|
||||
let bestMimeType = file.type
|
||||
|
||||
for (const scale of SCALE_STEPS) {
|
||||
const width = Math.max(1, Math.round(image.naturalWidth * scale))
|
||||
const height = Math.max(1, Math.round(image.naturalHeight * scale))
|
||||
|
||||
for (const mimeType of preferredMimeTypes) {
|
||||
const canvas = drawImageToCanvas(image, width, height, mimeType)
|
||||
const qualitySteps = mimeType === 'image/png' ? [undefined] : QUALITY_STEPS
|
||||
|
||||
for (const quality of qualitySteps) {
|
||||
const blob = await canvasToBlob(canvas, mimeType, quality)
|
||||
|
||||
if (!bestBlob || blob.size < bestBlob.size) {
|
||||
bestBlob = blob
|
||||
bestMimeType = mimeType
|
||||
}
|
||||
|
||||
if (blob.size <= maxSize) {
|
||||
const compressedFile = toCompressedFile(blob, file, mimeType)
|
||||
return {
|
||||
file: compressedFile,
|
||||
originalSize: file.size,
|
||||
finalSize: blob.size,
|
||||
compressed: true,
|
||||
converted: mimeType !== file.type
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!bestBlob) {
|
||||
throw new Error('图片压缩失败')
|
||||
}
|
||||
|
||||
const compressedFile = toCompressedFile(bestBlob, file, bestMimeType)
|
||||
return {
|
||||
file: compressedFile,
|
||||
originalSize: file.size,
|
||||
finalSize: bestBlob.size,
|
||||
compressed: true,
|
||||
converted: bestMimeType !== file.type
|
||||
}
|
||||
}
|
||||
|
||||
export const MAX_IMAGE_UPLOAD_SIZE = DEFAULT_MAX_IMAGE_SIZE
|
||||
@@ -0,0 +1,88 @@
|
||||
import { permissionApi } from '@/api/permission'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const USER_PERMISSIONS_STORAGE_KEY = 'userPermissions'
|
||||
|
||||
const readPermissionsFromStorage = () => {
|
||||
const raw = localStorage.getItem(USER_PERMISSIONS_STORAGE_KEY)
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
return Array.isArray(parsed) ? parsed.map(item => String(item)) : null
|
||||
} catch (error) {
|
||||
console.error('Failed to parse stored user permissions:', error)
|
||||
localStorage.removeItem(USER_PERMISSIONS_STORAGE_KEY)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const userPermissions = ref<string[]>(readPermissionsFromStorage() || [])
|
||||
const loadingPermissions = ref(false)
|
||||
|
||||
export const getStoredUserPermissions = () => readPermissionsFromStorage()
|
||||
|
||||
export const setStoredUserPermissions = (permissions: string[]) => {
|
||||
userPermissions.value = Array.from(new Set((permissions || []).map(code => String(code))))
|
||||
localStorage.setItem(USER_PERMISSIONS_STORAGE_KEY, JSON.stringify(userPermissions.value))
|
||||
return userPermissions.value
|
||||
}
|
||||
|
||||
export const clearStoredPermissions = () => {
|
||||
userPermissions.value = []
|
||||
localStorage.removeItem(USER_PERMISSIONS_STORAGE_KEY)
|
||||
}
|
||||
|
||||
export const fetchUserPermissionsStrict = async () => {
|
||||
loadingPermissions.value = true
|
||||
try {
|
||||
const permissions = await permissionApi.getUserPermissions()
|
||||
const normalizedPermissions = permissions && Array.isArray(permissions)
|
||||
? permissions.map(permission => permission.permissionCode)
|
||||
: []
|
||||
|
||||
return setStoredUserPermissions(normalizedPermissions)
|
||||
} finally {
|
||||
loadingPermissions.value = false
|
||||
}
|
||||
}
|
||||
|
||||
export const usePermission = () => {
|
||||
const hasPermission = (permissionCode: string) => {
|
||||
return userPermissions.value.includes(permissionCode)
|
||||
}
|
||||
|
||||
const hasAnyPermission = (permissionCodes: string[]) => {
|
||||
return permissionCodes.some(code => userPermissions.value.includes(code))
|
||||
}
|
||||
|
||||
const hasAllPermissions = (permissionCodes: string[]) => {
|
||||
return permissionCodes.every(code => userPermissions.value.includes(code))
|
||||
}
|
||||
|
||||
const loadUserPermissions = async () => {
|
||||
try {
|
||||
return await fetchUserPermissionsStrict()
|
||||
} catch (error) {
|
||||
console.error('加载用户权限失败:', error)
|
||||
clearStoredPermissions()
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const clearPermissions = () => {
|
||||
clearStoredPermissions()
|
||||
}
|
||||
|
||||
return {
|
||||
userPermissions: computed(() => userPermissions.value),
|
||||
loadingPermissions: computed(() => loadingPermissions.value),
|
||||
hasPermission,
|
||||
hasAnyPermission,
|
||||
hasAllPermissions,
|
||||
loadUserPermissions,
|
||||
clearPermissions
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user