refactor(utils): reorganize shared utilities and hooks

This commit is contained in:
XiaoDaiGua-Ray 2026-11-03 14:40:30 +08:00
parent 7f75de4b70
commit 83bada950b
113 changed files with 2485 additions and 2665 deletions

View File

@ -191,6 +191,7 @@ pnpm report
## Hooks、布局与图标
- [工具分包与兼容契约](src/utils/README.md):公共工具入口、边界和回归测试。
- [Hooks 示例与约定](src/hooks/README.md):`/template-hooks`、`/web-hooks`,覆盖 19 个自定义 Hook。
- [布局模式与插槽](src/layout/README.md):`/layout-demo`,可即时调整并保存偏好。
- [分包图标与类型提示](src/icons/A_README.md):`/svg-icons`;使用 `pnpm icons:generate` 与 `pnpm icons:check` 维护名称。

View File

@ -27,3 +27,37 @@ describe('callWithAsyncErrorHandling', () => {
expect(callbackFnExecuted).toBe(2)
})
})
it('handles Promise rejections from both async functions and regular factories', async () => {
const rejected = new Error('rejected')
const callback = vi.fn()
const asyncFn = async () => {
throw rejected
}
const factory = () => Promise.reject(rejected)
await expect(
callWithAsyncErrorHandling(asyncFn, callback),
).resolves.toBeUndefined()
await expect(
callWithAsyncErrorHandling(factory, callback),
).resolves.toBeUndefined()
expect(callback.mock.calls).toEqual([[rejected], [rejected]])
await expect(
callWithAsyncErrorHandling(async () => 42, callback),
).resolves.toBe(42)
})
it('does not invoke the error callback again when the callback throws', async () => {
const failure = new Error('callback failed')
const callback = vi.fn(() => {
throw failure
})
await expect(
callWithAsyncErrorHandling(() => {
throw new Error('original error')
}, callback),
).rejects.toBe(failure)
expect(callback).toHaveBeenCalledTimes(1)
})

View File

@ -1,7 +1,19 @@
import { detectOperatingSystem } from '../../src/utils/basic'
describe('detectOperatingSystem', () => {
it('should return Unknown', () => {
expect(detectOperatingSystem()).toBe('Unknown')
afterEach(() => vi.restoreAllMocks())
it.each([
['Mozilla/5.0 (Linux; Android 14; Pixel 8)', 0, 'Android'],
['Mozilla/5.0 (iPhone; CPU iPhone OS 16_4 like Mac OS X)', 0, 'IOS'],
['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', 5, 'IOS'],
['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', 0, 'MacOS'],
['Mozilla/5.0 (Windows NT 10.0; Win64; x64)', 0, 'Windows'],
['Mozilla/5.0 (X11; Linux x86_64)', 0, 'Linux'],
['Unrecognized', 0, 'Unknown'],
])('classifies %s (%s touch points) as %s', (agent, touchPoints, system) => {
vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue(agent)
vi.spyOn(navigator, 'maxTouchPoints', 'get').mockReturnValue(touchPoints)
expect(detectOperatingSystem()).toBe(system)
})
})

View File

@ -1,33 +1,82 @@
import { downloadAnyFile } from '../../src/utils/basic'
describe('downloadAnyFile', () => {
it('should download data when data is a string', async () => {
const data = 'test data'
const fileName = 'test.txt'
const url = 'blob:test'
await expect(downloadAnyFile(data, fileName)).resolves.toBeUndefined()
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(URL, 'createObjectURL').mockReturnValue(url)
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
})
// it('should download data when data is a ArrayBuffer', () => {
// const data = new ArrayBuffer(8)
// const fileName = 'test.txt'
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
// expect(downloadAnyFile(data, fileName)).resolves.toBeUndefined()
// })
it('requests a Data URL download without allocating an object URL', async () => {
const data = 'data:text/plain;base64,dGVzdA=='
const click = vi
.spyOn(HTMLAnchorElement.prototype, 'click')
.mockImplementation(function (this: HTMLAnchorElement) {
expect(this.href).toBe(data)
expect(this.download).toBe('test.txt')
expect(this.isConnected).toBe(true)
})
// it('should download data when data is a Blob', () => {
// const data = new Blob(['hello', 'world'], {
// type: 'text/plain',
// })
// const fileName = 'test.txt'
await downloadAnyFile(data, 'test.txt')
expect(click).toHaveBeenCalledOnce()
expect(URL.createObjectURL).not.toHaveBeenCalled()
expect(document.querySelector('a[download]')).toBeNull()
})
// expect(downloadAnyFile(data, fileName)).resolves.toBeUndefined()
// })
it.each([
new Blob(['test'], { type: 'text/plain' }),
new File(['test'], 'source.txt'),
new Uint8Array([1, 2, 3, 4]).buffer,
])(
'releases temporary resources after requesting a binary download',
async (data) => {
const click = vi
.spyOn(HTMLAnchorElement.prototype, 'click')
.mockImplementation(function (this: HTMLAnchorElement) {
expect(this.href).toBe(url)
expect(this.download).toBe('copy.txt')
})
// it('should download data when data is a File', () => {
// const data = new File(['hello', 'world'], 'test.txt')
// const fileName = 'test.txt'
await downloadAnyFile(data, 'copy.txt')
const [blob] = vi.mocked(URL.createObjectURL).mock.calls[0]
// expect(downloadAnyFile(data, fileName)).resolves.toBeUndefined()
// })
expect(click).toHaveBeenCalledOnce()
expect(blob).toBeInstanceOf(Blob)
if (data instanceof ArrayBuffer && blob instanceof Blob) {
expect(new Uint8Array(await blob.arrayBuffer())).toEqual(
new Uint8Array(data),
)
} else {
expect(blob).toBe(data)
}
expect(document.querySelector('a[download]')).toBeNull()
expect(URL.revokeObjectURL).not.toHaveBeenCalled()
vi.runAllTimers()
expect(URL.revokeObjectURL).toHaveBeenCalledExactlyOnceWith(url)
},
)
it('rejects invalid input and cleans up the object URL immediately on a click error', async () => {
await expect(downloadAnyFile(42 as never, 'invalid')).rejects.toThrow(
TypeError,
)
expect(URL.createObjectURL).not.toHaveBeenCalled()
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {
throw new Error('click failed')
})
await expect(downloadAnyFile(new Blob(), 'failed')).rejects.toThrow(
'click failed',
)
expect(URL.revokeObjectURL).toHaveBeenCalledExactlyOnceWith(url)
expect(document.querySelector('a[download]')).toBeNull()
})
})

View File

@ -15,3 +15,9 @@ describe('equalRouterPath', () => {
expect(equalRouterPath(p1, p2)).toBe(true)
})
})
it('ignores query, hash and trailing slashes and handles an empty route', () => {
expect(equalRouterPath('/items///?q=1#row', '/items#header')).toBe(true)
expect(equalRouterPath('', '?')).toBe(true)
expect(equalRouterPath('/a', '/aa')).toBe(false)
})

View File

@ -25,9 +25,16 @@ describe('isPromise', () => {
expect(isPromise(fn)).toBe(false)
})
it('should return true if the value is an async function', () => {
it('should distinguishes an async function from its result', () => {
const asyncFn = async () => {}
expect(isPromise(asyncFn)).toBe(true)
expect(isPromise(asyncFn)).toBe(false)
expect(isPromise(asyncFn())).toBe(true)
})
})
it('recognizes thenables without accepting non-callable then properties', () => {
expect(isPromise({ then: vi.fn() })).toBe(true)
expect(isPromise({ then: true })).toBe(false)
expect(isPromise(null)).toBe(false)
})

View File

@ -46,3 +46,10 @@ describe('isValueType', () => {
expect(isValueType<Function>(/a/i, 'Function')).toBe(false)
})
})
it('matches a full tag and treats async functions as functions', () => {
expect(isValueType(new Uint8Array(), 'Array')).toBe(false)
expect(isValueType(new Map(), 'WeakMap')).toBe(false)
expect(isValueType(new WeakMap(), 'Map')).toBe(false)
expect(isValueType(async () => {}, 'Function')).toBe(true)
})

View File

@ -18,3 +18,16 @@ describe('uuid', () => {
expect(uid.length).toBe(36)
})
})
it('enforces the requested radix and rejects invalid bounds', () => {
expect(uuid(16, 1)).toBe('0'.repeat(16))
expect(uuid(24, 10)).toMatch(/^\d{24}$/)
expect(uuid(0)).toBe('')
for (const radix of [0, -1, 63, 1.1, NaN]) {
expect(() => uuid(8, radix)).toThrow(RangeError)
}
expect(() => uuid(-1)).toThrow(RangeError)
expect(() => uuid(Infinity)).toThrow(RangeError)
})

View File

@ -115,3 +115,53 @@ describe('cache utils', () => {
).toBe(false)
})
})
describe('storage failures and namespace boundaries', () => {
beforeEach(() => {
localStorage.clear()
sessionStorage.clear()
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => vi.restoreAllMocks())
it('preserves falsy JSON values and leaves prior data intact on a bad write', () => {
setStorage('test', false)
setStorage('test', void 0)
expect(hasStorage('test')).toBe(true)
expect(getStorage('test')).toBe(false)
expect(console.error).toHaveBeenCalledOnce()
setStorage('test', null)
expect(getStorage('test', void 0, { defaultValue: 'fallback' })).toBeNull()
})
it('uses the fallback for corrupt JSON or an unavailable storage area', () => {
sessionStorage.setItem('broken', 'invalid JSON')
expect(
getStorage('broken', 'sessionStorage', { defaultValue: false }),
).toBe(false)
vi.spyOn(window, 'sessionStorage', 'get').mockImplementation(() => {
throw new DOMException('blocked', 'SecurityError')
})
expect(hasStorage('test')).toBe(false)
expect(getStorage('test', 'sessionStorage', { defaultValue: 7 })).toBe(7)
expect(() => setStorage('test', 'value')).not.toThrow()
expect(() => removeStorage('test', 'sessionStorage')).not.toThrow()
})
it('removes prefixed keys from both stores without clearing adjacent namespaces', () => {
for (const storage of [localStorage, sessionStorage]) {
storage.setItem('test:a', '1')
storage.setItem('test:b', '2')
storage.setItem('test-other:a', '3')
}
removeStorage('__all__', 'all', { prefix: true, prefixKey: 'test:' })
for (const storage of [localStorage, sessionStorage]) {
expect(storage.length).toBe(1)
expect(storage.getItem('test-other:a')).toBe('3')
}
})
})

View File

@ -0,0 +1,91 @@
import { toJpeg } from 'html-to-image'
import print from 'print-js'
import { printDom } from '../../src/utils/dom'
vi.mock('html-to-image', () => ({
toSvg: vi.fn(),
toPng: vi.fn(),
toJpeg: vi.fn(),
toBlob: vi.fn(),
toPixelData: vi.fn(),
toCanvas: vi.fn(),
}))
vi.mock('print-js', () => ({ default: vi.fn() }))
describe('printDom', () => {
const loading = { start: vi.fn(), finish: vi.fn(), error: vi.fn() }
beforeEach(() => {
vi.resetAllMocks()
vi.stubGlobal('$loadingBar', loading)
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('prints the captured JPEG and prevents runtime overrides of printable and type', async () => {
const element = document.createElement('div')
const jpeg = 'data:image/jpeg;base64,test'
const created = vi.fn()
vi.mocked(toJpeg).mockResolvedValue(jpeg)
await expect(
printDom(element, {
printOptions: {
documentTitle: 'Report',
type: 'pdf',
printable: 'other',
} as never,
domToImageOptions: { created, quality: 0.8 },
}),
).resolves.toBe(true)
expect(toJpeg).toHaveBeenCalledExactlyOnceWith(element, { quality: 0.8 })
expect(created).toHaveBeenCalledExactlyOnceWith(jpeg, element)
expect(print).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
documentTitle: 'Report',
type: 'image',
printable: jpeg,
base64: true,
}),
)
expect(loading.start).toHaveBeenCalledOnce()
expect(loading.finish).toHaveBeenCalledOnce()
expect(loading.error).not.toHaveBeenCalled()
})
it('reports capture failure and does not print', async () => {
const error = new Error('cannot capture')
const createdError = vi.fn()
const done = vi.fn()
vi.mocked(toJpeg).mockRejectedValue(error)
await expect(
printDom(document.createElement('div'), {
domToImageOptions: { createdError, finally: done },
}),
).resolves.toBe(false)
expect(createdError).toHaveBeenCalledWith(error)
expect(done).toHaveBeenCalledOnce()
expect(print).not.toHaveBeenCalled()
expect(loading.error).toHaveBeenCalledOnce()
expect(loading.finish).not.toHaveBeenCalled()
})
it('reports synchronous print failures', async () => {
vi.mocked(toJpeg).mockResolvedValue('data:image/jpeg;base64,test')
vi.mocked(print).mockImplementation(() => {
throw new Error('print refused')
})
await expect(printDom(document.createElement('div'))).resolves.toBe(false)
expect(loading.error).toHaveBeenCalledOnce()
expect(loading.finish).not.toHaveBeenCalled()
})
})

View File

@ -1,49 +0,0 @@
import { mount } from '@vue/test-utils'
import { printDom } from '../../src/utils/dom'
import renderHook from '../utils/renderHook'
// happy-dom 官方有一个 bug,无法使用 canvas.toDataURL 方法。所以该模块单测暂时无法通过
describe('printDom', () => {
// let count = 1
// const domRef = ref<HTMLElement>()
// const canvas = document.createElement('canvas')
// canvas.width = 100
// canvas.height = 100
// console.log('canvas.toDataURL result', canvas.toDataURL)
// const wrapper = mount(
// defineComponent({
// setup() {
// const print = () => {
// count = 2
// printDom(canvas, {
// domToImageOptions: {
// created: () => {
// count = 2
// },
// },
// })
// }
// return {
// domRef,
// print,
// }
// },
// render() {
// const { print } = this
// return (
// <>
// <div ref="domRef">print html</div>
// <button onClick={print.bind(this)}>print</button>
// </>
// )
// },
// }),
// )
// it('print dom', () => {
// const button = wrapper.find('button')
// button.trigger('click')
// expect(count).toBe(2)
// })
it('print dom', () => {})
})

View File

@ -66,3 +66,32 @@ describe('setClass', () => {
expect(classList.includes(CLASS_NAME)).toBe(false)
})
})
it('uses exact class tokens on SVG, clears all classes, and follows target replacement', async () => {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
const target = shallowRef<Element | null>(svg)
const scope = effectScope()
try {
setClass(svg, 'foo-bar\tready\nactive')
expect(hasClass(svg, 'foo').value).toBe(false)
expect(hasClass(svg, ['miss', 'ready']).value).toBe(true)
removeClass(svg, 'removeAllClass')
expect(svg.classList.length).toBe(0)
scope.run(() => setClass(target, 'selected'))
expect(svg.classList.contains('selected')).toBe(true)
const div = document.createElement('div')
target.value = div
await nextTick()
expect(div.classList.contains('selected')).toBe(true)
scope.stop()
const replacement = document.createElement('div')
target.value = replacement
await nextTick()
expect(replacement.classList.contains('selected')).toBe(false)
} finally {
scope.stop()
}
})

View File

@ -21,3 +21,9 @@ describe('colorToRgba', () => {
expect(colorToRgba('hi')).toBe('hi')
})
})
it('handles shorthand alpha, whitespace, uppercase colors, and invalid hex', () => {
expect(colorToRgba('#F008', 0.1)).toBe('rgba(255, 0, 0, 0.53)')
expect(colorToRgba(' RGB(1, 2, 3) ', 0.6)).toBe('rgba(1, 2, 3, 0.6)')
expect(colorToRgba('#XYZ', 0.5, 'fallback')).toBe('fallback')
})

View File

@ -15,3 +15,11 @@ describe('completeSize', () => {
expect(completeSize(0)).toBe('0px')
})
})
it('only adds a unit to numbers and preserves valid CSS expressions and keywords', () => {
expect(completeSize(' 12.5 ', 'rem')).toBe('12.5rem')
expect(completeSize('-.5')).toBe('-.5px')
expect(completeSize('calc(100% - 2rem)')).toBe('calc(100% - 2rem)')
expect(completeSize('var(--card-width)')).toBe('var(--card-width)')
expect(completeSize('fit-content')).toBe('fit-content')
})

View File

@ -69,3 +69,23 @@ describe('setStyle', () => {
expect(style.height).toBe('100px')
})
})
it('keeps existing styles, parses complete CSS values, and removes camelCase names', () => {
const element = document.createElement('div')
element.style.color = 'red'
setStyle(element, { zIndex: 3, '--Token': 'large' })
expect(element.style.zIndex).toBe('3')
expect(element.style.getPropertyValue('--Token')).toBe('large')
setStyle(
element,
'width: 20px !important; background-image: url("https://example.test/a:b");',
)
expect(element.style.color).toBe('red')
expect(element.style.getPropertyPriority('width')).toBe('important')
expect(element.style.backgroundImage).toContain('https://example.test/a:b')
removeStyle(element, ['zIndex', '--Token', 'backgroundImage'])
expect(element.style.zIndex).toBe('')
expect(element.style.getPropertyValue('--Token')).toBe('')
expect(element.style.backgroundImage).toBe('')
})

View File

@ -1,42 +1,71 @@
import { createMemoryHistory, createRouter } from 'vue-router'
import { useAppNavigation } from '../../src/hooks/template/useAppNavigation'
import type { AppMenuOption } from '../../src/types'
const { push, replace, menus } = vi.hoisted(() => ({
push: vi.fn().mockResolvedValue(void 0),
replace: vi.fn().mockResolvedValue(void 0),
const { state, menus } = vi.hoisted(() => ({
state: { router: void 0 as ReturnType<typeof createRouter> | undefined },
menus: [{ fullPath: '/parent', children: [{ fullPath: '/target' }] }],
}))
vi.mock('../../src/hooks', () => ({
useVueRouter: () => ({
router: { push, replace, getRoutes: () => [{ path: '/target' }] },
}),
vi.mock('../../src/hooks/template/useVueRouter', () => ({
useVueRouter: () => ({ router: state.router }),
}))
vi.mock('../../src/store', () => ({
useMenuGetters: () => ({ getMenuOptions: { value: menus } }),
}))
describe('useAppNavigation', () => {
beforeEach(() => vi.clearAllMocks())
it('returns the navigation promise and supports paths, menu objects and indices', async () => {
const { navigationTo } = useAppNavigation()
expect(navigationTo('/target')).toBeInstanceOf(Promise)
await navigationTo(0)
expect(push).toHaveBeenLastCalledWith({ path: '/target', query: void 0 })
await navigationTo('/target', { isPush: false, query: { from: 'demo' } })
expect(replace).toHaveBeenCalledWith({
path: '/target',
query: { from: 'demo' },
beforeEach(() => {
state.router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/target', component: {} },
{ path: '/items/:id', component: {} },
{ path: '/:catchAll(.*)', component: {} },
],
})
})
it.each([-1, NaN, Infinity, 0.5, 1])('ignores invalid index %s', (index) => {
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
afterEach(() => vi.restoreAllMocks())
expect(() => useAppNavigation().navigationTo(index)).not.toThrow()
expect(push).not.toHaveBeenCalled()
expect(warning).toHaveBeenCalled()
warning.mockRestore()
it('returns the navigation promise and supports indices and menu objects', async () => {
const { navigationTo } = useAppNavigation()
const pending = navigationTo(0)
expect(pending).toBeInstanceOf(Promise)
await pending
expect(state.router?.currentRoute.value.path).toBe('/target')
await navigationTo({ fullPath: '/items/4' } as AppMenuOption)
expect(state.router?.currentRoute.value.path).toBe('/items/4')
})
it('resolves a dynamic path and preserves URL query and hash when replacing', async () => {
const replace = vi.spyOn(state.router!, 'replace')
await useAppNavigation().navigationTo('/items/8?source=url&keep=1#header', {
isPush: false,
query: { source: 'option' },
})
expect(replace).toHaveBeenCalledOnce()
expect(state.router?.currentRoute.value).toMatchObject({
path: '/items/8',
params: { id: '8' },
query: { source: 'option', keep: '1' },
hash: '#header',
})
})
it.each([-1, NaN, Infinity, 0.5, 1, '/unknown'])(
'ignores invalid target %s',
(target) => {
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
const push = vi.spyOn(state.router!, 'push')
expect(useAppNavigation().navigationTo(target)).toBeUndefined()
expect(push).not.toHaveBeenCalled()
expect(warning).toHaveBeenCalledOnce()
},
)
})

View File

@ -1,6 +1,7 @@
import { useBadge } from '../../src/hooks/template/useBadge'
import type { AppMenuExtraOptions } from '../../src/router/types'
import { useMenuGetters } from '../../src/store'
import { depthSearchAppMenu, useMenuGetters } from '../../src/store'
import type { AppMenuOption } from '../../src/types'
import setupMiniApp from '../utils/setupMiniApp'
describe('useBadge', async () => {
@ -73,4 +74,39 @@ describe('useBadge', async () => {
update(dashboard, { label: 'Changed while visible' })
expect(dashboard.meta.extra?.show).toBe(true)
})
it('updates the badge of a nested menu item by path', () => {
const parent = getMenuOptions.value.find((item) => item.children?.length)
const leaf = parent?.children?.[0]
expect(leaf).toBeDefined()
if (!leaf) return
const previous = leaf.meta.extra
show(leaf.fullPath, { label: 'Nested badge' })
expect(leaf.meta.extra).toMatchObject({ label: 'Nested badge', show: true })
update(leaf, { show: previous?.show ?? false, label: previous?.label })
})
})
it('finds nested menu items in the supplied tree instead of returning a stale cached match', () => {
const item = (path: string) => ({
name: path,
label: path,
key: path,
fullPath: path,
path,
meta: {},
})
const first = item('/nested')
const second = item('/nested')
const tree = (leaf: AppMenuOption) => [
{ ...item('/branch'), children: [leaf] },
{ ...item('/later'), children: [item('/nested')] },
]
expect(depthSearchAppMenu(tree(first), '/nested?query=yes')).toBe(first)
expect(depthSearchAppMenu(tree(second), '/nested')).toBe(second)
expect(depthSearchAppMenu(tree(second), '/missing')).toBeUndefined()
})

View File

@ -61,3 +61,37 @@ describe('useContextmenuCoordinate', () => {
app.unmount()
})
})
it('honors the outside handler, prevents the native menu and cannot reopen after disposal', async () => {
const target = document.createElement('div')
const outside = document.createElement('button')
document.body.append(target, outside)
const clickOutside = vi.fn()
const [menu, app] = renderHook(() =>
useContextmenuCoordinate(target, { clickOutside, passive: true }),
)
try {
const event = new MouseEvent('contextmenu', {
cancelable: true,
clientX: 14,
})
target.dispatchEvent(event)
await nextTick()
expect(event.defaultPrevented).toBe(true)
expect(menu.show.value).toBe(true)
outside.dispatchEvent(new MouseEvent('click', { bubbles: true }))
await nextTick()
expect(clickOutside).toHaveBeenCalledOnce()
expect(menu.show.value).toBe(false)
menu.stop()
menu.updateShow(true)
expect(menu.show.value).toBe(false)
} finally {
app.unmount()
target.remove()
outside.remove()
}
})

View File

@ -1,4 +1,5 @@
import dayjs from 'dayjs'
import { DEFAULT_DAYJS_LOCAL } from '../../src/app-config'
import { useDayjs } from '../../src/hooks/web/useDayjs'
describe('useDayjs', () => {
@ -11,16 +12,19 @@ describe('useDayjs', () => {
isDateInRange,
} = useDayjs()
it('check whether the locale method runs properly', () => {
const m = {
locale,
it('switches the global Day.js locale and falls back for unrecognized keys', () => {
const previous = dayjs.locale()
try {
locale('zh-CN')
expect(dayjs.locale()).toBe('zh-cn')
locale('en-US')
expect(dayjs.locale()).toBe('en')
locale('unsupported' as never)
expect(dayjs.locale()).toBe(DEFAULT_DAYJS_LOCAL)
} finally {
dayjs.locale(previous)
}
const localSpy = vi.spyOn(m, 'locale')
m.locale('en-US')
m.locale('zh-CN')
expect(localSpy).toHaveBeenCalledTimes(2)
})
it('gets Returns the current date, start time, and end time of the current date ', () => {

View File

@ -114,3 +114,40 @@ describe('useDevice', () => {
expect(isTabletOrSmaller.value).toBe(true)
})
})
it('observes changes at the custom breakpoint and stops after scope disposal', async () => {
const before = window.innerWidth
const scope = effectScope()
const unrelated = ref(0)
const observer = vi.fn(() => unrelated.value)
window.innerWidth = 640
try {
const state = scope.run(() => useDevice({ media: 640, observer }))!
await nextTick()
expect(state.isTabletOrSmaller.value).toBe(true)
expect(observer).toHaveBeenLastCalledWith(true, {
width: 640,
height: window.innerHeight,
})
observer.mockClear()
unrelated.value += 1
await nextTick()
expect(observer).not.toHaveBeenCalled()
window.innerWidth = 641
window.dispatchEvent(new Event('resize'))
await nextTick()
expect(state.isTabletOrSmaller.value).toBe(false)
scope.stop()
observer.mockClear()
window.dispatchEvent(new Event('resize'))
await nextTick()
expect(observer).not.toHaveBeenCalled()
} finally {
scope.stop()
window.innerWidth = before
}
})

View File

@ -68,3 +68,21 @@ describe('useDomToImage', () => {
expect(finished).toHaveBeenCalledTimes(1)
})
})
it('notifies errors and cleanup even if the target getter throws', async () => {
const createdError = vi.fn()
const done = vi.fn()
const { create } = useDomToImage(
() => {
throw 'getter failed'
},
{
createdError,
finally: done,
},
)
await expect(create()).rejects.toThrow('getter failed')
expect(createdError).toHaveBeenCalledWith(expect.any(Error))
expect(done).toHaveBeenCalledExactlyOnceWith(void 0)
})

View File

@ -97,3 +97,31 @@ describe('useElementFullscreen', () => {
expect(div.style.position).toBe('')
})
})
it('restores original style priority and releases ownership even when manual exit is vetoed', () => {
const element = document.createElement('div')
element.style.setProperty('width', '240px', 'important')
element.setAttribute('data-element-fullscreen', 'prior')
const scope = effectScope()
const first = scope.run(() =>
useElementFullscreen(element, {
beforeExit: () => {
throw new Error('veto')
},
}),
)!
const second = useElementFullscreen(element)
first.enter()
second.enter()
expect(second.isFullscreen.value).toBe(false)
expect(first.exit).toThrow('veto')
scope.stop()
expect(element.style.width).toBe('240px')
expect(element.style.getPropertyPriority('width')).toBe('important')
expect(element.getAttribute('data-element-fullscreen')).toBe('prior')
second.enter()
expect(second.isFullscreen.value).toBe(true)
second.exit()
})

View File

@ -56,3 +56,16 @@ describe('useI18n namespaces', () => {
expect(hook.t('code')).toBe('updated:hooks.code')
})
})
it('forwards interpolation and leaves plain text and route keys untouched', async () => {
const native = vi.fn((key: string) => `translated:${key}`)
state.instance!.global.t = native
const { t: translate } = useI18n()
const { t } = await import('../../src/hooks/template/useI18n')
expect(translate('Already readable')).toBe('Already readable')
expect(t('menu.Dashboard')).toBe('menu.Dashboard')
expect(translate('hooks.count', { count: 2 })).toBe('translated:hooks.count')
expect(native).toHaveBeenCalledExactlyOnceWith('hooks.count', { count: 2 })
})

View File

@ -24,3 +24,28 @@ it('shares maximize state across callers and cancels stale completion callbacks'
disposePinia(pinia)
}
})
it('runs only the last completion after an enter-exit-enter sequence', async () => {
const pinia = createPinia()
setActivePinia(pinia)
try {
const obsolete = vi.fn()
const exit = vi.fn()
const current = vi.fn()
const page = useMaximize()
const toolbar = useMaximize()
page.maximize(true, { enter: obsolete })
toolbar.maximize(false, { exit })
page.maximize(true, { enter: current })
await nextTick()
expect(obsolete).not.toHaveBeenCalled()
expect(exit).not.toHaveBeenCalled()
expect(current).toHaveBeenCalledOnce()
} finally {
disposePinia(pinia)
}
})

View File

@ -64,3 +64,33 @@ describe('usePagination', () => {
expect(count).toBe(2)
})
})
it('resets to the first object page size and reports new values to the current callbacks', () => {
const pageChange = vi.fn()
const pageSizeChange = vi.fn()
const oldCallback = vi.fn()
const callback = vi.fn()
const [pagination, api] = usePagination(oldCallback, {
page: 5,
pageSize: 10,
pageSizes: [{ label: 'Fifteen', value: 15 }],
pageChange,
pageSizeChange,
})
expect(api.getCallback()).toBe(oldCallback)
api.setCallback(callback)
api.resetPagination()
expect(api.getPagination()).toBe(pagination.value)
expect(api.getPage()).toBe(1)
expect(api.getPageSize()).toBe(15)
expect(pageChange).toHaveBeenCalledExactlyOnceWith(1)
expect(pageSizeChange).toHaveBeenCalledExactlyOnceWith(15)
expect(callback).toHaveBeenCalledOnce()
expect(oldCallback).not.toHaveBeenCalled()
api.setCallback()
api.setPage(2)
expect(api.getCallback()).toBeUndefined()
expect(callback).toHaveBeenCalledOnce()
})

View File

@ -0,0 +1,44 @@
import print from 'print-js'
import { usePrint } from '../../src/hooks/web/usePrint'
vi.mock('print-js', () => ({ default: vi.fn() }))
beforeEach(() => vi.clearAllMocks())
it('skips a missing target and prints the latest element in html mode', () => {
const target = ref<HTMLElement>()
const printer = usePrint(target)
printer.print()
expect(print).not.toHaveBeenCalled()
target.value = document.createElement('div')
printer.print()
expect(print).toHaveBeenCalledExactlyOnceWith({
printable: target.value,
type: 'html',
})
})
it('uses the caller’s print mode but never accepts a second printable value', () => {
const printer = usePrint('/report.pdf', {
printable: '/wrong.pdf',
type: 'pdf',
} as never)
printer.print()
expect(print).toHaveBeenCalledExactlyOnceWith({
printable: '/report.pdf',
type: 'pdf',
})
})
it('converts binary PDF and image targets to the payloads print-js expects', async () => {
await usePrint(new Uint8ClampedArray([1, 2, 3])).print()
await usePrint(new Blob(['abc'], { type: 'image/png' })).print()
expect(vi.mocked(print).mock.calls).toEqual([
[{ printable: 'AQID', base64: true, type: 'pdf' }],
[{ printable: 'data:image/png;base64,YWJj', base64: false, type: 'image' }],
])
})

View File

@ -1,3 +1,4 @@
import { useAppRoot } from '../../src/hooks/template/useAppRoot'
import { useSiderBar } from '../../src/hooks/template/useSiderBar'
import { useVueRouter } from '../../src/hooks/web/useVueRouter'
import { useMenuActions, useMenuGetters } from '../../src/store'
@ -163,4 +164,21 @@ describe('useSiderBar', async () => {
expect(checkCloseRight(s.fullPath)).toBe(true)
expect(checkCloseLeft(s.fullPath)).toBe(true)
})
it('keeps existing tags if the configured home route is no longer registered', () => {
updateMenuTagOptions()
const { getMenuTagOptions } = useMenuGetters()
const { getRootRoute, setRootRoute } = useAppRoot()
const currentRoot = { ...getRootRoute.value }
const currentTags = getMenuTagOptions.value.map((item) => item.fullPath)
try {
setRootRoute({ path: '/deleted-home-route' })
closeAll()
expect(getMenuTagOptions.value.map((item) => item.fullPath)).toEqual(
currentTags,
)
} finally {
setRootRoute(currentRoot)
}
})
})

View File

@ -1,10 +1,12 @@
import { useTheme } from '../../src/hooks/template/useTheme'
import { useSettingGetters } from '../../src/store'
import setupMiniApp from '../utils/setupMiniApp'
describe('useTheme', async () => {
await setupMiniApp()
const { darkTheme, lightTheme, toggleTheme, getAppTheme } = useTheme()
const { darkTheme, lightTheme, toggleTheme, getAppTheme, syncSystemTheme } =
useTheme()
it('should change to dark theme', () => {
darkTheme()
@ -43,4 +45,19 @@ describe('useTheme', async () => {
expect(__lightTheme).toBe(false)
expect(__lightThemeLabel).toBe('Light')
})
it('selects auto mode and applies the system color preference', () => {
const spy = vi
.spyOn(window, 'matchMedia')
.mockReturnValue({ matches: true } as MediaQueryList)
try {
syncSystemTheme()
expect(getAppTheme()).toMatchObject({ theme: true, themeLabel: 'Dark' })
expect(useSettingGetters().getAppThemeStr.value).toBe('auto')
} finally {
lightTheme()
spy.mockRestore()
}
})
})

View File

@ -1,15 +1,22 @@
import { useVueRouter } from '../../src/hooks/web/useVueRouter'
import setupMiniApp from '../utils/setupMiniApp'
import { router } from '../../src/router'
describe('useVueRouter', async () => {
await setupMiniApp()
it('shares the live router outside setup and exposes the current route after navigation', async () => {
const a = useVueRouter()
const b = useVueRouter()
const remove = router.addRoute({ path: '/router-hook-test', component: {} })
const { router } = useVueRouter()
it('should get push and replace methods', () => {
const { push, replace } = router
assert.isFunction(push)
assert.isFunction(replace)
})
try {
expect(a.router).toBe(router)
expect(b.router.currentRoute).toBe(a.router.currentRoute)
await a.router.push('/router-hook-test?source=spec')
expect(b.router.currentRoute.value).toMatchObject({
path: '/router-hook-test',
query: { source: 'spec' },
})
await b.router.replace('/router-hook-test?source=replace')
expect(a.router.currentRoute.value.query.source).toBe('replace')
} finally {
remove()
}
})

View File

@ -80,3 +80,28 @@ describe('precision', () => {
expect(distribute(add(20, 1), 3)).toEqual([7, 7, 7])
})
})
it('handles empty, single and mixed input without losing input order', () => {
for (const operation of [add, subtract, multiply, divide]) {
expect(operation().value).toBe(0)
expect(operation('1.125').value).toBe(1.125)
}
expect(multiply(add(1, 1), add(1, 2), '0.5').value).toBe(3)
expect(divide(24, 3, 2).value).toBe(4)
expect(subtract(20, 3, 2).value).toBe(15)
expect(() => divide(1, 0)).toThrow(RangeError)
})
it('preserves signed remainders, formats one portion, and rejects invalid counts', () => {
expect(distribute(-10, 3, { precision: 2 })).toEqual([-3.34, -3.33, -3.33])
expect(distribute('2.1', 1, { precision: 2, type: 'string' })).toEqual([
'2.10',
])
expect(distribute(0, 2, { precision: 2, type: 'string' })).toEqual([
'0.00',
'0.00',
])
expect(() => distribute(1, 1.5)).toThrow(RangeError)
expect(() => distribute(1, Infinity)).toThrow(RangeError)
})

View File

@ -0,0 +1,33 @@
import { fileToBase64 } from '../../src/utils/files'
it('encodes a file with its MIME type and preserves raw byte values', async () => {
const file = new File([new Uint8Array([0, 128, 255])], 'binary', {
type: 'application/octet-stream',
})
await expect(fileToBase64(file)).resolves.toBe(
'data:application/octet-stream;base64,AID/',
)
})
it.each(['error', 'abort'] as const)(
'rejects when FileReader emits %s',
async (event) => {
const error = new DOMException('failed', 'NotReadableError')
const read = vi
.spyOn(FileReader.prototype, 'readAsDataURL')
.mockImplementation(function (this: FileReader) {
Object.defineProperty(this, 'error', { value: error })
this.dispatchEvent(new Event(event))
})
try {
const promise = fileToBase64(new File([], 'test'))
if (event === 'error') await expect(promise).rejects.toBe(error)
else await expect(promise).rejects.toMatchObject({ name: 'AbortError' })
} finally {
read.mockRestore()
}
},
)

View File

@ -0,0 +1,45 @@
import { AES, enc } from 'crypto-js'
import { decrypt, encrypt } from '../../src/utils/legacy-crypto'
describe('legacy AES JSON format', () => {
afterEach(() => vi.restoreAllMocks())
it('reads a fixed legacy OpenSSL ciphertext and writes compatible passphrase data', () => {
const ciphertext =
'U2FsdGVkX18AAQIDBAUGBy60iFpMmTEA+nDHjARaQ1CAs63rZpKJyAVJoCv34SKp'
const key = 'test-passphrase'
const value = { name: 'Ray', active: true }
expect(decrypt(ciphertext, key)).toEqual(value)
expect(
JSON.parse(AES.decrypt(encrypt(value, key), key).toString(enc.Utf8)),
).toEqual(value)
expect(decrypt(encrypt({ text: '旧缓存' }))).toEqual({ text: '旧缓存' })
})
it('writes a unique IV per raw key encryption and accepts direct CipherParams', () => {
const key = enc.Hex.parse('00112233445566778899aabbccddeeff')
const value = { entries: [0, false, null, '中文'] }
const first = encrypt(value, key)
const second = encrypt(value, key)
expect(first).toMatch(/^[0-9a-f]{32}:/)
expect(first.split(':')[0]).not.toBe(second.split(':')[0])
expect(decrypt(first, key)).toEqual(value)
const iv = enc.Hex.parse('000102030405060708090a0b0c0d0e0f')
expect(
decrypt(AES.encrypt(JSON.stringify(value), key, { iv }), key),
).toEqual(value)
})
it('rejects unserializable input and returns undefined for corrupt ciphertext', () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => encrypt(void 0)).toThrow(TypeError)
expect(decrypt('corrupt', 'test-passphrase')).toBeUndefined()
expect(
decrypt('no iv', enc.Hex.parse('00112233445566778899aabbccddeeff')),
).toBeUndefined()
expect(console.error).toHaveBeenCalledTimes(2)
})
})

View File

@ -0,0 +1,53 @@
import { getDateByNaiveDatePicker } from '../../src/utils/get-date-by-naive-date-picker'
import { removeDuplicateKeys } from '../../src/utils/remove-duplicate-keys'
import { updateObjectValue } from '../../src/utils/update-object-value'
it('copies only own enumerable keys and preserves Symbol and __proto__ data', () => {
const symbol = Symbol('meta')
const input = { ['__proto__']: { inert: true }, [symbol]: 42 }
const result = removeDuplicateKeys(input)
expect(result).not.toBe(input)
expect(result).toEqual(input)
expect(Object.getPrototypeOf(result)).toBe(Object.prototype)
expect(Object.hasOwn(result, '__proto__')).toBe(true)
})
it('updates only own properties, shallow merges plain objects, and preserves class values', () => {
class Sample {
constructor(readonly id: number) {}
}
const value = Object.assign(
Object.create({ inherited: 1 }) as {
inherited: number
plain: { a: number; b?: number }
sample: Sample
count: number
},
{ plain: { a: 1 }, sample: new Sample(1), count: 1 },
)
const callback = vi.fn()
const sample = new Sample(2)
updateObjectValue(value, 'inherited', 9, callback)
expect(Object.hasOwn(value, 'inherited')).toBe(false)
expect(callback).not.toHaveBeenCalled()
updateObjectValue(value, 'plain', { a: 2, b: 3 }, callback)
updateObjectValue(value, 'plain', { a: 4 }, callback)
updateObjectValue(value, 'sample', sample, callback)
updateObjectValue(value, 'count', 0, callback)
expect(value.plain).toEqual({ a: 4, b: 3 })
expect(value.sample).toBe(sample)
expect(value.count).toBe(0)
expect(callback).toHaveBeenCalledTimes(4)
})
it('represents cleared ranges as two null endpoints and preserves epoch values', () => {
expect(getDateByNaiveDatePicker(null, true)).toEqual([null, null])
expect(getDateByNaiveDatePicker(null, false)).toBeNull()
expect(getDateByNaiveDatePicker(0, false)).toBe(0)
const range: [number, number] = [0, 10]
expect(getDateByNaiveDatePicker(range, true)).toBe(range)
})

View File

@ -0,0 +1,53 @@
import { mount } from '@vue/test-utils'
import { effectScope, h, nextTick, ref } from 'vue'
import { unrefElement } from '../../src/utils/vue/unref-element'
import { watchEffectWithTarget } from '../../src/utils/vue/watch-effect-with-target'
it('unwraps elements and component roots consistently across refs and getters', () => {
const div = document.createElement('div')
const fallback = document.createElement('main')
const wrapper = mount({ render: () => h('section') })
try {
expect(unrefElement(div)).toBe(div)
expect(unrefElement(() => div)).toBe(div)
expect(unrefElement(ref(div))).toBe(div)
expect(unrefElement(null, fallback)).toBe(fallback)
expect(unrefElement(ref(null), fallback)).toBe(fallback)
expect(unrefElement(() => null, fallback)).toBe(fallback)
expect(unrefElement(wrapper.vm)).toBe(wrapper.element)
expect(unrefElement(() => wrapper.vm)).toBe(wrapper.element)
expect(unrefElement(ref(wrapper.vm))).toBe(wrapper.element)
} finally {
wrapper.unmount()
}
})
it('returns a stop handle and cleans up a watch on both explicit stop and scope disposal', async () => {
const value = ref(1)
const effect = vi.fn()
const cleanup = vi.fn()
const scope = effectScope()
const run = () =>
watchEffectWithTarget((onCleanup) => {
effect(value.value)
onCleanup(cleanup)
})
const stop = run()
expect(effect).toHaveBeenLastCalledWith(1)
stop()
expect(cleanup).toHaveBeenCalledTimes(1)
const scoped = scope.run(run)
expect(scoped).toBeTypeOf('function')
value.value = 2
await nextTick()
expect(effect).toHaveBeenLastCalledWith(2)
scope.stop()
value.value = 3
await nextTick()
expect(effect.mock.calls).toEqual([[1], [1], [2]])
expect(cleanup).toHaveBeenCalledTimes(3)
})

View File

@ -25,3 +25,30 @@ describe('call', () => {
expect(fn).toHaveBeenCalledWith(1, 2)
})
})
it('forwards variadic arguments in order and stops when a callback throws', () => {
const first = vi.fn(
(_a: number, _b: string, _c: boolean, _d: null, _e: number) => {},
)
const error = new Error('stop')
const last = vi.fn()
expect(() =>
call(
[
first,
() => {
throw error
},
last,
],
1,
'a',
false,
null,
2,
),
).toThrow(error)
expect(first).toHaveBeenCalledExactlyOnceWith(1, 'a', false, null, 2)
expect(last).not.toHaveBeenCalled()
})

View File

@ -12,3 +12,12 @@ describe('renderNode', () => {
expect(text).toBe('hello world')
})
})
it('renders numbers and empty text without falling back', () => {
const fallback = h('span', 'fallback')
expect(renderNode(0, { defaultElement: fallback })()).toBe(0)
expect(renderNode('', { defaultElement: fallback })()).toBe('')
expect(renderNode(42)()).toBe(42)
expect(renderNode(null, { defaultElement: fallback })()).toBe(fallback)
})

View File

@ -19,6 +19,7 @@ Ray Template 是前端中后台模板,包含可运行的组件与路由示例
| 演示接口 | `mock/demo`、`mock/shared` | `vite-plugin-mock-dev-server`,生产环境按实际后端切换 |
| 通用组件 | `src/components/base`、`src/components/pro` | 组件、props、types、hook、样式放在同一功能目录 |
| 模板绑定组件 | `src/app-components` | [组件说明](../src/app-components/README.md) |
| 公共工具 | `src/utils` | [分包、兼容入口和测试](../src/utils/README.md) |
| 组合式函数 | `src/hooks/web`、`template`、`components` | [19 个 Hook 的示例与生命周期](../src/hooks/README.md),回归测试在 `__test__/hooks` |
| 国际化 | `src/locales/lang`、`src/hooks/web/useI18n.ts` | [国际化说明](../src/locales/README.md),中文和英文成对维护 |
| 主题与全局样式 | `src/app-config/design-config.ts`、`src/styles` | 保留 CSS 变量和 Naive UI 明暗主题配置 |
@ -33,7 +34,7 @@ Ray Template 是前端中后台模板,包含可运行的组件与路由示例
- `src/app-config` 管理模板配置。运行时 `__APP_CFG__` 由 Vite 注入;`__DEV__` 表示 development 模式。
- 路径别名 `@`、`@api`、`@images`、`@mock` 在 Vite 和 TypeScript 中必须一致。
- `src/store/hooks` 是已有业务对 Store 的访问层;所有全局可变 UI 状态统一归入 Pinia:临时状态由 `runtime` 管理且不持久化,布局偏好在 `setting.layoutConfig` 中沿用原缓存 key。
- `src/utils/c` 仍使用 CryptoJS 4.2.0 的同步 AES 格式。改用 Web Crypto 前需设计异步接口和历史密文迁移,不能直接替换并让既有数据无法解密。
- `src/utils/legacy-crypto`(原 `src/utils/c`)仍使用 CryptoJS 4.2.0 的同步 AES 格式。改用 Web Crypto 前需设计异步接口和历史密文迁移,不能直接替换并让既有数据无法解密。
- 演示页与业务组件同样属于模板能力。删除 demo 或更换第三方库前需要明确任务范围;升级工具链时应保留示例功能。
布局模式、配置与插槽见 [布局说明](../src/layout/README.md)。图标按包生成独立雪碧图,完整名称和严格类型由 `scripts/icons.mjs` 统一生成。

View File

@ -1,5 +1,5 @@
import './index.scss'
import { completeSize, isValueType, renderNode } from '@/utils'
import { completeSize, isValueType } from '@/utils'
import { NFlex, NPopover, NTab, NTabs } from 'naive-ui'
import type { TabsProps } from 'naive-ui'
import { themeOverrides } from './constant'
@ -12,7 +12,7 @@ const iconSegmentTab = (option: RSegmentOptions) => {
if (icon) {
return (
<NFlex align="center" wrap={false} size="small">
{renderNode(icon)?.()}
{typeof icon === 'function' ? icon() : icon}
<div>{label}</div>
</NFlex>
)

View File

@ -3,7 +3,7 @@ import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { APP_CATCH_KEY, DAYJS_LOCAL_MAP } from '@/app-config'
import type { SettingState } from '@/store/modules/setting/types'
import { getStorage } from '@/utils'
import { getStorage } from '@/utils/cache'
/**
*
@ -13,15 +13,12 @@ import { getStorage } from '@/utils'
* 初始化 dayjs 的语言环境。
*/
export const setupDayjs = () => {
const { localeLanguage } = getStorage<SettingState>(
const setting = getStorage<SettingState>(
APP_CATCH_KEY.appPiniaSettingStore,
'localStorage',
{
defaultValue: {} as SettingState,
},
)
const local =
DAYJS_LOCAL_MAP[localeLanguage as keyof typeof DAYJS_LOCAL_MAP] ||
DAYJS_LOCAL_MAP[setting?.localeLanguage as keyof typeof DAYJS_LOCAL_MAP] ||
DEFAULT_DAYJS_LOCAL
dayjs.locale(local)

View File

@ -1,28 +1,28 @@
# Hooks 示例与约定
所有自定义 Hook 从 `@/hooks` 导出。页面使用 Vue 3 Composition API + TSX;每个演示包含实际交互、响应式结果和可展开复制的用法代码。
共享 Hook 从 `@/hooks` 导出。内部调用优先按职责导入:`template` 依赖模板运行时,`components` 与组件契约配套,`web` 处理窗口、日期、截图和打印等能力。旧的 `web/useI18n`、`web/useVueRouter`、`web/usePagination` 入口继续转发。页面使用 Vue 3 Composition API + TSX;每个演示包含实际交互、响应式结果和可展开复制的用法代码。
| 分包 | Hook | 示例页面与操作 |
| ---------- | -------------------------- | ------------------------------------------------------------------------------- |
| template | `useTheme` | `/template-hooks`:明暗、切换、跟随系统 |
| template | `useSpinning` | `/template-hooks`:加载动画、重新挂载页面 |
| template | `useMaximize` | `/template-hooks`:内容最大化、共享退出按钮、Esc |
| template | `useBadge` | `/template-hooks`:菜单标记文本、图标与显隐 |
| template | `useWatermark` | `/template-hooks`:文本、显示、隐藏与切换 |
| template | `useAppNavigation` | `/template-hooks`:完整路径、索引、嵌套菜单与 query |
| template | `useAppRoot` | `/template-hooks`:读取首页、设置本页与恢复仪表盘 |
| template | `useSiderBar` | `/template-hooks`:按路径关闭标签与左右/其他/全部标签 |
| template | `useContentScroll` | `/template-hooks`:内容滚动到顶部或指定坐标 |
| template | `useSiderScroll` | `/template-hooks`:侧栏滚动到顶部或指定坐标 |
| web | `useDevice` | `/web-hooks`:随窗口尺寸更新断点判断 |
| web | `usePagination` | `/web-hooks`:实际分页数据、页码、每页条数与重置 |
| web | `useDayjs` | `/web-hooks`:日期格式化、天数差、开区间和日界限 |
| web | `useI18n` | `/web-hooks`:命名空间、完整键和语言切换 |
| web | `useVueRouter` | `/web-hooks`:当前路由、查询参数与页面导航 |
| web | `useElementFullscreen` | `/web-hooks`:指定元素 CSS 全屏与恢复 |
| web | `useDomToImage` | `/web-hooks`:PNG 生成、预览和失败提示 |
| web | `usePrint` | `/web-hooks`:元素打印预览 |
| components | `useContextmenuCoordinate` | `/web-hooks`:右键坐标、选择、外部关闭和停止监听;原 `/context-menu` 页面也保留 |
| 分包 | Hook | 示例页面与操作 | 回归测试 |
| ---------- | -------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| template | `useTheme` | `/template-hooks`:明暗、切换、跟随系统 | [useTheme](../../__test__/hooks/useTheme.spec.ts) |
| template | `useSpinning` | `/template-hooks`:加载动画、重新挂载页面 | [useSpinning](../../__test__/hooks/useSpinning.spec.ts) |
| template | `useMaximize` | `/template-hooks`:内容最大化、共享退出按钮、Esc | [useMaximize](../../__test__/hooks/useMaximize.spec.ts) |
| template | `useBadge` | `/template-hooks`:菜单标记文本、图标与显隐 | [useBadge](../../__test__/hooks/useBadge.spec.ts) |
| template | `useWatermark` | `/template-hooks`:文本、显示、隐藏与切换 | [useWatermark](../../__test__/hooks/useWatermark.spec.ts) |
| template | `useAppNavigation` | `/template-hooks`:完整路径、索引、嵌套菜单与 query | [useAppNavigation](../../__test__/hooks/useAppNavigation.spec.ts) |
| template | `useAppRoot` | `/template-hooks`:读取首页、设置本页与恢复仪表盘 | [useAppRoot](../../__test__/hooks/useAppRoot.spec.ts) |
| template | `useSiderBar` | `/template-hooks`:按路径关闭标签与左右/其他/全部标签 | [useSiderBar](../../__test__/hooks/useSiderBar.spec.ts) |
| template | `useContentScroll` | `/template-hooks`:内容滚动到顶部或指定坐标 | [useLayoutScroll](../../__test__/hooks/useLayoutScroll.spec.ts) |
| template | `useSiderScroll` | `/template-hooks`:侧栏滚动到顶部或指定坐标 | [useLayoutScroll](../../__test__/hooks/useLayoutScroll.spec.ts) |
| web | `useDevice` | `/web-hooks`:随窗口尺寸更新断点判断 | [useDevice](../../__test__/hooks/useDevice.spec.ts) |
| components | `usePagination` | `/web-hooks`:实际分页数据、页码、每页条数与重置 | [usePagination](../../__test__/hooks/usePagination.spec.ts) |
| web | `useDayjs` | `/web-hooks`:日期格式化、天数差、开区间和日界限 | [useDayjs](../../__test__/hooks/useDayjs.spec.ts) |
| template | `useI18n` | `/web-hooks`:命名空间、完整键和语言切换 | [useI18n](../../__test__/hooks/useI18n.spec.ts) |
| template | `useVueRouter` | `/web-hooks`:当前路由、查询参数与页面导航 | [useVueRouter](../../__test__/hooks/useVueRouter.spec.ts) |
| web | `useElementFullscreen` | `/web-hooks`:指定元素 CSS 全屏与恢复 | [useElementFullscreen](../../__test__/hooks/useElementFullscreen.spec.ts) |
| web | `useDomToImage` | `/web-hooks`:PNG 生成、预览和失败提示 | [useDomToImage](../../__test__/hooks/useDomToImage.spec.ts) |
| web | `usePrint` | `/web-hooks`:元素打印预览 | [usePrint](../../__test__/hooks/usePrint.spec.ts) |
| components | `useContextmenuCoordinate` | `/web-hooks`:右键坐标、选择、外部关闭和停止监听;原 `/context-menu` 页面也保留 | [useContextmenuCoordinate](../../__test__/hooks/useContextmenuCoordinate.spec.tsx) |
## 生命周期与状态
@ -31,9 +31,11 @@
- `useSpinning().reload(wait)` 会卸载页面,恢复计时器由 runtime Store 持有;多个调用以最后一次刷新为准。
- 两个滚动 Hook 可以在 setup 阶段创建,调用时才读取布局实例。无侧栏或未挂载时安全忽略。
- `useMaximize` 操作布局内容,多个调用方共享状态;`useElementFullscreen` 操作任意单个元素,其状态属于当前实例。二者均不调用浏览器 Fullscreen API。
- `navigationTo` 的索引从 0 开始;负数、小数、非有限数和越界索引不会导航。成功调用返回 Router 导航 Promise。
- `navigationTo` 的索引从 0 开始;负数、小数、非有限数和越界索引不会导航。完整 URL 支持动态参数、query 和 hash;额外 query 参数可覆盖 URL 中的同名参数。成功调用返回 Router 导航 Promise。
- `useDomToImage` 的返回类型跟随默认格式或本次 `create(format)`;失败通过 Error 拒绝,`finally` 在目标缺失时也会执行,此时参数可能为空。`created` 回调也会接收到运行时覆盖格式的结果,因此其参数为所有实际输出类型的联合,需先判断类型。
- `useI18n('hooks').t('code')` 和 `.t('hooks.code')` 指向同一个翻译键。切换应用语言使用 `useSettingActions().updateLocale`,保持日期与组件库同步。
- 国际化实例在开发热更新期间复用;初始化前创建的翻译方法会在调用时读取当前实例,不会永久停留在返回原始键的回退函数上。
- `usePagination` 重置时使用首个 pageSizes 选项的数值,兼容 Naive UI 的对象选项。调用 `setCallback()` 可移除默认回调。
- `usePrint` 在调用时解包目标。DOM 默认以 HTML 打印;Blob 图片与二进制 PDF 会先转换,调用方可以等待返回的 Promise。
截图和打印依赖实际浏览器。Happy DOM 测试验证状态与异常处理,不能替代原生打印界面或实际纸张输出验收。

View File

@ -1 +1,2 @@
export * from './useContextmenuCoordinate'
export * from './usePagination'

View File

@ -1,5 +1,5 @@
import type { BasicTarget } from '@/types'
import { effectDispose } from '@/utils'
import { effectDispose } from '@/utils/vue/effect-dispose'
import { onClickOutside, useEventListener } from '@vueuse/core'
import type {
MaybeElement,
@ -9,41 +9,37 @@ import type {
import type { MaybeRefOrGetter } from 'vue'
export interface UseContextmenuCoordinateOptions {
/**
*
* 自定义点击元素外部时的回调函数。
* 但是值得注意的事,该方法的优先级很高,可能会优先于其他方法执行
*
* @default null
*/
/** 关闭菜单后执行的外部点击回调。 */
clickOutside?: OnClickOutsideHandler
}
/**
*
* @param target 绑定元素
* @param target 绑定右键菜单的元素
* @param options 外部点击回调和监听器配置
*
* @description
* 右键点击元素时,获取鼠标坐标。该方法结合 NDropdown 组件使用,可以实现右键菜单功能。
* 右键时阻止原生菜单并读取视口坐标;作用域销毁时停止监听。
*
* @example
* const target = useTemplateRef<HTMLElement | null>('target')
* const { x, y, show, stop } = useContextmenuCoordinate(target)
*
* 如果需要手动停止右键菜单,可以调用 stop 方法
* stop()
*
* <NDropdown show={show} x={x} y={y} trigger="manual" placement="bottom-start" />
* @returns 只读坐标、菜单显隐状态和更新、停止方法。
*/
export const useContextmenuCoordinate = (
target: BasicTarget,
options?: UseContextmenuCoordinateOptions &
MaybeRefOrGetter<boolean | AddEventListenerOptions>,
options?: MaybeRefOrGetter<
boolean | (UseContextmenuCoordinateOptions & AddEventListenerOptions)
>,
) => {
const x = ref(0) // 鼠标 x 坐标
const y = ref(0) // 鼠标 y 坐标
const show = ref(false) // 是否显示右键菜单
const { clickOutside } = options ?? {}
const getEventOptions = () => {
const current = toValue(options)
// 必须允许 preventDefault,才能阻止原生菜单和自定义菜单同时打开。
return typeof current === 'boolean'
? { capture: current, passive: false }
: { ...current, passive: false }
}
let stopped = false
let generation = 0
@ -55,6 +51,8 @@ export const useContextmenuCoordinate = (
* 更新右键菜单的显示状态。
*/
const updateShow = (value: boolean) => {
if (stopped && value) return
if (!value) generation += 1
show.value = value
@ -90,27 +88,19 @@ export const useContextmenuCoordinate = (
target as MaybeElementRef<MaybeElement>,
(event) => {
updateShow(false)
clickOutside?.(event)
const current = toValue(options)
if (typeof current === 'object') current.clickOutside?.(event)
},
)
/**
*
* @description
* 为传递 ref dom 绑定右键菜单事件。
*/
const cleanupContextmenu = useEventListener(
target,
'contextmenu',
bindContextMenuEvent,
options,
getEventOptions,
)
/**
*
* @description
* 为传递 ref dom 绑定点击事件。
*/
const cleanupClick = useEventListener(target, 'click', () => {
updateShow(false)
})
@ -118,8 +108,7 @@ export const useContextmenuCoordinate = (
/**
*
* @description
* 注销绑定的右键菜单事件、点击事件。
* 仅注销该方法绑定的事件。
* 取消待显示的菜单并注销当前实例的所有监听。
*/
const stop = () => {
stopped = true

View File

@ -0,0 +1,182 @@
import { effectDispose } from '@/utils/vue/effect-dispose'
import { omit } from 'lodash-es'
import type { PaginationProps } from 'naive-ui'
import type { Ref } from 'vue'
type OmitKeys =
| 'themeOverrides'
| 'theme'
| 'on-update:page'
| 'on-update:page-size'
| 'onUpdatePage'
| 'onUpdatePageSize'
| 'onUpdate:page'
| 'onUpdate:page-size'
| 'onUpdate:pageSize'
export interface UsePaginationOptions extends Omit<PaginationProps, OmitKeys> {
/** 页码更新后接收新页码。 */
pageChange?: (page: number) => void
/** 每页条数更新后接收新条数。 */
pageSizeChange?: (pageSize: number) => void
}
const DEFAULT_OPTIONS: UsePaginationOptions = {
page: 1,
pageSize: 10,
showSizePicker: true,
pageSizes: [10, 20, 50, 100],
}
/**
*
* @param callback 页码或每页条数变化后的回调
* @param options 初始分页配置和事件回调
*
* @description
* 切换每页条数时先将页码复位,再通知回调。
*
* @returns 分页组件配置的引用以及读写和重置方法。
*/
export const usePagination = (
callback?: () => void,
options?: UsePaginationOptions,
) => {
// 回调函数
const callbackRef = shallowRef(callback)
// 分页方法
const paginationMethods = {
onUpdatePage: (page: number) => {
const { pageChange } = mergedOptions.value
paginationRef.value.page = page
callbackRef.value?.()
pageChange?.(page)
},
onUpdatePageSize: (pageSize: number) => {
const { pageSizeChange } = mergedOptions.value
paginationRef.value.pageSize = pageSize
paginationRef.value.page = DEFAULT_OPTIONS.page
callbackRef.value?.()
pageSizeChange?.(pageSize)
},
}
// 配置合并
const mergedOptions = computed(() => ({
...DEFAULT_OPTIONS,
...omit(options, [
'on-update:page',
'on-update:page-size',
'onUpdatePage',
'onUpdatePageSize',
'onUpdate:page',
'onUpdate:page-size',
'onUpdate:pageSize',
]),
...paginationMethods,
}))
// 分页配置
const paginationRef = ref<PaginationProps>(mergedOptions.value)
const getItemCount = () => paginationRef.value.itemCount ?? 0
/**
*
* @param itemCount 总条数
*
* @description
* 设置总条数。
*/
const setItemCount = (itemCount: number) => {
paginationRef.value.itemCount = itemCount
}
const getPage = () => paginationRef.value.page as number
/**
*
* @param page 新页码
*
* @description
* 通过同一个更新路径通知组件和手动设置的回调。
*/
const setPage = (page: number) => {
paginationMethods.onUpdatePage(page)
}
const getPageSize = () => paginationRef.value.pageSize as number
/**
*
* @param pageSize 新每页条数
*
* @description
* 同步将页码重置为 1,再通知回调。
*/
const setPageSize = (pageSize: number) => {
paginationMethods.onUpdatePageSize(pageSize)
}
const getPagination = () => paginationRef.value as UsePaginationOptions
/**
*
* @returns 当前回调;未设置或作用域已清理时返回 undefined。
*/
const getCallback = () => callbackRef.value
/**
*
* @param callback 新的分页更新回调;省略时移除回调
*/
const setCallback = (callback?: () => void) => {
callbackRef.value = callback
}
/**
*
* @description
* 页码恢复为 1,每页条数取第一个选项的值;选项为空时使用 10。
*/
const resetPagination = () => {
const { pageSizes, pageChange, pageSizeChange } = mergedOptions.value
paginationRef.value.page = DEFAULT_OPTIONS.page
const firstSize = pageSizes?.[0]
paginationRef.value.pageSize =
typeof firstSize === 'number'
? firstSize
: (firstSize?.value ?? DEFAULT_OPTIONS.pageSize)
callbackRef.value?.()
pageChange?.(paginationRef.value.page!)
pageSizeChange?.(paginationRef.value.pageSize!)
}
effectDispose(() => {
callbackRef.value = void 0
})
return [
paginationRef as Ref<UsePaginationOptions>,
{
getItemCount,
setItemCount,
getPage,
setPage,
getPageSize,
setPageSize,
getPagination,
getCallback,
setCallback,
resetPagination,
},
] as const
}
export type UsePaginationReturn = ReturnType<typeof usePagination>

View File

@ -8,3 +8,5 @@ export * from './useAppRoot'
export * from './useBadge'
export * from './useSiderScroll'
export * from './useContentScroll'
export * from './useI18n'
export * from './useVueRouter'

View File

@ -1,65 +1,38 @@
import { useVueRouter } from '@/hooks'
import { NOT_FOUND_ROUTE_PATH } from '@/router/constant'
import { useMenuGetters } from '@/store'
import type { AppMenuOption } from '@/types'
import type { LocationQuery } from 'vue-router'
import type { LocationQuery, RouteLocationRaw } from 'vue-router'
import { useVueRouter } from './useVueRouter'
export type Target = number | AppMenuOption | string
export interface NavigationToOptions {
/**
*
* 是否为 push 模式
* 如果设置为 true, 则会使用 vue-router 的 push 方法进行导航,否则使用 replace 方法进行导航
*
* @default true
*/
/** 默认 push;设为 false 时替换当前历史项。 */
isPush?: boolean
/**
*
* 跳转参数
*
* @default undefined
*/
/** 随导航传递的查询参数。 */
query?: LocationQuery
}
/**
*
* 导航函数
* 但是该方法仅限于在登入后调用
* @returns 模板菜单导航方法;按索引导航需要先加载菜单。
*/
export function useAppNavigation() {
/**
*
* @param target 需要导航的目标地址
* @param target 从 0 开始的菜单索引、菜单项或已注册路由路径
* @param option 导航模式与查询参数
*
* 当传递参数为 number:
* - 当传入参数值超过最大菜单长度,也会跳转失败并且抛出警告
* - 如果传递参数需要导航的菜单项为非根菜单项,会自动的递归导航至第一个子菜单项
* @description
* 索引指向父菜单时,沿首个子项查找叶节点。
*
* 当传递参数为 AppMenuOption 类型,会直接导航至目标页面。该方法可以不区分菜单层级
*
* @example
* navigationTo(1) // 导航至第二个菜单项,如果为根菜单项,会自动的递归导航至第一个子菜单项
* navigationTo({ AppMenuOption }) // 导航至目标菜单项
* navigationTo('path') // 导航至目标路由
* @returns 导航 Promise;目标无效时记录警告并返回 undefined。
*/
const navigationTo = (target: Target, option?: NavigationToOptions) => {
const {
router: { getRoutes, push, replace },
} = useVueRouter()
const { isPush = true, query } = option || {}
const isPushNavigation = (path: string) =>
isPush
? push({
path,
query,
})
: replace({
path,
query,
})
const { router } = useVueRouter()
const { isPush = true, query } = option ?? {}
const navigate = (location: RouteLocationRaw) =>
isPush ? router.push(location) : router.replace(location)
if (typeof target === 'number') {
// 校验是否为 NaN
@ -80,7 +53,7 @@ export function useAppNavigation() {
return
}
const option = getMenuOptions.value[target]
const menu = getMenuOptions.value[target]
// 递归获取第一级子菜单
const deepNavigation = (routes: AppMenuOption) => {
@ -92,21 +65,31 @@ export function useAppNavigation() {
return deepNavigation(firstChild)
}
return isPushNavigation(routes.fullPath)
return navigate({ path: routes.fullPath, query })
}
return deepNavigation(option)
} else if (typeof target === 'string') {
const fd = getRoutes().find((curr) => curr.path === target)
if (fd) {
return isPushNavigation(fd.path)
} else {
console.warn(`[navigationTo]: The path "${target}" is not found.`)
}
} else {
return isPushNavigation(target.fullPath)
return deepNavigation(menu)
}
if (typeof target !== 'string')
return navigate({ path: target.fullPath, query })
const resolved = router.resolve(target)
if (
!resolved.matched.length ||
resolved.matched.at(-1)?.path === NOT_FOUND_ROUTE_PATH
) {
console.warn(`[navigationTo]: The path "${target}" is not found.`)
return
}
return navigate({
path: resolved.path,
hash: resolved.hash,
query: { ...resolved.query, ...query },
})
}
return {

View File

@ -5,23 +5,8 @@ export function useAppRoot() {
const { getAppRootRoute } = useSettingGetters()
const { updateSettingState } = useSettingActions()
/**
*
* @description
* 获取根路由。
*/
const getRootRoute = getAppRootRoute
/**
*
* @description
* 获取根路由 path。
*/
const getRootPath = computed(() => getAppRootRoute.value.path)
/**
*
* @description
* 获取根路由 name。
*/
const getRootName = computed(() => getAppRootRoute.value.name)
/**
@ -30,9 +15,6 @@ export function useAppRoot() {
*
* @description
* 设置根路由。
*
* @example
* setRootRoute({ path: '/your root path', name: 'your root name' })
*/
const setRootRoute = (route: Partial<AppRootRoute>) => {
updateSettingState(

View File

@ -2,86 +2,54 @@ import type { AppMenuExtraOptions } from '@/router/types'
import { depthSearchAppMenu, useMenuGetters } from '@/store'
import { createMenuExtra } from '@/store/modules/menu/utils'
import type { AppMenuOption } from '@/types'
import { isValueType } from '@/utils'
export type BadgeKey = string | AppMenuOption
// 渲染 extra
const renderExtra = (
option: AppMenuOption,
assignExtra: AppMenuExtraOptions,
) => {
option.meta.extra = Object.assign({}, option.meta.extra, {
...assignExtra,
})
option.extra = createMenuExtra(option)
}
// 根据匹配的菜单项渲染 extra
const renderExtraWithNormalMenuOption = (
options: AppMenuOption[],
target: string,
assignExtra: AppMenuExtraOptions,
) => {
const menuOption = depthSearchAppMenu(options, target)
if (menuOption) {
renderExtra(menuOption, assignExtra)
}
}
// 匹配菜单项
const normalOption = (
target: BadgeKey,
fn: string,
assignExtra: AppMenuExtraOptions,
) => {
const updateBadge = (target: BadgeKey, extra: AppMenuExtraOptions) => {
const { getMenuOptions } = useMenuGetters()
const key = typeof target === 'string' ? target : target?.fullPath
if (typeof target === 'string') {
renderExtraWithNormalMenuOption(getMenuOptions.value, target, assignExtra)
} else if (isValueType<'object'>(target, 'Object')) {
const { fullPath } = target
if (!key) {
console.warn('[useBadge]: Expected a menu path or menu option.')
renderExtraWithNormalMenuOption(getMenuOptions.value, fullPath, assignExtra)
} else {
console.warn(`[useBadge ${fn}]: target expect string or object.`)
return
}
const option = depthSearchAppMenu(getMenuOptions.value, key)
if (!option) return
option.meta.extra = { ...option.meta.extra, ...extra }
option.extra = createMenuExtra(option)
}
export function useBadge() {
/**
*
* @param target 目标菜单 key 或者菜单项(AppMenuOption)
* @param target 菜单路径或菜单项
*
* @example
* const { hidden } = useBadge()
*
* hidden('your key')
* hidden({ ...AppMenuOption })
* @description
* 隐藏标记并保留其余配置。
*/
const hidden = (target: BadgeKey) => {
normalOption(target, 'hidden', {
updateBadge(target, {
show: false,
})
}
/**
*
* @param target 目标菜单 key 或者菜单项(AppMenuOption)
* @param extraOption 菜单标记配置项
* @param target 菜单路径或菜单项
* @param extraOption 显示时合并的标记配置
*
* @example
* const { show } = useBadge()
*
* show('your key')
* show({ ...AppMenuOption })
* @description
* 显示标记,强制启用 show。
*/
const show = (
target: BadgeKey,
extraOption?: Omit<AppMenuExtraOptions, 'show'>,
) => {
normalOption(target, 'show', {
updateBadge(target, {
...extraOption,
show: true,
})
@ -89,17 +57,14 @@ export function useBadge() {
/**
*
* @param target 目标菜单 key 或者菜单项(AppMenuOption)
* @param extraOption 菜单标记配置项
* @param target 菜单路径或菜单项
* @param extraOption 要合并的标记配置
*
* @example
* const { update } = useBadge()
*
* update('your key', { ...AppMenuExtraOptions })
* update({ ...AppMenuOption }, { ...AppMenuExtraOptions })
* @description
* 局部更新标记,未指定的字段保留原值。
*/
const update = (target: BadgeKey, extraOption: AppMenuExtraOptions) => {
normalOption(target, 'update', extraOption)
updateBadge(target, extraOption)
}
return {

View File

@ -3,16 +3,7 @@ import type { LayoutInst } from 'naive-ui'
/**
*
* @description
* 滚动侧边栏、内容区域。
*
* @see https://www.naiveui.com/zh-CN/dark/components/layout#scroll-to.vue
*
* @example
* const contentScrollTo = useContentScroll()
*
* contentScrollTo({ top: 0, left: 0, behavior: 'smooth' }) // 滚动内容区域
* contentScrollTo(10, 10) // x, y 方向滚动到 10 位置
* @returns 内容区 scrollTo;调用时读取当前布局实例,未挂载时不操作。
*/
export const useContentScroll = () => {
// 在事件触发时读取当前实例,支持 setup 中调用和布局重新挂载。

View File

@ -0,0 +1,85 @@
import { i18n } from '@/locales'
import type { I18n } from 'vue-i18n'
export interface OverrideUseI18nReturnType extends Partial<
Omit<I18n['global'], 't' | 'locale'>
> {
t: <T extends string = string>(key: string, ...args: unknown[]) => T
locale: (lang: string) => void
}
const getI18nKey = (namespace: string | undefined, key: string) => {
if (!namespace) {
return key
}
if (key === namespace || key.startsWith(`${namespace}.`)) {
return key
}
return `${namespace}.${key}`
}
/**
*
* @param namespace 翻译键的可选命名空间
*
* @description
* 翻译和切换语言时读取最新的国际化实例;初始化前翻译返回解析后的键。
*
* @returns 始终可用的翻译、语言设置方法,以及初始化后的原生能力。
*/
export const useI18n = (namespace?: string): OverrideUseI18nReturnType => {
const translate = <T extends string = string>(
key: string,
...args: unknown[]
): T => {
if (!key) return '' as T
if (!key.includes('.') && !namespace) return key as T
const fullKey = getI18nKey(namespace, key)
const instance = i18n
if (!instance) return fullKey as T
const nativeTranslate = instance.global.t as (
key: string,
...args: unknown[]
) => unknown
return nativeTranslate(fullKey, ...args) as T
}
const locale = (lang: string) => {
const instance = i18n
if (!instance) return
if (instance.mode === 'legacy') {
instance.global.locale = lang
} else if (isRef(instance.global.locale)) {
instance.global.locale.value = lang
} else {
instance.global.locale = lang
}
}
// 初始化前创建的 Hook 也在调用时读取实例,避免永久停留在回退函数上。
if (!i18n) return { t: translate, locale }
return { ...i18n.global, t: translate, locale }
}
/**
*
* @param key 需要供 i18n-ally 识别的翻译键
*
* @description
* 原样返回翻译键,不执行翻译,也不读取国际化实例。
*
* @returns 原始翻译键
*/
export const t = (key: string) => key
export type UseI18nReturnType = OverrideUseI18nReturnType

View File

@ -12,8 +12,18 @@ export interface MaximizeOptions extends UseElementFullscreenOptions {
scrollToOptions?: ScrollToOptions
}
/**
*
* @param defaults 每次切换的默认回调与样式
*
* @description
* 操作当前 Pinia 实例的布局最大化状态;连续切换仅执行最新的完成回调。
*
* @returns 只读状态和布局切换方法。
*/
export const useMaximize = (defaults?: MaximizeOptions) => {
const { layoutContentMaximize } = useRuntimeGetters()
const { layoutContentMaximize, layoutContentMaximizeVersion } =
useRuntimeGetters()
const { setRuntimeState } = useRuntimeActions()
// 最大化由布局 class 驱动;不同页面、标签菜单与退出按钮共享同一状态。
@ -34,8 +44,10 @@ export const useMaximize = (defaults?: MaximizeOptions) => {
}
setRuntimeState('layoutContentMaximize', full)
const version = layoutContentMaximizeVersion.value
nextTick(() => {
if (layoutContentMaximize.value !== full) return
if (layoutContentMaximizeVersion.value !== version) return
if (full && config.scrollToOptions) {
LAYOUT_CONTENT_REF.value?.scrollTo(config.scrollToOptions)

View File

@ -1,76 +1,39 @@
import { useAppRoot, useVueRouter } from '@/hooks'
import { useMenuActions, useMenuGetters } from '@/store'
import { pickRouteRecordNormalizedConstant } from '@/store/modules/menu/constant'
import type { AppMenuOption, Key, MenuTagOptions } from '@/types'
import { pick } from 'lodash-es'
import { useAppRoot } from './useAppRoot'
import { useVueRouter } from './useVueRouter'
export type CloseMenuTag = Key | MenuTagOptions
/**
*
* @param target 标签页对象、索引、key
* @param fn 触发函数
* @param target 标签页对象、索引或路径
* @param fn 用于日志的调用方方法名
*
* @description
* 该方法用于统一获取目标标签页方法。
* @returns 当前标签列表中的对象和索引,找不到时返回 undefined。
*/
const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
const { getMenuTagOptions } = useMenuGetters()
if (typeof target === 'number') {
// 判断是否为 NaN
if (!Number.isInteger(target)) {
console.warn(`${fn}: The ${target} is NaN, expect number.`)
return
}
// 判断是否超出当前标签页列表最大长度或者是否为负数
if (target >= getMenuTagOptions.value.length || target < 0) {
console.warn(
`${fn}: The incoming index ${target} did not match the corresponding item.`,
)
return
}
return {
option: getMenuTagOptions.value[target],
index: target,
}
} else if (typeof target === 'string') {
// 查找符合条件的 key
const index = getMenuTagOptions.value.findIndex(
(curr) => curr.fullPath === target,
)
return index > -1
? {
option: getMenuTagOptions.value[index],
index,
}
: console.warn(
`${fn}: The incoming key ${target} did not match the corresponding item.`,
const tags = getMenuTagOptions.value
const index =
typeof target === 'number'
? target
: tags.findIndex(
(tag) =>
tag.fullPath ===
(typeof target === 'string' ? target : target.fullPath),
)
} else {
const { fullPath } = target
const index = getMenuTagOptions.value.findIndex(
(curr) => curr.fullPath === fullPath,
)
if (index === -1) {
console.warn(
`${fn}: The incoming menuTag option ${target.fullPath} did not match the corresponding item.`,
)
if (!Number.isInteger(index) || index < 0 || index >= tags.length) {
console.warn(`[${fn}]: Could not find menu tag.`)
return
}
return {
option: target,
index,
}
return
}
return { option: tags[index], index }
}
export function useSiderBar() {
@ -105,24 +68,9 @@ export function useSiderBar() {
// 校验指定标签左侧是否有可关闭的标签
const checkCloseLeft = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'checkCloseRight')
const normal = normalMenuTagOption(target, 'checkCloseLeft')
if (normal) {
const { index } = normal
const length = getMenuTagOptions.value.length - 1
if (index === 0) {
return false
}
if (index > 0 && length > 0) {
return true
}
return false
}
return false
return !!normal && normal.index > 0
}
// 关闭当前标签
@ -139,17 +87,7 @@ export function useSiderBar() {
spliceMenTagOptions(index)
if (option.fullPath === getMenuKey.value) {
let i = checkCloseLeft(index)
? index - 1
: checkCloseRight(index)
? index
: index - 1
if (i < 0) {
i = 0
}
const tag = getMenuTagOptions.value[i]
const tag = getMenuTagOptions.value[Math.max(0, index - 1)]
tag && changeMenuModelValue(tag.fullPath, tag)
}
@ -158,8 +96,6 @@ export function useSiderBar() {
// 关闭所有标签并且导航至 root path
const closeAll = () => {
spliceMenTagOptions(0, getMenuTagOptions.value.length)
const { getRootPath } = useAppRoot()
const {
router: { getRoutes },
@ -170,6 +106,7 @@ export function useSiderBar() {
)
if (findMenuOption) {
spliceMenTagOptions(0, getMenuTagOptions.value.length)
const pickOption = pick(findMenuOption, pickRouteRecordNormalizedConstant)
const res = resolveOption(pickOption as unknown as AppMenuOption)

View File

@ -3,16 +3,7 @@ import type { LayoutInst } from 'naive-ui'
/**
*
* @description
* 滚动侧边栏。
*
* @see https://www.naiveui.com/zh-CN/dark/components/layout#scroll-to.vue
*
* @example
* const siderScrollTo = useSiderScroll()
*
* siderScrollTo({ top: 0, behavior: 'smooth' }) // y 方向侧边栏滚动
* siderScrollTo(0, 0) // x, y 方向滚动到 0 位置
* @returns 侧栏 scrollTo;调用时读取当前布局实例,未挂载时不操作。
*/
export const useSiderScroll = () => {
const scrollTo: LayoutInst['scrollTo'] = (

View File

@ -1,28 +1,16 @@
import { APP_THEME } from '@/app-config'
import { useI18n } from '@/hooks'
import { useSettingActions, useSettingGetters } from '@/store'
import { merge } from 'lodash-es'
import { useI18n } from './useI18n'
export type ThemeLabel = 'Dark' | 'Light'
export interface AppThemeInfo {
/**
*
* @description
* 当前主题状态,true 为暗色主题,false 为明色主题
*/
/** true 表示暗色主题。 */
theme: boolean
/**
*
* @description
* 当前主题描述,默认描述。
*/
/** 固定英文标签 Dark 或 Light。 */
themeLabel: ThemeLabel
/**
*
* @description
* 当前主题描述,国际化描述,会根据当前语言环境自动切换。
*/
/** 随语言切换的主题标签。 */
themeI18nLabel: string
}
@ -49,13 +37,7 @@ const setThemeOverrides = (theme: boolean) => {
export const useTheme = () => {
/**
*
* @description
* 获取当前主题色与主题色描述
* 并且描述会根据当前语言环境自动切换
*
* @example
* getAppTheme() // { theme: true, themeLabel: '暗色' | 'Dark' }
* getAppTheme() // { theme: false, themeLabel: '亮色' | 'Light' }
* @returns 当前主题、固定英文标签和随语言切换的翻译标签。
*/
const getAppTheme = (): AppThemeInfo => {
const { getAppTheme } = useSettingGetters()
@ -74,9 +56,6 @@ export const useTheme = () => {
*
* @description
* 切换至暗色主题
*
* @example
* darkTheme()
*/
const darkTheme = () => {
const { updateSettingState } = useSettingActions()
@ -90,9 +69,6 @@ export const useTheme = () => {
*
* @description
* 切换至明色主题
*
* @example
* lightTheme()
*/
const lightTheme = () => {
const { updateSettingState } = useSettingActions()
@ -106,9 +82,6 @@ export const useTheme = () => {
*
* @description
* 同步系统主题。
*
* @example
* syncSystemTheme()
*/
const syncSystemTheme = () => {
const { getAppTheme } = useSettingGetters()
@ -123,20 +96,13 @@ export const useTheme = () => {
}
/**
*
* @param theme 当前主题色
*
* @description
* 当前主题有明暗两套
*
* @example
* 假设当前主题为暗色主题
* toggleTheme() // 切换至明色主题
* 假设当前主题为明色主题
* toggleTheme() // 切换至暗色主题
* 切换到与当前相反的手动主题。
*/
const toggleTheme = () => {
const { theme } = getAppTheme()
const { getAppTheme } = useSettingGetters()
const theme = getAppTheme.value
const { updateSettingState } = useSettingActions()
updateSettingState('_appTheme', !theme)

View File

@ -0,0 +1,12 @@
import { router } from '@/router'
/**
*
* @description
* 读取模板的共享 Router 实例,可在 Vue setup 之外调用。
*
* @returns Router 及其响应式 currentRoute。
*/
export const useVueRouter = () => ({ router })
export type UseVueRouterReturnType = ReturnType<typeof useVueRouter>

View File

@ -3,16 +3,10 @@ import { useSettingActions, useSettingGetters } from '@/store'
export const useWatermark = () => {
/**
*
* @param content 水印内容
* @param content 非空水印文本
*
* @description
* 设置水印内容。
* 如果覆盖的水印内容为: '', undefined, null, 0, false, NaN,则会沿用上次一次的水印内容。
*
* @example
* setWatermarkContent('Ray Template Yes!')
* setWatermarkContent('') // 沿用上次一次的水印内容
* setWatermarkContent(undefined) // 沿用上次一次的水印内容
* 空字符串保留现有文本。
*/
const setWatermarkContent = (content: string) => {
if (!content) return
@ -30,9 +24,6 @@ export const useWatermark = () => {
*
* @description
* 显示水印。
*
* @example
* showWatermark() // 水印切换至显示状态
*/
const showWatermark = () => {
const { updateSettingState } = useSettingActions()
@ -44,9 +35,6 @@ export const useWatermark = () => {
*
* @description
* 隐藏水印。
*
* @example
* hiddenWatermark() // 水印切换至隐藏状态
*/
const hiddenWatermark = () => {
const { updateSettingState } = useSettingActions()
@ -55,17 +43,9 @@ export const useWatermark = () => {
}
/**
*
* @param value 是否显示水印
*
* @description
* 切换水印显示状态。
*
* @example
* 假设当前水印显示状态为隐藏
* toggleWatermark() // 显示水印
* 假设当前水印显示状态为显示
* toggleWatermark() // 隐藏水印
* 按当前共享状态切换水印显隐。
*/
const toggleWatermark = () => {
const { getWatermarkSwitch } = useSettingGetters()

View File

@ -1,6 +1,7 @@
import { DAYJS_LOCAL_MAP, DEFAULT_DAYJS_LOCAL } from '@/app-config'
import type { DayjsLocalMap } from '@/types'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
export interface FormatOption {
format?: string
@ -27,10 +28,7 @@ const defaultDayjsFormat = 'YYYY-MM-DD HH:mm:ss'
/**
*
* @description
* dayjs hook。
*
* 说明:
* - locale: 切换 dayjs 语言配置
* 日期格式化使用本地时区;locale 修改 Day.js 全局语言。
*/
export const useDayjs = () => {
/**
@ -39,10 +37,6 @@ export const useDayjs = () => {
*
* @description
* 手动配置 dayjs 语言(国际化)。
*
* @example
* locale('zh-CN')
* locale('en-US')
*/
const locale = (key: LocalKey) => {
const locale = DAYJS_LOCAL_MAP[key]
@ -56,11 +50,6 @@ export const useDayjs = () => {
*
* @description
* 校验是否为 dayjs 对象。
*
* @example
* isDayjs('2022-11-11') // false
* isDayjs('1699687245973') // false
* isDayjs(dayjs()) // true
*/
const isDayjs = (d: unknown) => {
return dayjs.isDayjs(d)
@ -73,11 +62,6 @@ export const useDayjs = () => {
*
* @description
* 格式化日期。
*
* @example
* dayjs().format() // '2020-04-02T08:02:17-05:00'
* dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYYescape 2019-01-25T00:00:00-02:00Z'
* dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'
*/
const format = (date: dayjs.ConfigType, formatOption?: FormatOption) => {
const { format = defaultDayjsFormat } = formatOption ?? {}
@ -126,11 +110,6 @@ export const useDayjs = () => {
* 返回正数: date2 比 date1 晚。
* 返回负数: date2 比 date1 早。
* 返回零(0): date2 等于 date1。
*
* @example
* daysDiff('2022-01-11', '2022-01-12') // 1
* daysDiff('2021-01-11', '2022-01-12') // 366
* daysDiff('2023-01-11', '2022-01-12') // -364
*/
const daysDiff = (date1: dayjs.ConfigType, date2: dayjs.ConfigType) => {
const start = dayjs(date1)
@ -142,16 +121,9 @@ export const useDayjs = () => {
/**
*
* @param date 待比较时间
* @param range 待比较开始与结束时间
* @param range 起止时间
*
* @description
* 判断一个时间是否在 start date 与 end date 之间。
* 如果刚还是等于开始、结束时间,也会返回 false。
*
* @example
* isDateInRange('2023-01-16', { start: '2023-01-15', end: '2023-01-20' }) // true
* isDateInRange('2023-01-15', { start: '2023-01-15', end: '2023-01-20' }) // false
* isDateInRange('2023-01-20', { start: '2023-01-15', end: '2023-01-20' }) // false
* @returns 时间是否落在开区间内,等于端点时返回 false。
*/
const isDateInRange = (date: dayjs.ConfigType, range: DateRange): boolean => {
const { start, end } = range

View File

@ -1,4 +1,3 @@
import { watchEffectWithTarget } from '@/utils'
import { useWindowSize } from '@vueuse/core'
import type { UseWindowSizeOptions } from '@vueuse/core'
@ -8,60 +7,42 @@ type Callback = (
) => void
export interface UseDeviceOptions extends UseWindowSizeOptions {
/**
*
* @description
* 自定义 isTabletOrSmaller 的判断尺寸。
*
* @default 768
*/
/** 平板宽度上限,默认 768 像素。 */
media?: number
/**
*
* @description
* 当尺寸更新后的回调函数。
*
* @default undefined
*/
/** 窗口尺寸或断点结果更新后执行。 */
observer?: Callback
}
/**
*
* @param options 配置项
* @param options 窗口尺寸选项、断点与观察回调
*
* @description
* 检测当前尺寸是否为平板或者更小
* 默认主流平板尺寸为 768px
* 默认断点为 768 像素(含等于)。
*
* @example
* const { width, height, isTabletOrSmaller } = useDevice()
*
* isTabletOrSmaller.value => true // 当前尺寸为平板或者更小
* isTabletOrSmaller.value => false // 当前尺寸为桌面或者更大
* @returns 响应式窗口宽高和只读的断点判断。
*/
export function useDevice(options?: UseDeviceOptions) {
const { width, height } = useWindowSize(options)
const isTabletOrSmaller = ref(false)
const { observer } = options ?? {}
const isTabletOrSmaller = computed(
() => width.value <= (options?.media ?? 768),
)
const update = () => {
const { media = 768 } = options ?? {}
isTabletOrSmaller.value = width.value <= media
observer?.(isTabletOrSmaller.value, {
width: width.value,
height: height.value,
})
if (options?.observer) {
// 只跟踪尺寸与断点,避免观察回调读到的其他状态触发重复通知。
watch(
[isTabletOrSmaller, width, height],
([smaller, width, height]) => {
options.observer?.(smaller, { width, height })
},
{ immediate: true },
)
}
watchEffectWithTarget(update)
return {
width,
height,
isTabletOrSmaller: readonly(isTabletOrSmaller),
isTabletOrSmaller,
} as const
}

View File

@ -1,5 +1,5 @@
import type { BasicTarget, TargetType } from '@/types'
import { unrefElement } from '@/utils'
import { unrefElement } from '@/utils/vue/unref-element'
import {
toBlob,
toCanvas,
@ -35,56 +35,18 @@ type Options<
T extends TargetType = Element,
ImageType extends DomToImageMethodKeys = DomToImageMethodKeys,
> = {
/**
*
* @description
* 指定图片类型,允许传递 imageType 参数,用于指定图片类型。
*
* @default jpeg
*/
/** 默认输出格式,可由 create 覆盖,缺省为 JPEG。 */
imageType?: ImageType
/**
*
* @param element current dom
*
* @description
* 在 dom 转换为图片之前执行。
*
* @default undefined
*/
/** 渲染前调用;目标未挂载时可能为空。 */
beforeCreate?: (element: T | null | undefined) => void
/**
*
* @param element current dom
* @param result dom to image result
*
* @description
* 在 dom 转换为图片之后执行。
*
* @default undefined
*/
/** 渲染成功后的回调;结果类型随本次格式变化。 */
created?: (
result: DomToImageReturnType<DomToImageMethodKeys>,
element: T,
) => void
/**
*
* @param error dom to image error
*
* 在 dom 转换为图片失败时执行
*
* @default undefined
*/
/** 渲染、目标解析或前置回调抛错时通知。 */
createdError?: (error?: Error) => void
/**
*
* @param element current dom
*
* @description
* 无论 dom 转换为图片成功或失败,都会执行。
*
* @default undefined
*/
/** 一次创建结束时执行;目标解析失败时参数为空。 */
finally?: (element: T | null | undefined) => void
}
@ -95,30 +57,13 @@ export type UseDomToImageOptions<
/**
*
* @param target ref dom
* @param options html-to-image options
*
* @see https://github.com/bubkoo/html-to-image
* @param target 截图目标,执行时解包
* @param options 默认格式、渲染配置与生命周期回调
*
* @description
* 使用 html-to-image 将 dom 转换为图片。
* 拓展了 imageType 参数,用于指定图片类型。
* 本次 create 的格式覆盖默认配置,缺省为 JPEG;created 可能收到不同格式的结果。
*
* create 方法支持在执行时传递 imageType 参数,用于指定图片类型。并且优先级大于 options.imageType;
* 当然,你也可以不传递 imageType 参数,此时会使用 options.imageType,
* 如果都未传递,则默认使用 jpeg。
*
* create 的返回类型跟随配置或本次传入的格式;created 可能接收覆盖格式后的结果,
* 因此应先用 typeof / instanceof 判断回调中的结果类型。
*
* @example
* const refDom = ref<HTMLElement>()
* const { create } = useDomToImage(refDom, {
* beforeCreate: (element) => { ... },
* created: (result, element) => { ... },
* createdError: (error) => { ... },
* finally: () => { ... },
* })
* @returns create 方法,其 Promise 结果类型跟随所选格式。
*/
export const useDomToImage = <
T extends HTMLElement,
@ -133,29 +78,44 @@ export const useDomToImage = <
createdError,
finally: _finally,
imageType: _imageType,
...imageOptions
} = options ?? {}
/**
*
* @param imageType 仅覆盖本次创建的输出格式
*
* @returns 对应格式的渲染结果。
*
* @throws 解析目标或渲染失败时拒绝,并调用错误与清理回调。
*/
const run = async <OutputType extends DomToImageMethodKeys = ImageType>(
imageType?: OutputType,
): Promise<DomToImageReturnType<OutputType>> => {
const element = unrefElement(target)
let element: T | null | undefined
try {
element = unrefElement(target)
beforeCreate?.(element)
if (!element)
throw new Error('[useDomToImage]: target element is undefined.')
const imageTypeKey = imageType ?? _imageType ?? 'jpeg'
const result = await domToImageMethods[imageTypeKey](element, options)
const result = await domToImageMethods[imageTypeKey](
element,
imageOptions,
)
// 分发映射的返回类型与传入的 imageType 一一对应。
created?.(result, element)
return result as DomToImageReturnType<OutputType>
} catch (error) {
createdError?.(error instanceof Error ? error : new Error(String(error)))
throw error
const cause = error instanceof Error ? error : new Error(String(error))
createdError?.(cause)
throw cause
} finally {
_finally?.(element)
}

View File

@ -1,93 +1,36 @@
import type { BasicTarget } from '@/types'
import { effectDispose, isValueType, unrefElement } from '@/utils'
import { pick } from 'lodash-es'
import { effectDispose } from '@/utils/vue/effect-dispose'
import { unrefElement } from '@/utils/vue/unref-element'
export interface UseElementFullscreenOptions {
/**
*
* @description
* 进入全屏前的回调。
*
* @default undefined
*/
/** 在覆盖样式前调用,抛错可取消进入。 */
beforeEnter?: () => void
/**
*
* @description
* 进入全屏后的回调。
*
* @default undefined
*/
/** 在进入状态后调用,最终尺寸会在下一帧应用。 */
enter?: () => void
/**
*
* @description
* 退出全屏前的回调。
*
* @default undefined
*/
/** 手动退出前调用,抛错可取消退出。 */
beforeExit?: () => void
/**
*
* @description
* 退出全屏后的回调。
*
* @default undefined
*/
/** 恢复原始样式后调用。 */
exit?: () => void
/**
*
* @description
* 全屏时的 z-index。
*
* @default 999
*/
/** 未指定时按进入顺序分配层级。 */
zIndex?: number
/**
*
* @description
* 全屏时的背景色。
*
* @default null
*/
backgroundColor?: string
/**
*
* @description
* 手动设定 transition 过度效果。
*
* @default 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
*/
/** 全屏过渡样式;传入 none 禁用。 */
transition?: string
}
// 全局 z-index 管理
let globalZIndex = 999
const ID_TAG = 'data-element-fullscreen'
const activeElements = new WeakSet<HTMLElement>()
/**
*
* @param target target dom
* @param options useElementFullscreen options
* @param target 需要占满视口的元素
* @param options 生命周期回调和样式配置
*
* @description
* 使元素全屏,但是不调用浏览器的全屏 API,仅使用纯 css 实现。
* 该方法具有入侵性,并且会在元素上覆盖 transition 样式。
* 使用 CSS fixed 定位。每个元素同时只能由一个实例控制,退出或作用域销毁时恢复原有行内样式。
*
* 该方法虽然能够实现全屏,但是会覆盖元素的一些基本样式,因此需要注意管理元素的一些基本样式,例如:position、z-index、transition、transform、width、height。
*
* @example
* <template>
* <div ref="refDom" />
* </template>
* <script lang="ts" setup>
* const refDom = useTemplateRef<HTMLElement>('refDom')
* const { enter, exit, toggleFullscreen } = useElementFullscreen(refDom, { UseElementFullscreenOptions })
*
* enter() // 进入全屏
* exit() // 退出全屏
* toggleFullscreen() // 切换全屏
* </script>
* @returns 全屏状态以及进入、退出和切换方法。
*/
export const useElementFullscreen = (
target: BasicTarget,
@ -96,185 +39,110 @@ export const useElementFullscreen = (
const {
beforeEnter,
beforeExit,
enter: _enter,
exit: _exit,
enter: onEnter,
exit: onExit,
backgroundColor,
zIndex,
transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
} = options ?? {}
// 每个实例独立的状态
const isFullscreen = ref(false)
const instanceZIndex = ref(0)
let frame: number | undefined
let activeElement: HTMLElement | null = null
const originalStyles = {
position: '',
width: '',
height: '',
top: '',
left: '',
transform: '',
transition: '',
zIndex: '',
backgroundColor: '',
boxSizing: '',
let restore: (() => void) | undefined
const exit = () => {
if (!restore) return
beforeExit?.()
restore()
onExit?.()
}
const enter = () => {
const element = unrefElement(target) as HTMLElement | null
const element = unrefElement(target)
if (!element) {
return
}
if (!(element instanceof HTMLElement) || activeElements.has(element)) return
if (activeElement === element) return
if (activeElement) exit()
if (restore) exit()
beforeEnter?.()
activeElement = element
// 保存原始样式(只在第一次进入时保存)
if (!isFullscreen.value) {
const o = pick(element.style, [
'position',
'width',
'height',
'top',
'left',
'transform',
'transition',
'zIndex',
'backgroundColor',
'boxSizing',
])
Object.assign(originalStyles, o)
}
// 获取当前位置
const { top, left, width, height } = element.getBoundingClientRect()
const styles = {
position: 'fixed',
'box-sizing': 'border-box',
top: `${top}px`,
left: `${left}px`,
width: `${width}px`,
height: `${height}px`,
transform: 'translate(0, 0)',
'z-index': String(zIndex ?? ++globalZIndex),
transition: 'none',
...(backgroundColor ? { 'background-color': backgroundColor } : {}),
}
const originalStyles = Object.keys(styles).map((property) => [
property,
element.style.getPropertyValue(property),
element.style.getPropertyPriority(property),
])
const originalAttribute = element.getAttribute(ID_TAG)
// 分配 z-index
if (instanceZIndex.value === 0) {
if (
isValueType<null>(zIndex, 'Null') ||
isValueType<undefined>(zIndex, 'Undefined')
) {
globalZIndex += 1
instanceZIndex.value = globalZIndex
} else {
instanceZIndex.value = zIndex
activeElements.add(element)
restore = () => {
if (frame !== void 0) cancelAnimationFrame(frame)
frame = void 0
for (const [property, value, priority] of originalStyles) {
element.style.setProperty(property, value, priority)
}
if (originalAttribute === null) element.removeAttribute(ID_TAG)
else element.setAttribute(ID_TAG, originalAttribute)
restore = void 0
activeElements.delete(element)
isFullscreen.value = false
}
// 设置全屏样式
element.setAttribute(ID_TAG, 'true')
// 设置初始位置(不设置 transition)
element.style.position = 'fixed'
element.style.boxSizing = 'border-box'
element.style.top = `${top}px`
element.style.left = `${left}px`
element.style.width = `${width}px`
element.style.height = `${height}px`
element.style.transform = 'translate(0, 0)'
element.style.zIndex = String(instanceZIndex.value)
if (backgroundColor) {
element.style.backgroundColor = backgroundColor
for (const [property, value] of Object.entries(styles)) {
element.style.setProperty(property, value)
}
// 强制重排
// 提交原始位置后再应用过渡,避免从未绘制的中间状态开始。
void element.offsetHeight
// 添加 transition
element.style.transition = transition
// 使用 requestAnimationFrame 应用最终样式
frame = requestAnimationFrame(() => {
element.style.top = '0px'
element.style.left = '0px'
element.style.width = '100dvw'
element.style.height = '100dvh'
Object.assign(element.style, {
top: '0px',
left: '0px',
width: '100dvw',
height: '100dvh',
})
frame = void 0
})
// 先更新状态
isFullscreen.value = true
_enter?.()
}
const exit = () => {
const element = activeElement
if (!element) {
return
}
beforeExit?.()
if (frame !== void 0) cancelAnimationFrame(frame)
frame = void 0
// 先更新状态
isFullscreen.value = false
// 恢复原始样式
element.removeAttribute(ID_TAG)
// 样式属性映射表(camelCase -> kebab-case)
const styleMap: Record<keyof typeof originalStyles, string> = {
position: 'position',
width: 'width',
height: 'height',
top: 'top',
left: 'left',
transform: 'transform',
transition: 'transition',
zIndex: 'z-index',
backgroundColor: 'background-color',
boxSizing: 'box-sizing',
}
// 批量恢复样式
Object.entries(originalStyles).forEach(([key, value]) => {
const styleName = styleMap[key as keyof typeof originalStyles]
if (!value) {
element.style.removeProperty(styleName)
} else {
element.style.setProperty(styleName, value)
}
})
activeElement = null
_exit?.()
onEnter?.()
}
const toggleFullscreen = () => {
if (isFullscreen.value) {
exit()
} else {
enter()
}
if (isFullscreen.value) exit()
else enter()
}
effectDispose(() => {
if (isFullscreen.value) {
exit()
}
if (!restore) return
// 作用域销毁必须释放样式和动画帧,不允许前置回调取消。
restore()
onExit?.()
})
return {
enter,
exit,
toggleFullscreen,
isFullscreen: readonly(isFullscreen),
}
return { enter, exit, toggleFullscreen, isFullscreen: readonly(isFullscreen) }
}
export type UseElementFullscreenReturnTypes = ReturnType<

View File

@ -1,74 +1 @@
import { i18n } from '@/locales'
import type { I18n } from 'vue-i18n'
export interface OverrideUseI18nReturnType extends Omit<
I18n['global'],
't' | 'locale'
> {
t: <T = string>(key: string, ...args: unknown[]) => T
locale: (lang: string) => void
}
const getI18nKey = (namespace: string | undefined, key: string) => {
if (!namespace) {
return key
}
if (key === namespace || key.startsWith(`${namespace}.`)) {
return key
}
return `${namespace}.${key}`
}
export const useI18n = (namespace?: string): OverrideUseI18nReturnType => {
const translate = <T = string>(key: string, ...args: unknown[]): T => {
if (!key) return '' as T
if (!key.includes('.') && !namespace) return key as T
const fullKey = getI18nKey(namespace, key)
const instance = i18n
if (!instance) return fullKey as T
const nativeTranslate = instance.global.t as (
key: string,
...args: unknown[]
) => unknown
return nativeTranslate(fullKey, ...args) as T
}
const locale = (lang: string) => {
const instance = i18n
if (!instance) return
if (instance.mode === 'legacy') {
instance.global.locale = lang
} else if (isRef(instance.global.locale)) {
instance.global.locale.value = lang
} else {
instance.global.locale = lang
}
}
// 初始化前创建的 Hook 也在调用时读取实例,避免永久停留在回退函数上。
if (!i18n) return { t: translate, locale } as OverrideUseI18nReturnType
return { ...i18n.global, t: translate, locale }
}
/**
*
* @param key 需要供 i18n-ally 识别的翻译键
*
* @description
* 原样返回翻译键,不执行翻译,也不读取国际化实例。
*
* @returns 原始翻译键
*/
export const t = (key: string) => key
export type UseI18nReturnType = OverrideUseI18nReturnType
export * from '../template/useI18n'

View File

@ -1,241 +1 @@
import type { AnyFn } from '@/types'
import { effectDispose } from '@/utils'
import { omit } from 'lodash-es'
import type { PaginationProps } from 'naive-ui'
import type { Ref } from 'vue'
type OmitKeys =
| 'themeOverrides'
| 'theme'
| 'on-update:page'
| 'on-update:page-size'
| 'onUpdatePage'
| 'onUpdatePageSize'
| 'onUpdate:page'
| 'onUpdate:page-size'
| 'onUpdate:pageSize'
export interface UsePaginationOptions extends Omit<PaginationProps, OmitKeys> {
/**
*
* @param page 当前分页页码
*
* @description
* 分页页码更新的回调函数。
*/
pageChange?: (page: number) => void
/**
*
* @param pageSize 当前分页条数
*
* @description
* 分页页数更新回调函数。
*/
pageSizeChange?: (pageSize: number) => void
}
const DEFAULT_OPTIONS: UsePaginationOptions = {
page: 1,
pageSize: 10,
showSizePicker: true,
pageSizes: [10, 20, 50, 100],
}
/**
*
* @param callback 页码、页条数更新时的回调函数
* @param options 配置项
*
* @description
* Naive UI Pagination 便捷分页 hook。
*
* @example
* const [paginationRef, { getItemCount, setItemCount, getPage, setPage, getPageSize, setPageSize, getPagination, getCallback, setCallback, resetPagination }] = usePagination(() => {
* // do something...
* }, {
* // ...options
* })
*/
export const usePagination = <T extends AnyFn>(
callback?: T,
options?: UsePaginationOptions,
) => {
// 回调函数
const callbackRef = shallowRef(callback)
// 分页方法
const paginationMethods = {
onUpdatePage: (page: number) => {
const { pageChange } = mergedOptions.value
paginationRef.value.page = page
callbackRef.value?.()
pageChange?.(page)
},
onUpdatePageSize: (pageSize: number) => {
const { pageSizeChange } = mergedOptions.value
paginationRef.value.pageSize = pageSize
paginationRef.value.page = DEFAULT_OPTIONS.page
callbackRef.value?.()
pageSizeChange?.(pageSize)
},
}
// 配置合并
const mergedOptions = computed(() => ({
...DEFAULT_OPTIONS,
...omit(options, [
'on-update:page',
'on-update:page-size',
'onUpdatePage',
'onUpdatePageSize',
'onUpdate:page',
'onUpdate:page-size',
'onUpdate:pageSize',
]),
...paginationMethods,
}))
// 分页配置
const paginationRef = ref<PaginationProps>(mergedOptions.value)
// 更新分页页数
const updatePage = paginationRef.value.onUpdatePage as (page: number) => void
// 更新分页每页条数
const updatePageSize = paginationRef.value.onUpdatePageSize as (
pageSize: number,
) => void
/**
*
* @description
* 获取总条数。
*/
const getItemCount = () => paginationRef.value.itemCount as number
/**
*
* @param itemCount 总条数
*
* @description
* 设置总条数。
*/
const setItemCount = (itemCount: number) => {
paginationRef.value.itemCount = itemCount
}
/**
*
* @description
* 获取当前页页码。
*/
const getPage = () => paginationRef.value.page as number
/**
*
* @param page 当前页页码
*
* @description
* 设置当前页页码。
*
* 为了避免响应式丢失,手动调用 updatePage 方法。
*/
const setPage = (page: number) => {
updatePage(page)
}
/**
*
* @description
* 获取每页条数。
*/
const getPageSize = () => paginationRef.value.pageSize as number
/**
*
* @param pageSize 每页条数
*
* @description
* 设置每页条数。
*
* 为了避免响应式丢失,手动调用 updatePageSize 方法。
*/
const setPageSize = (pageSize: number) => {
updatePageSize(pageSize)
}
/**
*
* @description
* 获取分页配置,通常可以用来传递给 RTable 组件。
*/
const getPagination = () => paginationRef.value as UsePaginationOptions
/**
*
* @description
* 获取回调函数。
*/
const getCallback = <Fn extends AnyFn = T>(): Fn extends
undefined | null | unknown
? T
: Fn => callbackRef.value
/**
*
* @param callback 页码、页条数更新时的回调函数
*
* @description
* 手动设置回调函数。
*
* @example
* setCallback(() => {})
*/
const setCallback = <Fn extends AnyFn = AnyFn>(callback: Fn) => {
callbackRef.value = callback
}
/**
*
* @description
* 初始化分页。
*
* 重置页码为 1,每页条数为 pageSizes 的第一个值。
* 如果,pageSizes 为空,则设置每页条数为 10。
*/
const resetPagination = () => {
const { pageSizes, pageChange, pageSizeChange } = mergedOptions.value
paginationRef.value.page = DEFAULT_OPTIONS.page
paginationRef.value.pageSize =
(pageSizes?.[0] as number) || DEFAULT_OPTIONS.pageSize
callbackRef.value?.()
pageChange?.(paginationRef.value.page!)
pageSizeChange?.(paginationRef.value.pageSize!)
}
effectDispose(() => {
callbackRef.value = void 0
})
return [
paginationRef as Ref<UsePaginationOptions>,
{
getItemCount,
setItemCount,
getPage,
setPage,
getPageSize,
setPageSize,
getPagination,
getCallback,
setCallback,
resetPagination,
},
] as const
}
export type UsePaginationReturn = ReturnType<typeof usePagination>
export * from '../components/usePagination'

View File

@ -1,51 +1,66 @@
import type { BasicTarget } from '@/types'
import { unrefElement } from '@/utils'
import { omit } from 'lodash-es'
import { fileToBase64 } from '@/utils/files'
import { unrefElement } from '@/utils/vue/unref-element'
import print from 'print-js'
export interface UsePrintOptions extends Omit<
print.Configuration,
'printable'
> {}
export type UsePrintOptions = Omit<print.Configuration, 'printable'>
export type UsePrintTarget<T = unknown> =
BasicTarget | string | Blob | Uint8ClampedArray | T[]
/**
*
* @param target useTemplateRef dom
* @param options print-js options
* @param target DOM、元素引用或可打印的数据
* @param options print-js 配置;DOM 默认使用 html 模式
*
* @see https://printjs.crabbly.com/
*
* @description
* 拓展 print-js 的 usePrint 方法,允许 useTemplateRef Dom 直接调用打印,其余的不变。
*
* @example
* const refDom = useTemplateRef<HTMLElement>('refDom')
*
* const { print } = usePrint(refDom, {})
*
* @example
* const { print } = usePrint('#id', {})
* const { print } = usePrint('base64', {}) // 设置为 base64 时,一定要设置配置项 base64 为 true
* const { print } = usePrint('https://xxx.com/xxx.png', {})
* const { print } = usePrint(new Blob(), {})
* @returns print 方法;无目标时跳过,二进制内容需先读取。
*/
export const usePrint = (target: UsePrintTarget, options?: UsePrintOptions) => {
/**
*
* @description
* 以执行时的目标打开打印预览,始终使用当前目标作为 printable。
*
* @returns 二进制内容返回读取并提交打印的 Promise;其余在当前调用中提交。
*
* @throws 读取失败或 print-js 不能打开预览时传递原始错误。
*/
const run = () => {
// 为了兼容 ref 注册的 dom;如果未获取到 dom,则会视为其他的输出方式,交由 print-js 处理
const _target = unrefElement(target as BasicTarget) || target
const printable = unrefElement(target as BasicTarget) as UsePrintTarget
if (printable == null || printable === '') return
if (printable instanceof Blob || printable instanceof Uint8ClampedArray) {
const type =
options?.type ??
(printable instanceof Blob && printable.type.startsWith('image/')
? 'image'
: 'pdf')
const file =
printable instanceof Blob
? new File([printable], '', { type: printable.type })
: new File([Uint8Array.from(printable)], '', {
type: 'application/pdf',
})
return fileToBase64(file).then((url) => {
print({
...options,
type,
base64: type === 'pdf',
printable: type === 'pdf' ? url.slice(url.indexOf(',') + 1) : url,
})
})
}
print({
...omit(options, ['printable']),
printable: _target,
...options,
type: options?.type ?? (printable instanceof Element ? 'html' : 'pdf'),
printable,
})
}
return {
print: run,
}
return { print: run }
}
export type UsePrintReturnType = ReturnType<typeof usePrint>

View File

@ -1,46 +1 @@
import { router } from '@/router'
import type { Router } from 'vue-router'
/**
*
* @description
* 获取 vue-router 实例,允许你在非 setup 环境中使用。
*
* 可能考虑后期会加一些新的东西,所以与 vue-router useRouter 有点差异,需要解构使用 router,
* 但是,其余的所有使用方法都与 useRouter 一致。
*
* 如果需要使用类似于 useRoute 的方法,可以使用 useVueRouter().router.currentRoute 获取。
*
* @example
* const { router } = useVueRouter()
*
* // 使用 router
* router.push('/path')
* router.replace('/path')
*
* // 使用类似于 useRoute 的方法
* const { router: { currentRouter } } = useVueRouter()
*
* console.log(route.fullPath)
*/
export const useVueRouter = () => {
/**
*
* 该写法无实际意义,仅是为了避免 HMR 报错,导致开发流程中断。
* 在实际业务中,router 始终是有值状态,所以不用担心。
*
* 但是,其实这是一种很不友好的做好,并且在顶层做修改的时候,依旧可能会有 HMR 报错;
* 现在还未找到更好的解决方案,所以只能先这样。
*/
if (!router) {
return {
router: {} as Router,
}
}
return {
router,
}
}
export type UseVueRouterReturnType = ReturnType<typeof useVueRouter>
export * from '../template/useVueRouter'

View File

@ -1,6 +1,7 @@
import './index.scss'
import { LAYOUT_SIDER_REF } from '@/app-config'
import { useDevice } from '@/hooks'
import { positionSelectedMenuItem } from '@/layout/utils/position-selected-menu-item'
import {
useMenuActions,
useMenuGetters,
@ -9,7 +10,6 @@ import {
useSettingGetters,
} from '@/store'
import type { AppMenuOption, NaiveMenuOptions } from '@/types'
import { positionSelectedMenuItem } from '@/utils'
import { NDrawer, NLayoutContent, NLayoutSider, NMenu } from 'naive-ui'
import type { MenuInst } from 'naive-ui'
import type { PropType } from 'vue'

View File

@ -1,3 +1,4 @@
import { positionSelectedMenuItem } from '@/layout/utils/position-selected-menu-item'
import './index.scss'
import { RIcon } from '@/components'
import { useDevice } from '@/hooks'
@ -5,12 +6,7 @@ import type { AppRouteMeta } from '@/router/types'
import { validMenuItemShow } from '@/router/utils'
import { useMenuActions } from '@/store'
import type { AppMenuOption } from '@/types'
import {
positionSelectedMenuItem,
queryElements,
removeClass,
setClass,
} from '@/utils'
import { queryElements, removeClass, setClass } from '@/utils'
import { useEventListener } from '@vueuse/core'
import { pick, throttle } from 'lodash-es'
import {

View File

@ -0,0 +1,45 @@
import { LAYOUT_SIDER_REF } from '@/app-config'
import { useSiderScroll } from '@/hooks/template/useSiderScroll'
import { unrefElement } from '@/utils/vue/unref-element'
// 菜单激活样式 class name
const MENU_ITEM_SELECTED = '.n-menu-item-content--selected'
// 折叠菜单激活样式 class name
const MENU_COLLAPSED_ITEM_SELECTED = '.n-menu-item-content--child-active'
/**
*
* @description
* 仅在已渲染的激活项超出菜单可视区域时滚动;调用方负责展开父菜单并等待渲染。
*/
export const positionSelectedMenuItem = () => {
const siderEl = unrefElement(LAYOUT_SIDER_REF as Ref<HTMLElement | null>)
const scrollEl = siderEl?.querySelector<HTMLElement>(
'.n-layout-scroll-container, .n-scrollbar-container',
)
const selectedEl =
siderEl?.querySelector<HTMLElement>(MENU_ITEM_SELECTED) ||
siderEl?.querySelector<HTMLElement>(MENU_COLLAPSED_ITEM_SELECTED)
if (!selectedEl || !scrollEl) return
const selectedRect = selectedEl.getBoundingClientRect()
const scrollRect = scrollEl.getBoundingClientRect()
if (
selectedRect.top >= scrollRect.top &&
selectedRect.bottom <= scrollRect.bottom
)
return
const menuItemEl = selectedEl.closest('.n-menu-item')
const marginTop = menuItemEl
? parseFloat(window.getComputedStyle(menuItemEl).marginTop) || 0
: 0
useSiderScroll()({
top: scrollEl.scrollTop + selectedRect.top - scrollRect.top - marginTop,
left: 0,
behavior: 'smooth',
})
}

View File

@ -1,6 +1,6 @@
import { APP_CATCH_KEY, SYSTEM_DEFAULT_LOCAL } from '@/app-config'
import type { AppCurrentAppMessages } from '@/locales/types'
import { getStorage } from '@/utils'
import { getStorage } from '@/utils/cache'
/**
*

View File

@ -1 +1,3 @@
export const LAYOUT = () => import('@/layout/default/ContentWrapper')
export const NOT_FOUND_ROUTE_PATH = '/:catchAll(.*)'

View File

@ -1,4 +1,3 @@
import { useVueRouter } from '@/hooks'
import { scrollViewToTop, vueRouterRegister } from '@/router/utils'
import type { App } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
@ -23,7 +22,5 @@ export const router = createRouter({
export const setupRouter = (app: App<Element>) => {
app.use(router)
// 等待 router 挂载后,初始化 useRouter 方法
useVueRouter()
vueRouterRegister(router)
}

View File

@ -1,6 +1,7 @@
import { t } from '@/hooks/web/useI18n'
import Layout from '@/layout'
import { appExpandRoutes } from './app-route-modules'
import { NOT_FOUND_ROUTE_PATH } from './constant'
export default [
/**
@ -29,7 +30,7 @@ export default [
* 404 页面一定要放在最后面,避免奇奇怪怪的问题。
*/
{
path: '/:catchAll(.*)',
path: NOT_FOUND_ROUTE_PATH,
component: () => import('@/views/error/views/Error404'),
meta: {
i18nKey: t('menu.Error'),

View File

@ -1,6 +1,6 @@
import { APP_CATCH_KEY, WHITE_ROUTES } from '@/app-config'
import { useAppRoot } from '@/hooks'
import { getStorage, setStorage } from '@/utils'
import { getStorage, setStorage } from '@/utils/cache'
import type { Router } from 'vue-router'
import { validRole } from './valid-role'

View File

@ -1,6 +1,6 @@
import { APP_CATCH_KEY } from '@/app-config'
import { useAppRoot, useVueRouter } from '@/hooks'
import { setStorage } from '@/utils'
import { setStorage } from '@/utils/cache'
/**
*

View File

@ -1,5 +1,5 @@
import type { AppMenuOption } from '@/types'
import { getAppEnvironment } from '@/utils'
import { getAppEnvironment } from '@/utils/app/get-app-environment'
/**
*

View File

@ -9,6 +9,7 @@ export const useRuntimeGetters = () => {
globalDrawerValue: readonly(state.globalDrawerValue),
globalMainLayoutLoad: readonly(state.globalMainLayoutLoad),
layoutContentMaximize: readonly(state.layoutContentMaximize),
layoutContentMaximizeVersion: readonly(state.layoutContentMaximizeVersion),
layoutContentSpinning: readonly(state.layoutContentSpinning),
layoutContentMaximizeStyle: readonly(state.layoutContentMaximizeStyle),
}

View File

@ -5,7 +5,9 @@ import { canSkipRoute, validMenuItemShow, validRole } from '@/router/utils'
import { useKeepAliveActions } from '@/store'
import type { MenuState } from '@/store/modules/menu/types'
import type { AnyFn, AppMenuOption, MenuTagOptions } from '@/types'
import { equalRouterPath, setStorage, updateObjectValue } from '@/utils'
import { setStorage } from '@/utils/cache'
import { equalRouterPath } from '@/utils/equal-router-path'
import { updateObjectValue } from '@/utils/update-object-value'
import { pick } from 'lodash-es'
import { NEllipsis } from 'naive-ui'
import type { LocationQuery } from 'vue-router'
@ -19,44 +21,24 @@ import {
updateDocumentTitle,
} from './utils'
let cachePreNormal: AppMenuOption | undefined = void 0
/**
*
* @param options 菜单列表或者类似菜单列表的数据结构
* @param target 目标路径
* @param options 当前菜单树
* @param target 要匹配的路径
*
* @returns 匹配的菜单项
*
* @description
* 递归查找匹配的菜单项,缓存上一次的匹配项。
* 并且该方法一旦匹配成功就会立即返回。
*
* 通过 fullPath 进行匹配。
*
* @example
* depthSearchAppMenu([{ path: '/dashboard', name: 'Dashboard', meta: { i18nKey: 'menu.Dashboard' } }], '/dashboard')
* @returns 菜单树中第一个路径匹配项。
*/
export const depthSearchAppMenu = (
options: AppMenuOption[],
target: string,
) => {
if (cachePreNormal && equalRouterPath(cachePreNormal.fullPath, target)) {
return cachePreNormal
}
): AppMenuOption | undefined => {
for (const option of options) {
if (equalRouterPath(option.fullPath, target)) return option
for (const curr of options) {
if (equalRouterPath(curr.fullPath, target)) {
cachePreNormal = curr
const nested =
option.children && depthSearchAppMenu(option.children, target)
return curr
}
if (curr.children?.length) {
depthSearchAppMenu(curr.children, target)
continue
}
if (nested) return nested
}
}

View File

@ -3,7 +3,8 @@ import { RIcon } from '@/components'
import { useAppRoot, useI18n } from '@/hooks'
import { resolveIconName } from '@/icons'
import type { AppMenuKey, AppMenuOption } from '@/types/modules/app'
import { getStorage, isValueType } from '@/utils'
import { getStorage } from '@/utils/cache'
import { isValueType } from '@/utils/core'
import { NTag } from 'naive-ui'
import type { TagProps } from 'naive-ui'
import { piniaMenuStore } from '.'
@ -273,11 +274,10 @@ export const getCatchMenuKey = () => {
* @returns 获取缓存的菜单标签页
*/
export const getCatchMenuTagOptions = () => {
return getStorage<AppMenuOption[]>(
APP_CATCH_KEY.appMenuTagOptions,
'sessionStorage',
{
defaultValue: [],
},
return (
getStorage<AppMenuOption[]>(
APP_CATCH_KEY.appMenuTagOptions,
'sessionStorage',
) ?? []
)
}

View File

@ -3,6 +3,7 @@ export interface RuntimeState {
globalDrawerValue: boolean
globalMainLayoutLoad: boolean
layoutContentMaximize: boolean
layoutContentMaximizeVersion: number
layoutContentSpinning: boolean
layoutContentMaximizeStyle: {
zIndex: number
@ -17,6 +18,7 @@ export const piniaRuntimeStore = defineStore('runtime', () => {
globalDrawerValue: false,
globalMainLayoutLoad: true,
layoutContentMaximize: false,
layoutContentMaximizeVersion: 0,
layoutContentSpinning: false,
layoutContentMaximizeStyle: { zIndex: 999 },
})
@ -26,6 +28,10 @@ export const piniaRuntimeStore = defineStore('runtime', () => {
key: K,
value: RuntimeState[K],
) => {
if (key === 'layoutContentMaximize' && state[key] !== value) {
state.layoutContentMaximizeVersion += 1
}
state[key] = value
}

View File

@ -5,7 +5,9 @@ import { resolveIconName } from '@/icons'
import { getAppDefaultLanguage } from '@/locales/utils'
import type { SettingState } from '@/store/modules/setting/types'
import type { AnyFn } from '@/types'
import { colorToRgba, setStorage, setStyle, updateObjectValue } from '@/utils'
import { setStorage } from '@/utils/cache'
import { colorToRgba, setStyle } from '@/utils/element'
import { updateObjectValue } from '@/utils/update-object-value'
import { usePreferredDark } from '@vueuse/core'
import { cloneDeep, merge } from 'lodash-es'
import { getDefaultSettingConfig, normalizeLayoutConfig } from './constant'

View File

@ -5,7 +5,7 @@ import type {
SigningForm,
SigningResponse,
} from '@/store/modules/signing/types'
import { removeStorage } from '@/utils'
import { removeStorage } from '@/utils/cache'
import { isEmpty } from 'lodash-es'
/** 登录状态仓库,使用 localStorage 持久化 signingCallback。 */

26
src/utils/README.md Normal file
View File

@ -0,0 +1,26 @@
# 公共工具
`@/utils` 保留原有公开导出。实现和初始化链路应从所属子模块导入,避免加载无关依赖。
| 入口 | 职责 | 代表性回归测试 |
| ----------------------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `core` | 类型标签、PromiseLike、同步/异步错误处理、随机标识 | `__test__/basic` |
| `files` | Data URL、文件读取、Blob/ArrayBuffer 下载与资源清理 | `__test__/basic/downloadAnyFile.spec.ts`、`__test__/utils-contracts/fileToBase64.spec.ts` |
| `app`、`equal-router-path.ts` | 环境、操作系统、缓存键前缀、路由路径比较 | `__test__/app`、`__test__/basic` |
| `cache.ts` | Web Storage 的 JSON 读写、命名空间和失败回退 | `__test__/cache` |
| `element.ts` | DOM 类名、行内样式、查询、颜色和 CSS 尺寸 | `__test__/element` |
| `dom.ts` | 截图后打开打印预览 | `__test__/dom` |
| `vue` | 解包元素和组件根节点、渲染函数、回调与作用域清理 | `__test__/vue`、`__test__/utils-contracts/vue-target.spec.ts` |
| `precision.ts` | 定点小数运算、分配与格式化 | `__test__/precision` |
| `legacy-crypto` | 历史本地缓存的 AES JSON 格式 | `__test__/utils-contracts/legacy-crypto.spec.ts` |
| 对象与日期选择器辅助方法 | 自有属性更新、浅拷贝、范围清空值 | `__test__/utils-contracts/object-date.spec.ts` |
`basic.ts` 和 `c/` 是旧导入路径的兼容入口。选中菜单定位实现在 `src/layout/utils`,由布局调用,历史工具入口继续转发。组件、Router 和 Store 自己的内部工具跟随所属模块维护。
- `isPromise` 判断值是否可等待;要判断函数是否声明为 `async`,使用 `isAsyncFunction`。错误包装会等待任意函数返回的 PromiseLike。
- `uuid(length, radix)` 生成自定义标识,长度须为非负安全整数,基数须在 1 到 62。它不是 RFC UUID 格式。
- 下载 Promise 表示已请求浏览器下载,无法感知磁盘写入是否完成。打印返回是否成功发起预览;纸张输出由浏览器负责。
- `setStorage` 保留现有 JSON 和缓存键格式;读取失败返回指定的回退值,显式存入的 JSON `null` 仍是 `null`。配置前缀时,批量删除只作用于该前缀下的键。
- `setClass`、`removeClass`、`hasClass`、`setStyle`、`removeStyle` 随元素引用更新;使用响应式目标时应在 Vue 作用域内创建。原生 `class` 属性变化本身不会触发 `hasClass` 重新计算。
- `removeDuplicateKeys` 保留历史名称,返回对象自有可枚举属性的浅拷贝;同名键在创建 JavaScript 对象时已由最后一次赋值决定。 `updateObjectValue` 只更新自有属性,仅当新旧值均是普通对象时浅合并。
- `legacy-crypto` 的字符串口令保留 OpenSSL 格式;原始密钥密文包含随机 IV。它是兼容层,模板的默认口令对客户端可见。

View File

@ -0,0 +1,29 @@
import { OperatingSystem } from '@/types'
/**
*
* @description
* 按 User-Agent 识别常见操作系统,并识别使用桌面标识的 iPad。
*
* @returns 无法识别或没有浏览器时返回 Unknown。
*/
export const detectOperatingSystem = () => {
const agent = globalThis.navigator?.userAgent ?? ''
if (
/iphone|ipad|ipod/i.test(agent) ||
(/macintosh/i.test(agent) && navigator.maxTouchPoints > 1)
) {
return OperatingSystem.IOS
}
if (/android/i.test(agent)) return OperatingSystem.Android
if (/windows/i.test(agent)) return OperatingSystem.Windows
if (/macintosh|mac os x/i.test(agent)) return OperatingSystem.MacOS
if (/linux/i.test(agent)) return OperatingSystem.Linux
return OperatingSystem.Unknown
}

View File

@ -0,0 +1 @@
export const getAppEnvironment = () => import.meta.env

View File

@ -1 +1,3 @@
export * from './prefix-cache-key'
export * from './get-app-environment'
export * from './detect-operating-system'

View File

@ -6,23 +6,10 @@ export interface PrefixCacheKeyOptions {
/**
*
* @param key pinia 缓存 key
* @param key 原始缓存键
* @param options 可覆盖默认前缀;前缀需包含所需分隔符
*
* @returns 返回拼接后的缓存 key
*
* @description
* 为缓存 key 添加前缀,以便于区分不同的缓存,避免缓存 key 冲突。
*
* 默认使用 APP_CATCH_KEY_PREFIX 作为前缀。
*
* 当你需要自定义前缀时,可以传入 customPrefix,当 customPrefix 存在时,会使用 customPrefix 作为前缀。
*
* @example
* // 假设 APP_CATCH_KEY_PREFIX = 'r-template:'
* prefixCacheKey('signing') // 返回 'r-template:signing'
*
* // customPrefix 自定义前缀
* prefixCacheKey('signing', { customPrefix: 'ray' }) // 返回 'ray:signing'
* @returns 直接拼接前缀和原始键后的结果。
*/
export const prefixCacheKey = (
key: string,

View File

@ -1,399 +1,5 @@
import { OperatingSystem } from '@/types'
import type {
AnyFn,
BasicTypes,
DownloadAnyFileDataType,
ValidateValueType,
} from '@/types'
/**
*
* @description
* 获取当前项目环境。
*
* 如果你只是想单纯的判断是否为开发环境,可以直接使用: __DEV__。
*
* @example
* 是否为开发环境: __DEV__
*
* @example
* // 获取 BASE_URL
* const { BASE_URL } = getAppEnvironment()
* // 获取 MODE,当前环境
* const { MODE } = getAppEnvironment()
* // 是否启用 SSR
* const { SSR } = getAppEnvironment()
* // 获取你自定义的配置项
* const { your config } = getAppEnvironment()
*/
export const getAppEnvironment = () => {
const env = import.meta.env
return env
}
/**
*
* @param data 二进制流数据
*
* @description
* 将二进制流数据转换为 base64 图片。
*
* @example
* const Image = arrayBufferToBase64Image('base64')
*/
export const arrayBufferToBase64Image = (data: ArrayBuffer) => {
const base64 =
'data:image/png;base64,' +
window.btoa(
new Uint8Array(data).reduce(
(data, byte) => data + String.fromCharCode(byte),
'',
),
)
return base64
}
/**
*
* @param base64 base64
* @param fileName file name
*
* @description
* 该方法仅能下载 base64 文件,如果有其他的文件类型需要下载,请看 downloadAnyFile 方法。
*
* @example
* downloadBase64File('base64', 'file name')
*/
export const downloadBase64File = (base64: string, fileName: string) => {
const link = document.createElement('a')
link.href = base64
link.download = fileName
link.style.display = 'none'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
/**
*
* @param value 目标值
* @param type 类型
*
* @example
* isValueType<string>('123', 'String') // true
* isValueType<object>({}, 'Object') // true
* isValueType<number>([], 'Array') // true
* isValueType<number>([], 'Object') // false
* isValueType<undefined>(undefined, 'Undefined') // true
* isValueType<null>(null, 'Null') // true
*/
export const isValueType = <T extends BasicTypes>(
value: unknown,
type: ValidateValueType,
): value is T => {
const valid = Object.prototype.toString.call(value)
return valid.includes(type)
}
/**
*
* @param length uuid 长度
* @param radix uuid 基数
*
* @description
* 生成指定长度的 uuid。
*
* @example
* uuid(8) => 'B8tGcl0FCKJkpO0V'
*/
export const uuid = (length = 16, radix = 62) => {
// 定义可用的字符集,即 0-9, A-Z, a-z
const availableChars =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
// 定义存储随机字符串的数组
const arr: string[] = []
// 获取加密对象,兼容 IE11
const cryptoObj = window.crypto || window.msCrypto
// 循环 length 次,生成随机字符,并添加到数组中
for (let i = 0; i < length; i++) {
// 生成一个随机数
const randomValues = new Uint32Array(1)
cryptoObj.getRandomValues(randomValues)
// 根据随机数生成对应的字符,并添加到数组中
const index = randomValues[0] % radix
arr.push(availableChars[index])
}
// 将数组中的字符连接起来,返回最终的字符串
return arr.join('')
}
/**
*
* @param data base64, Blob, ArrayBuffer type
* @param fileName file name
*
* @description
* 支持下载任意类型的文件,包括 base64, Blob, ArrayBuffer。
*
* @example
* downloadAnyFile('base64', 'file name')
* downloadAnyFile('Blob', 'file name')
*/
export const downloadAnyFile = (
data: DownloadAnyFileDataType,
fileName: string,
): Promise<void> => {
return new Promise<void>((resolve, reject) => {
let blobData!: Blob
try {
if (typeof data === 'string') {
downloadBase64File(data, fileName)
return resolve()
}
if (data instanceof ArrayBuffer) {
blobData = new Blob([new Uint8Array(data)], {
type: 'application/octet-stream',
})
} else if (data instanceof File || data instanceof Blob) {
blobData = data
} else {
return reject(new Error('downloadAnyFile: Unsupported data type.'))
}
const url = URL.createObjectURL(blobData)
const link = document.createElement('a')
link.href = url
link.download = fileName
link.style.display = 'none'
const remove = () => {
URL.revokeObjectURL(url)
document.body.removeChild(link)
}
link.addEventListener('load', () => {
remove()
return resolve()
})
link.addEventListener('error', (error) => {
remove()
return reject(error)
})
document.body.appendChild(link)
link.click()
return resolve()
} catch (error) {
return reject(error)
}
})
}
/**
*
* @param file file object
*
* @description
* 将 File 文件对象转换为 base64。
*
* @example
* const base64 = await fileToBase64(file) // 'data:image/png;base64,...'
*/
export const fileToBase64 = (file: File) => {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => {
resolve(reader.result as string)
}
reader.onerror = (error) => {
reject(error)
}
reader.readAsDataURL(file)
})
}
/**
*
* @param func 待判断的函数
* @returns 是否为 async 函数
*
* @description
* 判断是否为 async 函数。
*
* @example
* isAsyncFunction(() => {}) // false
* isAsyncFunction(async () => {}) // true
* isAsyncFunction(function() {}) // false
* isAsyncFunction(async function() {}) // true
*/
export const isAsyncFunction = <T>(func: T) => {
return func instanceof Function && func.constructor.name === 'AsyncFunction'
}
/**
*
* @param value 待判断的值
*
* @description
* 判断是否为 Promise 函数。
*
* @example
* isPromise(Promise.resolve(123)) // true
* isPromise(() => {}) // false
* isPromise(123) // false
* isPromise(async () => {}) // true
*/
export const isPromise = <T>(value: unknown): value is Promise<T> => {
if (isAsyncFunction(value)) {
return true
}
return (
!!value &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as Promise<T>).then === 'function'
)
}
/**
*
* @param fn 正常执行的函数
* @param errorCallback 错误回调
* @param args 当前传递函数参数
*
* @description
* 用于捕获函数执行时的错误,如果有错误,则执行错误回调。
*
* @example
* callWithErrorHandling((x: number) => { return x }, () => {}, [123]) => 123
* callWithErrorHandling((x: number) => { throw new Error('error') }, (error) => { console.log(error) }, [123]) => undefined
*/
export const callWithErrorHandling = <T extends AnyFn, E extends Error>(
fn: T,
errorCallback: AnyFn<E, void>,
args?: Parameters<T>,
) => {
let result: ReturnType<T> | undefined
try {
result = args ? fn(...args) : fn()
} catch (error) {
errorCallback(error as E)
}
return result
}
/**
*
* @param fn 正常执行的函数
* @param errorCallback 错误回调
* @param args 当前传递函数参数
*
* @description
* 用于捕获异步函数执行时的错误,如果有错误,则执行错误回调。
*
* @example
* callWithAsyncErrorHandling(async () => { console.log('A') }, () => {}, []) => Promise { undefined }
* callWithAsyncErrorHandling(() => { throw new Error('error') }, (error) => { console.log(error) }, []) => undefined
* callWithAsyncErrorHandling(async () => { return Promise.resolve('hello') }, () => {}, []) => Promise { 'hello' }
*/
export const callWithAsyncErrorHandling = async <
T extends AnyFn,
E extends Error,
>(
fn: T,
errorCallback: (error: E) => void,
args?: Parameters<T>,
): Promise<ReturnType<T> | undefined> => {
try {
if (!isPromise(fn)) {
return Promise.resolve(callWithErrorHandling(fn, errorCallback, args))
}
return await fn(...(args as Parameters<T>))
} catch (error) {
errorCallback(error as E)
return void 0
}
}
/**
*
* @description
* 获取当前操作系统。
*
* 如果无法识别,则返回 Unknown。
*
* @example
* detectOperatingSystem() // 'Windows' | 'MacOS' | 'Linux' | 'Android' | 'IOS' | 'Unknown'
*/
export const detectOperatingSystem = () => {
const userAgent = navigator.userAgent
if (/windows/i.test(userAgent)) {
return OperatingSystem.Windows
}
if (/macintosh|mac os x/i.test(userAgent)) {
return OperatingSystem.MacOS
}
if (/linux/i.test(userAgent)) {
return OperatingSystem.Linux
}
if (/android/i.test(userAgent)) {
return OperatingSystem.Android
}
if (/iphone|ipad|ipod/i.test(userAgent)) {
return OperatingSystem.IOS
}
return OperatingSystem.Unknown
}
/**
*
* @param path1 待比较的路径1
* @param path2 待比较的路径2
*
* @returns 比较两个路径是否相等
*
* @description
* 判断两个路径是否相等,忽略最后的斜杠。
*
* @example
* equal('/a/', '/a') // true
* equal('/a', '/a') // true
*/
export const equalRouterPath = (path1: string, path2: string) => {
const p1 = path1.split('?').filter(Boolean)[0]
const p2 = path2.split('?').filter(Boolean)[0]
const regex = /\/$/
return p1.replace(regex, '') === p2.replace(regex, '')
}
export * from './core'
export * from './files'
export { detectOperatingSystem } from './app/detect-operating-system'
export { getAppEnvironment } from './app/get-app-environment'
export { equalRouterPath } from './equal-router-path'

View File

@ -1,2 +1 @@
/** 历史加解密格式使用的默认密钥。 */
export const CRYPTO_KEY = '4cP+dX5FI2EVYzln'
export * from '../legacy-crypto/constant'

View File

@ -1,31 +1 @@
import { AES, enc } from 'crypto-js'
import { CRYPTO_KEY } from './constant'
import type { CipherParams, WordArray } from './types'
/**
*
* @param data AES 加密后的数据
* @param key 解密 key
*
* @description
* 使用 AES 解密数据。
*
* @example
* const data = 'U2FsdGVkX1+3Q
* const key = CRYPTO_KEY
*
* const decrypted = decrypt(data, key) // { name: 'John Doe' }
*/
export const decrypt = (
data: string | CipherParams,
key?: string | WordArray,
) => {
try {
const decrypted = AES.decrypt(data, key || CRYPTO_KEY)
const decryptedData = decrypted.toString(enc.Utf8)
return JSON.parse(decryptedData)
} catch (e) {
console.error(`Unknown error: ${e}`)
}
}
export * from '../legacy-crypto/decrypt'

View File

@ -1,23 +1 @@
import { AES } from 'crypto-js'
import { CRYPTO_KEY } from './constant'
import type { WordArray } from './types'
/**
*
* @param data 待加密数据
* @param key 加密 key
*
* @description
* 使用 AES 加密数据。
*
* @example
* const data = { name: 'John Doe' }
* const key = CRYPTO_KEY
*
* const encrypted = encrypt(data, key) // 'U2FsdGVkX1+3Q'
*/
export const encrypt = (data: unknown, key?: string | WordArray) => {
const encrypted = AES.encrypt(JSON.stringify(data), key || CRYPTO_KEY)
return encrypted.toString()
}
export * from '../legacy-crypto/encrypt'

View File

@ -1,5 +1 @@
import { CRYPTO_KEY } from './constant'
import { decrypt } from './decrypt'
import { encrypt } from './encrypt'
export { CRYPTO_KEY, decrypt, encrypt }
export * from '../legacy-crypto'

View File

@ -1,4 +1 @@
import type CryptoJS from 'crypto-js'
export type WordArray = CryptoJS.lib.WordArray
export type CipherParams = CryptoJS.lib.CipherParams
export * from '../legacy-crypto/types'

View File

@ -1,62 +1,47 @@
import { APP_CATCH_KEY_PREFIX } from '@/app-config'
import type { RemoveStorageFC, StorageLike, StorageOptions } from '@/types'
import { prefixCacheKey } from './app/prefix-cache-key'
/**
* @param type 存储类型
* @returns Storage 实例
*/
const getStorageInstance = (type: StorageLike = 'sessionStorage'): Storage =>
type === 'localStorage' ? window.localStorage : window.sessionStorage
/**
* 获取带前缀的键名
* @param key 原始键名
* @param options 配置项
* @returns 处理后的键名
*/
const getKeyWithPrefix = (key: string, options?: StorageOptions): string => {
const { prefix, prefixKey } = options ?? {}
return prefix ? (prefixKey || APP_CATCH_KEY_PREFIX) + key : key
}
const getKeyWithPrefix = (key: string, options?: StorageOptions): string =>
options?.prefix
? prefixCacheKey(key, { customPrefix: options.prefixKey })
: key
/**
* @param key 需要查找的缓存值key
* @param storageType 需要查找的缓存类型
* @param options 配置项
*
* @description
* 查找当前缓存中是否含有某个 key。
* 默认查找 sessionStorage。
* @param key 缓存键
* @param storageType 存储区域,默认 sessionStorage
* @param options 键前缀配置
*
* @example
* hasStorage('signing') // 查找 session 中 signing 缓存字段
* @returns 键是否存在;浏览器拒绝访问存储时返回 false。
*/
function hasStorage(
key: string,
storageType: StorageLike = 'sessionStorage',
options?: StorageOptions,
) {
const prefixedKey = getKeyWithPrefix(key, options)
const storage = getStorageInstance(storageType)
return Object.keys(storage).includes(prefixedKey)
try {
return (
getStorageInstance(storageType).getItem(
getKeyWithPrefix(key, options),
) !== null
)
} catch {
return false
}
}
/**
* @param key 需要设置的缓存值key
* @param value 需要设置的值
* @param storageType 需要设置的缓存类型
* @param options 配置项
*
* @param key 非空缓存键
* @param value 可序列化为 JSON 的值
* @param storageType 存储区域,默认 sessionStorage
* @param options 键前缀配置
*
* @description
* 设置缓存值,默认设置 sessionStorage。
* 如果 key 为空,则会打印错误信息。
*
* @example
* setStorage('demo', 'hi') // 设置 session 中 demo 缓存字段
* setStorage('demo', 'hi', 'localStorage') // 设置 local 中 demo 缓存字段
* setStorage('demo', 'hi', 'sessionStorage', { prefix: true, prefixKey: 'ray' }) // 设置 session 中 ray_demo 缓存字段
* 写入 JSON;键为空、值不可序列化或浏览器拒绝写入时记录错误。
*/
function setStorage<T = unknown>(
key: string,
@ -70,11 +55,15 @@ function setStorage<T = unknown>(
return
}
const prefixedKey = getKeyWithPrefix(key, options)
const storage = getStorageInstance(storageType)
try {
storage.setItem(prefixedKey, JSON.stringify(value))
const data = JSON.stringify(value)
if (data === void 0) throw new TypeError('Value is not JSON serializable.')
getStorageInstance(storageType).setItem(
getKeyWithPrefix(key, options),
data,
)
} catch (error) {
console.error(
`[setStorage]: Failed to set stored data for key '${key}'`,
@ -83,72 +72,45 @@ function setStorage<T = unknown>(
}
}
function getStorage<T = unknown>(
key: string,
storageType: StorageLike,
options: StorageOptions<T> & { defaultValue: T },
): T
function getStorage<T = unknown>(
key: string,
storageType?: StorageLike,
options?: Omit<StorageOptions<T>, 'defaultValue'>,
): T | null
/**
* @param key 需要获取的缓存值key
* @param storageType 需要获取的缓存类型
* @param options 配置项
*
* @description
* 获取缓存值。
* 默认获取 sessionStorage。
* 如果 key 为空,则会打印错误信息。
* @param key 缓存键
* @param storageType 存储区域,默认 sessionStorage
* @param options 键前缀与回退值配置
*
* @example
* getStorage('demo') // 获取 session 中 demo 缓存字段
* getStorage('demo', 'localStorage') // 获取 local 中 demo 缓存字段
* getStorage('demo', 'sessionStorage', { prefix: true, prefixKey: 'ray' }) // 获取 session 中 ray_demo 缓存字段
* @returns JSON 值;键不存在、内容损坏或无法读取时返回回退值或 null。
*/
function getStorage<T = unknown>(
key: string,
storageType: StorageLike = 'sessionStorage',
options?: StorageOptions<T>,
): T | null {
const prefixedKey = getKeyWithPrefix(key, options)
const storage = getStorageInstance(storageType)
const { defaultValue } = options ?? {}
const fallback = options?.defaultValue ?? null
try {
const data = storage.getItem(prefixedKey)
const data = getStorageInstance(storageType).getItem(
getKeyWithPrefix(key, options),
)
return data === null ? (defaultValue ?? null) : (JSON.parse(data) as T)
return data === null ? fallback : (JSON.parse(data) as T)
} catch (error) {
console.error(
`[getStorage]: Failed to get stored data for key '${key}'`,
error,
)
return defaultValue ?? null
return fallback
}
}
/**
* @param key 需要删除的缓存值key
* @param storageType 需要删除的缓存类型
* @param options 配置项
*
* @param key 缓存键,或批量删除标识 __all__、__all_sessionStorage__、__all_localStorage__
* @param storageType 目标存储区域;批量删除时由标识决定
* @param options 键前缀配置;批量删除时只清理符合前缀的键
*
* @description
* 删除缓存值。
* 默认删除 sessionStorage。
* 预保留了 __all__、__all_sessionStorage__、__all_localStorage__ 三个 key,
* 分别代表清空所有缓存、清空 sessionStorage 缓存、清空 localStorage 缓存。
*
* @example
* removeStorage('__all__', 'all') // 清空所有缓存
* removeStorage('__all_sessionStorage__', 'sessionStorage') // 清空 sessionStorage 缓存
* removeStorage('__all_localStorage__', 'localStorage') // 清空 localStorage 缓存
* removeStorage('signing', 'sessionStorage' || 'localStorage') // 清空 session 或者 localStorage 中 signing 缓存字段
* 删除缓存;浏览器拒绝操作时记录错误。
*/
const removeStorage: RemoveStorageFC = (key, storageType, options) => {
if (!key) {
@ -157,38 +119,50 @@ const removeStorage: RemoveStorageFC = (key, storageType, options) => {
return
}
const prefixedKey = getKeyWithPrefix(key, options)
const localStorage = window.localStorage
const sessionStorage = window.sessionStorage
const remove = (type: StorageLike, all = false) => {
try {
const storage = getStorageInstance(type)
/**
* @param storage 存储实例
*/
const removeFromStorage = (storage: Storage) => {
Object.keys(storage).forEach((k) =>
storage.removeItem(getKeyWithPrefix(k, options)),
)
if (!all) {
storage.removeItem(getKeyWithPrefix(key, options))
return
}
const prefix = getKeyWithPrefix('', options)
if (!prefix) {
storage.clear()
return
}
for (let index = storage.length - 1; index >= 0; index--) {
const storedKey = storage.key(index)
if (storedKey?.startsWith(prefix)) storage.removeItem(storedKey)
}
} catch (error) {
console.error(
`[removeStorage]: Failed to remove stored data for key '${key}'`,
error,
)
}
}
switch (key) {
case '__all__':
removeFromStorage(localStorage)
removeFromStorage(sessionStorage)
remove('localStorage', true)
remove('sessionStorage', true)
break
case '__all_sessionStorage__':
removeFromStorage(sessionStorage)
remove('sessionStorage', true)
break
case '__all_localStorage__':
removeFromStorage(localStorage)
remove('localStorage', true)
break
default:
getStorageInstance(storageType as StorageLike).removeItem(prefixedKey)
remove(storageType === 'localStorage' ? 'localStorage' : 'sessionStorage')
}
}

127
src/utils/core/index.ts Normal file
View File

@ -0,0 +1,127 @@
import type { AnyFn, BasicTypes, ValidateValueType } from '@/types'
/**
*
* @param value 待判断的值
* @param type 要匹配的完整类型标签
*
* @description
* 按 Object.prototype.toString 的标签判断。普通函数和异步函数都匹配 Function。
*/
export const isValueType = <T extends BasicTypes>(
value: unknown,
type: ValidateValueType,
): value is T => {
const tag = Object.prototype.toString.call(value)
return (
tag === `[object ${type}]` ||
(type === 'Function' && typeof value === 'function')
)
}
/**
*
* @param length 生成的字符数
* @param radix 从字符集开头可选的字符数,范围 1 到 62
*
* @description
* 使用 Web Crypto 生成随机标识,字符集依次为数字、大写字母、小写字母。
*
* @throws 长度不是非负安全整数,或基数超出范围时抛出 RangeError。
*/
export const uuid = (length = 16, radix = 62) => {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
if (
!Number.isSafeInteger(length) ||
length < 0 ||
!Number.isInteger(radix) ||
radix < 1 ||
radix > chars.length
) {
throw new RangeError('[uuid]: Invalid length or radix.')
}
const range = 2 ** 32
const limit = range - (range % radix)
const sample = new Uint32Array(1)
let result = ''
while (result.length < length) {
crypto.getRandomValues(sample)
// 丢弃无法均匀分配到字符集的样本。
if (sample[0] < limit) result += chars[sample[0] % radix]
}
return result
}
/**
*
* @param func 待判断的值
*
* @returns 是否为 async 声明的函数;普通的 Promise 工厂函数返回 false。
*/
export const isAsyncFunction = (func: unknown) =>
typeof func === 'function' &&
Object.prototype.toString.call(func) === '[object AsyncFunction]'
/**
*
* @param value 待判断的值
*
* @returns 是否存在可调用的 then;async 函数本身不属于 PromiseLike。
*/
export const isPromise = <T>(value: unknown): value is PromiseLike<T> =>
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as PromiseLike<T>).then === 'function'
/**
*
* @param fn 待执行的函数
* @param errorCallback 同步抛错时执行的回调
* @param args 调用参数,省略时不传参
*
* @returns 函数结果,或处理错误后的 undefined。
*
* @throws 错误回调自身抛出的异常会传给调用方。
*/
export const callWithErrorHandling = <T extends AnyFn, E extends Error>(
fn: T,
errorCallback: (error: E) => void,
args?: Parameters<T>,
): ReturnType<T> | undefined => {
try {
return fn(...(args ?? []))
} catch (error) {
errorCallback(error as E)
}
}
/**
*
* @param fn 待执行的函数
* @param errorCallback 同步抛错或返回值拒绝时执行的回调
* @param args 调用参数,省略时不传参
*
* @returns 等待后的结果,或处理错误后的 undefined。
*
* @throws 错误回调自身抛出时,返回的 Promise 会拒绝。
*/
export const callWithAsyncErrorHandling = async <
T extends AnyFn,
E extends Error,
>(
fn: T,
errorCallback: (error: E) => void,
args?: Parameters<T>,
): Promise<Awaited<ReturnType<T>> | undefined> => {
try {
return await fn(...(args ?? []))
} catch (error) {
errorCallback(error as E)
}
}

View File

@ -1,15 +0,0 @@
// import HmacSHA256 from 'crypto-js/hmac-sha256'
// import SHA256 from 'crypto-js/sha256'
// import AES from 'crypto-js/aes'
// import MD5 from 'crypto-js/md5'
// import BASE64 from 'crypto-js/enc-base64'
// import type { WordArray, CipherParams } from '@/types'
/**
*
* 这个玩意儿实际使用意义不大, 建议自己参考官网 demo 使用
* 我又不想删除, 所以留在这儿了
*
* 手动补上官网地址: http://github.com/brix/crypto-js
*/

View File

@ -1,66 +1,50 @@
import { useDomToImage, usePrint } from '@/hooks'
import type { UseDomToImageOptions, UsePrintOptions } from '@/hooks'
import { useDomToImage } from '@/hooks/web/useDomToImage'
import type { UseDomToImageOptions } from '@/hooks/web/useDomToImage'
import { usePrint } from '@/hooks/web/usePrint'
import type { UsePrintOptions } from '@/hooks/web/usePrint'
import type { BasicTarget } from '@/types'
import { omit } from 'lodash-es'
export interface PrintDomOptions {
printOptions?: Omit<UsePrintOptions, 'printable' | 'type' | 'base64'>
domToImageOptions?: Omit<UseDomToImageOptions, 'imageType'>
export interface PrintDomOptions<T extends HTMLElement = HTMLElement> {
printOptions?: Omit<UsePrintOptions, 'type' | 'base64'>
domToImageOptions?: Omit<UseDomToImageOptions<T>, 'imageType'>
}
/**
*
* @param target ref dom
* @param options print-dom options, dom-to-image options
* @param target 截图的 DOM 目标,执行时解包
* @param options 截图与打印配置
*
* @description
* 基于 useDomToImage 和 print-js 封装,允许 Ref 注册 Dom 直接调用打印。
* 避免直接打印 dom 时出现一些诡异的问题。
* 将目标转成 JPEG 后交给打印预览,并同步全局加载条。
*
* 该方法会强制剔除 printOptions 中的 printable, type, base64 属性,即使忽略了 ts 的类型检查。
* 并且在绘制图片的时候,强制使用 jpeg 格式,即使是指定了其他格式。
*
* 支持 useDomToImage 方法的所有配置项,除了 imageType。
* 支持 print-js 的所有配置项,除了 printable 和 type。
*
* @example
* const refDom = ref<HTMLElement>()
*
* printDom(refDom, {
* printOptions: { title: 'Demo Print', ... },
* domToImageOptions: { ... }
* })
* @returns 已调用打印预览时返回 true;截图或调用失败时记录错误并返回 false。
*/
export const printDom = <T extends HTMLElement>(
export const printDom = async <T extends HTMLElement>(
target: BasicTarget<T>,
options?: PrintDomOptions,
options?: PrintDomOptions<T>,
) => {
const { domToImageOptions, printOptions } = options ?? {}
const loading = window.$loadingBar
const { create } = useDomToImage(target, {
...domToImageOptions,
beforeCreate: (element) => {
domToImageOptions?.beforeCreate?.(element)
window.$loadingBar?.start()
},
created(result, element) {
domToImageOptions?.created?.(result, element)
window.$loadingBar?.finish()
},
createdError(error) {
domToImageOptions?.createdError?.(error)
window.$loadingBar?.error()
},
} as UseDomToImageOptions)
try {
loading?.start()
create('jpeg')?.then((res) => {
const { print } = usePrint(res, {
const { create } = useDomToImage(target, options?.domToImageOptions)
const image = await create('jpeg')
await usePrint(image, {
targetStyles: ['*'],
...options?.printOptions,
type: 'image',
base64: true,
targetStyles: ['*'],
...omit(printOptions as UsePrintOptions, ['type', 'base64']),
})
}).print()
print()
})
loading?.finish()
return true
} catch (error) {
loading?.error()
console.error('[printDom]: Could not open print preview.', error)
return false
}
}

View File

@ -1,298 +1,179 @@
import { APP_REGEX } from '@/app-config'
import type {
BasicTarget,
ElementSelector,
QueryElementsOptions,
Recordable,
} from '@/types'
import { effectDispose, isValueType, unrefElement } from '@/utils'
import type { CSSProperties } from 'vue'
import { unrefElement } from './vue/unref-element'
const classTokens = (names: string | string[]) =>
(typeof names === 'string' ? [names] : names)
.flatMap((name) => name.split(/[\t\n\f\r ]+/))
.filter(Boolean)
/**
*
* @param target 目标元素或 ref 注册元素
* @param classNames 所需添加类名
* @param target 元素或可响应的元素引用
* @param classNames 空白分隔的类名或类名数组
*
* @description
* 为目标元素添加类名。
*
* @example
* // targetDom 当前 class: a-class b-class
* setClass(targetDom, 'c-class') // a-class b-class c-class
* setClass(targetDom, ['c-class', 'c-class']) // a-class b-class c-class
* 给当前和后续替换的元素添加类名。
*/
export const setClass = (
target: BasicTarget<Element | HTMLElement | SVGAElement>,
target: BasicTarget<Element>,
classNames: string | string[],
) => {
const update = () => {
const element = unrefElement(target)
const tokens = classTokens(classNames)
if (element) {
const classes =
typeof classNames === 'string'
? classNames.trim().split(' ')
: classNames
classes.forEach((item) => {
if (item) {
element.classList.add(item)
}
})
}
}
const watcher = watch(() => unrefElement(target), update, {
immediate: true,
})
effectDispose(watcher)
watch(
() => unrefElement(target),
(element) => element?.classList.add(...tokens),
{ immediate: true },
)
}
/**
*
* @param target 目标元素或 ref 注册元素
* @param className 所需删除类名
* @param target 元素或可响应的元素引用
* @param classNames 要移除的类名;removeAllClass 清空整个类名列表
*
* @description
* 为目标元素删除类名。
*
* @example
* // targetDom 当前 class: a-class b-class
* removeClass(targetDom, 'a-class') // b-class
* removeClass(targetDom, ['a-class', 'b-class']) // null
* removeClass(targetDom, 'removeAllClass') // null
* 操作当前和后续替换的元素。
*/
export const removeClass = (
target: BasicTarget<Element | HTMLElement | SVGAElement>,
classNames: string | 'removeAllClass' | string[],
target: BasicTarget<Element>,
classNames: string | string[],
) => {
const update = () => {
const element = unrefElement(target)
if (element) {
watch(
() => unrefElement(target),
(element) => {
if (classNames === 'removeAllClass') {
const classList = element.classList
classList.forEach((curr) => classList.remove(curr))
element?.removeAttribute('class')
} else {
const classes =
typeof classNames === 'string'
? classNames.trim().split(' ')
: classNames
classes.forEach((item) => {
if (item) {
element.classList.remove(item)
}
})
element?.classList.remove(...classTokens(classNames))
}
}
}
const watcher = watch(() => unrefElement(target), update, {
immediate: true,
})
effectDispose(watcher)
},
{ immediate: true },
)
}
/**
*
* @param target 目标元素或 ref 注册元素
* @param className 查询元素是否含有此类名
* @param target 元素或可响应的元素引用
* @param classNames 待查找的类名
*
* @description
* 查询元素是否含有此类名。
*
* @example
* hasClass(targetDom, 'matchClassName') // Ref<true> | Ref<false>
* hasClass(targetDom, ['matchClassName', 'matchClassName']) // Ref<true> | Ref<false>
* @returns 当前元素是否含至少一个完整类名;随引用更新,不监听外部 class 修改。
*/
export const hasClass = (
target: BasicTarget<Element>,
classNames: string | string[],
) => {
const hasClassRef = ref(false)
const result = ref(false)
const tokens = classTokens(classNames)
const update = () => {
const element = unrefElement(target)
watch(
() => unrefElement(target),
(element) => {
result.value = tokens.some((token) => element?.classList.contains(token))
},
{ immediate: true },
)
if (!element) {
hasClassRef.value = false
} else {
const elementClassName = element.className
const classes =
typeof classNames === 'string'
? classNames
.trim()
.split(' ')
.filter((curr: string) => curr !== '')
: classNames
hasClassRef.value = classes.some((curr) =>
elementClassName.includes(curr),
)
}
}
const watcher = watch(() => unrefElement(target), update, {
immediate: true,
})
effectDispose(watcher)
return hasClassRef
return result
}
/**
*
* @param style 所需添加样式
* @param style CSS 属性名
*
* @returns 添加前缀后的样式
*
* @description
* 为样式添加浏览器前缀,返回一个对象。
*
* @example
* autoPrefixStyle('transform') // {webkitTransform: 'transform', mozTransform: 'transform', msTransform: 'transform', oTransform: 'transform'}
* @returns 旧版兼容映射,包含原名和历史 camelCase 前缀名。
*/
export const autoPrefixStyle = (style: string) => {
const prefixes = ['webkit', 'moz', 'ms', 'o']
const styleWithPrefixes: Recordable = {}
export const autoPrefixStyle = (style: string) =>
Object.fromEntries([
...['webkit', 'moz', 'ms', 'o'].map((prefix) => [
`${prefix}${style.charAt(0).toUpperCase()}${style.slice(1)}`,
style,
]),
[style, style],
])
prefixes.forEach((prefix) => {
styleWithPrefixes[
`${prefix}${style.charAt(0).toUpperCase()}${style.slice(1)}`
] = style
})
styleWithPrefixes[style] = style
return styleWithPrefixes
}
const cssProperty = (key: string) =>
key.startsWith('--')
? key
: key
.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)
.replace(/^(webkit|moz|ms|o)-/, '-$1-')
/**
*
* @param target Target element dom
* @param styles 所需绑定样式(如果为字符串, 则必须以分号结尾每个行内样式描述)
* @param target 元素或可响应的元素引用
* @param styles CSS 声明字符串、声明数组或属性对象
*
* @description
* 为目标元素添加样式。
*
* @example
* style of string
* ```
* const styles = 'width: 100px; height: 100px; background: red;'
*
* setStyle(styles)
* ```
* style of object
* ```
* const styles = {
* width: '100px',
* height: '100px',
* }
*
* setStyle(styles)
* ```
* 保留已有的其他行内样式,支持 camelCase、自定义属性和 !important。
*/
export const setStyle = <Style extends CSSProperties>(
target: BasicTarget<HTMLElement | SVGAElement>,
target: BasicTarget<HTMLElement | SVGElement>,
styles: Partial<Style> | string | string[],
) => {
const set = (styleStr: string, element: HTMLElement | SVGAElement) => {
styleStr.split(';').forEach((curr) => {
const [key, value] = curr.split(':')
watch(
() => unrefElement(target),
(element) => {
if (!element) return
if (key && value) {
const trimKey = key.trim()
const trimValue = value.trim()
if (typeof styles === 'string' || Array.isArray(styles)) {
const parsed = element.ownerDocument.createElement('span').style
// 是否为 css variable
if (key.startsWith('--')) {
element.style.setProperty(trimKey, trimValue)
} else if (key.startsWith('-')) {
element.style.setProperty(key, value)
} else {
// 兼容浏览器前缀
const kitFix = autoPrefixStyle(trimKey)
// 让浏览器解析带冒号、分号或引号的属性值。
parsed.cssText = typeof styles === 'string' ? styles : styles.join(';')
Object.keys(kitFix).forEach((key) => {
element.style.setProperty(key, kitFix[key])
})
for (let index = 0; index < parsed.length; index++) {
const key = parsed.item(index)
// 设置默认需要添加样式
element.style.setProperty(trimKey, trimValue)
element.style.setProperty(
key,
parsed.getPropertyValue(key),
parsed.getPropertyPriority(key),
)
}
} else {
for (const [key, value] of Object.entries(styles)) {
if (value == null) continue
const text = String(value)
const important = /\s*!important\s*$/i
element.style.setProperty(
cssProperty(key),
text.replace(important, ''),
important.test(text) ? 'important' : '',
)
}
}
})
}
const update = () => {
const element = unrefElement(target)
if (!element) {
return
}
if (isValueType<string>(styles, 'String')) {
set(styles, element)
} else if (isValueType<string[]>(styles, 'Array')) {
styles.forEach((curr) => {
set(curr, element)
})
} else {
const keys = Object.keys(styles)
keys.forEach((curr) => {
set(`${curr}: ${styles[curr as keyof typeof styles]}`, element)
})
}
}
const watcher = watch(() => unrefElement(target), update, {
immediate: true,
})
effectDispose(watcher)
},
{ immediate: true },
)
}
/**
*
* @param el Target element dom
* @param styles 所需卸载样式
* @param target 元素或可响应的元素引用
* @param styles 要删除的 CSS 属性名
*
* @description
* 为目标元素卸载样式。
*
* 当你发现不能正常的移除某些样式的时候,应该考虑是否是样式表兼容问题。
*
* @example
* removeStyle(['zIndex', 'z-index'])
* 支持 camelCase 和 CSS 原生属性名。
*/
export const removeStyle = (
target: BasicTarget<HTMLElement | SVGAElement>,
styles: ((keyof CSSProperties & string) | string)[],
target: BasicTarget<HTMLElement | SVGElement>,
styles: string[],
) => {
const update = () => {
const element = unrefElement(target)
if (!element) {
return
}
styles.forEach((curr) => {
element.style.removeProperty(curr)
})
}
const watcher = watch(() => unrefElement(target), update, {
immediate: true,
})
effectDispose(watcher)
watch(
() => unrefElement(target),
(element) => {
styles.forEach((name) => element?.style.removeProperty(cssProperty(name)))
},
{ immediate: true },
)
}
/**
@ -302,17 +183,8 @@ export const removeStyle = (
* @param defaultColor 默认颜色值
*
* @description
* 转换 rgb/hex/hsl 颜色;已有 rgba/hsla 会更新 alpha,八位 hex 保留自带透明度。
* 转换 rgb/hex/hsl 颜色;已有 rgba/hsla 会更新 alpha,四位和八位 hex 保留自带透明度。
* 无法识别时返回默认色或原始值。
*
* @example
* colorToRgba('#123632', 0.8) // rgba(18, 54, 50, 0.8)
* colorToRgba('rgb(18, 54, 50)', 0.8) // rgba(18, 54, 50, 0.8)
* colorToRgba('#ee4f12', 0.3) // rgba(238, 79, 18, 0.3)
* colorToRgba('rgba(238, 79, 18, 0.3)', 0.3) // rgba(238, 79, 18, 0.3)
* colorToRgba('not a color', 0.3, '#000') // #000
* colorToRgba('hsl(0, 100%, 50%)', 0.5) // hsla(0, 100%, 50%, 0.5)
* colorToRgba('not a color') // not a color
*/
export const colorToRgba = (
color: string,
@ -323,8 +195,12 @@ export const colorToRgba = (
return defaultColor || color
}
const original = color
color = color.trim().toLowerCase()
// 处理 rgba 格式 - 替换原有的 alpha 值
if (color.includes('rgba')) {
if (/^rgba\([^,]+,[^,]+,[^,]+,[^,]+\)$/.test(color)) {
return color.replace(
/rgba\((.*?),(.*?),(.*?),.*?\)/,
(_, r: string, g: string, b: string) =>
@ -333,12 +209,12 @@ export const colorToRgba = (
}
// 处理 rgb 格式
if (color.includes('rgb(')) {
if (/^rgb\([^,]+,[^,]+,[^,]+\)$/.test(color)) {
return color.replace('rgb', 'rgba').replace(')', `, ${alpha})`)
}
// 处理 hsla 格式 - 替换原有的 alpha 值
if (color.includes('hsla')) {
if (/^hsla\([^,]+,[^,]+,[^,]+,[^,]+\)$/.test(color)) {
return color.replace(
/hsla\((.*?),(.*?),(.*?),.*?\)/,
(_, h: string, s: string, l: string) =>
@ -347,58 +223,37 @@ export const colorToRgba = (
}
// 处理 hsl 格式
if (color.includes('hsl(')) {
if (/^hsl\([^,]+,[^,]+,[^,]+\)$/.test(color)) {
return color.replace('hsl', 'hsla').replace(')', `, ${alpha})`)
}
// 处理 hex 格式
if (color.startsWith('#')) {
const hex = color.replace('#', '')
if (/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(color)) {
const hex = color.slice(1)
const channels =
hex.length <= 4
? [...hex].map((channel) => parseInt(channel + channel, 16))
: hex.match(/../g)!.map((channel) => parseInt(channel, 16))
const [r, g, b, embeddedAlpha] = channels
const opacity =
embeddedAlpha === void 0
? alpha
: Number((embeddedAlpha / 255).toFixed(2))
try {
switch (hex.length) {
case 3:
return `rgba(${parseInt(hex[0] + hex[0], 16)}, ${parseInt(hex[1] + hex[1], 16)}, ${parseInt(hex[2] + hex[2], 16)}, ${alpha})`
case 6:
return `rgba(${parseInt(hex.slice(0, 2), 16)}, ${parseInt(hex.slice(2, 4), 16)}, ${parseInt(hex.slice(4, 6), 16)}, ${alpha})`
case 8:
return `rgba(${parseInt(hex.slice(0, 2), 16)}, ${parseInt(hex.slice(2, 4), 16)}, ${parseInt(hex.slice(4, 6), 16)}, ${Number((parseInt(hex.slice(6, 8), 16) / 255).toFixed(2))})`
default:
return defaultColor || color
}
} catch {
return defaultColor || color
}
return `rgba(${r}, ${g}, ${b}, ${opacity})`
}
// 返回原始字符串或默认值
return defaultColor || color
return defaultColor ?? original
}
/**
*
* @param element 需要匹配元素参数名称
* @returns 匹配元素列表
* @param selector CSS 选择器,也可用 attr: 前缀简写属性选择器
* @param options 无匹配或选择器无效时的回退元素
*
* @description
* 使用 querySelectorAll 作为检索方法。
*
* 如果希望按照 attribute 匹配, 仅需要 'attr:xxx'传递参数即可。
*
* @example
* // class:
* const el = queryElements('.demo')
* // id:
* const el = queryElements('#demo')
* // attribute:
* const el = queryElements('attr:type=button')
* // 或者可以这样写
* const el = queryElements('attr:type')
* // 默认元素
* const el = queryElements('.demo', { defaultElement: document.body })
* @returns 匹配元素列表;选择器为空或无效且没有回退元素时返回 null。
*/
export const queryElements = <T extends Element = Element>(
selector: ElementSelector,
@ -438,21 +293,9 @@ export const queryElements = <T extends Element = Element>(
* @param unit 自动填充 css 尺寸单位
*
* @description
* 自动补全尺寸。
* 仅给数字或无单位的数字字符串补单位;保留原有 CSS 关键字和表达式。
*/
export const completeSize = (size: number | string, unit = 'px') => {
if (size === 'auto') {
return size
}
if (typeof size === 'number') {
return size.toString() + unit
} else if (
isValueType<string>(size, 'String') &&
APP_REGEX.cssUnit.test(size)
) {
return size
} else {
return size + unit
}
}
export const completeSize = (size: number | string, unit = 'px') =>
typeof size === 'number' || /^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(size.trim())
? `${typeof size === 'number' ? size : size.trim()}${unit}`
: size

View File

@ -0,0 +1,14 @@
/**
*
* @param path1 第一个路由路径
* @param path2 第二个路由路径
*
* @description
* 比较路径,忽略查询参数、片段和末尾斜杠。
*/
export const equalRouterPath = (path1: string, path2: string) => {
const normalize = (path: string) =>
path.split(/[?#]/, 1)[0].replace(/\/+$/, '')
return normalize(path1) === normalize(path2)
}

101
src/utils/files/index.ts Normal file
View File

@ -0,0 +1,101 @@
import type { DownloadAnyFileDataType } from '@/types'
/**
*
* @param data PNG 图像的原始字节
*
* @returns PNG Data URL。
*/
export const arrayBufferToBase64Image = (data: ArrayBuffer) =>
'data:image/png;base64,' +
btoa(
Array.from(new Uint8Array(data), (byte) => String.fromCharCode(byte)).join(
'',
),
)
/**
*
* @param base64 待下载的 Data URL
* @param fileName 建议文件名
*
* @description
* 触发浏览器下载并清理临时链接。
*/
export const downloadBase64File = (base64: string, fileName: string) => {
const link = document.createElement('a')
link.href = base64
link.download = fileName
link.hidden = true
document.body.appendChild(link)
try {
link.click()
} finally {
link.remove()
}
}
/**
*
* @param data Data URL、Blob、File 或 ArrayBuffer
* @param fileName 建议文件名
*
* @description
* 发起浏览器下载请求,不等待磁盘写入。为二进制内容创建临时对象 URL,
* 并延迟释放,以便浏览器开始读取。
*
* @throws 数据类型不支持或下载链接无法触发时拒绝。
*/
export const downloadAnyFile = async (
data: DownloadAnyFileDataType,
fileName: string,
): Promise<void> => {
if (typeof data === 'string') {
downloadBase64File(data, fileName)
return
}
const blob =
data instanceof ArrayBuffer
? new Blob([data], { type: 'application/octet-stream' })
: data
if (!(blob instanceof Blob)) {
throw new TypeError('[downloadAnyFile]: Unsupported data type.')
}
const url = URL.createObjectURL(blob)
try {
downloadBase64File(url, fileName)
} catch (error) {
URL.revokeObjectURL(url)
throw error
}
// 锚点下载不会触发 load;留出时间给浏览器接管对象 URL。
setTimeout(() => URL.revokeObjectURL(url), 1000)
}
/**
*
* @param file 待读取的文件
*
* @returns 包含 MIME 类型的 Data URL。
*
* @throws 文件读取失败或中止时拒绝。
*/
export const fileToBase64 = (file: File) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result as string)
reader.onerror = () => reject(reader.error)
reader.onabort = () =>
reject(new DOMException('File read aborted', 'AbortError'))
reader.readAsDataURL(file)
})

View File

@ -1,5 +1,12 @@
type ValueType = number | [number, number] | null
/**
*
* @param value Naive UI 日期选择器的值
* @param isRange 是否使用范围模式
*
* @returns 清空的范围返回 [null, null],其余保留原值。
*/
export function getDateByNaiveDatePicker<
T extends ValueType = ValueType,
V extends boolean = boolean,
@ -8,29 +15,6 @@ export function getDateByNaiveDatePicker<
isRange: V,
): V extends true ? (T extends null ? [null, null] : T) : T
/**
*
* @param value date value
* @param isRange date picker type props is range type
*
* @description
* 辅助获取 naive date picker 组件获取 value 的方法。
*
* 如果使用 BDatePicker 组件启用的 type 模式为 range,则需要设置第二个参数为 true,否则设置为 false。
*
* @example
* // s1: null, e1: null
* const [s1, e1] = getDateByNaiveDatePicker(null, true)
* // s2: null
* const s2 = getDateByNaiveDatePicker(null, false)
* // s3: new Date().getTime()
* const s3 = getDateByNaiveDatePicker(new Date().getTime(), false)
* // s4: new Date().getTime(), e4: new Date().getTime()
* const [s4, e4] = getDateByNaiveDatePicker(
* [new Date().getTime(), new Date().getTime()],
* true,
* )
*/
export function getDateByNaiveDatePicker(value: ValueType, isRange: boolean) {
if (value === null) {
return isRange ? [null, null] : null

View File

@ -1,14 +1,14 @@
import { positionSelectedMenuItem } from './position-selected-menu-item'
export * from './basic'
export * from './app'
export * from './cache'
export * from './core'
export * from './dom'
export * from './element'
export * from './equal-router-path'
export * from './files'
export * from './legacy-crypto'
export * from './precision'
export * from './vue'
export * from './app'
export * from './c'
export { positionSelectedMenuItem }
export { updateObjectValue } from './update-object-value'
export { removeDuplicateKeys } from './remove-duplicate-keys'
export { getDateByNaiveDatePicker } from './get-date-by-naive-date-picker'
export { positionSelectedMenuItem } from './position-selected-menu-item'
export { removeDuplicateKeys } from './remove-duplicate-keys'
export { updateObjectValue } from './update-object-value'

View File

@ -0,0 +1,2 @@
/** 历史加解密格式使用的默认密钥。 */
export const CRYPTO_KEY = '4cP+dX5FI2EVYzln'

Some files were not shown because too many files have changed in this diff Show More