初始化
This commit is contained in:
60
src/hooks/event/useScrollTo.ts
Normal file
60
src/hooks/event/useScrollTo.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
export interface ScrollToParams {
|
||||
el: HTMLElement
|
||||
to: number
|
||||
position: string
|
||||
duration?: number
|
||||
callback?: () => void
|
||||
}
|
||||
|
||||
const easeInOutQuad = (t: number, b: number, c: number, d: number) => {
|
||||
t /= d / 2
|
||||
if (t < 1) {
|
||||
return (c / 2) * t * t + b
|
||||
}
|
||||
t--
|
||||
return (-c / 2) * (t * (t - 2) - 1) + b
|
||||
}
|
||||
const move = (el: HTMLElement, position: string, amount: number) => {
|
||||
el[position] = amount
|
||||
}
|
||||
|
||||
export function useScrollTo({
|
||||
el,
|
||||
position = 'scrollLeft',
|
||||
to,
|
||||
duration = 500,
|
||||
callback
|
||||
}: ScrollToParams) {
|
||||
const isActiveRef = ref(false)
|
||||
const start = el[position]
|
||||
const change = to - start
|
||||
const increment = 20
|
||||
let currentTime = 0
|
||||
|
||||
function animateScroll() {
|
||||
if (!unref(isActiveRef)) {
|
||||
return
|
||||
}
|
||||
currentTime += increment
|
||||
const val = easeInOutQuad(currentTime, start, change, duration)
|
||||
move(el, position, val)
|
||||
if (currentTime < duration && unref(isActiveRef)) {
|
||||
requestAnimationFrame(animateScroll)
|
||||
} else {
|
||||
if (callback) {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function run() {
|
||||
isActiveRef.value = true
|
||||
animateScroll()
|
||||
}
|
||||
|
||||
function stop() {
|
||||
isActiveRef.value = false
|
||||
}
|
||||
|
||||
return { start: run, stop }
|
||||
}
|
||||
41
src/hooks/web/useCache.ts
Normal file
41
src/hooks/web/useCache.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 配置浏览器本地存储的方式,可直接存储对象数组。
|
||||
*/
|
||||
|
||||
import WebStorageCache from 'web-storage-cache'
|
||||
|
||||
type CacheType = 'localStorage' | 'sessionStorage'
|
||||
|
||||
export const CACHE_KEY = {
|
||||
// 用户相关
|
||||
ROLE_ROUTERS: 'roleRouters',
|
||||
USER: 'user',
|
||||
VisitTenantId: 'visitTenantId',
|
||||
// 系统设置
|
||||
IS_DARK: 'isDark',
|
||||
LANG: 'lang',
|
||||
THEME: 'theme',
|
||||
LAYOUT: 'layout',
|
||||
DICT_CACHE: 'dictCache',
|
||||
// 登录表单
|
||||
LoginForm: 'loginForm',
|
||||
TenantId: 'tenantId'
|
||||
}
|
||||
|
||||
export const useCache = (type: CacheType = 'localStorage') => {
|
||||
const wsCache: WebStorageCache = new WebStorageCache({
|
||||
storage: type
|
||||
})
|
||||
|
||||
return {
|
||||
wsCache
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteUserCache = () => {
|
||||
const { wsCache } = useCache()
|
||||
wsCache.delete(CACHE_KEY.USER)
|
||||
wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
|
||||
wsCache.delete(CACHE_KEY.VisitTenantId)
|
||||
// 注意,不要清理 LoginForm 登录表单
|
||||
}
|
||||
9
src/hooks/web/useConfigGlobal.ts
Normal file
9
src/hooks/web/useConfigGlobal.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { ConfigGlobalTypes } from '@/types/configGlobal'
|
||||
|
||||
export const useConfigGlobal = () => {
|
||||
const configGlobal = inject('configGlobal', {}) as ConfigGlobalTypes
|
||||
|
||||
return {
|
||||
configGlobal
|
||||
}
|
||||
}
|
||||
326
src/hooks/web/useCrudSchemas.ts
Normal file
326
src/hooks/web/useCrudSchemas.ts
Normal file
@@ -0,0 +1,326 @@
|
||||
import { reactive } from 'vue'
|
||||
import { AxiosPromise } from 'axios'
|
||||
import { findIndex } from '@/utils'
|
||||
import { eachTree, filter, treeMap } from '@/utils/tree'
|
||||
import { getBoolDictOptions, getDictOptions, getIntDictOptions } from '@/utils/dict'
|
||||
|
||||
import { FormSchema } from '@/types/form'
|
||||
import { TableColumn } from '@/types/table'
|
||||
import { DescriptionsSchema } from '@/types/descriptions'
|
||||
import { ComponentOptions, ComponentProps } from '@/types/components'
|
||||
import { DictTag } from '@/components/DictTag'
|
||||
import { cloneDeep, merge } from 'lodash-es'
|
||||
|
||||
export type CrudSchema = Omit<TableColumn, 'children'> & {
|
||||
isSearch?: boolean // 是否在查询显示
|
||||
search?: CrudSearchParams // 查询的详细配置
|
||||
isTable?: boolean // 是否在列表显示
|
||||
table?: CrudTableParams // 列表的详细配置
|
||||
isForm?: boolean // 是否在表单显示
|
||||
form?: CrudFormParams // 表单的详细配置
|
||||
isDetail?: boolean // 是否在详情显示
|
||||
detail?: CrudDescriptionsParams // 详情的详细配置
|
||||
children?: CrudSchema[]
|
||||
dictType?: string // 字典类型
|
||||
dictClass?: 'string' | 'number' | 'boolean' // 字典数据类型 string | number | boolean
|
||||
}
|
||||
|
||||
type CrudSearchParams = {
|
||||
// 是否显示在查询项
|
||||
show?: boolean
|
||||
// 接口
|
||||
api?: () => Promise<any>
|
||||
// 搜索字段
|
||||
field?: string
|
||||
} & Omit<FormSchema, 'field'>
|
||||
|
||||
type CrudTableParams = {
|
||||
// 是否显示表头
|
||||
show?: boolean
|
||||
// 列宽配置
|
||||
width?: number | string
|
||||
// 列是否固定在左侧或者右侧
|
||||
fixed?: 'left' | 'right'
|
||||
} & Omit<FormSchema, 'field'>
|
||||
type CrudFormParams = {
|
||||
// 是否显示表单项
|
||||
show?: boolean
|
||||
// 接口
|
||||
api?: () => Promise<any>
|
||||
} & Omit<FormSchema, 'field'>
|
||||
|
||||
type CrudDescriptionsParams = {
|
||||
// 是否显示表单项
|
||||
show?: boolean
|
||||
} & Omit<DescriptionsSchema, 'field'>
|
||||
|
||||
interface AllSchemas {
|
||||
searchSchema: FormSchema[]
|
||||
tableColumns: TableColumn[]
|
||||
formSchema: FormSchema[]
|
||||
detailSchema: DescriptionsSchema[]
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
// 过滤所有结构
|
||||
export const useCrudSchemas = (
|
||||
crudSchema: CrudSchema[]
|
||||
): {
|
||||
allSchemas: AllSchemas
|
||||
} => {
|
||||
// 所有结构数据
|
||||
const allSchemas = reactive<AllSchemas>({
|
||||
searchSchema: [],
|
||||
tableColumns: [],
|
||||
formSchema: [],
|
||||
detailSchema: []
|
||||
})
|
||||
|
||||
const searchSchema = filterSearchSchema(crudSchema, allSchemas)
|
||||
allSchemas.searchSchema = searchSchema || []
|
||||
|
||||
const tableColumns = filterTableSchema(crudSchema)
|
||||
allSchemas.tableColumns = tableColumns || []
|
||||
|
||||
const formSchema = filterFormSchema(crudSchema, allSchemas)
|
||||
allSchemas.formSchema = formSchema
|
||||
|
||||
const detailSchema = filterDescriptionsSchema(crudSchema)
|
||||
allSchemas.detailSchema = detailSchema
|
||||
|
||||
return {
|
||||
allSchemas
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤 Search 结构
|
||||
const filterSearchSchema = (crudSchema: CrudSchema[], allSchemas: AllSchemas): FormSchema[] => {
|
||||
const searchSchema: FormSchema[] = []
|
||||
|
||||
// 获取字典列表队列
|
||||
const searchRequestTask: Array<() => Promise<void>> = []
|
||||
eachTree(crudSchema, (schemaItem: CrudSchema) => {
|
||||
// 判断是否显示
|
||||
if (schemaItem?.isSearch || schemaItem.search?.show) {
|
||||
let component = schemaItem?.search?.component || 'Input'
|
||||
const options: ComponentOptions[] = []
|
||||
let comonentProps: ComponentProps = {}
|
||||
if (schemaItem.dictType) {
|
||||
const allOptions: ComponentOptions = { label: '全部', value: '' }
|
||||
options.push(allOptions)
|
||||
getDictOptions(schemaItem.dictType).forEach((dict) => {
|
||||
options.push(dict)
|
||||
})
|
||||
comonentProps = {
|
||||
options: options
|
||||
}
|
||||
if (!schemaItem.search?.component) component = 'Select'
|
||||
}
|
||||
|
||||
// updated by AKing: 解决了当使用默认的dict选项时,form中事件不能触发的问题
|
||||
const searchSchemaItem = merge(
|
||||
{
|
||||
// 默认为 input
|
||||
component,
|
||||
...schemaItem.search,
|
||||
field: schemaItem.field,
|
||||
label: schemaItem.search?.label || schemaItem.label
|
||||
},
|
||||
{ componentProps: comonentProps }
|
||||
)
|
||||
if (searchSchemaItem.api) {
|
||||
searchRequestTask.push(async () => {
|
||||
const res = await (searchSchemaItem.api as () => AxiosPromise)()
|
||||
if (res) {
|
||||
const index = findIndex(allSchemas.searchSchema, (v: FormSchema) => {
|
||||
return v.field === searchSchemaItem.field
|
||||
})
|
||||
if (index !== -1) {
|
||||
allSchemas.searchSchema[index]!.componentProps!.options = filterOptions(
|
||||
res,
|
||||
searchSchemaItem.componentProps.optionsAlias?.labelField
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// 删除不必要的字段
|
||||
delete searchSchemaItem.show
|
||||
|
||||
searchSchema.push(searchSchemaItem)
|
||||
}
|
||||
})
|
||||
for (const task of searchRequestTask) {
|
||||
task()
|
||||
}
|
||||
return searchSchema
|
||||
}
|
||||
|
||||
// 过滤 table 结构
|
||||
const filterTableSchema = (crudSchema: CrudSchema[]): TableColumn[] => {
|
||||
const tableColumns = treeMap<CrudSchema>(crudSchema, {
|
||||
conversion: (schema: CrudSchema) => {
|
||||
if (schema?.isTable !== false && schema?.table?.show !== false) {
|
||||
// add by 芋艿:增加对 dict 字典数据的支持
|
||||
if (!schema.formatter && schema.dictType) {
|
||||
schema.formatter = (_: Recordable, __: TableColumn, cellValue: any) => {
|
||||
return h(DictTag, {
|
||||
type: schema.dictType!, // ! 表示一定不为空
|
||||
value: cellValue
|
||||
})
|
||||
}
|
||||
}
|
||||
return {
|
||||
...schema.table,
|
||||
...schema
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 第一次过滤会有 undefined 所以需要二次过滤
|
||||
return filter<TableColumn>(tableColumns as TableColumn[], (data) => {
|
||||
if (data.children === void 0) {
|
||||
delete data.children
|
||||
}
|
||||
return !!data.field
|
||||
})
|
||||
}
|
||||
|
||||
// 过滤 form 结构
|
||||
const filterFormSchema = (crudSchema: CrudSchema[], allSchemas: AllSchemas): FormSchema[] => {
|
||||
const formSchema: FormSchema[] = []
|
||||
|
||||
// 获取字典列表队列
|
||||
const formRequestTask: Array<() => Promise<void>> = []
|
||||
|
||||
eachTree(crudSchema, (schemaItem: CrudSchema) => {
|
||||
// 判断是否显示
|
||||
if (schemaItem?.isForm !== false && schemaItem?.form?.show !== false) {
|
||||
let component = schemaItem?.form?.component || 'Input'
|
||||
let defaultValue: any = ''
|
||||
if (schemaItem.form?.value) {
|
||||
defaultValue = schemaItem.form?.value
|
||||
} else {
|
||||
if (component === 'InputNumber') {
|
||||
defaultValue = 0
|
||||
}
|
||||
}
|
||||
let comonentProps: ComponentProps = {}
|
||||
if (schemaItem.dictType) {
|
||||
const options: ComponentOptions[] = []
|
||||
if (schemaItem.dictClass && schemaItem.dictClass === 'number') {
|
||||
getIntDictOptions(schemaItem.dictType).forEach((dict) => {
|
||||
options.push(dict)
|
||||
})
|
||||
} else if (schemaItem.dictClass && schemaItem.dictClass === 'boolean') {
|
||||
getBoolDictOptions(schemaItem.dictType).forEach((dict) => {
|
||||
options.push(dict)
|
||||
})
|
||||
} else {
|
||||
getDictOptions(schemaItem.dictType).forEach((dict) => {
|
||||
options.push(dict)
|
||||
})
|
||||
}
|
||||
comonentProps = {
|
||||
options: options
|
||||
}
|
||||
if (!(schemaItem.form && schemaItem.form.component)) component = 'Select'
|
||||
}
|
||||
|
||||
// updated by AKing: 解决了当使用默认的dict选项时,form中事件不能触发的问题
|
||||
const formSchemaItem = merge(
|
||||
{
|
||||
// 默认为 input
|
||||
component,
|
||||
value: defaultValue,
|
||||
...schemaItem.form,
|
||||
field: schemaItem.field,
|
||||
label: schemaItem.form?.label || schemaItem.label
|
||||
},
|
||||
{ componentProps: comonentProps }
|
||||
)
|
||||
|
||||
if (formSchemaItem.api) {
|
||||
formRequestTask.push(async () => {
|
||||
const res = await (formSchemaItem.api as () => AxiosPromise)()
|
||||
if (res) {
|
||||
const index = findIndex(allSchemas.formSchema, (v: FormSchema) => {
|
||||
return v.field === formSchemaItem.field
|
||||
})
|
||||
if (index !== -1) {
|
||||
allSchemas.formSchema[index]!.componentProps!.options = filterOptions(
|
||||
res,
|
||||
formSchemaItem.componentProps.optionsAlias?.labelField
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 删除不必要的字段
|
||||
delete formSchemaItem.show
|
||||
|
||||
formSchema.push(formSchemaItem)
|
||||
}
|
||||
})
|
||||
|
||||
for (const task of formRequestTask) {
|
||||
task()
|
||||
}
|
||||
return formSchema
|
||||
}
|
||||
|
||||
// 过滤 descriptions 结构
|
||||
const filterDescriptionsSchema = (crudSchema: CrudSchema[]): DescriptionsSchema[] => {
|
||||
const descriptionsSchema: FormSchema[] = []
|
||||
|
||||
eachTree(crudSchema, (schemaItem: CrudSchema) => {
|
||||
// 判断是否显示
|
||||
if (schemaItem?.isDetail !== false && schemaItem.detail?.show !== false) {
|
||||
const descriptionsSchemaItem = {
|
||||
...schemaItem.detail,
|
||||
field: schemaItem.field,
|
||||
label: schemaItem.detail?.label || schemaItem.label
|
||||
}
|
||||
if (schemaItem.dictType) {
|
||||
descriptionsSchemaItem.dictType = schemaItem.dictType
|
||||
}
|
||||
if (schemaItem.detail?.dateFormat || schemaItem.formatter == 'formatDate') {
|
||||
// 优先使用 detail 下的配置,如果没有默认为 YYYY-MM-DD HH:mm:ss
|
||||
descriptionsSchemaItem.dateFormat = schemaItem?.detail?.dateFormat
|
||||
? schemaItem?.detail?.dateFormat
|
||||
: 'YYYY-MM-DD HH:mm:ss'
|
||||
}
|
||||
|
||||
// 删除不必要的字段
|
||||
delete descriptionsSchemaItem.show
|
||||
|
||||
descriptionsSchema.push(descriptionsSchemaItem)
|
||||
}
|
||||
})
|
||||
|
||||
return descriptionsSchema
|
||||
}
|
||||
|
||||
// 给options添加国际化
|
||||
const filterOptions = (options: Recordable, labelField?: string) => {
|
||||
return options?.map((v: Recordable) => {
|
||||
if (labelField) {
|
||||
v['labelField'] = t(v.labelField)
|
||||
} else {
|
||||
v['label'] = t(v.label)
|
||||
}
|
||||
return v
|
||||
})
|
||||
}
|
||||
|
||||
// 将 tableColumns 指定 fields 放到最前面
|
||||
export const sortTableColumns = (tableColumns: TableColumn[], field: string) => {
|
||||
const fieldIndex = tableColumns.findIndex((item) => item.field === field)
|
||||
const fieldColumn = cloneDeep(tableColumns[fieldIndex])
|
||||
tableColumns.splice(fieldIndex, 1)
|
||||
// 添加到开头
|
||||
tableColumns.unshift(fieldColumn)
|
||||
}
|
||||
18
src/hooks/web/useDesign.ts
Normal file
18
src/hooks/web/useDesign.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import variables from '@/styles/global.module.scss'
|
||||
|
||||
export const useDesign = () => {
|
||||
const scssVariables = variables
|
||||
|
||||
/**
|
||||
* @param scope 类名
|
||||
* @returns 返回空间名-类名
|
||||
*/
|
||||
const getPrefixCls = (scope: string) => {
|
||||
return `${scssVariables.namespace}-${scope}`
|
||||
}
|
||||
|
||||
return {
|
||||
variables: scssVariables,
|
||||
getPrefixCls
|
||||
}
|
||||
}
|
||||
22
src/hooks/web/useEmitt.ts
Normal file
22
src/hooks/web/useEmitt.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import mitt from 'mitt'
|
||||
|
||||
interface Option {
|
||||
name: string // 事件名称
|
||||
callback: Fn // 回调
|
||||
}
|
||||
|
||||
const emitter = mitt()
|
||||
|
||||
export const useEmitt = (option?: Option) => {
|
||||
if (option) {
|
||||
emitter.on(option.name, option.callback)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
emitter.off(option.name)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
emitter
|
||||
}
|
||||
}
|
||||
94
src/hooks/web/useForm.ts
Normal file
94
src/hooks/web/useForm.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import type { Form, FormExpose } from '@/components/Form'
|
||||
import type { ElForm } from 'element-plus'
|
||||
import type { FormProps } from '@/components/Form/src/types'
|
||||
import { FormSchema, FormSetPropsType } from '@/types/form'
|
||||
|
||||
export const useForm = (props?: FormProps) => {
|
||||
// From实例
|
||||
const formRef = ref<typeof Form & FormExpose>()
|
||||
|
||||
// ElForm实例
|
||||
const elFormRef = ref<ComponentRef<typeof ElForm>>()
|
||||
|
||||
/**
|
||||
* @param ref Form实例
|
||||
* @param elRef ElForm实例
|
||||
*/
|
||||
const register = (ref: typeof Form & FormExpose, elRef: ComponentRef<typeof ElForm>) => {
|
||||
formRef.value = ref
|
||||
elFormRef.value = elRef
|
||||
}
|
||||
|
||||
const getForm = async () => {
|
||||
await nextTick()
|
||||
const form = unref(formRef)
|
||||
if (!form) {
|
||||
console.error('The form is not registered. Please use the register method to register')
|
||||
}
|
||||
return form
|
||||
}
|
||||
|
||||
// 一些内置的方法
|
||||
const methods: {
|
||||
setProps: (props: Recordable) => void
|
||||
setValues: (data: Recordable) => void
|
||||
getFormData: <T = Recordable | undefined>() => Promise<T>
|
||||
setSchema: (schemaProps: FormSetPropsType[]) => void
|
||||
addSchema: (formSchema: FormSchema, index?: number) => void
|
||||
delSchema: (field: string) => void
|
||||
} = {
|
||||
setProps: async (props: FormProps = {}) => {
|
||||
const form = await getForm()
|
||||
form?.setProps(props)
|
||||
if (props.model) {
|
||||
form?.setValues(props.model)
|
||||
}
|
||||
},
|
||||
|
||||
setValues: async (data: Recordable) => {
|
||||
const form = await getForm()
|
||||
form?.setValues(data)
|
||||
},
|
||||
|
||||
/**
|
||||
* @param schemaProps 需要设置的schemaProps
|
||||
*/
|
||||
setSchema: async (schemaProps: FormSetPropsType[]) => {
|
||||
const form = await getForm()
|
||||
form?.setSchema(schemaProps)
|
||||
},
|
||||
|
||||
/**
|
||||
* @param formSchema 需要新增数据
|
||||
* @param index 在哪里新增
|
||||
*/
|
||||
addSchema: async (formSchema: FormSchema, index?: number) => {
|
||||
const form = await getForm()
|
||||
form?.addSchema(formSchema, index)
|
||||
},
|
||||
|
||||
/**
|
||||
* @param field 删除哪个数据
|
||||
*/
|
||||
delSchema: async (field: string) => {
|
||||
const form = await getForm()
|
||||
form?.delSchema(field)
|
||||
},
|
||||
|
||||
/**
|
||||
* @returns form data
|
||||
*/
|
||||
getFormData: async <T = Recordable>(): Promise<T> => {
|
||||
const form = await getForm()
|
||||
return form?.formModel as T
|
||||
}
|
||||
}
|
||||
|
||||
props && methods.setProps(props)
|
||||
|
||||
return {
|
||||
register,
|
||||
elFormRef,
|
||||
methods
|
||||
}
|
||||
}
|
||||
49
src/hooks/web/useGuide.ts
Normal file
49
src/hooks/web/useGuide.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Config, driver } from 'driver.js'
|
||||
import 'driver.js/dist/driver.css'
|
||||
import { useDesign } from '@/hooks/web/useDesign'
|
||||
import { useI18n } from '@/hooks/web/useI18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { variables } = useDesign()
|
||||
|
||||
export const useGuide = (options?: Config) => {
|
||||
const driverObj = driver(
|
||||
options || {
|
||||
showProgress: true,
|
||||
nextBtnText: t('common.nextLabel'),
|
||||
prevBtnText: t('common.prevLabel'),
|
||||
doneBtnText: t('common.doneLabel'),
|
||||
steps: [
|
||||
{
|
||||
element: `#${variables.namespace}-menu`,
|
||||
popover: {
|
||||
title: t('common.menu'),
|
||||
description: t('common.menuDes'),
|
||||
side: 'right'
|
||||
}
|
||||
},
|
||||
{
|
||||
element: `#${variables.namespace}-tool-header`,
|
||||
popover: {
|
||||
title: t('common.tool'),
|
||||
description: t('common.toolDes'),
|
||||
side: 'left'
|
||||
}
|
||||
},
|
||||
{
|
||||
element: `#${variables.namespace}-tags-view`,
|
||||
popover: {
|
||||
title: t('common.tagsView'),
|
||||
description: t('common.tagsViewDes'),
|
||||
side: 'bottom'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
...driverObj
|
||||
}
|
||||
}
|
||||
53
src/hooks/web/useI18n.ts
Normal file
53
src/hooks/web/useI18n.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { i18n } from '@/plugins/vueI18n'
|
||||
|
||||
type I18nGlobalTranslation = {
|
||||
(key: string): string
|
||||
(key: string, locale: string): string
|
||||
(key: string, locale: string, list: unknown[]): string
|
||||
(key: string, locale: string, named: Record<string, unknown>): string
|
||||
(key: string, list: unknown[]): string
|
||||
(key: string, named: Record<string, unknown>): string
|
||||
}
|
||||
|
||||
type I18nTranslationRestParameters = [string, any]
|
||||
|
||||
const getKey = (namespace: string | undefined, key: string) => {
|
||||
if (!namespace) {
|
||||
return key
|
||||
}
|
||||
if (key.startsWith(namespace)) {
|
||||
return key
|
||||
}
|
||||
return `${namespace}.${key}`
|
||||
}
|
||||
|
||||
export const useI18n = (
|
||||
namespace?: string
|
||||
): {
|
||||
t: I18nGlobalTranslation
|
||||
} => {
|
||||
const normalFn = {
|
||||
t: (key: string) => {
|
||||
return getKey(namespace, key)
|
||||
}
|
||||
}
|
||||
|
||||
if (!i18n) {
|
||||
return normalFn
|
||||
}
|
||||
|
||||
const { t, ...methods } = i18n.global
|
||||
|
||||
const tFn: I18nGlobalTranslation = (key: string, ...arg: any[]) => {
|
||||
if (!key) return ''
|
||||
if (!key.includes('.') && !namespace) return key
|
||||
//@ts-ignore
|
||||
return t(getKey(namespace, key), ...(arg as I18nTranslationRestParameters))
|
||||
}
|
||||
return {
|
||||
...methods,
|
||||
t: tFn
|
||||
}
|
||||
}
|
||||
|
||||
export const t = (key: string) => key
|
||||
8
src/hooks/web/useIcon.ts
Normal file
8
src/hooks/web/useIcon.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { h } from 'vue'
|
||||
import type { VNode } from 'vue'
|
||||
import { Icon } from '@/components/Icon'
|
||||
import { IconTypes } from '@/types/icon'
|
||||
|
||||
export const useIcon = (props: IconTypes): VNode => {
|
||||
return h(Icon, props)
|
||||
}
|
||||
35
src/hooks/web/useLocale.ts
Normal file
35
src/hooks/web/useLocale.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { i18n } from '@/plugins/vueI18n'
|
||||
import { useLocaleStoreWithOut } from '@/store/modules/locale'
|
||||
import { setHtmlPageLang } from '@/plugins/vueI18n/helper'
|
||||
|
||||
const setI18nLanguage = (locale: LocaleType) => {
|
||||
const localeStore = useLocaleStoreWithOut()
|
||||
|
||||
if (i18n.mode === 'legacy') {
|
||||
i18n.global.locale = locale
|
||||
} else {
|
||||
;(i18n.global.locale as any).value = locale
|
||||
}
|
||||
localeStore.setCurrentLocale({
|
||||
lang: locale
|
||||
})
|
||||
setHtmlPageLang(locale)
|
||||
}
|
||||
|
||||
export const useLocale = () => {
|
||||
// Switching the language will change the locale of useI18n
|
||||
// And submit to configuration modification
|
||||
const changeLocale = async (locale: LocaleType) => {
|
||||
const globalI18n = i18n.global
|
||||
|
||||
const langModule = await import(`../../locales/${locale}.ts`)
|
||||
|
||||
globalI18n.setLocaleMessage(locale, langModule.default)
|
||||
|
||||
setI18nLanguage(locale)
|
||||
}
|
||||
|
||||
return {
|
||||
changeLocale
|
||||
}
|
||||
}
|
||||
95
src/hooks/web/useMessage.ts
Normal file
95
src/hooks/web/useMessage.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
|
||||
import { useI18n } from './useI18n'
|
||||
export const useMessage = () => {
|
||||
const { t } = useI18n()
|
||||
return {
|
||||
// 消息提示
|
||||
info(content: string) {
|
||||
ElMessage.info(content)
|
||||
},
|
||||
// 错误消息
|
||||
error(content: string) {
|
||||
ElMessage.error(content)
|
||||
},
|
||||
// 成功消息
|
||||
success(content: string) {
|
||||
ElMessage.success(content)
|
||||
},
|
||||
// 警告消息
|
||||
warning(content: string) {
|
||||
ElMessage.warning(content)
|
||||
},
|
||||
// 弹出提示
|
||||
alert(content: string) {
|
||||
ElMessageBox.alert(content, t('common.confirmTitle'))
|
||||
},
|
||||
// 错误提示
|
||||
alertError(content: string) {
|
||||
ElMessageBox.alert(content, t('common.confirmTitle'), { type: 'error' })
|
||||
},
|
||||
// 成功提示
|
||||
alertSuccess(content: string) {
|
||||
ElMessageBox.alert(content, t('common.confirmTitle'), { type: 'success' })
|
||||
},
|
||||
// 警告提示
|
||||
alertWarning(content: string) {
|
||||
ElMessageBox.alert(content, t('common.confirmTitle'), { type: 'warning' })
|
||||
},
|
||||
// 通知提示
|
||||
notify(content: string) {
|
||||
ElNotification.info(content)
|
||||
},
|
||||
// 错误通知
|
||||
notifyError(content: string) {
|
||||
ElNotification.error(content)
|
||||
},
|
||||
// 成功通知
|
||||
notifySuccess(content: string) {
|
||||
ElNotification.success(content)
|
||||
},
|
||||
// 警告通知
|
||||
notifyWarning(content: string) {
|
||||
ElNotification.warning(content)
|
||||
},
|
||||
// 确认窗体
|
||||
confirm(content: string, tip?: string) {
|
||||
return ElMessageBox.confirm(content, tip ? tip : t('common.confirmTitle'), {
|
||||
confirmButtonText: t('common.ok'),
|
||||
cancelButtonText: t('common.cancel'),
|
||||
type: 'warning'
|
||||
})
|
||||
},
|
||||
// 删除窗体
|
||||
delConfirm(content?: string, tip?: string) {
|
||||
return ElMessageBox.confirm(
|
||||
content ? content : t('common.delMessage'),
|
||||
tip ? tip : t('common.confirmTitle'),
|
||||
{
|
||||
confirmButtonText: t('common.ok'),
|
||||
cancelButtonText: t('common.cancel'),
|
||||
type: 'warning'
|
||||
}
|
||||
)
|
||||
},
|
||||
// 导出窗体
|
||||
exportConfirm(content?: string, tip?: string) {
|
||||
return ElMessageBox.confirm(
|
||||
content ? content : t('common.exportMessage'),
|
||||
tip ? tip : t('common.confirmTitle'),
|
||||
{
|
||||
confirmButtonText: t('common.ok'),
|
||||
cancelButtonText: t('common.cancel'),
|
||||
type: 'warning'
|
||||
}
|
||||
)
|
||||
},
|
||||
// 提交内容
|
||||
prompt(content: string, tip: string) {
|
||||
return ElMessageBox.prompt(content, tip, {
|
||||
confirmButtonText: t('common.ok'),
|
||||
cancelButtonText: t('common.cancel'),
|
||||
type: 'warning'
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
33
src/hooks/web/useNProgress.ts
Normal file
33
src/hooks/web/useNProgress.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useCssVar } from '@vueuse/core'
|
||||
import type { NProgressOptions } from 'nprogress'
|
||||
import NProgress from 'nprogress'
|
||||
import 'nprogress/nprogress.css'
|
||||
|
||||
const primaryColor = useCssVar('--el-color-primary', document.documentElement)
|
||||
|
||||
export const useNProgress = () => {
|
||||
NProgress.configure({ showSpinner: false } as NProgressOptions)
|
||||
|
||||
const initColor = async () => {
|
||||
await nextTick()
|
||||
const bar = document.getElementById('nprogress')?.getElementsByClassName('bar')[0] as ElRef
|
||||
if (bar) {
|
||||
bar.style.background = unref(primaryColor.value)
|
||||
}
|
||||
}
|
||||
|
||||
initColor()
|
||||
|
||||
const start = () => {
|
||||
NProgress.start()
|
||||
}
|
||||
|
||||
const done = () => {
|
||||
NProgress.done()
|
||||
}
|
||||
|
||||
return {
|
||||
start,
|
||||
done
|
||||
}
|
||||
}
|
||||
21
src/hooks/web/useNetwork.ts
Normal file
21
src/hooks/web/useNetwork.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { ref, onBeforeUnmount } from 'vue'
|
||||
|
||||
const useNetwork = () => {
|
||||
const online = ref(true)
|
||||
|
||||
const updateNetwork = () => {
|
||||
online.value = navigator.onLine
|
||||
}
|
||||
|
||||
window.addEventListener('online', updateNetwork)
|
||||
window.addEventListener('offline', updateNetwork)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('online', updateNetwork)
|
||||
window.removeEventListener('offline', updateNetwork)
|
||||
})
|
||||
|
||||
return { online }
|
||||
}
|
||||
|
||||
export { useNetwork }
|
||||
60
src/hooks/web/useNow.ts
Normal file
60
src/hooks/web/useNow.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { dateUtil } from '@/utils/dateUtil'
|
||||
import { reactive, toRefs } from 'vue'
|
||||
import { tryOnMounted, tryOnUnmounted } from '@vueuse/core'
|
||||
|
||||
export const useNow = (immediate = true) => {
|
||||
let timer: IntervalHandle
|
||||
|
||||
const state = reactive({
|
||||
year: 0,
|
||||
month: 0,
|
||||
week: '',
|
||||
day: 0,
|
||||
hour: '',
|
||||
minute: '',
|
||||
second: 0,
|
||||
meridiem: ''
|
||||
})
|
||||
|
||||
const update = () => {
|
||||
const now = dateUtil()
|
||||
|
||||
const h = now.format('HH')
|
||||
const m = now.format('mm')
|
||||
const s = now.get('s')
|
||||
|
||||
state.year = now.get('y')
|
||||
state.month = now.get('M') + 1
|
||||
state.week = '星期' + ['日', '一', '二', '三', '四', '五', '六'][now.day()]
|
||||
state.day = now.get('date')
|
||||
state.hour = h
|
||||
state.minute = m
|
||||
state.second = s
|
||||
|
||||
state.meridiem = now.format('A')
|
||||
}
|
||||
|
||||
function start() {
|
||||
update()
|
||||
clearInterval(timer)
|
||||
timer = setInterval(() => update(), 1000)
|
||||
}
|
||||
|
||||
function stop() {
|
||||
clearInterval(timer)
|
||||
}
|
||||
|
||||
tryOnMounted(() => {
|
||||
immediate && start()
|
||||
})
|
||||
|
||||
tryOnUnmounted(() => {
|
||||
stop()
|
||||
})
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
start,
|
||||
stop
|
||||
}
|
||||
}
|
||||
18
src/hooks/web/usePageLoading.ts
Normal file
18
src/hooks/web/usePageLoading.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useAppStoreWithOut } from '@/store/modules/app'
|
||||
|
||||
const appStore = useAppStoreWithOut()
|
||||
|
||||
export const usePageLoading = () => {
|
||||
const loadStart = () => {
|
||||
appStore.setPageLoading(true)
|
||||
}
|
||||
|
||||
const loadDone = () => {
|
||||
appStore.setPageLoading(false)
|
||||
}
|
||||
|
||||
return {
|
||||
loadStart,
|
||||
loadDone
|
||||
}
|
||||
}
|
||||
223
src/hooks/web/useTable.ts
Normal file
223
src/hooks/web/useTable.ts
Normal file
@@ -0,0 +1,223 @@
|
||||
import download from '@/utils/download'
|
||||
import { Table, TableExpose } from '@/components/Table'
|
||||
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
|
||||
import { computed, nextTick, reactive, ref, unref, watch } from 'vue'
|
||||
import type { TableProps } from '@/components/Table/src/types'
|
||||
|
||||
import { TableSetPropsType } from '@/types/table'
|
||||
|
||||
const { t } = useI18n()
|
||||
interface ResponseType<T = any> {
|
||||
list: T[]
|
||||
total?: number
|
||||
}
|
||||
|
||||
interface UseTableConfig<T = any> {
|
||||
getListApi: (option: any) => Promise<T>
|
||||
delListApi?: (option: any) => Promise<T>
|
||||
exportListApi?: (option: any) => Promise<T>
|
||||
// 返回数据格式配置
|
||||
response?: ResponseType
|
||||
// 默认传递的参数
|
||||
defaultParams?: Recordable
|
||||
props?: TableProps
|
||||
}
|
||||
|
||||
interface TableObject<T = any> {
|
||||
pageSize: number
|
||||
currentPage: number
|
||||
total: number
|
||||
tableList: T[]
|
||||
params: any
|
||||
loading: boolean
|
||||
exportLoading: boolean
|
||||
currentRow: Nullable<T>
|
||||
}
|
||||
|
||||
export const useTable = <T = any>(config?: UseTableConfig<T>) => {
|
||||
const tableObject = reactive<TableObject<T>>({
|
||||
// 页数
|
||||
pageSize: 10,
|
||||
// 当前页
|
||||
currentPage: 1,
|
||||
// 总条数
|
||||
total: 10,
|
||||
// 表格数据
|
||||
tableList: [],
|
||||
// AxiosConfig 配置
|
||||
params: {
|
||||
...(config?.defaultParams || {})
|
||||
},
|
||||
// 加载中
|
||||
loading: true,
|
||||
// 导出加载中
|
||||
exportLoading: false,
|
||||
// 当前行的数据
|
||||
currentRow: null
|
||||
})
|
||||
|
||||
const paramsObj = computed(() => {
|
||||
return {
|
||||
...tableObject.params,
|
||||
pageSize: tableObject.pageSize,
|
||||
pageNo: tableObject.currentPage
|
||||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
() => tableObject.currentPage,
|
||||
() => {
|
||||
methods.getList()
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => tableObject.pageSize,
|
||||
() => {
|
||||
// 当前页不为1时,修改页数后会导致多次调用getList方法
|
||||
if (tableObject.currentPage === 1) {
|
||||
methods.getList()
|
||||
} else {
|
||||
tableObject.currentPage = 1
|
||||
methods.getList()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Table实例
|
||||
const tableRef = ref<typeof Table & TableExpose>()
|
||||
|
||||
// ElTable实例
|
||||
const elTableRef = ref<ComponentRef<typeof ElTable>>()
|
||||
|
||||
const register = (ref: typeof Table & TableExpose, elRef: ComponentRef<typeof ElTable>) => {
|
||||
tableRef.value = ref
|
||||
elTableRef.value = elRef
|
||||
}
|
||||
|
||||
const getTable = async () => {
|
||||
await nextTick()
|
||||
const table = unref(tableRef)
|
||||
if (!table) {
|
||||
console.error('The table is not registered. Please use the register method to register')
|
||||
}
|
||||
return table
|
||||
}
|
||||
|
||||
const delData = async (ids: string | number | string[] | number[]) => {
|
||||
let idsLength = 1
|
||||
if (ids instanceof Array) {
|
||||
idsLength = ids.length
|
||||
await Promise.all(
|
||||
ids.map(async (id: string | number) => {
|
||||
await (config?.delListApi && config?.delListApi(id))
|
||||
})
|
||||
)
|
||||
} else {
|
||||
await (config?.delListApi && config?.delListApi(ids))
|
||||
}
|
||||
ElMessage.success(t('common.delSuccess'))
|
||||
|
||||
// 计算出临界点
|
||||
tableObject.currentPage =
|
||||
tableObject.total % tableObject.pageSize === idsLength || tableObject.pageSize === 1
|
||||
? tableObject.currentPage > 1
|
||||
? tableObject.currentPage - 1
|
||||
: tableObject.currentPage
|
||||
: tableObject.currentPage
|
||||
await methods.getList()
|
||||
}
|
||||
|
||||
const methods = {
|
||||
getList: async () => {
|
||||
tableObject.loading = true
|
||||
const res = await config?.getListApi(unref(paramsObj)).finally(() => {
|
||||
tableObject.loading = false
|
||||
})
|
||||
if (res) {
|
||||
tableObject.tableList = (res as unknown as ResponseType).list
|
||||
tableObject.total = (res as unknown as ResponseType).total ?? 0
|
||||
}
|
||||
},
|
||||
setProps: async (props: TableProps = {}) => {
|
||||
const table = await getTable()
|
||||
table?.setProps(props)
|
||||
},
|
||||
setColumn: async (columnProps: TableSetPropsType[]) => {
|
||||
const table = await getTable()
|
||||
table?.setColumn(columnProps)
|
||||
},
|
||||
getSelections: async () => {
|
||||
const table = await getTable()
|
||||
return (table?.selections || []) as T[]
|
||||
},
|
||||
// 与Search组件结合
|
||||
setSearchParams: (data: Recordable) => {
|
||||
tableObject.params = Object.assign(tableObject.params, {
|
||||
pageSize: tableObject.pageSize,
|
||||
pageNo: 1,
|
||||
...data
|
||||
})
|
||||
// 页码不等于1时更新页码重新获取数据,页码等于1时重新获取数据
|
||||
if (tableObject.currentPage !== 1) {
|
||||
tableObject.currentPage = 1
|
||||
} else {
|
||||
methods.getList()
|
||||
}
|
||||
},
|
||||
// 删除数据
|
||||
delList: async (
|
||||
ids: string | number | string[] | number[],
|
||||
multiple: boolean,
|
||||
message = true
|
||||
) => {
|
||||
const tableRef = await getTable()
|
||||
if (multiple) {
|
||||
if (!tableRef?.selections.length) {
|
||||
ElMessage.warning(t('common.delNoData'))
|
||||
return
|
||||
}
|
||||
}
|
||||
if (message) {
|
||||
ElMessageBox.confirm(t('common.delMessage'), t('common.confirmTitle'), {
|
||||
confirmButtonText: t('common.ok'),
|
||||
cancelButtonText: t('common.cancel'),
|
||||
type: 'warning'
|
||||
}).then(async () => {
|
||||
await delData(ids)
|
||||
})
|
||||
} else {
|
||||
await delData(ids)
|
||||
}
|
||||
},
|
||||
// 导出列表
|
||||
exportList: async (fileName: string) => {
|
||||
tableObject.exportLoading = true
|
||||
ElMessageBox.confirm(t('common.exportMessage'), t('common.confirmTitle'), {
|
||||
confirmButtonText: t('common.ok'),
|
||||
cancelButtonText: t('common.cancel'),
|
||||
type: 'warning'
|
||||
})
|
||||
.then(async () => {
|
||||
const res = await config?.exportListApi?.(unref(paramsObj) as unknown as T)
|
||||
if (res) {
|
||||
download.excel(res as unknown as Blob, fileName)
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
tableObject.exportLoading = false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
config?.props && methods.setProps(config.props)
|
||||
|
||||
return {
|
||||
register,
|
||||
elTableRef,
|
||||
tableObject,
|
||||
methods,
|
||||
// add by 芋艿:返回 tableMethods 属性,和 tableObject 更统一
|
||||
tableMethods: methods
|
||||
}
|
||||
}
|
||||
63
src/hooks/web/useTagsView.ts
Normal file
63
src/hooks/web/useTagsView.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { useTagsViewStoreWithOut } from '@/store/modules/tagsView'
|
||||
import { RouteLocationNormalizedLoaded, useRouter } from 'vue-router'
|
||||
import { computed, nextTick, unref } from 'vue'
|
||||
|
||||
export const useTagsView = () => {
|
||||
const tagsViewStore = useTagsViewStoreWithOut()
|
||||
|
||||
const { replace, currentRoute } = useRouter()
|
||||
|
||||
const selectedTag = computed(() => tagsViewStore.getSelectedTag)
|
||||
|
||||
const closeAll = (callback?: Fn) => {
|
||||
tagsViewStore.delAllViews()
|
||||
callback?.()
|
||||
}
|
||||
|
||||
const closeLeft = (callback?: Fn) => {
|
||||
tagsViewStore.delLeftViews(unref(selectedTag) as RouteLocationNormalizedLoaded)
|
||||
callback?.()
|
||||
}
|
||||
|
||||
const closeRight = (callback?: Fn) => {
|
||||
tagsViewStore.delRightViews(unref(selectedTag) as RouteLocationNormalizedLoaded)
|
||||
callback?.()
|
||||
}
|
||||
|
||||
const closeOther = (callback?: Fn) => {
|
||||
tagsViewStore.delOthersViews(unref(selectedTag) as RouteLocationNormalizedLoaded)
|
||||
callback?.()
|
||||
}
|
||||
|
||||
const closeCurrent = (view?: RouteLocationNormalizedLoaded, callback?: Fn) => {
|
||||
if (view?.meta?.affix) return
|
||||
tagsViewStore.delView(view || unref(currentRoute))
|
||||
|
||||
callback?.()
|
||||
}
|
||||
|
||||
const refreshPage = async (view?: RouteLocationNormalizedLoaded, callback?: Fn) => {
|
||||
tagsViewStore.delCachedView()
|
||||
const { path, query } = view || unref(currentRoute)
|
||||
await nextTick()
|
||||
replace({
|
||||
path: '/redirect' + path,
|
||||
query: query
|
||||
})
|
||||
callback?.()
|
||||
}
|
||||
|
||||
const setTitle = (title: string, path?: string) => {
|
||||
tagsViewStore.setTitle(title, path)
|
||||
}
|
||||
|
||||
return {
|
||||
closeAll,
|
||||
closeLeft,
|
||||
closeRight,
|
||||
closeOther,
|
||||
closeCurrent,
|
||||
refreshPage,
|
||||
setTitle
|
||||
}
|
||||
}
|
||||
49
src/hooks/web/useTimeAgo.ts
Normal file
49
src/hooks/web/useTimeAgo.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useTimeAgo as useTimeAgoCore, UseTimeAgoMessages } from '@vueuse/core'
|
||||
import { useLocaleStoreWithOut } from '@/store/modules/locale'
|
||||
|
||||
const TIME_AGO_MESSAGE_MAP: {
|
||||
'zh-CN': UseTimeAgoMessages
|
||||
en: UseTimeAgoMessages
|
||||
} = {
|
||||
// @ts-ignore
|
||||
'zh-CN': {
|
||||
justNow: '刚刚',
|
||||
past: (n) => (n.match(/\d/) ? `${n}前` : n),
|
||||
future: (n) => (n.match(/\d/) ? `${n}后` : n),
|
||||
month: (n, past) => (n === 1 ? (past ? '上个月' : '下个月') : `${n} 个月`),
|
||||
year: (n, past) => (n === 1 ? (past ? '去年' : '明年') : `${n} 年`),
|
||||
day: (n, past) => (n === 1 ? (past ? '昨天' : '明天') : `${n} 天`),
|
||||
week: (n, past) => (n === 1 ? (past ? '上周' : '下周') : `${n} 周`),
|
||||
hour: (n) => `${n} 小时`,
|
||||
minute: (n) => `${n} 分钟`,
|
||||
second: (n) => `${n} 秒`
|
||||
},
|
||||
// @ts-ignore
|
||||
en: {
|
||||
justNow: 'just now',
|
||||
past: (n) => (n.match(/\d/) ? `${n} ago` : n),
|
||||
future: (n) => (n.match(/\d/) ? `in ${n}` : n),
|
||||
month: (n, past) =>
|
||||
n === 1 ? (past ? 'last month' : 'next month') : `${n} month${n > 1 ? 's' : ''}`,
|
||||
year: (n, past) =>
|
||||
n === 1 ? (past ? 'last year' : 'next year') : `${n} year${n > 1 ? 's' : ''}`,
|
||||
day: (n, past) => (n === 1 ? (past ? 'yesterday' : 'tomorrow') : `${n} day${n > 1 ? 's' : ''}`),
|
||||
week: (n, past) =>
|
||||
n === 1 ? (past ? 'last week' : 'next week') : `${n} week${n > 1 ? 's' : ''}`,
|
||||
hour: (n) => `${n} hour${n > 1 ? 's' : ''}`,
|
||||
minute: (n) => `${n} minute${n > 1 ? 's' : ''}`,
|
||||
second: (n) => `${n} second${n > 1 ? 's' : ''}`
|
||||
}
|
||||
}
|
||||
|
||||
export const useTimeAgo = (time: Date | number | string) => {
|
||||
const localeStore = useLocaleStoreWithOut()
|
||||
|
||||
const currentLocale = computed(() => localeStore.getCurrentLocale)
|
||||
|
||||
const timeAgo = useTimeAgoCore(time, {
|
||||
messages: TIME_AGO_MESSAGE_MAP[unref(currentLocale).lang]
|
||||
})
|
||||
|
||||
return timeAgo
|
||||
}
|
||||
24
src/hooks/web/useTitle.ts
Normal file
24
src/hooks/web/useTitle.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { watch, ref } from 'vue'
|
||||
import { isString } from '@/utils/is'
|
||||
import { useAppStoreWithOut } from '@/store/modules/app'
|
||||
|
||||
const appStore = useAppStoreWithOut()
|
||||
|
||||
export const useTitle = (newTitle?: string) => {
|
||||
const { t } = useI18n()
|
||||
const title = ref(
|
||||
newTitle ? `${appStore.getTitle} - ${t(newTitle as string)}` : appStore.getTitle
|
||||
)
|
||||
|
||||
watch(
|
||||
title,
|
||||
(n, o) => {
|
||||
if (isString(n) && n !== o && document) {
|
||||
document.title = n
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
return title
|
||||
}
|
||||
60
src/hooks/web/useValidator.ts
Normal file
60
src/hooks/web/useValidator.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { useI18n } from '@/hooks/web/useI18n'
|
||||
import { FormItemRule } from 'element-plus'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
interface LengthRange {
|
||||
min: number
|
||||
max: number
|
||||
message?: string
|
||||
}
|
||||
|
||||
export const useValidator = () => {
|
||||
const required = (message?: string): FormItemRule => {
|
||||
return {
|
||||
required: true,
|
||||
message: message || t('common.required')
|
||||
}
|
||||
}
|
||||
|
||||
const lengthRange = (options: LengthRange): FormItemRule => {
|
||||
const { min, max, message } = options
|
||||
|
||||
return {
|
||||
min,
|
||||
max,
|
||||
message: message || t('common.lengthRange', { min, max })
|
||||
}
|
||||
}
|
||||
|
||||
const notSpace = (message?: string): FormItemRule => {
|
||||
return {
|
||||
validator: (_, val, callback) => {
|
||||
if (val?.indexOf(' ') !== -1) {
|
||||
callback(new Error(message || t('common.notSpace')))
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const notSpecialCharacters = (message?: string): FormItemRule => {
|
||||
return {
|
||||
validator: (_, val, callback) => {
|
||||
if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
|
||||
callback(new Error(message || t('common.notSpecialCharacters')))
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
required,
|
||||
lengthRange,
|
||||
notSpace,
|
||||
notSpecialCharacters
|
||||
}
|
||||
}
|
||||
72
src/hooks/web/useWatermark.ts
Normal file
72
src/hooks/web/useWatermark.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useAppStore } from '@/store/modules/app'
|
||||
import { watch } from 'vue'
|
||||
|
||||
const domSymbol = Symbol('watermark-dom')
|
||||
|
||||
export function useWatermark(appendEl: HTMLElement | null = document.body) {
|
||||
let func: Fn = () => {}
|
||||
const id = domSymbol.toString()
|
||||
const appStore = useAppStore()
|
||||
let watermarkStr = ''
|
||||
|
||||
const clear = () => {
|
||||
const domId = document.getElementById(id)
|
||||
if (domId) {
|
||||
const el = appendEl
|
||||
el && el.removeChild(domId)
|
||||
}
|
||||
window.removeEventListener('resize', func)
|
||||
}
|
||||
const createWatermark = (str: string) => {
|
||||
clear()
|
||||
|
||||
const can = document.createElement('canvas')
|
||||
can.width = 300
|
||||
can.height = 240
|
||||
|
||||
const cans = can.getContext('2d')
|
||||
if (cans) {
|
||||
cans.rotate((-20 * Math.PI) / 120)
|
||||
cans.font = '15px Vedana'
|
||||
cans.fillStyle = appStore.getIsDark ? 'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.15)'
|
||||
cans.textAlign = 'left'
|
||||
cans.textBaseline = 'middle'
|
||||
cans.fillText(str, can.width / 20, can.height)
|
||||
}
|
||||
|
||||
const div = document.createElement('div')
|
||||
div.id = id
|
||||
div.style.pointerEvents = 'none'
|
||||
div.style.top = '0px'
|
||||
div.style.left = '0px'
|
||||
div.style.position = 'absolute'
|
||||
div.style.zIndex = '100000000'
|
||||
div.style.width = document.documentElement.clientWidth + 'px'
|
||||
div.style.height = document.documentElement.clientHeight + 'px'
|
||||
div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
|
||||
const el = appendEl
|
||||
el && el.appendChild(div)
|
||||
return id
|
||||
}
|
||||
|
||||
function setWatermark(str: string) {
|
||||
watermarkStr = str
|
||||
createWatermark(str)
|
||||
func = () => {
|
||||
createWatermark(str)
|
||||
}
|
||||
window.addEventListener('resize', func)
|
||||
}
|
||||
|
||||
// 监听主题变化
|
||||
watch(
|
||||
() => appStore.getIsDark,
|
||||
() => {
|
||||
if (watermarkStr) {
|
||||
createWatermark(watermarkStr)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return { setWatermark, clear }
|
||||
}
|
||||
Reference in New Issue
Block a user