From 83bada950bc2e7dbdf739a68c57d669098ad1d20 Mon Sep 17 00:00:00 2001 From: XiaoDaiGua-Ray <51957438+XiaoDaiGua-Ray@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:40:30 +0800 Subject: [PATCH] refactor(utils): reorganize shared utilities and hooks --- README.zh-CN.md | 1 + .../basic/callWithAsyncErrorHandling.spec.ts | 34 ++ __test__/basic/detectOperatingSystem.spec.ts | 16 +- __test__/basic/downloadAnyFile.spec.ts | 91 +++- __test__/basic/equalRouterPath.spec.ts | 6 + __test__/basic/isPromise.spec.ts | 11 +- __test__/basic/isValueType.spec.ts | 7 + __test__/basic/uuid.spec.ts | 13 + __test__/cache/index.spec.ts | 50 ++ __test__/dom/printDom.spec.ts | 91 ++++ __test__/dom/printDom.spec.tsx | 49 -- __test__/element/classMethods.spec.tsx | 29 ++ __test__/element/colorToRgba.spec.ts | 6 + __test__/element/completeSize.spec.ts | 8 + __test__/element/styleMethods.spec.ts | 20 + __test__/hooks/useAppNavigation.spec.ts | 79 +++- __test__/hooks/useBadge.spec.ts | 38 +- .../hooks/useContextmenuCoordinate.spec.tsx | 34 ++ __test__/hooks/useDayjs.spec.ts | 22 +- __test__/hooks/useDevice.spec.ts | 37 ++ __test__/hooks/useDomToImage.spec.ts | 18 + __test__/hooks/useElementFullscreen.spec.ts | 28 ++ __test__/hooks/useI18n.spec.ts | 13 + __test__/hooks/useMaximize.spec.ts | 25 + __test__/hooks/usePagination.spec.ts | 30 ++ __test__/hooks/usePrint.spec.ts | 44 ++ __test__/hooks/useSiderBar.spec.ts | 18 + __test__/hooks/useTheme.spec.ts | 19 +- __test__/hooks/useVueRouter.spec.ts | 29 +- __test__/precision/index.spec.ts | 25 + __test__/utils-contracts/fileToBase64.spec.ts | 33 ++ .../utils-contracts/legacy-crypto.spec.ts | 45 ++ __test__/utils-contracts/object-date.spec.ts | 53 +++ __test__/utils-contracts/vue-target.spec.ts | 53 +++ __test__/vue/call.spec.ts | 27 ++ __test__/vue/renderNode.spec.tsx | 9 + docs/architecture.md | 3 +- src/components/base/RSegment/src/Segment.tsx | 4 +- src/dayjs/index.ts | 9 +- src/hooks/README.md | 48 +- src/hooks/components/index.ts | 1 + .../components/useContextmenuCoordinate.ts | 59 +-- src/hooks/components/usePagination.ts | 182 ++++++++ src/hooks/template/index.ts | 2 + src/hooks/template/useAppNavigation.ts | 93 ++-- src/hooks/template/useAppRoot.ts | 18 - src/hooks/template/useBadge.ts | 87 ++-- src/hooks/template/useContentScroll.ts | 11 +- src/hooks/template/useI18n.ts | 85 ++++ src/hooks/template/useMaximize.ts | 16 +- src/hooks/template/useSiderBar.ts | 107 +---- src/hooks/template/useSiderScroll.ts | 11 +- src/hooks/template/useTheme.ts | 50 +- src/hooks/template/useVueRouter.ts | 12 + src/hooks/template/useWatermark.ts | 26 +- src/hooks/web/useDayjs.ts | 36 +- src/hooks/web/useDevice.ts | 55 +-- src/hooks/web/useDomToImage.ts | 98 ++-- src/hooks/web/useElementFullscreen.ts | 286 ++++-------- src/hooks/web/useI18n.ts | 75 +-- src/hooks/web/usePagination.ts | 242 +--------- src/hooks/web/usePrint.ts | 75 +-- src/hooks/web/useVueRouter.ts | 47 +- src/layout/components/Menu/index.tsx | 2 +- .../components/Search/GlobalSearch/index.tsx | 8 +- .../utils/position-selected-menu-item.ts | 45 ++ src/locales/utils/get-app-default-language.ts | 2 +- src/router/constant/index.ts | 2 + src/router/index.ts | 3 - src/router/routes.ts | 3 +- src/router/utils/permission.ts | 2 +- .../utils/redirect-router-to-dashboard.ts | 2 +- src/router/utils/valid-menu-item-show.ts | 2 +- src/store/hooks/useRuntimeStore.ts | 1 + src/store/modules/menu/index.ts | 42 +- src/store/modules/menu/utils.ts | 14 +- src/store/modules/runtime/index.ts | 6 + src/store/modules/setting/index.ts | 4 +- src/store/modules/signing/index.ts | 2 +- src/utils/README.md | 26 ++ src/utils/app/detect-operating-system.ts | 29 ++ src/utils/app/get-app-environment.ts | 1 + src/utils/app/index.ts | 2 + src/utils/app/prefix-cache-key.ts | 19 +- src/utils/basic.ts | 404 +---------------- src/utils/c/constant.ts | 3 +- src/utils/c/decrypt.ts | 32 +- src/utils/c/encrypt.ts | 24 +- src/utils/c/index.ts | 6 +- src/utils/c/types.ts | 5 +- src/utils/cache.ts | 186 ++++---- src/utils/core/index.ts | 127 ++++++ src/utils/crypto.ts | 15 - src/utils/dom.ts | 80 ++-- src/utils/element.ts | 427 ++++++------------ src/utils/equal-router-path.ts | 14 + src/utils/files/index.ts | 101 +++++ src/utils/get-date-by-naive-date-picker.ts | 30 +- src/utils/index.ts | 16 +- src/utils/legacy-crypto/constant.ts | 2 + src/utils/legacy-crypto/decrypt.ts | 36 ++ src/utils/legacy-crypto/encrypt.ts | 31 ++ src/utils/legacy-crypto/index.ts | 5 + src/utils/legacy-crypto/types.ts | 4 + src/utils/position-selected-menu-item.ts | 50 +- src/utils/precision.ts | 265 +++-------- src/utils/remove-duplicate-keys.ts | 26 +- src/utils/update-object-value.ts | 27 +- src/utils/vue/call.ts | 46 +- src/utils/vue/effect-dispose.ts | 12 +- src/utils/vue/render-node.ts | 46 +- src/utils/vue/unref-element.ts | 36 +- src/utils/vue/watch-effect-with-target.ts | 28 +- 113 files changed, 2485 insertions(+), 2665 deletions(-) create mode 100644 __test__/dom/printDom.spec.ts delete mode 100644 __test__/dom/printDom.spec.tsx create mode 100644 __test__/hooks/usePrint.spec.ts create mode 100644 __test__/utils-contracts/fileToBase64.spec.ts create mode 100644 __test__/utils-contracts/legacy-crypto.spec.ts create mode 100644 __test__/utils-contracts/object-date.spec.ts create mode 100644 __test__/utils-contracts/vue-target.spec.ts create mode 100644 src/hooks/components/usePagination.ts create mode 100644 src/hooks/template/useI18n.ts create mode 100644 src/hooks/template/useVueRouter.ts create mode 100644 src/layout/utils/position-selected-menu-item.ts create mode 100644 src/utils/README.md create mode 100644 src/utils/app/detect-operating-system.ts create mode 100644 src/utils/app/get-app-environment.ts create mode 100644 src/utils/core/index.ts delete mode 100644 src/utils/crypto.ts create mode 100644 src/utils/equal-router-path.ts create mode 100644 src/utils/files/index.ts create mode 100644 src/utils/legacy-crypto/constant.ts create mode 100644 src/utils/legacy-crypto/decrypt.ts create mode 100644 src/utils/legacy-crypto/encrypt.ts create mode 100644 src/utils/legacy-crypto/index.ts create mode 100644 src/utils/legacy-crypto/types.ts diff --git a/README.zh-CN.md b/README.zh-CN.md index 7b4201e2..a31dbb3f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -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` 维护名称。 diff --git a/__test__/basic/callWithAsyncErrorHandling.spec.ts b/__test__/basic/callWithAsyncErrorHandling.spec.ts index eeeca007..d6c45f45 100644 --- a/__test__/basic/callWithAsyncErrorHandling.spec.ts +++ b/__test__/basic/callWithAsyncErrorHandling.spec.ts @@ -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) +}) diff --git a/__test__/basic/detectOperatingSystem.spec.ts b/__test__/basic/detectOperatingSystem.spec.ts index 2833d805..fd99effb 100644 --- a/__test__/basic/detectOperatingSystem.spec.ts +++ b/__test__/basic/detectOperatingSystem.spec.ts @@ -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) }) }) diff --git a/__test__/basic/downloadAnyFile.spec.ts b/__test__/basic/downloadAnyFile.spec.ts index 62060301..44c70df9 100644 --- a/__test__/basic/downloadAnyFile.spec.ts +++ b/__test__/basic/downloadAnyFile.spec.ts @@ -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() + }) }) diff --git a/__test__/basic/equalRouterPath.spec.ts b/__test__/basic/equalRouterPath.spec.ts index ced12731..7c2b9613 100644 --- a/__test__/basic/equalRouterPath.spec.ts +++ b/__test__/basic/equalRouterPath.spec.ts @@ -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) +}) diff --git a/__test__/basic/isPromise.spec.ts b/__test__/basic/isPromise.spec.ts index d58d4593..fe2dcc61 100644 --- a/__test__/basic/isPromise.spec.ts +++ b/__test__/basic/isPromise.spec.ts @@ -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) +}) diff --git a/__test__/basic/isValueType.spec.ts b/__test__/basic/isValueType.spec.ts index 6ecf70b8..b16b481c 100644 --- a/__test__/basic/isValueType.spec.ts +++ b/__test__/basic/isValueType.spec.ts @@ -46,3 +46,10 @@ describe('isValueType', () => { expect(isValueType(/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) +}) diff --git a/__test__/basic/uuid.spec.ts b/__test__/basic/uuid.spec.ts index 711b5f9b..58ed3e05 100644 --- a/__test__/basic/uuid.spec.ts +++ b/__test__/basic/uuid.spec.ts @@ -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) +}) diff --git a/__test__/cache/index.spec.ts b/__test__/cache/index.spec.ts index 6c9b7339..2294fa2c 100644 --- a/__test__/cache/index.spec.ts +++ b/__test__/cache/index.spec.ts @@ -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') + } + }) +}) diff --git a/__test__/dom/printDom.spec.ts b/__test__/dom/printDom.spec.ts new file mode 100644 index 00000000..b3af1c33 --- /dev/null +++ b/__test__/dom/printDom.spec.ts @@ -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() + }) +}) diff --git a/__test__/dom/printDom.spec.tsx b/__test__/dom/printDom.spec.tsx deleted file mode 100644 index 1ad04a32..00000000 --- a/__test__/dom/printDom.spec.tsx +++ /dev/null @@ -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() - // 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 ( - // <> - //
print html
- // - // - // ) - // }, - // }), - // ) - // it('print dom', () => { - // const button = wrapper.find('button') - // button.trigger('click') - // expect(count).toBe(2) - // }) - - it('print dom', () => {}) -}) diff --git a/__test__/element/classMethods.spec.tsx b/__test__/element/classMethods.spec.tsx index 53080a0a..0f882ae8 100644 --- a/__test__/element/classMethods.spec.tsx +++ b/__test__/element/classMethods.spec.tsx @@ -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(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() + } +}) diff --git a/__test__/element/colorToRgba.spec.ts b/__test__/element/colorToRgba.spec.ts index 3a5b1491..3759a69b 100644 --- a/__test__/element/colorToRgba.spec.ts +++ b/__test__/element/colorToRgba.spec.ts @@ -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') +}) diff --git a/__test__/element/completeSize.spec.ts b/__test__/element/completeSize.spec.ts index ed0482d4..0616769d 100644 --- a/__test__/element/completeSize.spec.ts +++ b/__test__/element/completeSize.spec.ts @@ -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') +}) diff --git a/__test__/element/styleMethods.spec.ts b/__test__/element/styleMethods.spec.ts index 0bdd759b..53fd7ef5 100644 --- a/__test__/element/styleMethods.spec.ts +++ b/__test__/element/styleMethods.spec.ts @@ -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('') +}) diff --git a/__test__/hooks/useAppNavigation.spec.ts b/__test__/hooks/useAppNavigation.spec.ts index 18ad15cc..dae41082 100644 --- a/__test__/hooks/useAppNavigation.spec.ts +++ b/__test__/hooks/useAppNavigation.spec.ts @@ -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 | 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() + }, + ) }) diff --git a/__test__/hooks/useBadge.spec.ts b/__test__/hooks/useBadge.spec.ts index 64ec6ff1..df8f9a22 100644 --- a/__test__/hooks/useBadge.spec.ts +++ b/__test__/hooks/useBadge.spec.ts @@ -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() }) diff --git a/__test__/hooks/useContextmenuCoordinate.spec.tsx b/__test__/hooks/useContextmenuCoordinate.spec.tsx index 09c0fe7a..0fd4dc91 100644 --- a/__test__/hooks/useContextmenuCoordinate.spec.tsx +++ b/__test__/hooks/useContextmenuCoordinate.spec.tsx @@ -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() + } +}) diff --git a/__test__/hooks/useDayjs.spec.ts b/__test__/hooks/useDayjs.spec.ts index a7cba094..9ad29c7f 100644 --- a/__test__/hooks/useDayjs.spec.ts +++ b/__test__/hooks/useDayjs.spec.ts @@ -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 ', () => { diff --git a/__test__/hooks/useDevice.spec.ts b/__test__/hooks/useDevice.spec.ts index 4258f816..21f7d13b 100644 --- a/__test__/hooks/useDevice.spec.ts +++ b/__test__/hooks/useDevice.spec.ts @@ -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 + } +}) diff --git a/__test__/hooks/useDomToImage.spec.ts b/__test__/hooks/useDomToImage.spec.ts index 57e7669d..41e1bcfa 100644 --- a/__test__/hooks/useDomToImage.spec.ts +++ b/__test__/hooks/useDomToImage.spec.ts @@ -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) +}) diff --git a/__test__/hooks/useElementFullscreen.spec.ts b/__test__/hooks/useElementFullscreen.spec.ts index 520559c1..5fa5c94d 100644 --- a/__test__/hooks/useElementFullscreen.spec.ts +++ b/__test__/hooks/useElementFullscreen.spec.ts @@ -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() +}) diff --git a/__test__/hooks/useI18n.spec.ts b/__test__/hooks/useI18n.spec.ts index 23196d5a..bed5bcec 100644 --- a/__test__/hooks/useI18n.spec.ts +++ b/__test__/hooks/useI18n.spec.ts @@ -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 }) +}) diff --git a/__test__/hooks/useMaximize.spec.ts b/__test__/hooks/useMaximize.spec.ts index ec211064..f93f2d21 100644 --- a/__test__/hooks/useMaximize.spec.ts +++ b/__test__/hooks/useMaximize.spec.ts @@ -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) + } +}) diff --git a/__test__/hooks/usePagination.spec.ts b/__test__/hooks/usePagination.spec.ts index d6cce96f..09548f69 100644 --- a/__test__/hooks/usePagination.spec.ts +++ b/__test__/hooks/usePagination.spec.ts @@ -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() +}) diff --git a/__test__/hooks/usePrint.spec.ts b/__test__/hooks/usePrint.spec.ts new file mode 100644 index 00000000..04562183 --- /dev/null +++ b/__test__/hooks/usePrint.spec.ts @@ -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() + 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' }], + ]) +}) diff --git a/__test__/hooks/useSiderBar.spec.ts b/__test__/hooks/useSiderBar.spec.ts index e3c477e9..6a4716a7 100644 --- a/__test__/hooks/useSiderBar.spec.ts +++ b/__test__/hooks/useSiderBar.spec.ts @@ -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) + } + }) }) diff --git a/__test__/hooks/useTheme.spec.ts b/__test__/hooks/useTheme.spec.ts index 7f054e6d..cb7c517f 100644 --- a/__test__/hooks/useTheme.spec.ts +++ b/__test__/hooks/useTheme.spec.ts @@ -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() + } + }) }) diff --git a/__test__/hooks/useVueRouter.spec.ts b/__test__/hooks/useVueRouter.spec.ts index 6fa90358..41bd0812 100644 --- a/__test__/hooks/useVueRouter.spec.ts +++ b/__test__/hooks/useVueRouter.spec.ts @@ -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() + } }) diff --git a/__test__/precision/index.spec.ts b/__test__/precision/index.spec.ts index cc59c5a4..cb57f191 100644 --- a/__test__/precision/index.spec.ts +++ b/__test__/precision/index.spec.ts @@ -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) +}) diff --git a/__test__/utils-contracts/fileToBase64.spec.ts b/__test__/utils-contracts/fileToBase64.spec.ts new file mode 100644 index 00000000..ed2f1b4d --- /dev/null +++ b/__test__/utils-contracts/fileToBase64.spec.ts @@ -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() + } + }, +) diff --git a/__test__/utils-contracts/legacy-crypto.spec.ts b/__test__/utils-contracts/legacy-crypto.spec.ts new file mode 100644 index 00000000..2e4ae4b4 --- /dev/null +++ b/__test__/utils-contracts/legacy-crypto.spec.ts @@ -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) + }) +}) diff --git a/__test__/utils-contracts/object-date.spec.ts b/__test__/utils-contracts/object-date.spec.ts new file mode 100644 index 00000000..f2554e63 --- /dev/null +++ b/__test__/utils-contracts/object-date.spec.ts @@ -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) +}) diff --git a/__test__/utils-contracts/vue-target.spec.ts b/__test__/utils-contracts/vue-target.spec.ts new file mode 100644 index 00000000..a133abfe --- /dev/null +++ b/__test__/utils-contracts/vue-target.spec.ts @@ -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) +}) diff --git a/__test__/vue/call.spec.ts b/__test__/vue/call.spec.ts index 1892b715..a14ab189 100644 --- a/__test__/vue/call.spec.ts +++ b/__test__/vue/call.spec.ts @@ -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() +}) diff --git a/__test__/vue/renderNode.spec.tsx b/__test__/vue/renderNode.spec.tsx index e47c7094..a0475f09 100644 --- a/__test__/vue/renderNode.spec.tsx +++ b/__test__/vue/renderNode.spec.tsx @@ -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) +}) diff --git a/docs/architecture.md b/docs/architecture.md index ef1b9a2f..5ea3475e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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` 统一生成。 diff --git a/src/components/base/RSegment/src/Segment.tsx b/src/components/base/RSegment/src/Segment.tsx index e242aa56..47b3d8db 100644 --- a/src/components/base/RSegment/src/Segment.tsx +++ b/src/components/base/RSegment/src/Segment.tsx @@ -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 ( - {renderNode(icon)?.()} + {typeof icon === 'function' ? icon() : icon}
{label}
) diff --git a/src/dayjs/index.ts b/src/dayjs/index.ts index 7c85dc45..681d54fa 100644 --- a/src/dayjs/index.ts +++ b/src/dayjs/index.ts @@ -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( + const setting = getStorage( 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) diff --git a/src/hooks/README.md b/src/hooks/README.md index 1ae76ef9..b881935c 100644 --- a/src/hooks/README.md +++ b/src/hooks/README.md @@ -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 测试验证状态与异常处理,不能替代原生打印界面或实际纸张输出验收。 diff --git a/src/hooks/components/index.ts b/src/hooks/components/index.ts index 7fb265e0..31a3719b 100644 --- a/src/hooks/components/index.ts +++ b/src/hooks/components/index.ts @@ -1 +1,2 @@ export * from './useContextmenuCoordinate' +export * from './usePagination' diff --git a/src/hooks/components/useContextmenuCoordinate.ts b/src/hooks/components/useContextmenuCoordinate.ts index b9fc1c5e..abd7cd77 100644 --- a/src/hooks/components/useContextmenuCoordinate.ts +++ b/src/hooks/components/useContextmenuCoordinate.ts @@ -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('target') - * const { x, y, show, stop } = useContextmenuCoordinate(target) - * - * 如果需要手动停止右键菜单,可以调用 stop 方法 - * stop() - * - * + * @returns 只读坐标、菜单显隐状态和更新、停止方法。 */ export const useContextmenuCoordinate = ( target: BasicTarget, - options?: UseContextmenuCoordinateOptions & - MaybeRefOrGetter, + 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, (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 diff --git a/src/hooks/components/usePagination.ts b/src/hooks/components/usePagination.ts new file mode 100644 index 00000000..f1a89c84 --- /dev/null +++ b/src/hooks/components/usePagination.ts @@ -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 { + /** 页码更新后接收新页码。 */ + 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(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, + { + getItemCount, + setItemCount, + getPage, + setPage, + getPageSize, + setPageSize, + getPagination, + getCallback, + setCallback, + resetPagination, + }, + ] as const +} + +export type UsePaginationReturn = ReturnType diff --git a/src/hooks/template/index.ts b/src/hooks/template/index.ts index 2427f599..61389735 100644 --- a/src/hooks/template/index.ts +++ b/src/hooks/template/index.ts @@ -8,3 +8,5 @@ export * from './useAppRoot' export * from './useBadge' export * from './useSiderScroll' export * from './useContentScroll' +export * from './useI18n' +export * from './useVueRouter' diff --git a/src/hooks/template/useAppNavigation.ts b/src/hooks/template/useAppNavigation.ts index 39538575..1c07def5 100644 --- a/src/hooks/template/useAppNavigation.ts +++ b/src/hooks/template/useAppNavigation.ts @@ -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 { diff --git a/src/hooks/template/useAppRoot.ts b/src/hooks/template/useAppRoot.ts index 642b53bb..42c184b0 100644 --- a/src/hooks/template/useAppRoot.ts +++ b/src/hooks/template/useAppRoot.ts @@ -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) => { updateSettingState( diff --git a/src/hooks/template/useBadge.ts b/src/hooks/template/useBadge.ts index 810508cf..862cc792 100644 --- a/src/hooks/template/useBadge.ts +++ b/src/hooks/template/useBadge.ts @@ -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, ) => { - 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 { diff --git a/src/hooks/template/useContentScroll.ts b/src/hooks/template/useContentScroll.ts index 5cb9c873..4e589372 100644 --- a/src/hooks/template/useContentScroll.ts +++ b/src/hooks/template/useContentScroll.ts @@ -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 中调用和布局重新挂载。 diff --git a/src/hooks/template/useI18n.ts b/src/hooks/template/useI18n.ts new file mode 100644 index 00000000..211e751a --- /dev/null +++ b/src/hooks/template/useI18n.ts @@ -0,0 +1,85 @@ +import { i18n } from '@/locales' +import type { I18n } from 'vue-i18n' + +export interface OverrideUseI18nReturnType extends Partial< + Omit +> { + t: (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 = ( + 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 diff --git a/src/hooks/template/useMaximize.ts b/src/hooks/template/useMaximize.ts index 9f96b88d..68198ea1 100644 --- a/src/hooks/template/useMaximize.ts +++ b/src/hooks/template/useMaximize.ts @@ -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) diff --git a/src/hooks/template/useSiderBar.ts b/src/hooks/template/useSiderBar.ts index 32f9a0c8..6a8eb9cd 100644 --- a/src/hooks/template/useSiderBar.ts +++ b/src/hooks/template/useSiderBar.ts @@ -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) diff --git a/src/hooks/template/useSiderScroll.ts b/src/hooks/template/useSiderScroll.ts index 7a320808..1746a989 100644 --- a/src/hooks/template/useSiderScroll.ts +++ b/src/hooks/template/useSiderScroll.ts @@ -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'] = ( diff --git a/src/hooks/template/useTheme.ts b/src/hooks/template/useTheme.ts index d3c6f0ed..e1d03572 100644 --- a/src/hooks/template/useTheme.ts +++ b/src/hooks/template/useTheme.ts @@ -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) diff --git a/src/hooks/template/useVueRouter.ts b/src/hooks/template/useVueRouter.ts new file mode 100644 index 00000000..038991ae --- /dev/null +++ b/src/hooks/template/useVueRouter.ts @@ -0,0 +1,12 @@ +import { router } from '@/router' + +/** + * + * @description + * 读取模板的共享 Router 实例,可在 Vue setup 之外调用。 + * + * @returns Router 及其响应式 currentRoute。 + */ +export const useVueRouter = () => ({ router }) + +export type UseVueRouterReturnType = ReturnType diff --git a/src/hooks/template/useWatermark.ts b/src/hooks/template/useWatermark.ts index f7bd4781..e0424d16 100644 --- a/src/hooks/template/useWatermark.ts +++ b/src/hooks/template/useWatermark.ts @@ -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() diff --git a/src/hooks/web/useDayjs.ts b/src/hooks/web/useDayjs.ts index 9e18480d..56366e4c 100644 --- a/src/hooks/web/useDayjs.ts +++ b/src/hooks/web/useDayjs.ts @@ -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 diff --git a/src/hooks/web/useDevice.ts b/src/hooks/web/useDevice.ts index 9c6933c2..f992f881 100644 --- a/src/hooks/web/useDevice.ts +++ b/src/hooks/web/useDevice.ts @@ -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 } diff --git a/src/hooks/web/useDomToImage.ts b/src/hooks/web/useDomToImage.ts index 84afb73d..317cf155 100644 --- a/src/hooks/web/useDomToImage.ts +++ b/src/hooks/web/useDomToImage.ts @@ -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, 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() - * 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 ( imageType?: OutputType, ): Promise> => { - 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 } 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) } diff --git a/src/hooks/web/useElementFullscreen.ts b/src/hooks/web/useElementFullscreen.ts index 9e460196..2bb47229 100644 --- a/src/hooks/web/useElementFullscreen.ts +++ b/src/hooks/web/useElementFullscreen.ts @@ -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() /** * - * @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 - * - * + * @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(zIndex, 'Null') || - isValueType(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 = { - 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< diff --git a/src/hooks/web/useI18n.ts b/src/hooks/web/useI18n.ts index 54c3489a..7dc907a8 100644 --- a/src/hooks/web/useI18n.ts +++ b/src/hooks/web/useI18n.ts @@ -1,74 +1 @@ -import { i18n } from '@/locales' -import type { I18n } from 'vue-i18n' - -export interface OverrideUseI18nReturnType extends Omit< - I18n['global'], - 't' | 'locale' -> { - t: (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 = (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' diff --git a/src/hooks/web/usePagination.ts b/src/hooks/web/usePagination.ts index a5a3de6c..293da6c5 100644 --- a/src/hooks/web/usePagination.ts +++ b/src/hooks/web/usePagination.ts @@ -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 { - /** - * - * @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 = ( - 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(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 - undefined | null | unknown - ? T - : Fn => callbackRef.value - - /** - * - * @param callback 页码、页条数更新时的回调函数 - * - * @description - * 手动设置回调函数。 - * - * @example - * setCallback(() => {}) - */ - const setCallback = (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, - { - getItemCount, - setItemCount, - getPage, - setPage, - getPageSize, - setPageSize, - getPagination, - getCallback, - setCallback, - resetPagination, - }, - ] as const -} - -export type UsePaginationReturn = ReturnType +export * from '../components/usePagination' diff --git a/src/hooks/web/usePrint.ts b/src/hooks/web/usePrint.ts index 05cf1c71..f0398358 100644 --- a/src/hooks/web/usePrint.ts +++ b/src/hooks/web/usePrint.ts @@ -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 export type UsePrintTarget = 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('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 diff --git a/src/hooks/web/useVueRouter.ts b/src/hooks/web/useVueRouter.ts index 0bd107ad..3da08596 100644 --- a/src/hooks/web/useVueRouter.ts +++ b/src/hooks/web/useVueRouter.ts @@ -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 +export * from '../template/useVueRouter' diff --git a/src/layout/components/Menu/index.tsx b/src/layout/components/Menu/index.tsx index f911316f..b673afea 100644 --- a/src/layout/components/Menu/index.tsx +++ b/src/layout/components/Menu/index.tsx @@ -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' diff --git a/src/layout/components/Search/GlobalSearch/index.tsx b/src/layout/components/Search/GlobalSearch/index.tsx index dc03ce1c..aa396df7 100644 --- a/src/layout/components/Search/GlobalSearch/index.tsx +++ b/src/layout/components/Search/GlobalSearch/index.tsx @@ -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 { diff --git a/src/layout/utils/position-selected-menu-item.ts b/src/layout/utils/position-selected-menu-item.ts new file mode 100644 index 00000000..d37504a5 --- /dev/null +++ b/src/layout/utils/position-selected-menu-item.ts @@ -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) + const scrollEl = siderEl?.querySelector( + '.n-layout-scroll-container, .n-scrollbar-container', + ) + const selectedEl = + siderEl?.querySelector(MENU_ITEM_SELECTED) || + siderEl?.querySelector(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', + }) +} diff --git a/src/locales/utils/get-app-default-language.ts b/src/locales/utils/get-app-default-language.ts index ee606524..c03cde92 100644 --- a/src/locales/utils/get-app-default-language.ts +++ b/src/locales/utils/get-app-default-language.ts @@ -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' /** * diff --git a/src/router/constant/index.ts b/src/router/constant/index.ts index 5bed6cc4..9f83483f 100644 --- a/src/router/constant/index.ts +++ b/src/router/constant/index.ts @@ -1 +1,3 @@ export const LAYOUT = () => import('@/layout/default/ContentWrapper') + +export const NOT_FOUND_ROUTE_PATH = '/:catchAll(.*)' diff --git a/src/router/index.ts b/src/router/index.ts index 0dba19b0..a33ef89f 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -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) => { app.use(router) - // 等待 router 挂载后,初始化 useRouter 方法 - useVueRouter() vueRouterRegister(router) } diff --git a/src/router/routes.ts b/src/router/routes.ts index 6ee7a587..1fed8ea1 100644 --- a/src/router/routes.ts +++ b/src/router/routes.ts @@ -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'), diff --git a/src/router/utils/permission.ts b/src/router/utils/permission.ts index ce6f4dba..b586e836 100644 --- a/src/router/utils/permission.ts +++ b/src/router/utils/permission.ts @@ -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' diff --git a/src/router/utils/redirect-router-to-dashboard.ts b/src/router/utils/redirect-router-to-dashboard.ts index 55e618e7..81eb759d 100644 --- a/src/router/utils/redirect-router-to-dashboard.ts +++ b/src/router/utils/redirect-router-to-dashboard.ts @@ -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' /** * diff --git a/src/router/utils/valid-menu-item-show.ts b/src/router/utils/valid-menu-item-show.ts index b8b67ad0..3afd0a0b 100644 --- a/src/router/utils/valid-menu-item-show.ts +++ b/src/router/utils/valid-menu-item-show.ts @@ -1,5 +1,5 @@ import type { AppMenuOption } from '@/types' -import { getAppEnvironment } from '@/utils' +import { getAppEnvironment } from '@/utils/app/get-app-environment' /** * diff --git a/src/store/hooks/useRuntimeStore.ts b/src/store/hooks/useRuntimeStore.ts index 96c15c01..442cf42b 100644 --- a/src/store/hooks/useRuntimeStore.ts +++ b/src/store/hooks/useRuntimeStore.ts @@ -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), } diff --git a/src/store/modules/menu/index.ts b/src/store/modules/menu/index.ts index 5d462e5f..7e15935d 100644 --- a/src/store/modules/menu/index.ts +++ b/src/store/modules/menu/index.ts @@ -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 } } diff --git a/src/store/modules/menu/utils.ts b/src/store/modules/menu/utils.ts index cfb86319..6c82b08b 100644 --- a/src/store/modules/menu/utils.ts +++ b/src/store/modules/menu/utils.ts @@ -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( - APP_CATCH_KEY.appMenuTagOptions, - 'sessionStorage', - { - defaultValue: [], - }, + return ( + getStorage( + APP_CATCH_KEY.appMenuTagOptions, + 'sessionStorage', + ) ?? [] ) } diff --git a/src/store/modules/runtime/index.ts b/src/store/modules/runtime/index.ts index 96a5fe84..3dbab3f5 100644 --- a/src/store/modules/runtime/index.ts +++ b/src/store/modules/runtime/index.ts @@ -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 } diff --git a/src/store/modules/setting/index.ts b/src/store/modules/setting/index.ts index 1d693b03..5fc54d30 100644 --- a/src/store/modules/setting/index.ts +++ b/src/store/modules/setting/index.ts @@ -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' diff --git a/src/store/modules/signing/index.ts b/src/store/modules/signing/index.ts index 8c087a0a..d3cb2d4a 100644 --- a/src/store/modules/signing/index.ts +++ b/src/store/modules/signing/index.ts @@ -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。 */ diff --git a/src/utils/README.md b/src/utils/README.md new file mode 100644 index 00000000..275ecb1f --- /dev/null +++ b/src/utils/README.md @@ -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。它是兼容层,模板的默认口令对客户端可见。 diff --git a/src/utils/app/detect-operating-system.ts b/src/utils/app/detect-operating-system.ts new file mode 100644 index 00000000..ac4bf838 --- /dev/null +++ b/src/utils/app/detect-operating-system.ts @@ -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 +} diff --git a/src/utils/app/get-app-environment.ts b/src/utils/app/get-app-environment.ts new file mode 100644 index 00000000..64c98d49 --- /dev/null +++ b/src/utils/app/get-app-environment.ts @@ -0,0 +1 @@ +export const getAppEnvironment = () => import.meta.env diff --git a/src/utils/app/index.ts b/src/utils/app/index.ts index d7f56b94..62453dd3 100644 --- a/src/utils/app/index.ts +++ b/src/utils/app/index.ts @@ -1 +1,3 @@ export * from './prefix-cache-key' +export * from './get-app-environment' +export * from './detect-operating-system' diff --git a/src/utils/app/prefix-cache-key.ts b/src/utils/app/prefix-cache-key.ts index 1db4a722..f10d202e 100644 --- a/src/utils/app/prefix-cache-key.ts +++ b/src/utils/app/prefix-cache-key.ts @@ -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, diff --git a/src/utils/basic.ts b/src/utils/basic.ts index d6054294..840b4631 100644 --- a/src/utils/basic.ts +++ b/src/utils/basic.ts @@ -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('123', 'String') // true - * isValueType({}, 'Object') // true - * isValueType([], 'Array') // true - * isValueType([], 'Object') // false - * isValueType(undefined, 'Undefined') // true - * isValueType(null, 'Null') // true - */ -export const isValueType = ( - 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 => { - return new Promise((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((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 = (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 = (value: unknown): value is Promise => { - if (isAsyncFunction(value)) { - return true - } - - return ( - !!value && - (typeof value === 'object' || typeof value === 'function') && - typeof (value as Promise).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 = ( - fn: T, - errorCallback: AnyFn, - args?: Parameters, -) => { - let result: ReturnType | 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, -): Promise | undefined> => { - try { - if (!isPromise(fn)) { - return Promise.resolve(callWithErrorHandling(fn, errorCallback, args)) - } - - return await fn(...(args as Parameters)) - } 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' diff --git a/src/utils/c/constant.ts b/src/utils/c/constant.ts index 95f2d528..fd84cb90 100644 --- a/src/utils/c/constant.ts +++ b/src/utils/c/constant.ts @@ -1,2 +1 @@ -/** 历史加解密格式使用的默认密钥。 */ -export const CRYPTO_KEY = '4cP+dX5FI2EVYzln' +export * from '../legacy-crypto/constant' diff --git a/src/utils/c/decrypt.ts b/src/utils/c/decrypt.ts index 5fb05f1c..4f35f6e6 100644 --- a/src/utils/c/decrypt.ts +++ b/src/utils/c/decrypt.ts @@ -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' diff --git a/src/utils/c/encrypt.ts b/src/utils/c/encrypt.ts index 1c4a1c81..00ffa54f 100644 --- a/src/utils/c/encrypt.ts +++ b/src/utils/c/encrypt.ts @@ -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' diff --git a/src/utils/c/index.ts b/src/utils/c/index.ts index 6b5aba16..7a453ac5 100644 --- a/src/utils/c/index.ts +++ b/src/utils/c/index.ts @@ -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' diff --git a/src/utils/c/types.ts b/src/utils/c/types.ts index cf051fcb..09941c62 100644 --- a/src/utils/c/types.ts +++ b/src/utils/c/types.ts @@ -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' diff --git a/src/utils/cache.ts b/src/utils/cache.ts index 8184966e..61c1c90c 100644 --- a/src/utils/cache.ts +++ b/src/utils/cache.ts @@ -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( key: string, @@ -70,11 +55,15 @@ function setStorage( 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( } } -function getStorage( - key: string, - storageType: StorageLike, - options: StorageOptions & { defaultValue: T }, -): T - -function getStorage( - key: string, - storageType?: StorageLike, - options?: Omit, '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( key: string, storageType: StorageLike = 'sessionStorage', options?: StorageOptions, ): 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') } } diff --git a/src/utils/core/index.ts b/src/utils/core/index.ts new file mode 100644 index 00000000..25c13073 --- /dev/null +++ b/src/utils/core/index.ts @@ -0,0 +1,127 @@ +import type { AnyFn, BasicTypes, ValidateValueType } from '@/types' + +/** + * + * @param value 待判断的值 + * @param type 要匹配的完整类型标签 + * + * @description + * 按 Object.prototype.toString 的标签判断。普通函数和异步函数都匹配 Function。 + */ +export const isValueType = ( + 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 = (value: unknown): value is PromiseLike => + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as PromiseLike).then === 'function' + +/** + * + * @param fn 待执行的函数 + * @param errorCallback 同步抛错时执行的回调 + * @param args 调用参数,省略时不传参 + * + * @returns 函数结果,或处理错误后的 undefined。 + * + * @throws 错误回调自身抛出的异常会传给调用方。 + */ +export const callWithErrorHandling = ( + fn: T, + errorCallback: (error: E) => void, + args?: Parameters, +): ReturnType | 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, +): Promise> | undefined> => { + try { + return await fn(...(args ?? [])) + } catch (error) { + errorCallback(error as E) + } +} diff --git a/src/utils/crypto.ts b/src/utils/crypto.ts deleted file mode 100644 index 96a09237..00000000 --- a/src/utils/crypto.ts +++ /dev/null @@ -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 - */ diff --git a/src/utils/dom.ts b/src/utils/dom.ts index 30a35a6b..6d32491b 100644 --- a/src/utils/dom.ts +++ b/src/utils/dom.ts @@ -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 - domToImageOptions?: Omit +export interface PrintDomOptions { + printOptions?: Omit + domToImageOptions?: Omit, '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() - * - * printDom(refDom, { - * printOptions: { title: 'Demo Print', ... }, - * domToImageOptions: { ... } - * }) + * @returns 已调用打印预览时返回 true;截图或调用失败时记录错误并返回 false。 */ -export const printDom = ( +export const printDom = async ( target: BasicTarget, - options?: PrintDomOptions, + options?: PrintDomOptions, ) => { - 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 + } } diff --git a/src/utils/element.ts b/src/utils/element.ts index 4d63630b..843bf30b 100644 --- a/src/utils/element.ts +++ b/src/utils/element.ts @@ -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, + target: BasicTarget, 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, - classNames: string | 'removeAllClass' | string[], + target: BasicTarget, + 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 | Ref - * hasClass(targetDom, ['matchClassName', 'matchClassName']) // Ref | Ref + * @returns 当前元素是否含至少一个完整类名;随引用更新,不监听外部 class 修改。 */ export const hasClass = ( target: BasicTarget, 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 =