diff --git a/AGENTS.md b/AGENTS.md index 4cfdc231..93baf15e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,7 @@ - 网络调用从 `src/api` 进入 `src/axios`,不要绕过拦截器。Mock 位于 `mock`,不是生产后端或真实鉴权。 - 界面文本同时更新 `src/locales/lang/zh-CN` 与 `en-US`。检查明暗主题和窄屏;不要为修复构建随意删除样式或交互。 - 修改公共组件或工具前先查看调用方、类型、测试与导出;优先修共享根因,补有意义的回归用例。不得通过跳过测试、降低严格度或宽泛 `any` 掩盖问题。 +- 新增或修改注释前阅读并遵循 [注释规范](docs/comment-style.md)。禁止在文件顶部或组件声明前写多行介绍,也不得将文件说明移动到首个函数或常量前;同一声明不堆叠多个 JSDoc。 - 注释解释接口契约或非显然原因,避免逐行复述。不要进行与任务无关的重构或新增抽象。 ## AI 工作方式 diff --git a/README.md b/README.md index c9fa4d1e..6ecbe3b0 100644 --- a/README.md +++ b/README.md @@ -188,3 +188,10 @@ Build target: Vite 8 Baseline Widely Available (Chrome/Edge 111+, Firefox 114+, ## 📄 License [MIT License](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/LICENSE) © 2022-PRESENT [Ray](https://github.com/XiaoDaiGua-Ray) + +## Hooks, Layout & Icons + +- [Hooks examples](src/hooks/README.md): `/template-hooks`, `/web-hooks`, covering all 19 custom hooks. +- [Layout modes and slots](src/layout/README.md): `/layout-demo`, with live persistent preferences. +- [Namespaced SVG icons](src/icons/A_README.md): `/svg-icons`; `pnpm icons:generate`, `pnpm icons:check`. +- [Pinia state](src/store/README.md): temporary UI state in `runtime`, saved preferences in `setting`. diff --git a/README.zh-CN.md b/README.zh-CN.md index 6aabd7c4..7b4201e2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -188,3 +188,10 @@ pnpm report ## 📄 证书 [MIT License](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/LICENSE) © 2022-PRESENT [Ray](https://github.com/XiaoDaiGua-Ray) + +## Hooks、布局与图标 + +- [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` 维护名称。 +- [全局状态](src/store/README.md):临时状态归入 Pinia `runtime`,偏好保留在 `setting`。 diff --git a/__test__/hooks/useAppNavigation.spec.ts b/__test__/hooks/useAppNavigation.spec.ts index 151948d1..18ad15cc 100644 --- a/__test__/hooks/useAppNavigation.spec.ts +++ b/__test__/hooks/useAppNavigation.spec.ts @@ -1,18 +1,42 @@ import { useAppNavigation } from '../../src/hooks/template/useAppNavigation' -import { useMenuGetters } from '../../src/store' -import setupMiniApp from '../utils/setupMiniApp' -describe('useAppNavigation', async () => { - await setupMiniApp() +const { push, replace, menus } = vi.hoisted(() => ({ + push: vi.fn().mockResolvedValue(void 0), + replace: vi.fn().mockResolvedValue(void 0), + menus: [{ fullPath: '/parent', children: [{ fullPath: '/target' }] }], +})) - const { navigationTo } = useAppNavigation() - const { getMenuOptions } = useMenuGetters() +vi.mock('../../src/hooks', () => ({ + useVueRouter: () => ({ + router: { push, replace, getRoutes: () => [{ path: '/target' }] }, + }), +})) +vi.mock('../../src/store', () => ({ + useMenuGetters: () => ({ getMenuOptions: { value: menus } }), +})) - it('navigationTo', () => { - const [dashboard] = getMenuOptions.value +describe('useAppNavigation', () => { + beforeEach(() => vi.clearAllMocks()) - expect(navigationTo(dashboard.fullPath)).toBeUndefined() - expect(navigationTo(dashboard)).toBeUndefined() - expect(navigationTo(0)).toBeUndefined() + 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' }, + }) + }) + + it.each([-1, NaN, Infinity, 0.5, 1])('ignores invalid index %s', (index) => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + expect(() => useAppNavigation().navigationTo(index)).not.toThrow() + expect(push).not.toHaveBeenCalled() + expect(warning).toHaveBeenCalled() + warning.mockRestore() }) }) diff --git a/__test__/hooks/useBadge.spec.ts b/__test__/hooks/useBadge.spec.ts index 31848698..64ec6ff1 100644 --- a/__test__/hooks/useBadge.spec.ts +++ b/__test__/hooks/useBadge.spec.ts @@ -63,4 +63,14 @@ describe('useBadge', async () => { expect(dashboard.meta.extra?.label).toBe(label) }) + it('preserves explicit visibility when updating only the label', () => { + const [dashboard] = getMenuOptions.value + + hidden(dashboard) + update(dashboard, { label: 'Changed while hidden' }) + expect(dashboard.meta.extra?.show).toBe(false) + show(dashboard) + update(dashboard, { label: 'Changed while visible' }) + expect(dashboard.meta.extra?.show).toBe(true) + }) }) diff --git a/__test__/hooks/useContextmenuCoordinate.spec.tsx b/__test__/hooks/useContextmenuCoordinate.spec.tsx index ee035139..09c0fe7a 100644 --- a/__test__/hooks/useContextmenuCoordinate.spec.tsx +++ b/__test__/hooks/useContextmenuCoordinate.spec.tsx @@ -47,4 +47,17 @@ describe('useContextmenuCoordinate', () => { expect(result.x.value).toBe(100) expect(result.y.value).toBe(200) }) + it('does not reopen after stop interrupts a pending context-menu event', async () => { + const target = document.createElement('div') + const [menu, app] = renderHook(() => useContextmenuCoordinate(target)) + + target.dispatchEvent(new MouseEvent('contextmenu')) + menu.stop() + await nextTick() + expect(menu.show.value).toBe(false) + target.dispatchEvent(new MouseEvent('contextmenu')) + await nextTick() + expect(menu.show.value).toBe(false) + app.unmount() + }) }) diff --git a/__test__/hooks/useDomToImage.spec.ts b/__test__/hooks/useDomToImage.spec.ts new file mode 100644 index 00000000..57e7669d --- /dev/null +++ b/__test__/hooks/useDomToImage.spec.ts @@ -0,0 +1,70 @@ +import { toBlob, toPng } from 'html-to-image' +import { useDomToImage } from '../../src/hooks/web/useDomToImage' + +vi.mock('html-to-image', () => ({ + toSvg: vi.fn(), + toPng: vi.fn(), + toJpeg: vi.fn(), + toBlob: vi.fn(), + toPixelData: vi.fn(), + toCanvas: vi.fn(), +})) + +describe('useDomToImage', () => { + afterEach(() => vi.clearAllMocks()) + + it('infers the configured format and supports typed per-call overrides', async () => { + vi.mocked(toPng).mockResolvedValue('data:image/png;base64,test') + const blob = new Blob(['test']) + + vi.mocked(toBlob).mockResolvedValue(blob) + const created = vi.fn() + const element = document.createElement('div') + const { create } = useDomToImage(element, { + imageType: 'png', + created, + }) + const png = await create() + const result = await create('blob') + + expectTypeOf(png).toEqualTypeOf() + expectTypeOf(result).toEqualTypeOf() + expect(png).toBe('data:image/png;base64,test') + expect(result).toBe(blob) + expect(created).toHaveBeenLastCalledWith(blob, element) + }) + + it('rejects with an Error and runs cleanup when the target is missing', async () => { + const failed = vi.fn() + const finished = vi.fn() + const { create } = useDomToImage(null, { + createdError: failed, + finally: finished, + }) + + await expect(create()).rejects.toThrow('target element is undefined') + expect(failed).toHaveBeenCalledWith(expect.any(Error)) + expect(finished).toHaveBeenCalledTimes(1) + expect(toPng).not.toHaveBeenCalled() + }) + + it('propagates renderer failures and completes cleanup before settling', async () => { + const error = new Error('capture failed') + const finished = vi.fn() + const failed = vi.fn() + + vi.mocked(toPng).mockRejectedValue(error) + const created = vi.fn() + const element = document.createElement('div') + const { create } = useDomToImage(element, { + imageType: 'png', + created, + createdError: failed, + finally: finished, + }) + + await expect(create()).rejects.toThrow('capture failed') + expect(failed).toHaveBeenCalledWith(error) + expect(finished).toHaveBeenCalledTimes(1) + }) +}) diff --git a/__test__/hooks/useElementFullscreen.spec.ts b/__test__/hooks/useElementFullscreen.spec.ts index 8da28ece..520559c1 100644 --- a/__test__/hooks/useElementFullscreen.spec.ts +++ b/__test__/hooks/useElementFullscreen.spec.ts @@ -51,4 +51,49 @@ describe('useElementFullscreen', () => { expect(isFullscreen.value).toBe(false) expect(div.style.transition).toBe('') }) + it('cancels a pending animation frame when exiting immediately', () => { + vi.useFakeTimers() + div.style.width = '240px' + const { enter, exit } = useElementFullscreen(div) + + enter() + exit() + vi.runAllTimers() + expect(div.style.width).toBe('240px') + expect(div.style.position).toBe('') + vi.useRealTimers() + }) + + it('restores the original element if the target ref changes while fullscreen', () => { + const target = ref(div) + const { enter, exit } = useElementFullscreen(target) + + enter() + target.value = document.createElement('div') + exit() + expect(div.hasAttribute('data-element-fullscreen')).toBe(false) + expect(div.style.position).toBe('') + }) + it('keeps transitions retryable when a before callback rejects the action', () => { + const beforeEnter = vi.fn().mockImplementationOnce(() => { + throw new Error('enter refused') + }) + const beforeExit = vi.fn().mockImplementationOnce(() => { + throw new Error('exit refused') + }) + const { enter, exit, isFullscreen } = useElementFullscreen(div, { + beforeEnter, + beforeExit, + }) + + expect(enter).toThrow('enter refused') + expect(isFullscreen.value).toBe(false) + enter() + expect(isFullscreen.value).toBe(true) + expect(exit).toThrow('exit refused') + expect(isFullscreen.value).toBe(true) + exit() + expect(isFullscreen.value).toBe(false) + expect(div.style.position).toBe('') + }) }) diff --git a/__test__/hooks/useI18n.spec.ts b/__test__/hooks/useI18n.spec.ts new file mode 100644 index 00000000..23196d5a --- /dev/null +++ b/__test__/hooks/useI18n.spec.ts @@ -0,0 +1,58 @@ +import { ref } from 'vue' +import type { Ref } from 'vue' +import { useI18n } from '../../src/hooks/web/useI18n' + +const { state } = vi.hoisted(() => ({ + state: { + instance: void 0 as + | { + mode: string + global: { + t: (key: string, ...args: unknown[]) => string + locale: Ref + } + } + | undefined, + }, +})) + +vi.mock('../../src/locales', () => ({ + get i18n() { + return state.instance + }, +})) + +beforeEach(() => { + state.instance = { + mode: 'composition', + global: { t: (key) => key, locale: ref('zh-CN') }, + } +}) + +describe('useI18n namespaces', () => { + it('prefixes relative keys and preserves fully qualified keys', () => { + const { t } = useI18n('hooks') + + expect(t('webIntro')).toBe('hooks.webIntro') + expect(t('hooks.webIntro')).toBe('hooks.webIntro') + expect(t('hooksExtra.title')).toBe('hooks.hooksExtra.title') + expect(t('')).toBe('') + }) + + it('recovers when the instance initializes after the hook was created', () => { + state.instance = void 0 + const hook = useI18n('hooks') + + expect(hook.t('code')).toBe('hooks.code') + expectTypeOf(hook.t('code')).toEqualTypeOf() + state.instance = { + mode: 'composition', + global: { t: (key) => `translated:${key}`, locale: ref('zh-CN') }, + } + expect(hook.t('code')).toBe('translated:hooks.code') + hook.locale('en-US') + expect(state.instance.global.locale.value).toBe('en-US') + state.instance.global.t = (key) => `updated:${key}` + expect(hook.t('code')).toBe('updated:hooks.code') + }) +}) diff --git a/__test__/hooks/useLayoutScroll.spec.ts b/__test__/hooks/useLayoutScroll.spec.ts new file mode 100644 index 00000000..4d1b78aa --- /dev/null +++ b/__test__/hooks/useLayoutScroll.spec.ts @@ -0,0 +1,34 @@ +import type { LayoutInst } from 'naive-ui' +import type { Ref } from 'vue' +import { LAYOUT_CONTENT_REF, LAYOUT_SIDER_REF } from '../../src/app-config' +import { useContentScroll } from '../../src/hooks/template/useContentScroll' +import { useSiderScroll } from '../../src/hooks/template/useSiderScroll' + +describe.each([ + [useContentScroll, LAYOUT_CONTENT_REF], + [useSiderScroll, LAYOUT_SIDER_REF], +] as const)('layout scrolling', (useScroll, target) => { + const writable = target as Ref + + afterEach(() => { + writable.value = null + }) + + it('can be created before mount and follows replacement layout instances', () => { + writable.value = null + const scroll = useScroll() + + expect(() => scroll({ top: 0 })).not.toThrow() + const first = vi.fn() + + writable.value = { scrollTo: first } as unknown as LayoutInst + scroll({ top: 10 }) + expect(first).toHaveBeenCalledWith({ top: 10 }) + const second = vi.fn() + + writable.value = { scrollTo: second } as unknown as LayoutInst + scroll(0, 300) + expect(second).toHaveBeenCalledWith(0, 300) + expect(first).toHaveBeenCalledTimes(1) + }) +}) diff --git a/__test__/hooks/useMaximize.spec.ts b/__test__/hooks/useMaximize.spec.ts new file mode 100644 index 00000000..ec211064 --- /dev/null +++ b/__test__/hooks/useMaximize.spec.ts @@ -0,0 +1,26 @@ +import { createPinia, disposePinia, setActivePinia } from 'pinia' +import { nextTick } from 'vue' +import { useMaximize } from '../../src/hooks/template/useMaximize' +import { piniaRuntimeStore } from '../../src/store/modules/runtime' + +it('shares maximize state across callers and cancels stale completion callbacks', async () => { + const pinia = createPinia() + + setActivePinia(pinia) + + try { + const entered = vi.fn() + const page = useMaximize({ enter: entered, zIndex: 1200 }) + const toolbar = useMaximize() + + page.maximize(true) + expect(toolbar.isFullscreen.value).toBe(true) + expect(piniaRuntimeStore().layoutContentMaximizeStyle.zIndex).toBe(1200) + toolbar.toggleFullscreen() + await nextTick() + expect(page.isLayoutContentMaximized.value).toBe(false) + expect(entered).not.toHaveBeenCalled() + } finally { + disposePinia(pinia) + } +}) diff --git a/__test__/hooks/useSpinning.spec.ts b/__test__/hooks/useSpinning.spec.ts index 15c4944f..ae09c229 100644 --- a/__test__/hooks/useSpinning.spec.ts +++ b/__test__/hooks/useSpinning.spec.ts @@ -1,38 +1,50 @@ -import { getVariableToRefs, setVariable } from '../../src/global-variable' +import { createPinia, disposePinia, setActivePinia } from 'pinia' import { useSpinning } from '../../src/hooks/template/useSpinning' -import setupMiniApp from '../utils/setupMiniApp' +import { piniaRuntimeStore } from '../../src/store/modules/runtime' -describe('useSpinning', async () => { - await setupMiniApp() +describe('useSpinning', () => { + let pinia: ReturnType - const { reload, openSpin, closeSpin } = useSpinning() - const globalMainLayoutLoad = getVariableToRefs('globalMainLayoutLoad') - - it('should open spinning', () => { - openSpin() - - expect(globalMainLayoutLoad.value).toBe(true) + beforeEach(() => { + vi.useFakeTimers() + pinia = createPinia() + setActivePinia(pinia) }) - it('should close spinning', () => { + afterEach(() => { + disposePinia(pinia) + vi.useRealTimers() + }) + + it('opens and closes the content spinner without remounting the page', () => { + const { openSpin, closeSpin } = useSpinning() + const store = piniaRuntimeStore() + openSpin() - - expect(globalMainLayoutLoad.value).toBe(true) - + expect(store.layoutContentSpinning).toBe(true) + expect(store.globalMainLayoutLoad).toBe(true) closeSpin() - - expect(globalMainLayoutLoad.value).toBe(true) + expect(store.layoutContentSpinning).toBe(false) }) - it('should reload', () => { - const wait = 1000 + it('keeps a remount pending until the latest reload finishes, across callers', () => { + const store = piniaRuntimeStore() - reload(wait) + useSpinning().reload(1000) + vi.advanceTimersByTime(500) + useSpinning().reload(1000) + vi.advanceTimersByTime(500) + expect(store.globalMainLayoutLoad).toBe(false) + vi.advanceTimersByTime(500) + expect(store.globalMainLayoutLoad).toBe(true) + }) - expect(globalMainLayoutLoad.value).toBe(false) - - setTimeout(() => { - expect(globalMainLayoutLoad.value).toBe(true) - }, wait) + it('disposes timers and isolates runtime state between applications', () => { + useSpinning().reload() + disposePinia(pinia) + expect(vi.getTimerCount()).toBe(0) + pinia = createPinia() + setActivePinia(pinia) + expect(piniaRuntimeStore().globalMainLayoutLoad).toBe(true) }) }) diff --git a/__test__/hooks/useWatermark.spec.ts b/__test__/hooks/useWatermark.spec.ts index 08a17585..16798ec0 100644 --- a/__test__/hooks/useWatermark.spec.ts +++ b/__test__/hooks/useWatermark.spec.ts @@ -29,4 +29,11 @@ describe('useWatermark', async () => { expect(hidden.value).toBe(false) }) + it('keeps the previous text when an empty string is supplied', () => { + setWatermarkContent('Keep this') + setWatermarkContent('') + expect(useSettingGetters().getWatermarkConfig.value.content).toBe( + 'Keep this', + ) + }) }) diff --git a/__test__/icons/generation.spec.ts b/__test__/icons/generation.spec.ts new file mode 100644 index 00000000..b2cfc391 --- /dev/null +++ b/__test__/icons/generation.spec.ts @@ -0,0 +1,74 @@ +// @vitest-environment node +import { execFileSync } from 'node:child_process' +import { + copyFileSync, + mkdirSync, + mkdtempSync, + renameSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +it('generates usable types and package imports after additions, moves and deletions', () => { + const root = mkdtempSync(join(tmpdir(), 'ray-icon-generation-')) + const script = join(root, 'scripts/icons.mjs') + const manifest = join(root, 'src/icons/manifest.ts') + const run = (...args: string[]) => + execFileSync(process.execPath, [script, ...args], { + cwd: root, + stdio: 'pipe', + }) + const read = (): { names: string[]; sprites: Record } => + JSON.parse( + execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + 'const m = await import(process.argv[1]); process.stdout.write(JSON.stringify({ names: m.iconNames, sprites: m.iconSprites }))', + pathToFileURL(manifest).href, + ], + { cwd: root, encoding: 'utf8' }, + ), + ) + + try { + mkdirSync(join(root, 'scripts'), { recursive: true }) + mkdirSync(join(root, 'src/icons/action'), { recursive: true }) + symlinkSync(resolve('node_modules'), join(root, 'node_modules'), 'junction') + copyFileSync('scripts/icons.mjs', script) + copyFileSync('.prettierrc.cjs', join(root, '.prettierrc.cjs')) + writeFileSync(join(root, 'package.json'), '{"type":"module"}') + writeFileSync(join(root, 'src/icons/action/first.svg'), '') + run() + run('--check') + expect(read()).toEqual({ + names: ['action/first'], + sprites: { action: '/__spritemap-action' }, + }) + renameSync( + join(root, 'src/icons/action/first.svg'), + join(root, 'src/icons/action/renamed.svg'), + ) + run() + expect(read().names).toEqual(['action/renamed']) + mkdirSync(join(root, 'src/icons/business-tools'), { recursive: true }) + writeFileSync(join(root, 'src/icons/business-tools/new.svg'), '') + expect(() => run('--check')).toThrow() + run() + expect(read().sprites['business-tools']).toBe('/__spritemap-business-tools') + expect(read().names).toContain('business-tools/new') + rmSync(join(root, 'src/icons/action'), { recursive: true }) + run() + expect(read()).toEqual({ + names: ['business-tools/new'], + sprites: { 'business-tools': '/__spritemap-business-tools' }, + }) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}, 15_000) diff --git a/__test__/icons/hmr.spec.ts b/__test__/icons/hmr.spec.ts new file mode 100644 index 00000000..c92b9281 --- /dev/null +++ b/__test__/icons/hmr.spec.ts @@ -0,0 +1,107 @@ +// @vitest-environment node +import { EventEmitter } from 'node:events' +import { join } from 'node:path' +import type { ViteDevServer } from 'vite' +import { iconManifestPlugin } from '../../vite-helper/icons' + +const { generate, scan } = vi.hoisted(() => ({ + generate: vi.fn<() => Promise>(), + scan: vi.fn<() => string[]>(), +})) + +vi.mock('../../scripts/icons.mjs', () => ({ + iconsRoot: '/ray/src/icons', + generateIcons: generate, + scanIcons: scan, +})) + +function createServer() { + return { + watcher: Object.assign(new EventEmitter(), { add: vi.fn() }), + httpServer: new EventEmitter(), + config: { logger: { error: vi.fn() } }, + ws: { send: vi.fn() }, + restart: vi.fn<() => Promise>().mockResolvedValue(void 0), + } +} + +function configure() { + const plugin = iconManifestPlugin(['action']) + const server = createServer() + const configureServer = plugin.configureServer as ( + server: ViteDevServer, + ) => void + + configureServer(server as unknown as ViteDevServer) + + return { plugin, server } +} + +beforeEach(() => { + generate.mockReset().mockResolvedValue(void 0) + scan.mockReset().mockReturnValue(['action/close']) +}) + +it('synchronizes at build start before modules are bundled', async () => { + const hook = iconManifestPlugin(['action']).buildStart as () => Promise + + await hook() + expect(generate).toHaveBeenCalledOnce() +}) + +it.each(['add', 'change', 'unlink'])( + 'synchronizes SVG %s events without restarting an existing package', + async (event) => { + const { server } = configure() + + server.watcher.emit(event, join('/ray/src/icons', 'action/close.svg')) + await vi.waitFor(() => expect(generate).toHaveBeenCalledOnce()) + expect(server.restart).not.toHaveBeenCalled() + server.httpServer.emit('close') + }, +) + +it('rebuilds package configuration before generation and discards disposed work', async () => { + const { plugin, server } = configure() + const stages: string[] = [] + const buildStart = plugin.buildStart as () => Promise + + generate.mockImplementation(async () => { + stages.push('generate') + }) + + scan.mockReturnValue(['action/close', 'business/new']) + server.restart.mockImplementation(async () => { + stages.push('close') + server.httpServer.emit('close') + await buildStart() + }) + server.watcher.emit('add', '/ray/src/icons/business/new.svg') + server.watcher.emit('add', '/ray/src/icons/business/another.svg') + await vi.waitFor(() => expect(server.restart).toHaveBeenCalledOnce()) + expect(generate).toHaveBeenCalledOnce() + expect(stages).toEqual(['close', 'generate']) + expect(server.ws.send).toHaveBeenCalledWith({ + type: 'full-reload', + path: '*', + }) + expect(server.watcher.listenerCount('change')).toBe(0) +}) + +it('shows generation errors in the browser and continues handling later edits', async () => { + const { server } = configure() + + generate.mockRejectedValueOnce(new Error('invalid icon path')) + server.watcher.emit('change', '/ray/src/icons/action/close.svg') + await vi.waitFor(() => + expect(server.ws.send).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'error', + err: expect.objectContaining({ message: 'invalid icon path' }), + }), + ), + ) + server.watcher.emit('change', '/ray/src/icons/action/close.svg') + await vi.waitFor(() => expect(generate).toHaveBeenCalledTimes(2)) + server.httpServer.emit('close') +}) diff --git a/__test__/icons/registry.spec.ts b/__test__/icons/registry.spec.ts new file mode 100644 index 00000000..0b69c776 --- /dev/null +++ b/__test__/icons/registry.spec.ts @@ -0,0 +1,49 @@ +// @vitest-environment node +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { iconNameFromPath, scanIcons } from '../../scripts/icons.mjs' +import type { IconProps } from '../../src/components/base/RIcon' +import { iconNames, isIconName, resolveIconName } from '../../src/icons' +import type { IconName } from '../../src/icons' + +describe('namespaced icons', () => { + it('keeps the generated registry synchronized and exposes strict component props', () => { + expect(scanIcons()).toEqual([...iconNames]) + expect(isIconName('directional/resize_h')).toBe(true) + expect(isIconName('resize_h')).toBe(false) + expect(isIconName('directional/missing')).toBe(false) + expectTypeOf().toEqualTypeOf() + expectTypeOf>().toEqualTypeOf() + }) + + it('supports duplicate basenames in different packages and nested paths', () => { + const root = mkdtempSync(join(tmpdir(), 'ray-icons-')) + + try { + for (const name of ['first/resize.svg', 'second/nested/resize.svg']) { + const path = join(root, name) + + mkdirSync(join(path, '..'), { recursive: true }) + writeFileSync(path, '') + } + + expect(scanIcons(root)).toEqual(['first/resize', 'second/nested/resize']) + expect(iconNameFromPath(join(root, 'first/resize.svg'), root)).toBe( + 'first/resize', + ) + expect(() => iconNameFromPath(join(root, 'loose.svg'), root)).toThrow( + 'package/name', + ) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('resolves existing persisted bare names without accepting unknown paths', () => { + expect(resolveIconName('ray')).toBe('logo/ray') + expect(resolveIconName('directional/resize_h')).toBe('directional/resize_h') + expect(resolveIconName('unknown')).toBeUndefined() + expect(resolveIconName('../ray')).toBeUndefined() + }) +}) diff --git a/__test__/layout/mobile-search.spec.ts b/__test__/layout/mobile-search.spec.ts new file mode 100644 index 00000000..6d3af9e9 --- /dev/null +++ b/__test__/layout/mobile-search.spec.ts @@ -0,0 +1,23 @@ +import { mount } from '@vue/test-utils' +import GlobalSearch from '../../src/layout/components/Search/GlobalSearch' +import { router } from '../../src/router' +import setupMiniApp from '../utils/setupMiniApp' + +it('mounts the header search on a narrow viewport and closes it immediately', async () => { + vi.stubGlobal('innerWidth', 390) + const { app } = await setupMiniApp() + + try { + const wrapper = mount(GlobalSearch, { + props: { show: true }, + global: { plugins: [router] }, + }) + + expect(wrapper.emitted('update:show')).toContainEqual([false]) + expect(wrapper.find('.global-search').exists()).toBe(false) + wrapper.unmount() + } finally { + app.unmount() + vi.unstubAllGlobals() + } +}) diff --git a/__test__/layout/preferences.spec.ts b/__test__/layout/preferences.spec.ts new file mode 100644 index 00000000..074c4608 --- /dev/null +++ b/__test__/layout/preferences.spec.ts @@ -0,0 +1,122 @@ +import { createPinia, disposePinia, setActivePinia } from 'pinia' +import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' +import { createApp, nextTick } from 'vue' +import { APP_CATCH_KEY } from '../../src/app-config' +import { findMenuRoot, firstMenuLeaf } from '../../src/layout/navigation' +import { piniaLockScreenStore } from '../../src/store/modules/lock-screen' +import { piniaSettingStore } from '../../src/store/modules/setting' +import { + getDefaultSettingConfig, + normalizeLayoutConfig, +} from '../../src/store/modules/setting/constant' +import type { AppMenuOption } from '../../src/types' + +const menu = ( + fullPath: string, + children?: AppMenuOption[], + show = true, +): AppMenuOption => ({ + name: fullPath, + path: fullPath, + fullPath, + key: fullPath, + label: fullPath, + meta: {}, + children, + show, +}) + +describe('layout preferences', () => { + it('adds defaults and bounds persisted or programmatic invalid values', () => { + expect(normalizeLayoutConfig(null)).toEqual( + getDefaultSettingConfig().layoutConfig, + ) + expect( + normalizeLayoutConfig({ + mode: 'unknown', + contentMaxWidth: NaN, + contentPadding: -100, + }), + ).toMatchObject({ mode: 'side', contentMaxWidth: 1200, contentPadding: 0 }) + expect( + normalizeLayoutConfig({ + mode: 'mixed', + contentWidth: 'fixed', + contentMaxWidth: 99999, + }), + ).toMatchObject({ + mode: 'mixed', + contentWidth: 'fixed', + contentMaxWidth: 2560, + }) + }) + + it('hydrates old preferences without changing the storage key or losing data', () => { + localStorage.setItem( + APP_CATCH_KEY.appPiniaSettingStore, + JSON.stringify({ + localeLanguage: 'en-US', + sideBarLogo: { icon: 'ray', title: 'Saved title' }, + menuTagSwitch: false, + }), + ) + const pinia = createPinia().use(piniaPluginPersistedstate) + const app = createApp({ render: () => null }).use(pinia) + + app.mount(document.createElement('div')) + setActivePinia(pinia) + + try { + const store = piniaSettingStore() + + expect(store.layoutConfig).toEqual(getDefaultSettingConfig().layoutConfig) + expect(store.sideBarLogo).toMatchObject({ + icon: 'logo/ray', + title: 'Saved title', + }) + expect(store.localeLanguage).toBe('en-US') + expect(store.menuTagSwitch).toBe(false) + store.updateSettingState('layoutConfig', { mode: 'top' }) + expect(store.layoutConfig.fixedHeader).toBe(true) + expect(store.layoutConfig.mode).toBe('top') + } finally { + app.unmount() + disposePinia(pinia) + localStorage.removeItem(APP_CATCH_KEY.appPiniaSettingStore) + } + }) + + it('finds mixed navigation roots by nested leaf and skips hidden branches', () => { + const root = menu('/root', [ + menu('/hidden', [], false), + menu('/child', [menu('/leaf')]), + ]) + + expect(findMenuRoot([root], '/leaf')).toBe(root) + expect(firstMenuLeaf(root)?.fullPath).toBe('/leaf') + expect( + findMenuRoot([menu('/hidden', [], false)], '/hidden'), + ).toBeUndefined() + expect( + firstMenuLeaf(menu('/empty', [menu('/hidden', [], false)])), + ).toBeUndefined() + }) + it('keeps the legacy lock-screen boolean storage contract inside Pinia', async () => { + localStorage.setItem(APP_CATCH_KEY.isAppLockScreen, 'true') + const pinia = createPinia() + + setActivePinia(pinia) + + try { + const store = piniaLockScreenStore() + + expect(store.locked).toBe(true) + store.setLocked(false) + await nextTick() + expect(localStorage.getItem(APP_CATCH_KEY.isAppLockScreen)).toBe('false') + } finally { + disposePinia(pinia) + localStorage.removeItem(APP_CATCH_KEY.isAppLockScreen) + } + }) +}) diff --git a/__test__/layout/slots.spec.ts b/__test__/layout/slots.spec.ts new file mode 100644 index 00000000..3c95720c --- /dev/null +++ b/__test__/layout/slots.spec.ts @@ -0,0 +1,34 @@ +import { shallowMount } from '@vue/test-utils' +import { createPinia, disposePinia, setActivePinia } from 'pinia' +import { h } from 'vue' +import Layout from '../../src/layout' +import { router } from '../../src/router' +import { piniaSettingStore } from '../../src/store/modules/setting' + +it('lets a custom header replace the complete default header and top navigation', () => { + const pinia = createPinia() + + setActivePinia(pinia) + piniaSettingStore().updateSettingState('layoutConfig', { mode: 'top' }) + const options = { + global: { renderStubDefaultSlot: true, plugins: [router, pinia] }, + } + const standard = shallowMount(Layout, options) + + expect(standard.find('top-navigation-stub').exists()).toBe(true) + standard.unmount() + const custom = shallowMount(Layout, { + ...options, + slots: { + header: () => h('div', { 'data-test': 'custom-header' }, 'Custom'), + }, + }) + + try { + expect(custom.find('[data-test="custom-header"]').exists()).toBe(true) + expect(custom.find('top-navigation-stub').exists()).toBe(false) + } finally { + custom.unmount() + disposePinia(pinia) + } +}) diff --git a/docs/ai-development.md b/docs/ai-development.md index 67791058..d7504129 100644 --- a/docs/ai-development.md +++ b/docs/ai-development.md @@ -19,6 +19,8 @@ pnpm dev Codex 自动读取根目录 `AGENTS.md`;Cursor、Copilot 和 Claude 的项目入口也指向同一份规则。新对话只需提供目标、影响页面或报错、预期行为、约束和验收条件,无需粘贴整个仓库。 +编写或修改注释时统一遵循 [注释规范](comment-style.md),由 `AGENTS.md` 引入。组件说明放在 README 和示例页;函数契约、模块声明与内部逻辑使用各自规定的形式,不在工具适配文件重复维护规范。 + ## 命令契约 | 命令 | 用途与结果 | diff --git a/docs/architecture.md b/docs/architecture.md index 69484d25..ef1b9a2f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -10,28 +10,32 @@ Ray Template 是前端中后台模板,包含可运行的组件与路由示例 ## 模块与扩展入口 -| 需求 | 入口 | 相关约定 | -| -------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| 新增页面与菜单 | `src/views`、`src/router/modules` | [路由文档](../src/router/README.md),菜单由路由生成 | -| 权限与守卫 | `src/router/utils/vue-router-register.ts`、`src/router/utils/permission.ts` | 同时检查菜单显示与实际导航;前端权限不能替代后端授权 | -| 全局状态 | `src/store/modules`、`src/store/hooks` | [Store 文档](../src/store/README.md),持久化配置使用 `pick`/`omit` | -| 请求与接口 | `src/api`、`src/axios` | [请求文档](../src/axios/README.md),请求/响应拦截器分开注册 | -| 演示接口 | `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/hooks/web`、`template`、`components` | 复用 Vue 响应式与作用域清理,已有回归测试在 `__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 明暗主题配置 | -| SVG 图标 | `src/icons`、`RIcon` | [图标说明](../src/icons/A_README.md),名称与分包约定影响 symbol ID | -| 全局指令 | `src/directives/modules` | [注册约定](../src/directives/README.md)、[用法](../src/directives/README.DIR.md) | -| 构建与插件 | `vite.config.ts`、`vite.plugin.config.ts`、`vite.custom.config.ts` | 部署 base、输出目录、CDN、开发代理均在配置中管理 | -| 自动导入 | `vite.plugin.config.ts`、`unplugin` | 首次构建可更新生成声明;生成声明需要随对应依赖变化一起提交 | -| 测试 | `__test__`、`vitest.config.ts` | Happy DOM 单元测试,不能证明真实浏览器布局、下载或打印正确 | +| 需求 | 入口 | 相关约定 | +| -------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| 新增页面与菜单 | `src/views`、`src/router/modules` | [路由文档](../src/router/README.md),菜单由路由生成 | +| 权限与守卫 | `src/router/utils/vue-router-register.ts`、`src/router/utils/permission.ts` | 同时检查菜单显示与实际导航;前端权限不能替代后端授权 | +| 全局状态 | `src/store/modules`、`src/store/hooks` | [Store 文档](../src/store/README.md),持久化配置使用 `pick`/`omit` | +| 请求与接口 | `src/api`、`src/axios` | [请求文档](../src/axios/README.md),请求/响应拦截器分开注册 | +| 演示接口 | `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/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 明暗主题配置 | +| SVG 图标 | `src/icons`、`RIcon` | [图标说明](../src/icons/A_README.md),名称与分包约定影响 symbol ID | +| 全局指令 | `src/directives/modules` | [注册约定](../src/directives/README.md)、[用法](../src/directives/README.DIR.md) | +| 构建与插件 | `vite.config.ts`、`vite.plugin.config.ts`、`vite.custom.config.ts` | 部署 base、输出目录、CDN、开发代理均在配置中管理 | +| 自动导入 | `vite.plugin.config.ts`、`unplugin` | 首次构建可更新生成声明;生成声明需要随对应依赖变化一起提交 | +| 测试 | `__test__`、`vitest.config.ts` | Happy DOM 单元测试,不能证明真实浏览器布局、下载或打印正确 | ## 数据与调用约束 - `src/app-config` 管理模板配置。运行时 `__APP_CFG__` 由 Vite 注入;`__DEV__` 表示 development 模式。 - 路径别名 `@`、`@api`、`@images`、`@mock` 在 Vite 和 TypeScript 中必须一致。 -- `src/store/hooks` 是已有业务对 Store 的访问层;简单全局响应式变量另见 [global-variable](../src/global-variable/README.md)。 +- `src/store/hooks` 是已有业务对 Store 的访问层;所有全局可变 UI 状态统一归入 Pinia:临时状态由 `runtime` 管理且不持久化,布局偏好在 `setting.layoutConfig` 中沿用原缓存 key。 - `src/utils/c` 仍使用 CryptoJS 4.2.0 的同步 AES 格式。改用 Web Crypto 前需设计异步接口和历史密文迁移,不能直接替换并让既有数据无法解密。 - 演示页与业务组件同样属于模板能力。删除 demo 或更换第三方库前需要明确任务范围;升级工具链时应保留示例功能。 + +布局模式、配置与插槽见 [布局说明](../src/layout/README.md)。图标按包生成独立雪碧图,完整名称和严格类型由 `scripts/icons.mjs` 统一生成。 + +页面标题、配色与示例排版见 [视觉与排版](ui-design.md);注释位置与格式遵循 [注释规范](comment-style.md)。 diff --git a/docs/comment-style.md b/docs/comment-style.md new file mode 100644 index 00000000..cb116111 --- /dev/null +++ b/docs/comment-style.md @@ -0,0 +1,56 @@ +# 注释规范 + +本规范适用于本仓库的 TypeScript、JavaScript、TSX/JSX、脚本与配置。新增或修改注释时必须遵循;不为自解释代码机械补注释。参考用户指定的统一注释风格,按 Ray Template 的组件与模块边界调整。 + +## 组件与文件说明 + +- 不在文件顶部、`defineComponent` 前或函数组件声明前添加多行介绍性注释。组件职责、继承关系、用法与示例放在相应 README;非显然约束放在实际受影响的位置。 +- 不把文件介绍移动到第一个函数、常量或导出对象前。注释必须描述紧邻声明的真实契约,不能借换位置保留整段文件说明。 +- 同一个声明只保留一份契约说明,禁止连续堆叠多个 JSDoc 块。 + +## 函数与方法契约 + +确有需要说明参数、资源所有权、副作用、异步归属或失败语义时,使用多行 JSDoc。参数、返回值以实际签名与实现为准。 + +1. 使用独立的 `/**` 和 ` */`,内部每行以 ` *` 开头,并与被说明的声明对齐。 +2. 开头先放一行仅含 ` *` 的空白注释行;区段之间也使用这样的空白行,不保留行尾空格。 +3. 标签按 `@param` → `@description` → `@returns` → `@throws` 排列,仅保留需要的区段。 +4. 有参数时按签名顺序列出真实参数名与含义;多个 `@param` 连续排列。无参数时省略参数区。 +5. `@description` 独占一行,正文从下一行开始,不在标签前重复写一段函数介绍。 +6. `void`、`Promise` 和构造函数不写 `@returns`;副作用放在描述区。`@throws` 只描述调用方可观察的抛出或 Promise 拒绝。 + +```ts +/** + * + * @param wait 页面恢复前的等待时间,单位为毫秒 + * + * @description + * 重新挂载当前页面;恢复计时器由 Store 持有,避免随页面卸载而取消。 + */ +const reload = (wait = 800) => { + // 实现省略。 +} +``` + +公开 Hook 的完整示例优先放在 README 与可运行示例页,不在函数前堆放长篇教程。历史 `@example` 不应在无关任务中机械删除;本次修改契约时应同步核对它是否仍准确。 + +## 声明与逻辑说明 + +- 模块级常量、变量、类字段和类型属性的简短说明使用单行 JSDoc `/** 说明 */`,不加标签。 +- 类、接口或类型确需说明整体职责时,使用带开头空白行的多行 JSDoc,正文放在独占一行的 `@description` 后,不虚构参数或返回值。 +- 函数内部的分支、局部变量、执行顺序和原因说明使用 `//`;多行逻辑说明逐行写 `//`,不套用函数契约格式。 +- 注释用中文解释非显然的原因与约束,技术标识符保留原名。避免逐行复述、作者闲谈、过时行为和没有实现依据的保证。 + +```ts +/** 内容区恢复前的默认等待时间,单位为毫秒 */ +const RELOAD_DELAY = 800 + +const update = () => { + // 页面可能已被替换,执行时再读取当前布局实例。 + const layout = contentRef.value +} +``` + +许可证、来源归属、生成标记和工具指令保留其必要语法,例如 `// @ts-expect-error`、`/// `、`/* @__PURE__ */`。JSX 子节点使用 `{/* 说明 */}`;HTML、CSS 使用各自合法的定界符。 + +交付前检查注释位置、是否堆叠、参数名、标签顺序和内容真实性。注释规范不替代 ESLint、Prettier、类型检查或浏览器验收。 diff --git a/docs/toolchain-upgrade.md b/docs/toolchain-upgrade.md index a368aa6b..093b824d 100644 --- a/docs/toolchain-upgrade.md +++ b/docs/toolchain-upgrade.md @@ -97,6 +97,45 @@ CI 工作流仅完成配置和官方 Action 输入核对,尚未在远端执行 生产构建仍提示一个约 2 MB 的公共 chunk(包含模板公共组件依赖)及 ContentWrapper 同时静态/动态导入;功能检查通过,未提高告警阈值来隐藏问题。后续若做性能专项,应基于静态报告拆解组件导出与加载边界,并重新验证路由缓存及初始化顺序。 +## 2026-11-03:Hooks、布局和图标改造验证 + +未升级依赖或改动锁文件。新增 `icons:generate` / `icons:check`,生成脚本使用项目现有 Prettier 配置输出代码,并保留 ESLint 所需的声明空行。Vite 按顶层分包生成独立雪碧图,名称与类型来自同一目录清单。 + +| 检查 | 实际结果 | +| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Node.js 26.13.0、pnpm 12.16.1、冻结锁文件安装、`pnpm env:check` | 通过;本机原有 Node 26.12.1 低于项目要求,本轮使用临时 26.13.0 运行时 | +| `pnpm typecheck`(包含 `icons:check`)、`pnpm lint` | 通过,未降低规则或增加全局忽略 | +| `pnpm format:check` / `pnpm check` | 格式检查报本地 `TODO.md` 与 `.vscode/settings.json`,保留这两项非本任务变更;`pnpm check` 在格式阶段停止,未声称全绿 | +| 本任务修改与新增文件的 Prettier 检查 | 通过;生成清单也由项目 Prettier 配置直接格式化 | +| `pnpm test:run` | 单独继续执行,50 个测试文件 / 173 条测试全部通过 | +| `pnpm exec vite build` | 单独继续执行并通过;44 个图标输出为 7 个带 hash 的独立包,各包 symbol ID 无重复 | +| Chrome 开发版 | 侧边、顶部、混合导航;嵌套页面菜单匹配;定宽 1200px 居中;390px 抽屉打开、选中自动收起且无页面横向溢出;刷新后保留桌面偏好;PNG 截图与元素全屏/恢复 | +| Chrome 生产预览 | 演示登录、44 个图标渲染、7 个带 base 的图标资源路径、完整图标复制操作、深色主题、中英文新页面文本、内容最大化及 Esc、页面卸载后刷新恢复、内容滚动到 300px、滚动页脚与既有自适应表格渲染 | + +Pinia 设置沿用原持久化 key,旧裸 Logo 名称在读取时迁移;锁屏仍使用历史布尔值格式。对应迁移、并发刷新、滚动实例替换、导航越界、右键异步关闭、全屏帧清理及截图失败处理均有回归用例。 + +本机截图位于 `.ai-local/evidence/2026-11-03/`。文件监听首次触发 EMFILE,本轮开发服务使用 `CHOKIDAR_USEPOLLING=1` 进行验收,未将该环境绕行写入默认开发配置。保留公共 chunk 大小、ContentWrapper 静态/动态导入及 Mock CORS 序列化提示;未调整告警阈值。本轮未验证实际纸张打印、最低版本浏览器或无界宿主。 + +## 2026-11-03:自动同步、注释规范与视觉整理 + +本轮未升级依赖、未改动锁文件。图标生成已接入 `dev`、`build`、`dev-build`、`report`、`check` 与 Vite 构建入口;独立 `typecheck` 和 `icons:check` 保持只读。`AGENTS.md` 引入 [统一注释规范](comment-style.md),页面排版与主题入口见 [视觉约定](ui-design.md)。 + +| 检查 | 实际结果 | +| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 冻结锁文件安装与 `pnpm env:check` | 通过,使用 Node.js 26.13.0 / pnpm 12.16.1 | +| `pnpm check` | 图标同步、类型和 ESLint 通过;格式阶段仅报未改动的 `.vscode/settings.json`,未声称全量检查通过 | +| `pnpm test:run` | 单独执行,52 个测试文件 / 181 条测试全部通过 | +| `pnpm build` | 通过,包含自动生成、类型检查和生产构建;最终为 44 个图标、7 个独立雪碧图 | +| 无开发服务参与的构建 | 临时新增 SVG 后先确认 `icons:check` 报清单过期,再直接执行 `pnpm build`,自动生成成功;删除临时 SVG 后再次构建恢复最终产物 | +| 实际图标 HMR | 新增、改名、删除自动同步清单;修改内容后资源 hash 改变且保留搜索状态;新增/删除整个分包自动重建插件配置并通知浏览器重载;带连字符的分包名与符号链接路径的 CLI 执行有回归覆盖 | +| 注释位置 | 移除组件介绍块和重复堆叠;类型、Store 与常量说明按相邻声明重新核对,修正原登录状态说明中错误的存储介质描述 | +| Chrome 排版 | 工作台、Hooks、布局实验室、图标库;1440/1280px 桌面与 390px 单列,无页面横向溢出;保留登录页紧凑资源入口 | +| 主题与语言 | 生产页明暗切换、暗色选中态前景、中英文标题;修复热更新后国际化实例被替换导致显示原始键的边界,并覆盖初始化前创建 Hook 后恢复翻译的场景 | + +开发验收仍使用本机 `CHOKIDAR_USEPOLLING=1`,未改动默认监听方式。浏览器控制连接在还原视口时中断,后续通过 Chrome 开发者工具的独立上下文核对最终生产产物;最终截图与阶段记录放在 `.ai-local/evidence/2026-11-03/polish/`。复杂基础组件自身的 Vue JSX 热替换场景未穷尽,生产验收基于最终完整加载的产物;没有把这些检查写成真实后端、最低版本设备或实体打印验收。 + +公共 chunk 大小、ContentWrapper 静态/动态导入与 Mock CORS 序列化提示仍保留,未降低检查严格度或调高告警门槛。 + ## 参考资料 - [Node.js 26.13.0 LTS](https://nodejs.org/en/blog/release/v26.13.0) diff --git a/docs/ui-design.md b/docs/ui-design.md new file mode 100644 index 00000000..b53d24eb --- /dev/null +++ b/docs/ui-design.md @@ -0,0 +1,24 @@ +# 页面视觉与排版 + +模板采用克制的蓝色与中性色。精致感来自一致的层级、间距与密度,而非给每个区域增加阴影或装饰。 + +## 主题与尺度 + +- 页面背景、卡片、分割线与文字优先使用 `src/styles/design-system.scss` 中的语义变量。Naive UI 的主题覆盖集中在 `src/app-config/design-config.ts`,保持同一色阶,避免页面单独拼出另一套主题。 +- 控件通常为 8px 圆角、卡片为 12px;页面区块间距使用 20–28px。强调色用于选择与主要操作,正文、说明、眉题使用不同文字层级。 +- 顶栏、标签栏和侧栏使用轻分割线,不叠加区域阴影;少量内容卡片使用两层轻阴影。 +- 页面标题复用 `AppPageHeader`:眉题、一个主标题、简短说明与可选操作区。不要以大段说明或同等权重的卡片标题代替页面层级。 + +## 页面组织 + +- 工作台与说明型示例限制到 1360px 并居中;业务表格仍遵循用户的流式/定宽布局设置,不全局强行收窄。 +- 示例使用 `DemoPage` 和 `HookExample`,按功能分组;将交互区域和可展开的代码区域分开。代码展开使用原生 details,支持键盘操作,并保留复制入口。 +- Hooks 在内容容器达到 900px 后显示双列;布局实验室在 760px 后使用设置/预览双栏。容器不足时按默认单列堆叠,判断可用内容宽度,不只看整个浏览器窗口。 +- 先复用现有 Naive UI 与模板组件,再补少量排版结构。不为展示效果编造统计数据;工作台版本号读取实际 package 配置,快捷入口跟随可见菜单。 +- 共用组件的不同调用场景分别保留:例如资源链接在登录页保持 compact,在工作台使用 cards,不以统一排版破坏原有页面约束。 + +## 验证 + +检查桌面与 390px 窄屏、明暗主题、中英文、长代码和操作按钮换行。默认正文用色按至少 4.5:1、输入框等控件边界按至少 3:1 选取;用户自定义主色仍需按实际组合确认。 + +保留 `forced-colors` 系统颜色回退、可见键盘焦点与减少动态效果设置。截图、颜色数值与浏览器检查不能互相替代,也不代表已验证全部最低版本设备。 diff --git a/package.json b/package.json index 48bec454..d7a1484b 100644 --- a/package.json +++ b/package.json @@ -8,12 +8,14 @@ "pnpm": "12.16.1" }, "scripts": { - "dev": "vite", - "typecheck": "vue-tsc --noEmit", - "build": "pnpm typecheck && vite build", + "dev": "pnpm icons:generate && vite", + "icons:generate": "node scripts/icons.mjs", + "icons:check": "node scripts/icons.mjs --check", + "typecheck": "pnpm icons:check && vue-tsc --noEmit", + "build": "pnpm icons:generate && pnpm typecheck && vite build", "preview": "vite preview", - "dev-build": "pnpm typecheck && vite build --mode development", - "report": "vite build --mode report", + "dev-build": "pnpm icons:generate && pnpm typecheck && vite build --mode development", + "report": "pnpm icons:generate && vite build --mode report", "prepare": "husky", "test": "vitest", "test:run": "vitest run", @@ -22,7 +24,7 @@ "lint:fix": "eslint . --fix --max-warnings=0", "format": "prettier --write .", "format:check": "prettier --check .", - "check": "pnpm env:check && pnpm typecheck && pnpm lint && pnpm format:check && pnpm test:run && vite build", + "check": "pnpm env:check && pnpm icons:generate && pnpm typecheck && pnpm lint && pnpm format:check && pnpm test:run && vite build", "env:check": "node scripts/doctor.mjs" }, "lint-staged": { diff --git a/scripts/icons.d.mts b/scripts/icons.d.mts new file mode 100644 index 00000000..277146cf --- /dev/null +++ b/scripts/icons.d.mts @@ -0,0 +1,4 @@ +export const iconsRoot: string +export function iconNameFromPath(filePath: string, root?: string): string +export function scanIcons(root?: string): string[] +export function generateIcons(check?: boolean): Promise diff --git a/scripts/icons.mjs b/scripts/icons.mjs new file mode 100644 index 00000000..3837367d --- /dev/null +++ b/scripts/icons.mjs @@ -0,0 +1,74 @@ +import { + existsSync, + readdirSync, + readFileSync, + realpathSync, + writeFileSync, +} from 'node:fs' +import { dirname, relative, resolve, sep } from 'node:path' +import { fileURLToPath } from 'node:url' +import { format, resolveConfig } from 'prettier' + +export const iconsRoot = resolve( + dirname(fileURLToPath(import.meta.url)), + '../src/icons', +) + +const manifest = resolve(iconsRoot, 'manifest.ts') + +export function iconNameFromPath(filePath, root = iconsRoot) { + const name = relative(root, filePath) + .split(sep) + .join('/') + .replace(/\.svg$/, '') + + if (!/^[a-z][a-z0-9_-]*(\/[a-z][a-z0-9_-]*)+$/.test(name)) { + throw new Error(`SVG must use a package/name path: ${name}`) + } + + return name +} + +export function scanIcons(root = iconsRoot) { + const names = [] + const walk = (directory) => { + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const path = resolve(directory, entry.name) + + if (entry.isDirectory()) walk(path) + else if (entry.name.endsWith('.svg')) + names.push(iconNameFromPath(path, root)) + } + } + + walk(root) + + return names.sort() +} + +export async function generateIcons(check = false) { + const names = scanIcons() + const packages = [...new Set(names.map((name) => name.split('/')[0]))] + const list = (values) => + `[\n${values.map((value) => ` '${value}',`).join('\n')}\n]` + const formatted = `// Generated by scripts/icons.mjs. Do not edit.\nexport const iconNames = ${list(names)} as const\n\nexport type IconName = (typeof iconNames)[number]\n\nexport const iconPackages = ${list(packages)} as const\n\nexport type IconPackage = (typeof iconPackages)[number]\n\nexport const iconSprites = {\n${packages.map((name) => ` ${JSON.stringify(name)}: '/__spritemap-${name}',`).join('\n')}\n} as const\n\nconst names: ReadonlySet = new Set(iconNames)\n\nexport const isIconName = (value: unknown): value is IconName =>\n typeof value === 'string' && names.has(value)\n` + const source = await format(formatted, { + ...(await resolveConfig(manifest)), + filepath: manifest, + }) + const previous = existsSync(manifest) ? readFileSync(manifest, 'utf8') : '' + + if (previous === source) return + + if (check) throw new Error('Icon manifest is stale. Run pnpm icons:generate.') + + writeFileSync(manifest, source) +} + +if ( + process.argv[1] && + existsSync(process.argv[1]) && + realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)) +) { + await generateIcons(process.argv.includes('--check')) +} diff --git a/src/api/demo/test.ts b/src/api/demo/test.ts index 5beb0bd3..281c905e 100644 --- a/src/api/demo/test.ts +++ b/src/api/demo/test.ts @@ -1,13 +1,3 @@ -/** - * - * 该方法演示如何封装一个通用请求方法 - * - * 步骤: - * 1. 定义一个方法(见下面的 demo 方法) - * 2. 暴露该函数 - * 3. 如果该方法在 setup 环境中使用,则可以使用 useHookPlusRequest 包裹该方法,即可便捷使用该请求函数。如果请求方法在非 setup 环境中使用,直接使用即可 - */ - import { request } from '@/axios' import type { BasicResponse } from '@/types' @@ -25,9 +15,12 @@ interface JSONPlaceholder { /** * - * @returns 测试 + * @param city 天气查询接口所需的城市名称 * - * @method get + * @description + * 按城市名称请求演示天气接口。 + * + * @returns 演示接口的响应 Promise */ export const getWeather = (city: string) => { return request({ diff --git a/src/app-components/README.md b/src/app-components/README.md index c70aaa84..bc79c99d 100644 --- a/src/app-components/README.md +++ b/src/app-components/README.md @@ -4,3 +4,14 @@ - app:存放与模板数据绑定的组件 - provider:存放模板注入类组件 + +## 页面与 Provider + +- `AppPageHeader` 统一页面眉题、主标题、说明与右侧操作区;页面正文保留各自布局,不在此封装业务内容。 +- `AppShareLink` 默认使用紧凑入口,工作台通过 `variant="cards"` 显示具名链接卡片,保留登录页的空间约束。 +- `AppAvatar` 从 signing Store 读取头像与名称;保留 Naive UI Avatar 相关 props。 +- `AppNaiveGlobalProvider` 提供 Naive UI 上下文以及 `window.$message`、`$notification`、`$dialog`、`$loadingBar`。Provider 初始化前不要调用这些对象;全局提示跟随应用的主题和语言。 +- `AppWatermarkProvider` 为全局水印提供入口,显示与内容通过 `useWatermark` 调整。需要限制水印覆盖范围时,调整 Provider 的挂载位置。 +- `AppRequestCancelerProvider` 在路由更新前取消旧请求;默认布局内容负责挂载。自定义内容插槽时需保留所需的请求取消行为。 + +组件介绍放在此类文档中,声明前不再保留大段说明;注释位置与格式遵循 [统一注释规范](../../docs/comment-style.md)。 diff --git a/src/app-components/app/AppAvatar/index.tsx b/src/app-components/app/AppAvatar/index.tsx index 4e21e194..ea238b4e 100644 --- a/src/app-components/app/AppAvatar/index.tsx +++ b/src/app-components/app/AppAvatar/index.tsx @@ -1,11 +1,3 @@ -/** - * - * 系统管理员头像与名称 - * - * 头像展示基于 naive ui Avatar 组件, 继承该组件所有属性与方法 - * 默认读取本地 session catch 缓存 - */ - import { useSigningGetters } from '@/store' import { avatarProps, NAvatar, NButton, NFlex } from 'naive-ui' import type { AvatarProps, FlexProps } from 'naive-ui' diff --git a/src/app-components/app/AppGlobalSpin/index.tsx b/src/app-components/app/AppGlobalSpin/index.tsx index 133084c6..e71a358e 100644 --- a/src/app-components/app/AppGlobalSpin/index.tsx +++ b/src/app-components/app/AppGlobalSpin/index.tsx @@ -1,21 +1,4 @@ -/** - * - * 全屏加载效果 - * - * 基于 Naive UI Spin 组件 - * - * 使用方法 - * 1. import { setVariable } from '@/hooks' - * 2. setVariable('globalSpinning', true) | setVariable('globalSpinning', false) - * - * 仅需按照上述步骤实现全屏加载动画 - * - * 注意 - * 1. 该组件为全屏加载动画效果, 其遮罩会导致页面元素不可被命中 - * 2. 如果需要使用该组件请注意控制取消时机 - */ - -import { getVariableToRefs } from '@/global-variable' +import { useRuntimeActions, useRuntimeGetters } from '@/store' import { NSpin, spinProps } from 'naive-ui' import type { SpinProps } from 'naive-ui' @@ -28,7 +11,7 @@ const GlobalSpin = defineComponent({ const overrides = { opacitySpinning: '0.3', } - const spinValue = getVariableToRefs('globalSpinning') + const spinValue = useRuntimeGetters().globalSpinning return { spinValue, diff --git a/src/app-components/app/AppLockScreen/appLockVar.ts b/src/app-components/app/AppLockScreen/appLockVar.ts index 3d52ca17..1636775d 100644 --- a/src/app-components/app/AppLockScreen/appLockVar.ts +++ b/src/app-components/app/AppLockScreen/appLockVar.ts @@ -1,25 +1,12 @@ -import { APP_CATCH_KEY } from '@/app-config' -import { useStorage } from '@vueuse/core' - -const appLockScreen = useStorage( - APP_CATCH_KEY.isAppLockScreen, - false, - window.localStorage, - { - mergeDefaults: true, - }, -) +import { useLockScreenActions, useLockScreenGetters } from '@/store' const useAppLockScreen = () => { - const setLockAppScreen = (bool: boolean) => { - appLockScreen.value = bool - } - - const getLockAppScreen = () => appLockScreen.value + const { getLocked } = useLockScreenGetters() + const { setLocked } = useLockScreenActions() return { - setLockAppScreen, - getLockAppScreen, + setLockAppScreen: setLocked, + getLockAppScreen: () => getLocked.value, } } diff --git a/src/app-components/app/AppPageHeader/index.scss b/src/app-components/app/AppPageHeader/index.scss new file mode 100644 index 00000000..8ba335ec --- /dev/null +++ b/src/app-components/app/AppPageHeader/index.scss @@ -0,0 +1,52 @@ +.r-page-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; + padding-block: 8px 4px; + + &__copy { + min-width: 0; + } + + &__eyebrow { + margin-block-end: 10px; + color: var(--r-text-muted); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.12em; + text-transform: uppercase; + } + + h1 { + color: var(--r-text); + font-size: clamp(1.5rem, calc(1.15rem + 1cqi), 1.875rem); + line-height: 1.3; + font-weight: 650; + letter-spacing: -0.03em; + } + + &__description { + max-width: 68ch; + margin-block-start: 12px; + color: var(--r-text-secondary); + font-size: 14px; + line-height: 1.8; + } + + &__actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; + flex-shrink: 0; + } +} + +@container (max-width: 600px) { + .r-page-header { + align-items: flex-start; + flex-direction: column; + gap: 16px; + } +} diff --git a/src/app-components/app/AppPageHeader/index.tsx b/src/app-components/app/AppPageHeader/index.tsx new file mode 100644 index 00000000..f8d89185 --- /dev/null +++ b/src/app-components/app/AppPageHeader/index.tsx @@ -0,0 +1,26 @@ +import './index.scss' + +export default defineComponent({ + name: 'AppPageHeader', + props: { + title: { type: String, required: true }, + description: { type: String, default: '' }, + eyebrow: { type: String, default: 'RAY TEMPLATE' }, + }, + setup(props, { slots }) { + return () => ( +
+
+

{props.eyebrow}

+

{props.title}

+ {props.description ? ( +

{props.description}

+ ) : null} +
+ {slots.default ? ( +
{slots.default()}
+ ) : null} +
+ ) + }, +}) diff --git a/src/app-components/app/AppShareLink/index.scss b/src/app-components/app/AppShareLink/index.scss new file mode 100644 index 00000000..b9498e64 --- /dev/null +++ b/src/app-components/app/AppShareLink/index.scss @@ -0,0 +1,64 @@ +.r-share-links { + container-type: inline-size; +} +.r-share-links__grid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 12px; +} +.r-share-link { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; + padding: 13px 16px; + border: 1px solid var(--r-line); + border-radius: 8px; + color: var(--r-text-secondary); + text-decoration: none; + font-size: 13px; + background: var(--r-surface-muted); + + > span:nth-child(2) { + flex: 1; + overflow-wrap: anywhere; + } + > .n-avatar { + flex-shrink: 0; + } + &:hover { + color: var(--r-text); + border-color: var(--r-control-border); + } +} +@container (min-width: 700px) { + .r-share-links__grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +.r-share-links--compact { + .r-share-links__grid { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 8px; + } + .r-share-link { + display: grid; + place-items: center; + width: 36px; + height: 36px; + padding: 0; + border: 0; + border-radius: 50%; + background: transparent; + > span:nth-child(2), + > .r-icon { + display: none; + } + &:hover { + background: var(--r-surface-muted); + } + } +} diff --git a/src/app-components/app/AppShareLink/index.tsx b/src/app-components/app/AppShareLink/index.tsx index cb185cc2..b69598e4 100644 --- a/src/app-components/app/AppShareLink/index.tsx +++ b/src/app-components/app/AppShareLink/index.tsx @@ -1,4 +1,8 @@ -import { NAvatar, NFlex, NTooltip } from 'naive-ui' +import './index.scss' +import { RIcon } from '@/components' +import { useI18n } from '@/hooks' +import { NAvatar } from 'naive-ui' +import type { PropType } from 'vue' interface AvatarOptions { key: string @@ -9,66 +13,64 @@ interface AvatarOptions { export default defineComponent({ name: 'AppShareLink', + props: { + variant: { + type: String as PropType<'compact' | 'cards'>, + default: 'compact', + }, + }, setup() { + const { t } = useI18n('dashboard') const avatarOptions: AvatarOptions[] = [ { key: 'ray-js-note', src: 'https://note.youdao.com/s/ObWEe2BB', - tooltip: 'Ray的前端学习笔记', + tooltip: 'links.notes', icon: 'https://avatars.githubusercontent.com/u/51957438?v=4', }, { key: 'ray-js-cover', src: 'https://note.youdao.com/s/IC8xKPdB', - tooltip: 'Ray的面试题总结', + tooltip: 'links.interviews', icon: 'https://avatars.githubusercontent.com/u/51957438?v=4', }, { key: 'ray-template-doc', src: 'https://xiaodaigua-ray.github.io/ray-template-doc/', - tooltip: 'Ray Template Doc', + tooltip: 'links.docs', icon: 'https://avatars.githubusercontent.com/u/51957438?v=4', }, { key: 'ray-template-doc-out', src: 'https://ray-template.yunkuangao.com/', - tooltip: 'Ray Template Doc (国内地址)', + tooltip: 'links.docsMirror', icon: 'https://avatars.githubusercontent.com/u/51957438?v=4', }, ] - const handleLinkClick = (item: AvatarOptions) => { - window.open(item.src) - } - - return { - handleLinkClick, - avatarOptions, - } + return { avatarOptions, t } }, render() { return ( - - {this.avatarOptions.map((curr) => ( - - {{ - trigger: () => ( - - ), - default: () => curr.tooltip, - }} - - ))} - + ) }, }) diff --git a/src/app-components/provider/AppNaiveGlobalProvider/index.tsx b/src/app-components/provider/AppNaiveGlobalProvider/index.tsx index 3e78ca6c..854ce724 100644 --- a/src/app-components/provider/AppNaiveGlobalProvider/index.tsx +++ b/src/app-components/provider/AppNaiveGlobalProvider/index.tsx @@ -1,11 +1,3 @@ -/** - * - * 全局注入 naive ui 提示性组件 - * 使用该组件注册后, 可以直接通过 window.$message、window.$notification、window.$dialog、window.$loadingBar 访问 - * 但是, 使用该组件注册后, 使用 window.$notification 组件时不能更改 placement 位置(只能默认右上角弹出) - * 如果需要更改弹出位置, 需要在需要地方重新定义组件注册 - */ - import { MESSAGE_PROVIDER } from '@/app-config' import { getNaiveLocales } from '@/locales/utils' import { useSettingGetters } from '@/store' @@ -35,11 +27,8 @@ export default defineComponent({ /** * - * 使用 createDiscreteApi 脱离上下文 api 注入一些常用的组件 - * 通过 window.$message、window.$notification、window.$dialog、window.$loadingBar 访问 - * 但是,使用该组件注册后,使用 window.$notification 组件时不能更改 placement 位置(只能默认右上角弹出) - * - * 改为函数包裹,避免 `slot default invoked outside of render` 警告 + * @description + * 在渲染作用域内创建全局提示实例,使离散提示与当前主题和语言保持一致。 */ const discreteApi = () => { const { message, notification, dialog, loadingBar } = createDiscreteApi( @@ -47,6 +36,9 @@ export default defineComponent({ { configProviderProps: computed(() => ({ theme: getAppTheme.value ? darkTheme : null, + themeOverrides: getPrimaryColorOverride.value, + locale: localePackage.value.locale, + dateLocale: localePackage.value.dateLocal, })), }, ) diff --git a/src/app-components/provider/AppRequestCancelerProvider/index.tsx b/src/app-components/provider/AppRequestCancelerProvider/index.tsx index aa8a74ba..e6d73514 100644 --- a/src/app-components/provider/AppRequestCancelerProvider/index.tsx +++ b/src/app-components/provider/AppRequestCancelerProvider/index.tsx @@ -1,11 +1,3 @@ -/** - * - * 路由更新前,取消上一路由所有请求 - * - * 生命周期示意图: - * beforeRouteUpdate -> cancelAllRequest -> routeUpdate - */ - import { axiosCanceler } from '@/axios/utils/interceptor' const AppRequestCancelerProvider = defineComponent({ diff --git a/src/app-components/provider/AppVersionProvider/index.tsx b/src/app-components/provider/AppVersionProvider/index.tsx index 4b1c69a5..67da9db0 100644 --- a/src/app-components/provider/AppVersionProvider/index.tsx +++ b/src/app-components/provider/AppVersionProvider/index.tsx @@ -1,9 +1,3 @@ -/** - * - * 检测当前版本是否为最新版本 - * 如果不是最新版本则弹出提示框,提示用户更新,点击确认后退出登录并且刷新资源 - */ - import { APP_CATCH_KEY } from '@/app-config' import { RModal } from '@/components' import { useSigningActions } from '@/store' diff --git a/src/app-components/provider/AppWatermarkProvider/index.tsx b/src/app-components/provider/AppWatermarkProvider/index.tsx index 6fca1eaf..661f1272 100644 --- a/src/app-components/provider/AppWatermarkProvider/index.tsx +++ b/src/app-components/provider/AppWatermarkProvider/index.tsx @@ -1,13 +1,3 @@ -/** - * - * 全局水印注入 - * - * 该组件启用时,会在全局(包括首页)展示 - * 如果你不希望在登录页显示,可以手动将该组件放置于 Layout 中 - * - * 当然你也可以通过 useWatermark hook 自定义控制水印的显示以及内容 - */ - import { useSettingGetters } from '@/store' import { NWatermark } from 'naive-ui' diff --git a/src/app-config/design-config.ts b/src/app-config/design-config.ts index c00fcab1..cba52183 100644 --- a/src/app-config/design-config.ts +++ b/src/app-config/design-config.ts @@ -1,5 +1,24 @@ import type { AppTheme } from '@/types' +/** 明暗主题共用的菜单尺寸与前景色配置。 */ +const menuThemeOverrides = { + itemHeight: '40px', + borderRadius: '8px', + itemTextColorActive: 'var(--r-selected-text)', + itemTextColorActiveHover: 'var(--r-selected-text)', + itemTextColorChildActive: 'var(--r-selected-text)', + itemTextColorChildActiveHover: 'var(--r-selected-text)', + itemTextColorActiveHorizontal: 'var(--r-selected-text)', + itemTextColorChildActiveHorizontal: 'var(--r-selected-text)', + itemTextColorHoverHorizontal: 'var(--r-selected-text)', + itemIconColorActive: 'var(--r-selected-text)', + itemIconColorActiveHover: 'var(--r-selected-text)', + itemIconColorChildActive: 'var(--r-selected-text)', + itemIconColorChildActiveHover: 'var(--r-selected-text)', + itemIconColorActiveHorizontal: 'var(--r-selected-text)', + itemIconColorChildActiveHorizontal: 'var(--r-selected-text)', +} + export const APP_THEME: AppTheme = { /** * @@ -8,7 +27,7 @@ export const APP_THEME: AppTheme = { * 支持 RGBA、RGB、十六进制。 */ appThemeColors: [ - '#2d8cf0', + '#3b63d9', '#3f9eff', '#ff42bc', '#ee4f12', @@ -18,9 +37,9 @@ export const APP_THEME: AppTheme = { // 系统主题色 appPrimaryColor: { // 主题色 - primaryColor: '#2d8cf0', + primaryColor: '#3b63d9', // 主题辅助色(用于整体 hover、active 等之类颜色) - primaryFadeColor: 'rgba(45, 140, 240, 0.85)', + primaryFadeColor: 'rgba(59, 99, 217, 0.85)', }, /** * @@ -50,15 +69,65 @@ export const APP_THEME: AppTheme = { appNaiveUIThemeOverrides: { dark: { common: { - borderRadius: '4px', - baseColor: 'rgba(18, 18, 18, 1)', + borderRadius: '8px', + fontWeightStrong: '600', + lineHeight: '1.6', + heightMedium: '36px', + heightSmall: '30px', + baseColor: '#172131', + bodyColor: '#101722', + cardColor: '#172131', + modalColor: '#192638', + popoverColor: '#192638', + actionColor: '#1c293b', + textColor1: '#e9eef7', + textColor2: '#b3c0d3', + textColor3: '#a0b0c6', + placeholderColor: '#a0b0c6', + borderColor: '#687b96', + dividerColor: '#2c394d', + hoverColor: 'rgba(179, 192, 211, 0.08)', }, + Card: { + borderRadius: '12px', + titleFontSizeMedium: '16px', + paddingMedium: '20px 24px', + }, + Menu: menuThemeOverrides, + Button: { fontWeight: '500' }, + Tag: { borderRadius: '5px', textColorPrimary: 'var(--r-primary-text)' }, + Layout: { siderColor: '#172131', headerColor: '#172131' }, }, light: { common: { - borderRadius: '4px', - baseColor: 'rgba(255, 255, 255, 1)', + borderRadius: '8px', + fontWeightStrong: '600', + lineHeight: '1.6', + heightMedium: '36px', + heightSmall: '30px', + baseColor: '#ffffff', + bodyColor: '#f5f7fb', + cardColor: '#ffffff', + modalColor: '#ffffff', + popoverColor: '#ffffff', + actionColor: '#f7f9fc', + textColor1: '#1d2a3e', + textColor2: '#52647c', + textColor3: '#617187', + placeholderColor: '#617187', + borderColor: '#8492a8', + dividerColor: '#e4e9f1', + hoverColor: 'rgba(82, 100, 124, 0.06)', }, + Card: { + borderRadius: '12px', + titleFontSizeMedium: '16px', + paddingMedium: '20px 24px', + }, + Menu: menuThemeOverrides, + Button: { fontWeight: '500' }, + Tag: { borderRadius: '5px', textColorPrimary: 'var(--r-primary-text)' }, + Layout: { siderColor: '#ffffff', headerColor: '#ffffff' }, }, }, /** diff --git a/src/app-config/regex-config.ts b/src/app-config/regex-config.ts index dc8ca720..f375f132 100644 --- a/src/app-config/regex-config.ts +++ b/src/app-config/regex-config.ts @@ -1,9 +1,3 @@ -/** - * - * 正则入口 - * 系统公共正则, 配置在该文件中 - */ - export const APP_REGEX: Record = { /** css 尺寸单位匹配 */ cssUnit: diff --git a/src/axios/axios-interceptor/request/provider.ts b/src/axios/axios-interceptor/request/provider.ts index ba8165bf..e153c9c3 100644 --- a/src/axios/axios-interceptor/request/provider.ts +++ b/src/axios/axios-interceptor/request/provider.ts @@ -1,22 +1,7 @@ -/** - * - * 请求拦截器入口 - * 被注册方法执行时其实例能够保证获取到, 所以不需要做额外空判断 - * 在内部执行方法中, 已经做了边界处理 - * - * 提供两个工具方法, 方便类型推导 - * - * 其中 injectRequestCanceler requestErrorCanceler 方法为 axios request interceptor 方法 - */ - import { injectRequestCanceler, requestErrorCanceler } from './plugins/cancel' import { injectRequestHeaders } from './plugins/request-headers' -/** - * - * 注册请求拦截器 - * 请注意执行顺序 - */ +/** 请求拦截器注册列表;调整顺序前需核对 Axios 的执行顺序。 */ export default { // 请求正常 implementRequestInterceptorArray: [ diff --git a/src/axios/axios-interceptor/response/provider.ts b/src/axios/axios-interceptor/response/provider.ts index 880fa8f8..1663e18a 100644 --- a/src/axios/axios-interceptor/response/provider.ts +++ b/src/axios/axios-interceptor/response/provider.ts @@ -1,21 +1,6 @@ -/** - * - * 响应拦截器入口 - * 被注册方法执行时其实例能够保证获取到, 所以不需要做额外空判断 - * 在内部执行方法中, 已经做了边界处理 - * - * 提供两个工具方法, 方便类型推导 - * - * 其中 injectResponseCanceler responseErrorCanceler 方法是注入的 axios response interceptor 方法 - */ - import { injectResponseCanceler, responseErrorCanceler } from './plugins/cancel' -/** - * - * 注册响应拦截器 - * 请注意执行顺序 - */ +/** 响应拦截器注册列表,分别管理成功和失败分支。 */ export default { // 响应正常 implementResponseInterceptorArray: [injectResponseCanceler], diff --git a/src/axios/index.ts b/src/axios/index.ts index 657f7142..8826f57c 100644 --- a/src/axios/index.ts +++ b/src/axios/index.ts @@ -1,15 +1,3 @@ -/** - * - * 基于 vue-hook-plus 与 axios 封装 - * - * (vue-hook-plus 参考文档)[https://inhiblab-core.gitee.io/docs/hooks/useRequest/basic/] - * - * 借助 vue-hook-plus useRequest 方法实现拓展功能 - * 结合模板已封装好的 axios 实现了该 hook - * - * 由于中间件注册了自动取消重复请求的方法,所以会导致方法在初始化时,会抛出一个重复请求被取消的错误(该问题不影响使用) - */ - import request from '@/axios/instance' import type { AppRawRequestConfig } from '@/axios/types' import useHookPlusRequest from 'vue-hooks-plus/es/useRequest' @@ -17,19 +5,13 @@ import type { UseRequestOptions } from 'vue-hooks-plus/es/useRequest/types' /** * - * @param fetchOption axios 请求配置 - * @param option useRequest 配置项 + * @param fetchOptions Axios 请求配置 + * @param option vue-hooks-plus 请求选项 * * @description - * 该方法有一定的局限性,仅可在 effect 作用域中使用, - * 如果在非 vue effect scope 中使用,会抛出一些警告。 + * 使用项目 Axios 实例创建请求 Hook,应在有效的 Vue effect 作用域中调用。 * - * @example - * // 请求函数 - * const getUser = () => request({ url: 'http://localhost:3000/user' }) - * - * // effect 中使用 - * const { data } = useHookPlusRequest(getUser) + * @returns 请求状态与控制方法 */ function useRequest< Response, diff --git a/src/components/README.md b/src/components/README.md new file mode 100644 index 00000000..60b4e16d --- /dev/null +++ b/src/components/README.md @@ -0,0 +1,13 @@ +# 组件使用约定 + +基础组件在 `base`,组合组件在 `pro`;对外入口为 `src/components/index.ts`。优先复用 Naive UI 与现有组件,不把组件介绍复制到 `defineComponent` 前。 + +## 非显然的调用约束 + +- `RCollapseGrid` 基于 Naive UI Grid,子项需要使用 `NGridItem`;折叠表单 `RCollapse` 的表单项需要使用 `NFormItemGi` / `NGridItem`。不要用普通容器替代 Grid 子项。 +- `RChart` 与 `useChart` 负责实例初始化、销毁、尺寸与主题同步;调用方维护 ECharts options,需要的图表与组件按现有 ECharts 注册方式引入。 +- `PageResult` 基于 Naive UI Result,可作为组件或错误页面使用,保留继承的 props 与 slots。 +- `RTable` 的列顺序配置以第一层列为单位,深层子列跟随根列;大量列数据的性能需按实际业务验证。 +- `RIcon.name` 为生成的完整分包路径类型,图标改动会在开发、HMR 和构建时同步;不要手工修改生成清单。 + +示例见 `src/views/demo`;Hooks 的独立交互示例与生命周期约定见 [Hooks 文档](../hooks/README.md)。新增或修改注释遵循 [注释规范](../../docs/comment-style.md),完整教程放在 README 与示例页。 diff --git a/src/components/base/RChart/src/Chart.tsx b/src/components/base/RChart/src/Chart.tsx index 34af4a5a..6e7419f4 100644 --- a/src/components/base/RChart/src/Chart.tsx +++ b/src/components/base/RChart/src/Chart.tsx @@ -59,30 +59,6 @@ echartThemes.forEach((curr) => { registerTheme(curr.name, curr.theme) }) -/** - * - * @description - * 基于 echarts 的图表组件。 - * - * 让你仅需要关注 echarts options 的配置管理,而不需要关心 echarts 的初始化、销毁、主题切换等操作。 - * - * 如果需要拓展配置项,进需要在使用该组件的时候使用 use 方法注册对应 chart 组件即可。 - * - * @example - * - * - * - */ export default defineComponent({ name: 'RChart', props, diff --git a/src/components/base/RChart/src/types.ts b/src/components/base/RChart/src/types.ts index fbce00f7..a897c7f5 100644 --- a/src/components/base/RChart/src/types.ts +++ b/src/components/base/RChart/src/types.ts @@ -1,14 +1,3 @@ -/** - * - * @author Ray - * - * @date 2023-07-22 - * - * @workspace ray-template - * - * @remark 今天也是元气满满撸代码的一天 - */ - import type { ECharts } from 'echarts/core' import type { CanvasRenderer } from 'echarts/renderers' // `echarts` 渲染器 diff --git a/src/components/base/RCollapseGrid/src/index.tsx b/src/components/base/RCollapseGrid/src/index.tsx index 7d61e014..a1bb89fd 100644 --- a/src/components/base/RCollapseGrid/src/index.tsx +++ b/src/components/base/RCollapseGrid/src/index.tsx @@ -1,13 +1,3 @@ -/** - * - * - * - * 可折叠操作栏 - * 可以结合表单或者表格使用,让你快捷的实现高级搜索功能 - * - * 该组件完全基于 `NGrid` `NGridItem` 实现, 所以需要在使用该组件时使用 `NGridItem` 包裹元素 - */ - import './index.scss' import { RIcon } from '@/components' import { call } from '@/utils' @@ -51,7 +41,7 @@ export default defineComponent({ customClassName={`collapse-icon--arrow ${ collapse ? '' : 'collapse-icon--arrow__expanded' }`} - name="expanded" + name="directional/expanded" size="14" /> diff --git a/src/components/base/RIcon/index.ts b/src/components/base/RIcon/index.ts index e2ffa099..2f183171 100644 --- a/src/components/base/RIcon/index.ts +++ b/src/components/base/RIcon/index.ts @@ -3,5 +3,6 @@ import RIcon from './src/Icon' import iconProps from './src/props' export type IconProps = ExtractPublicPropTypes +export type { IconName, IconPackage } from '@/icons/manifest' export { RIcon, iconProps } diff --git a/src/components/base/RIcon/src/Icon.tsx b/src/components/base/RIcon/src/Icon.tsx index b5f94d91..ac71606d 100644 --- a/src/components/base/RIcon/src/Icon.tsx +++ b/src/components/base/RIcon/src/Icon.tsx @@ -1,4 +1,6 @@ import './index.scss' +import type { IconPackage } from '@/icons' +import { iconSprites } from '@/icons/manifest' import { call, completeSize } from '@/utils' import props from './props' @@ -7,7 +9,8 @@ export default defineComponent({ props, setup(props) { const symbolId = computed( - () => `/__spritemap#${props.prefix}-${props.name}`, + () => + `${iconSprites[props.name.split('/')[0] as IconPackage]}#${props.prefix}-${props.name}`, ) const cssVars = computed(() => { const cssVar = { diff --git a/src/components/base/RIcon/src/props.ts b/src/components/base/RIcon/src/props.ts index 95237f49..a5f7fa3e 100644 --- a/src/components/base/RIcon/src/props.ts +++ b/src/components/base/RIcon/src/props.ts @@ -1,3 +1,4 @@ +import type { IconName } from '@/icons/manifest' import type { MaybeArray } from '@/types' import type { PropType } from 'vue' @@ -11,8 +12,8 @@ const props = { default: 'icon', }, name: { - type: String, - required: true, + type: String as PropType, + required: true as const, }, size: { type: [Number, String], diff --git a/src/components/base/RMoreDropdown/src/props.ts b/src/components/base/RMoreDropdown/src/props.ts index aa6749e3..2b6edf47 100644 --- a/src/components/base/RMoreDropdown/src/props.ts +++ b/src/components/base/RMoreDropdown/src/props.ts @@ -1,10 +1,12 @@ +import type { IconName } from '@/icons' import { dropdownProps } from 'naive-ui' +import type { PropType } from 'vue' const props = { ...dropdownProps, icon: { - type: String, - default: 'more', + type: String as PropType, + default: 'action/more', }, iconSize: { type: Number, diff --git a/src/components/base/RTable/src/components/C.tsx b/src/components/base/RTable/src/components/C.tsx index bc979a27..4a7d43ce 100644 --- a/src/components/base/RTable/src/components/C.tsx +++ b/src/components/base/RTable/src/components/C.tsx @@ -1,13 +1,5 @@ -/** - * - * 自定义表格列的顺序 - * - * 但是该方法有几个缺陷地方: - * 1. 只能代理第一层的数据,也就意味着深层次的子列不支持配置操作,只会跟随根列更新 - * 2. 大量数据的时候,可能会出现性能问题 - */ - import { RIcon } from '@/components' +import type { IconName } from '@/icons' import type { AnyFn, MaybeArray } from '@/types' import { call } from '@/utils' import { cloneDeep, isEmpty } from 'lodash-es' @@ -20,7 +12,7 @@ import type { C } from '../types' type FixedClick = (type: 'left' | 'right', option: C, index: number) => void const renderSwitcherIcon = () => ( - + ) const RowIconRender = ({ @@ -29,7 +21,7 @@ const RowIconRender = ({ onClick, customClassName, }: { - icon: string + icon: IconName title: string onClick?: AnyFn customClassName?: string @@ -130,7 +122,7 @@ export default defineComponent({ suffix: () => ( ( ( { diff --git a/src/components/base/RTable/src/components/Print.tsx b/src/components/base/RTable/src/components/Print.tsx index 95a18ba2..a9141815 100644 --- a/src/components/base/RTable/src/components/Print.tsx +++ b/src/components/base/RTable/src/components/Print.tsx @@ -40,7 +40,7 @@ export default defineComponent({ render() { return ( - + ) }, diff --git a/src/components/base/RTransitionComponent/src/TransitionComponent.vue b/src/components/base/RTransitionComponent/src/TransitionComponent.vue index 1cd0de65..2f3193ba 100644 --- a/src/components/base/RTransitionComponent/src/TransitionComponent.vue +++ b/src/components/base/RTransitionComponent/src/TransitionComponent.vue @@ -28,12 +28,6 @@ import { useKeepAliveGetters, useSettingGetters } from '@/store' import props from './props' import type { TransitionProps } from './types' -/** - * - * @description - * 使用宏编译模式时,可以使用 defineOptions 声明组件选项。 - * 常用方法即是声明该组件的 name inheritAttrs 等属性。 - */ defineOptions({ name: 'RTransitionComponent', }) diff --git a/src/components/pro/RCollapse/Collapse.tsx b/src/components/pro/RCollapse/Collapse.tsx index 9c8102a2..1e91830d 100644 --- a/src/components/pro/RCollapse/Collapse.tsx +++ b/src/components/pro/RCollapse/Collapse.tsx @@ -23,12 +23,6 @@ export const collapseProps = Object.assign({}, formProps, { }, }) -/** - * - * @description - * 基于 RCollapseGrid 和 RForm 的折叠表单组件; - * 同样也继承了 RCollapseGrid 组件的缺点,必须使用 NFormItemGi, NGridItem 组件包裹表单项。 - */ export default defineComponent({ name: 'RCollapse', props: collapseProps, diff --git a/src/directives/README.md b/src/directives/README.md index ec906c5f..350e3279 100644 --- a/src/directives/README.md +++ b/src/directives/README.md @@ -39,3 +39,9 @@ export default demoDirective // 4. 按照上述步骤执行后,会自动在模板中创建一个 v-demo 的指令供全局使用 ``` + +## 说明与来源 + +指令用法与绑定值示例统一维护在 [使用说明](README.DIR.md),不在指令工厂前重复整段教程。`disabled` 仅限制 CSS 交互,业务权限和提交校验仍需独立处理。 + +水波纹辅助实现保留原有 [Pure Admin 来源标注](https://github.dev/pure-admin/vue-pure-admin/blob/main/src/components/ReCol/index.ts)。新增注释遵循 [仓库注释规范](../../docs/comment-style.md)。 diff --git a/src/directives/modules/copy/index.ts b/src/directives/modules/copy/index.ts index cb1b7b91..a292576c 100644 --- a/src/directives/modules/copy/index.ts +++ b/src/directives/modules/copy/index.ts @@ -1,18 +1,3 @@ -/** - * - * directive name: copy - * - * @description - * 该指令用于处理复制,使用的时候必须传递正确的 value 值。 - * - * 指令基于 clipboard.js 实现。 - * - * @example - * - */ - import type { CustomDirectiveFC } from '@/directives/types' import ClipboardJS from 'clipboard' import type { CopyElement } from './types' diff --git a/src/directives/modules/debounce/index.ts b/src/directives/modules/debounce/index.ts index c7ccf7e2..4e594649 100644 --- a/src/directives/modules/debounce/index.ts +++ b/src/directives/modules/debounce/index.ts @@ -1,22 +1,3 @@ -/** - * - * directive name: debounce - * - * @description - * - * 该指令用于处理防抖,使用的时候必须传递正确的 func 值。 - * - * 其中 trigger 和 wait 是可选的,trigger 默认为 click,wait 默认为 500。 - * - * @example - * - * - */ - import type { CustomDirectiveFC } from '@/directives/types' import type { AnyFn } from '@/types' import { useEventListener } from '@vueuse/core' diff --git a/src/directives/modules/disabled/index.ts b/src/directives/modules/disabled/index.ts index 3f374d50..e42181ee 100644 --- a/src/directives/modules/disabled/index.ts +++ b/src/directives/modules/disabled/index.ts @@ -1,19 +1,3 @@ -/** - * - * directive name: disabled - * - * @description - * 该指令用于处理元素的禁用状态,使用的时候必须传递正确的 value 值。 - * - * 该方法依赖 r-template__directive--disabled 样式类,需要在全局样式中定义, - * 并且该指令仅仅是做了 css 样式层面的禁用效果,如果有需要,还需要在业务逻辑中做相应的处理。 - * - * @example - * - */ - import type { CustomDirectiveFC } from '@/directives/types' import { removeClass, setClass } from '@/utils' diff --git a/src/directives/modules/ellipsis/index.ts b/src/directives/modules/ellipsis/index.ts index e4e9bbda..b4167f98 100644 --- a/src/directives/modules/ellipsis/index.ts +++ b/src/directives/modules/ellipsis/index.ts @@ -1,35 +1,14 @@ -/** - * - * directive name: ellipsis - * - * @description - * 该指令用于处理文本溢出省略,使用的时候必须传递正确的 width 值。 - * - * 其中 line 和 type 是可选的,line 默认为 1,type 默认为 block。 - * - * @example - * - * - */ - import type { CustomDirectiveFC } from '@/directives/types' import { completeSize, setStyle } from '@/utils' import type { EllipsisBindingValue } from './types' /** * - * @param el 待绑定的元素 - * @param options 配置项 + * @param el 待设置省略样式的元素 + * @param options 宽度、行数、渲染方式与悬浮文本选项 * * @description - * 绑定省略样式。 - * - * @example - * bindEllipsis(el, { line: 2, width: 200 }) + * 根据绑定值设置文本省略样式;缺少 width 时记录错误,不写入样式。 */ const bindEllipsis = (el: HTMLElement, options: EllipsisBindingValue) => { const { line = 1, type = 'block', width, popoverText } = options diff --git a/src/directives/modules/ripple/index.ts b/src/directives/modules/ripple/index.ts index 551ad560..7c5ecdfd 100644 --- a/src/directives/modules/ripple/index.ts +++ b/src/directives/modules/ripple/index.ts @@ -1,28 +1,3 @@ -/** - * - * directive name: ripple - * - * @description - * 水波纹指令。 - * - * 使用方式: - * @example - * - * - * - * const DemoOne = () =>
hi
- * const DemoTwo = () =>
hi
- */ - import './index.scss' import type { CustomDirectiveFC } from '@/directives/types' import type { RippleElement, RippleValue } from './types' diff --git a/src/directives/modules/ripple/utils.ts b/src/directives/modules/ripple/utils.ts index 3a9e8124..8dc24a2a 100644 --- a/src/directives/modules/ripple/utils.ts +++ b/src/directives/modules/ripple/utils.ts @@ -1,16 +1,7 @@ -/** - * - * @description - * 该方法借鉴 pure admin ripple directive 实现。 - * - * 在原有指令实现基础上,补充了 ts 签名与注释。并且结合本模板的特性实现。 - * - * @see https://github.dev/pure-admin/vue-pure-admin/blob/main/src/components/ReCol/index.ts - */ - import { isValueType } from '@/utils' import type { RippleBindingValue, RippleElement, RippleOptions } from './types' +/** 水波纹动画使用的样式类名。 */ const animationClasses = { vRippleAnimationEnter: 'v-ripple__animation--enter', vRippleAnimationVisible: 'v-ripple__animation--visible', diff --git a/src/directives/modules/throttle/index.ts b/src/directives/modules/throttle/index.ts index 460652e0..f95ad2c5 100644 --- a/src/directives/modules/throttle/index.ts +++ b/src/directives/modules/throttle/index.ts @@ -1,21 +1,3 @@ -/** - * - * directive name: throttle - * - * @description - * 该指令用于处理节流,使用的时候必须传递正确的 func 值。 - * - * 其中 trigger 和 wait 是可选的,trigger 默认为 click,wait 默认为 500。 - * - * @example - * - * - */ - import type { CustomDirectiveFC } from '@/directives/types' import type { AnyFn } from '@/types' import { useEventListener } from '@vueuse/core' diff --git a/src/global-variable/README.md b/src/global-variable/README.md deleted file mode 100644 index 6c18809a..00000000 --- a/src/global-variable/README.md +++ /dev/null @@ -1,30 +0,0 @@ -## global-variable - -简单的管理全局响应式变量,但是不支持缓存。 - -创建该模块是因为在有时候不需要 `pinia` 这么复杂流程的全局变量。所以该模块管理的都是一些简单的全局变量,并且不支持缓存。 - -## 添加全局变量 - -1. 首先在 `variableState` 变量中添加对应变量 -2. 调用对应方法获取、更新变量 - -```ts -// 添加变量 -const variableState = reactive({ - globalSpinning: false, - globalDrawerValue: false, - yourGlobalValue: 'demo value', -}) - -// 更新变量 -setVariable(key, value) - -// 获取非响应式变量 -const yourGlobalValue = getVariable('yourGlobalValue') // Readonly - -// 获取响应式变量 -const yourGlobalValue = getVariableToRefs('yourGlobalValue') // Readonly> -``` - -> 注意,避免滥用该模块。可能会导致管理不当引起内存泄漏。 diff --git a/src/global-variable/index.ts b/src/global-variable/index.ts deleted file mode 100644 index c6b65aec..00000000 --- a/src/global-variable/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './variable' - -export type * from './variable' diff --git a/src/global-variable/variable.ts b/src/global-variable/variable.ts deleted file mode 100644 index 790cae9e..00000000 --- a/src/global-variable/variable.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * - * @description - * 存放全局响应式变量,脱离 pinia 使用的变量。 - * 简单的全局变量,并不需要复杂的控制流程。 - * - * @example - * 获取响应式变量 - * getVariableToRefs('target key') - * - * 更改 state 变量 - * setVariable('key', 'value') - * - * 创建响应式说仓库 - * createVariableState({ your state }) - */ - -import type { AnyFn } from '@/types' -import { updateObjectValue } from '@/utils' - -/** - * - * @description - * 全局响应式变量。 - * - * 不推荐直接访问、设置该 state不建议在组件中直接使用该 state, - * 请使用 `getVariable`、`getVariableToRefs`、`setVariable` 方法进行操作。 - */ -const variableState = reactive({ - globalSpinning: false, // 全局加载控制器 - globalDrawerValue: false, // 全局抽屉控制器(小尺寸设备可用) - globalMainLayoutLoad: true, // LayoutContent 区域加载控制器,会触发强制刷新 - layoutContentMaximize: false, // LayoutContent 区域全屏控制器 - layoutContentSpinning: false, // LayoutContent 区域加载控制器,不会触发强制刷新 -}) - -export type VariableState = typeof variableState -export type VariableStateKey = keyof VariableState - -type ReadonlyVariableState = { - [K in keyof T & string]: Readonly> -} - -/** - * - * @param key variable key - * @param value variable value - * @param cb 设置完成后的回调函数 - * - * 手动设置 variableState 的值 - * - * @example - * setVariable('globalSpinning', true) // 设置全局加载状态为 true - * setVariable('globalSpinning', true, () => {}) // 设置全局加载状态为 true,并且在设置完成后执行回调函数 - */ -export function setVariable( - key: T, - value: VariableState[T], - cb?: FC, -) { - updateObjectValue(variableState, key, value, cb) -} - -/** - * - * @param key 目标值 key - * - * 返回目标值的响应式 ref - * - * @example - * getVariableToRefs('globalSpinning') // 返回 Ref - */ -export function getVariableToRefs(key: K) { - return readonly(toRef(variableState, key)) -} - -/** - * - * @description - * 允许解构获取 variable 属性。并且返回一个只读的 ref。 - * - * 该方法为了解决 getVariableToRefs 方法的解构问题,如果需要在一个地方获取很多 variable 属性,可以使用该方法。 - * - * @example - * const { globalMainLayoutLoad } = getVariable() - */ -export function getVariable(): ReadonlyVariableState { - return { - ...toRefs(readonly(variableState)), - } -} diff --git a/src/hooks/README.md b/src/hooks/README.md new file mode 100644 index 00000000..1ae76ef9 --- /dev/null +++ b/src/hooks/README.md @@ -0,0 +1,39 @@ +# Hooks 示例与约定 + +所有自定义 Hook 从 `@/hooks` 导出。页面使用 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` 页面也保留 | + +## 生命周期与状态 + +- 组合式函数在 `setup` 或有效 effect scope 内创建,DOM 操作由用户事件或挂载后的回调触发。事件、订阅、动画帧随作用域清理。 +- 全局 UI 状态由 Pinia `runtime` 管理,通过 `useRuntimeGetters` / `useRuntimeActions` 访问,不写入持久化缓存。 +- `useSpinning().reload(wait)` 会卸载页面,恢复计时器由 runtime Store 持有;多个调用以最后一次刷新为准。 +- 两个滚动 Hook 可以在 setup 阶段创建,调用时才读取布局实例。无侧栏或未挂载时安全忽略。 +- `useMaximize` 操作布局内容,多个调用方共享状态;`useElementFullscreen` 操作任意单个元素,其状态属于当前实例。二者均不调用浏览器 Fullscreen API。 +- `navigationTo` 的索引从 0 开始;负数、小数、非有限数和越界索引不会导航。成功调用返回 Router 导航 Promise。 +- `useDomToImage` 的返回类型跟随默认格式或本次 `create(format)`;失败通过 Error 拒绝,`finally` 在目标缺失时也会执行,此时参数可能为空。`created` 回调也会接收到运行时覆盖格式的结果,因此其参数为所有实际输出类型的联合,需先判断类型。 +- `useI18n('hooks').t('code')` 和 `.t('hooks.code')` 指向同一个翻译键。切换应用语言使用 `useSettingActions().updateLocale`,保持日期与组件库同步。 +- 国际化实例在开发热更新期间复用;初始化前创建的翻译方法会在调用时读取当前实例,不会永久停留在返回原始键的回退函数上。 + +截图和打印依赖实际浏览器。Happy DOM 测试验证状态与异常处理,不能替代原生打印界面或实际纸张输出验收。 diff --git a/src/hooks/components/useContextmenuCoordinate.ts b/src/hooks/components/useContextmenuCoordinate.ts index 5415d40b..b9fc1c5e 100644 --- a/src/hooks/components/useContextmenuCoordinate.ts +++ b/src/hooks/components/useContextmenuCoordinate.ts @@ -1,4 +1,5 @@ import type { BasicTarget } from '@/types' +import { effectDispose } from '@/utils' import { onClickOutside, useEventListener } from '@vueuse/core' import type { MaybeElement, @@ -43,6 +44,8 @@ export const useContextmenuCoordinate = ( const y = ref(0) // 鼠标 y 坐标 const show = ref(false) // 是否显示右键菜单 const { clickOutside } = options ?? {} + let stopped = false + let generation = 0 /** * @@ -52,6 +55,8 @@ export const useContextmenuCoordinate = ( * 更新右键菜单的显示状态。 */ const updateShow = (value: boolean) => { + if (!value) generation += 1 + show.value = value } @@ -67,8 +72,11 @@ export const useContextmenuCoordinate = ( evt.preventDefault() updateShow(false) + const current = generation nextTick().then(() => { + if (stopped || current !== generation) return + const { clientX, clientY } = evt as MouseEvent x.value = clientX @@ -78,16 +86,13 @@ export const useContextmenuCoordinate = ( }) } - if (clickOutside) { - /** - * - * @description - * 自定义点击元素外部时的回调函数。 - */ - onClickOutside(target as MaybeElementRef, (detectIframe) => { - clickOutside(detectIframe) - }) - } + const cleanupOutside = onClickOutside( + target as MaybeElementRef, + (event) => { + updateShow(false) + clickOutside?.(event) + }, + ) /** * @@ -117,10 +122,15 @@ export const useContextmenuCoordinate = ( * 仅注销该方法绑定的事件。 */ const stop = () => { + stopped = true + updateShow(false) cleanupContextmenu() cleanupClick() + cleanupOutside() } + effectDispose(stop) + return { stop, x: readonly(x), diff --git a/src/hooks/template/useAppNavigation.ts b/src/hooks/template/useAppNavigation.ts index 3e13bdb3..39538575 100644 --- a/src/hooks/template/useAppNavigation.ts +++ b/src/hooks/template/useAppNavigation.ts @@ -63,7 +63,7 @@ export function useAppNavigation() { if (typeof target === 'number') { // 校验是否为 NaN - if (isNaN(target)) { + if (!Number.isInteger(target) || target < 0) { console.warn(`[navigationTo]: The ${target} is NaN, expect number.`) return @@ -72,7 +72,7 @@ export function useAppNavigation() { const { getMenuOptions } = useMenuGetters() // 校验是否超出最大菜单长度 - if (target > getMenuOptions.value.length) { + if (target >= getMenuOptions.value.length) { console.warn( `[navigationTo]: The current ${target} exceeds the maximum number of menus.`, ) @@ -89,25 +89,23 @@ export function useAppNavigation() { children: [firstChild], } = routes - deepNavigation(firstChild) - - return + return deepNavigation(firstChild) } - isPushNavigation(routes.fullPath) + return isPushNavigation(routes.fullPath) } - deepNavigation(option) + return deepNavigation(option) } else if (typeof target === 'string') { const fd = getRoutes().find((curr) => curr.path === target) if (fd) { - isPushNavigation(fd.path) + return isPushNavigation(fd.path) } else { console.warn(`[navigationTo]: The path "${target}" is not found.`) } } else { - isPushNavigation(target.fullPath) + return isPushNavigation(target.fullPath) } } diff --git a/src/hooks/template/useBadge.ts b/src/hooks/template/useBadge.ts index b807ab13..810508cf 100644 --- a/src/hooks/template/useBadge.ts +++ b/src/hooks/template/useBadge.ts @@ -6,22 +6,15 @@ import { isValueType } from '@/utils' export type BadgeKey = string | AppMenuOption -let cachePreNormal: AppMenuOption | undefined = void 0 - // 渲染 extra const renderExtra = ( option: AppMenuOption, assignExtra: AppMenuExtraOptions, ) => { - const { show, ...params } = assignExtra - option.meta.extra = Object.assign({}, option.meta.extra, { - ...params, - show: show, + ...assignExtra, }) option.extra = createMenuExtra(option) - - cachePreNormal = option } // 根据匹配的菜单项渲染 extra diff --git a/src/hooks/template/useContentScroll.ts b/src/hooks/template/useContentScroll.ts index b3775a2f..5cb9c873 100644 --- a/src/hooks/template/useContentScroll.ts +++ b/src/hooks/template/useContentScroll.ts @@ -1,4 +1,5 @@ import { LAYOUT_CONTENT_REF } from '@/app-config' +import type { LayoutInst } from 'naive-ui' /** * @@ -14,15 +15,16 @@ import { LAYOUT_CONTENT_REF } from '@/app-config' * contentScrollTo(10, 10) // x, y 方向滚动到 10 位置 */ export const useContentScroll = () => { - const contentInst = LAYOUT_CONTENT_REF.value + // 在事件触发时读取当前实例,支持 setup 中调用和布局重新挂载。 + const scrollTo: LayoutInst['scrollTo'] = ( + options: number | object, + y?: number, + ) => { + const content = LAYOUT_CONTENT_REF.value - const { scrollTo: contentScrollTo } = contentInst || {} - - if (!contentScrollTo) { - throw new Error( - `[useContentScroll]: LAYOUT_CONTENT_REF is not ready yet. please wait component mounted!`, - ) + if (typeof options === 'number') content?.scrollTo(options, y ?? 0) + else content?.scrollTo(options) } - return contentScrollTo + return scrollTo } diff --git a/src/hooks/template/useMaximize.ts b/src/hooks/template/useMaximize.ts index 81a131b7..9f96b88d 100644 --- a/src/hooks/template/useMaximize.ts +++ b/src/hooks/template/useMaximize.ts @@ -1,6 +1,5 @@ import { LAYOUT_CONTENT_REF } from '@/app-config' -import { getVariableToRefs, setVariable } from '@/global-variable' -import { useElementFullscreen } from '../web' +import { useRuntimeActions, useRuntimeGetters } from '@/store' import type { UseElementFullscreenOptions } from '../web' export interface ScrollToOptions { @@ -10,70 +9,48 @@ export interface ScrollToOptions { } export interface MaximizeOptions extends UseElementFullscreenOptions { - /** - * - * 配置全屏后滚动的位置,left、top、behavior - * 基于 LAYOUT_CONTENT_REF 实现 - * - * 但是,该配置项仅在传递 true 时生效 - * - * @default undefined - */ scrollToOptions?: ScrollToOptions } -export const useMaximize = (options?: MaximizeOptions) => { - const contentEl = LAYOUT_CONTENT_REF as Ref - const { enter, exit, toggleFullscreen, isFullscreen } = useElementFullscreen( - contentEl, - options, - ) +export const useMaximize = (defaults?: MaximizeOptions) => { + const { layoutContentMaximize } = useRuntimeGetters() + const { setRuntimeState } = useRuntimeActions() - /** - * - * 当前 LayoutContent 是处于否全屏状态 - * - true: 全屏 - * - false: 非全屏 - * - * @example - * isLayoutContentMaximized() // true or false - */ - const isLayoutContentMaximized = computed( - () => getVariableToRefs('layoutContentMaximize').value, - ) - - /** - * - * @param full 是否网页全屏内容区域 - * - * @description - * 该方法仅针对于 LayoutContent 区域,并且依赖全局属性 layoutContentMaximize。 - * - * @example - * maximize(true) 全屏内容区域 - * maximize(false) 取消全屏内容区域 - */ + // 最大化由布局 class 驱动;不同页面、标签菜单与退出按钮共享同一状态。 const maximize = (full: boolean, options?: MaximizeOptions) => { - const { scrollToOptions } = options ?? {} + if (layoutContentMaximize.value === full) return - setVariable('layoutContentMaximize', full) + const config = { ...defaults, ...options } if (full) { - enter() + config.beforeEnter?.() + setRuntimeState('layoutContentMaximizeStyle', { + zIndex: config.zIndex ?? 999, + backgroundColor: config.backgroundColor, + transition: config.transition, + }) } else { - exit() + config.beforeExit?.() } - if (scrollToOptions && full) { - contentEl?.value?.scrollTo(scrollToOptions) - } + setRuntimeState('layoutContentMaximize', full) + nextTick(() => { + if (layoutContentMaximize.value !== full) return + + if (full && config.scrollToOptions) { + LAYOUT_CONTENT_REF.value?.scrollTo(config.scrollToOptions) + } + + if (full) config.enter?.() + else config.exit?.() + }) } return { - isLayoutContentMaximized, - isFullscreen, + isLayoutContentMaximized: layoutContentMaximize, + isFullscreen: layoutContentMaximize, maximize, - toggleFullscreen, + toggleFullscreen: () => maximize(!layoutContentMaximize.value), } } diff --git a/src/hooks/template/useSiderBar.ts b/src/hooks/template/useSiderBar.ts index c909d5bf..32f9a0c8 100644 --- a/src/hooks/template/useSiderBar.ts +++ b/src/hooks/template/useSiderBar.ts @@ -19,14 +19,14 @@ const normalMenuTagOption = (target: CloseMenuTag, fn: string) => { if (typeof target === 'number') { // 判断是否为 NaN - if (isNaN(target)) { + if (!Number.isInteger(target)) { console.warn(`${fn}: The ${target} is NaN, expect number.`) return } // 判断是否超出当前标签页列表最大长度或者是否为负数 - if (target > getMenuTagOptions.value.length || target < -1) { + if (target >= getMenuTagOptions.value.length || target < 0) { console.warn( `${fn}: The incoming index ${target} did not match the corresponding item.`, ) diff --git a/src/hooks/template/useSiderScroll.ts b/src/hooks/template/useSiderScroll.ts index a0f2a4fe..7a320808 100644 --- a/src/hooks/template/useSiderScroll.ts +++ b/src/hooks/template/useSiderScroll.ts @@ -1,4 +1,5 @@ import { LAYOUT_SIDER_REF } from '@/app-config' +import type { LayoutInst } from 'naive-ui' /** * @@ -14,14 +15,15 @@ import { LAYOUT_SIDER_REF } from '@/app-config' * siderScrollTo(0, 0) // x, y 方向滚动到 0 位置 */ export const useSiderScroll = () => { - const siderInst = LAYOUT_SIDER_REF.value - const { scrollTo: siderScrollTo } = siderInst || {} + const scrollTo: LayoutInst['scrollTo'] = ( + options: number | object, + y?: number, + ) => { + const sider = LAYOUT_SIDER_REF.value - if (!siderScrollTo) { - throw new Error( - `[useSiderScroll]: LAYOUT_SIDER_REF is not ready yet. please wait component mounted!`, - ) + if (typeof options === 'number') sider?.scrollTo(options, y ?? 0) + else sider?.scrollTo(options) } - return siderScrollTo + return scrollTo } diff --git a/src/hooks/template/useSpinning.ts b/src/hooks/template/useSpinning.ts index f2837f3a..395ca0a3 100644 --- a/src/hooks/template/useSpinning.ts +++ b/src/hooks/template/useSpinning.ts @@ -1,48 +1,12 @@ -import { setVariable } from '@/global-variable' +import { useRuntimeActions } from '@/store' export const useSpinning = () => { - /** - * - * @param wait 延迟时长 - * - * 刷新当前路由(强制触发刷新) - * - * @example - * reload(1200) - */ - const reload = (wait = 800) => { - setVariable('globalMainLayoutLoad', false) + const { reloadContent: reload, setRuntimeState } = useRuntimeActions() - setTimeout(() => setVariable('globalMainLayoutLoad', true), wait) - } + const openSpin = () => setRuntimeState('layoutContentSpinning', true) + const closeSpin = () => setRuntimeState('layoutContentSpinning', false) - /** - * - * 打开加载动画(不触发强制刷新) - * - * @example - * openSpin() - */ - const openSpin = () => { - setVariable('layoutContentSpinning', true) - } - - /** - * - * 关闭加载动画(不触发强制刷新) - * - * @example - * closeSpin() - */ - const closeSpin = () => { - setVariable('layoutContentSpinning', false) - } - - return { - reload, - openSpin, - closeSpin, - } + return { reload, openSpin, closeSpin } } export type UseSpinningReturnType = ReturnType diff --git a/src/hooks/template/useTheme.ts b/src/hooks/template/useTheme.ts index 5c1e4bca..d3c6f0ed 100644 --- a/src/hooks/template/useTheme.ts +++ b/src/hooks/template/useTheme.ts @@ -1,7 +1,6 @@ import { APP_THEME } from '@/app-config' import { useI18n } from '@/hooks' import { useSettingActions, useSettingGetters } from '@/store' -import { useColorMode } from '@vueuse/core' import { merge } from 'lodash-es' export type ThemeLabel = 'Dark' | 'Light' @@ -114,9 +113,11 @@ export const useTheme = () => { const syncSystemTheme = () => { const { getAppTheme } = useSettingGetters() const { updateSettingState } = useSettingActions() - const { system } = useColorMode() - updateSettingState('_appTheme', system.value === 'dark') + updateSettingState( + '_appTheme', + window.matchMedia('(prefers-color-scheme: dark)').matches, + ) updateSettingState('appTheme', 'auto') setThemeOverrides(getAppTheme.value) } diff --git a/src/hooks/template/useWatermark.ts b/src/hooks/template/useWatermark.ts index 260a99b9..f7bd4781 100644 --- a/src/hooks/template/useWatermark.ts +++ b/src/hooks/template/useWatermark.ts @@ -15,6 +15,8 @@ export const useWatermark = () => { * setWatermarkContent(undefined) // 沿用上次一次的水印内容 */ const setWatermarkContent = (content: string) => { + if (!content) return + const { getWatermarkConfig } = useSettingGetters() const assignWatermark = Object.assign({}, getWatermarkConfig.value, { content, diff --git a/src/hooks/web/useDomToImage.ts b/src/hooks/web/useDomToImage.ts index 333a26f4..84afb73d 100644 --- a/src/hooks/web/useDomToImage.ts +++ b/src/hooks/web/useDomToImage.ts @@ -63,7 +63,10 @@ type Options< * * @default undefined */ - created?: (result: DomToImageReturnType, element: T) => void + created?: ( + result: DomToImageReturnType, + element: T, + ) => void /** * * @param error dom to image error @@ -82,12 +85,12 @@ type Options< * * @default undefined */ - finally?: (element: T) => void + finally?: (element: T | null | undefined) => void } export type UseDomToImageOptions< T extends TargetType = Element, - ImageType extends DomToImageMethodKeys = DomToImageMethodKeys, + ImageType extends DomToImageMethodKeys = 'jpeg', > = Options & HtmlToImageOptions /** @@ -105,21 +108,21 @@ export type UseDomToImageOptions< * 当然,你也可以不传递 imageType 参数,此时会使用 options.imageType, * 如果都未传递,则默认使用 jpeg。 * - * 如果希望 created 获得准确的类型,可以给 useDomToImage 手动声明第二个类型参数; - * 或者就是在显式声明 options.imageType 参数。 + * create 的返回类型跟随配置或本次传入的格式;created 可能接收覆盖格式后的结果, + * 因此应先用 typeof / instanceof 判断回调中的结果类型。 * * @example * const refDom = ref() * const { create } = useDomToImage(refDom, { * beforeCreate: (element) => { ... }, - * created: (element, result) => { ... }, + * created: (result, element) => { ... }, * createdError: (error) => { ... }, * finally: () => { ... }, * }) */ export const useDomToImage = < T extends HTMLElement, - ImageType extends DomToImageMethodKeys = DomToImageMethodKeys, + ImageType extends DomToImageMethodKeys = 'jpeg', >( target: BasicTarget, options?: UseDomToImageOptions, @@ -132,40 +135,30 @@ export const useDomToImage = < imageType: _imageType, } = options ?? {} - const run = ( - imageType?: ImageType, - ): Promise> => { - return new Promise((resolve, reject) => { - const element = unrefElement(target) + const run = async ( + imageType?: OutputType, + ): Promise> => { + const element = unrefElement(target) + try { beforeCreate?.(element) - if (!element) { - createdError?.() + if (!element) + throw new Error('[useDomToImage]: target element is undefined.') - return reject(`[useDomToImage]: target element is undefined.`) - } + const imageTypeKey = imageType ?? _imageType ?? 'jpeg' + const result = await domToImageMethods[imageTypeKey](element, options) - const imageTypeKey = (imageType ?? - _imageType ?? - 'jpeg') as DomToImageMethodKeys + // 分发映射的返回类型与传入的 imageType 一一对应。 + created?.(result, element) - domToImageMethods[imageTypeKey]?.(element, options) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .then((res: any) => { - created?.(res, element) - - return resolve(res) - }) - .catch((error: Error) => { - createdError?.(error) - - return reject(error) - }) - .finally(() => { - _finally?.(element) - }) - }) + return result as DomToImageReturnType + } catch (error) { + createdError?.(error instanceof Error ? error : new Error(String(error))) + throw error + } finally { + _finally?.(element) + } } return { diff --git a/src/hooks/web/useElementFullscreen.ts b/src/hooks/web/useElementFullscreen.ts index b919b509..9e460196 100644 --- a/src/hooks/web/useElementFullscreen.ts +++ b/src/hooks/web/useElementFullscreen.ts @@ -106,6 +106,8 @@ export const useElementFullscreen = ( // 每个实例独立的状态 const isFullscreen = ref(false) const instanceZIndex = ref(0) + let frame: number | undefined + let activeElement: HTMLElement | null = null const originalStyles = { position: '', width: '', @@ -116,6 +118,7 @@ export const useElementFullscreen = ( transition: '', zIndex: '', backgroundColor: '', + boxSizing: '', } const enter = () => { @@ -125,7 +128,12 @@ export const useElementFullscreen = ( return } + if (activeElement === element) return + + if (activeElement) exit() + beforeEnter?.() + activeElement = element // 保存原始样式(只在第一次进入时保存) if (!isFullscreen.value) { @@ -139,6 +147,7 @@ export const useElementFullscreen = ( 'transition', 'zIndex', 'backgroundColor', + 'boxSizing', ]) Object.assign(originalStyles, o) @@ -165,6 +174,7 @@ export const useElementFullscreen = ( // 设置初始位置(不设置 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` @@ -183,11 +193,12 @@ export const useElementFullscreen = ( element.style.transition = transition // 使用 requestAnimationFrame 应用最终样式 - requestAnimationFrame(() => { + frame = requestAnimationFrame(() => { element.style.top = '0px' element.style.left = '0px' - element.style.width = '100vw' - element.style.height = '100vh' + element.style.width = '100dvw' + element.style.height = '100dvh' + frame = void 0 }) // 先更新状态 @@ -197,7 +208,7 @@ export const useElementFullscreen = ( } const exit = () => { - const element = unrefElement(target) as HTMLElement | null + const element = activeElement if (!element) { return @@ -205,6 +216,10 @@ export const useElementFullscreen = ( beforeExit?.() + if (frame !== void 0) cancelAnimationFrame(frame) + + frame = void 0 + // 先更新状态 isFullscreen.value = false @@ -222,6 +237,7 @@ export const useElementFullscreen = ( transition: 'transition', zIndex: 'z-index', backgroundColor: 'background-color', + boxSizing: 'box-sizing', } // 批量恢复样式 @@ -235,6 +251,7 @@ export const useElementFullscreen = ( } }) + activeElement = null _exit?.() } diff --git a/src/hooks/web/useI18n.ts b/src/hooks/web/useI18n.ts index 1d90494c..54c3489a 100644 --- a/src/hooks/web/useI18n.ts +++ b/src/hooks/web/useI18n.ts @@ -5,7 +5,7 @@ export interface OverrideUseI18nReturnType extends Omit< I18n['global'], 't' | 'locale' > { - t: (key: string, ...args: T[]) => T + t: (key: string, ...args: unknown[]) => T locale: (lang: string) => void } @@ -14,75 +14,60 @@ const getI18nKey = (namespace: string | undefined, key: string) => { return key } - if (key[0] === namespace) { + if (key === namespace || key.startsWith(`${namespace}.`)) { return key } return `${namespace}.${key}` } -export const useI18n = (namespace?: string) => { - /** - * - * 避免 HMR 时 i18n 未初始化导致报错。 - * 但是在开发环境下,i18n 始终会被初始化,所以不会影响其正常使用。 - * - * 但是,其实这是一种很不友好的做好,并且在顶层做修改的时候,依旧可能会有 HMR 报错; - * 现在还未找到更好的解决方案,所以只能先这样。 - */ - if (!i18n) { - return { - t: (key: string) => { - return getI18nKey(namespace, key) - }, - locale: (lang: string) => {}, - } as OverrideUseI18nReturnType +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 { t, ...methods } = i18n.global + const locale = (lang: string) => { + const instance = i18n - const overridesTFunc = (key: string, ...args: any[]) => { - if (!key) { - return '' - } + if (!instance) return - if (!key.includes('.') && !namespace) { - return key - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return (t as any)(getI18nKey(namespace, key), ...args) - } - - /** 重写 locale 方法 */ - const overrideLocaleFunc = (lang: string) => { - if (i18n.mode === 'legacy') { - i18n.global.locale = lang + if (instance.mode === 'legacy') { + instance.global.locale = lang + } else if (isRef(instance.global.locale)) { + instance.global.locale.value = lang } else { - if (isRef(i18n.global.locale)) { - i18n.global.locale.value = lang - } else { - i18n.global.locale = lang - } + instance.global.locale = lang } } - return { - ...methods, - t: overridesTFunc, - locale: overrideLocaleFunc, - } + // 初始化前创建的 Hook 也在调用时读取实例,避免永久停留在回退函数上。 + if (!i18n) return { t: translate, locale } as OverrideUseI18nReturnType + + return { ...i18n.global, t: translate, locale } } /** * - * @description - * 该方法为纯函数,无任何副作用,单纯为了配合 i18n-ally 插件使用。 - * 该插件识别 t 方法包裹 path 进行提示文案内容。 + * @param key 需要供 i18n-ally 识别的翻译键 * - * 不过在使用的时候必须按照示例导入,避免 vitest 抛出奇奇怪怪的错误。 - * @example - * import { t } from '@/hooks/web/useI18n' + * @description + * 原样返回翻译键,不执行翻译,也不读取国际化实例。 + * + * @returns 原始翻译键 */ export const t = (key: string) => key diff --git a/src/icons/A_README.md b/src/icons/A_README.md index 1a7a8932..4635a6e9 100644 --- a/src/icons/A_README.md +++ b/src/icons/A_README.md @@ -1,30 +1,39 @@ -## 说明 +# SVG 图标 -该文件包属于全局 `svg icon`,配合 `RIcon` 组件使用。 +图标使用相对目录作为完整名称,不再依赖全局唯一的文件名: -## TIP +```tsx +import { RIcon } from '@/components' +import type { IconName } from '@/icons' -添加新的 `svg` 图标时,应该注意图标自带 `fill` 属性的管理。如果自带了 `fill` 属性的图标,则会导致使用组件 `color` 属性失效的问题。所以如果是需要动态使用 `css` 属性控制样式的图标,应该去掉其 `fill` 属性或者配置为 `fill = currentColor`。 - -```html - +const name: IconName = 'directional/resize_h' + ``` -## 使用方法 - -- 导入 `svg` 图标 -- 命名(`命名必须全局唯一,并且尽量避免使用特殊符号`) -- 导入 `RIcon` 组件,配置 `name` 属性即可将 `svg` 作为图标使用 +`RIcon.name`、路由 `meta.icon`、侧栏 Logo 和图标包装组件共享严格的 `IconName` 联合类型。输入 `name` 时可获得完整分包路径提示,裸名称与不存在的路径会被 TypeScript 拒绝。类型来自文件生成,并非 TypeScript 自行读取文件系统。 ## 分包 -从 `4.8.0` 版本起,支持了 `svg icon` 分包,可以按照业务模块进行分包管理。 +| 目录 | 用途 | +| --- | --- | +| `action` | 搜索、刷新、关闭、全屏、设置、打印等操作 | +| `directional` | 箭头、方向、行首行尾与尺寸方向 | +| `navigation` | 页面和功能导航 | +| `logo` | 品牌及产品标识 | +| `status` | 错误、帮助等状态提示 | +| `system` | 语言、明暗主题与系统偏好 | +| `illustration` | 保留原色的插画 | -仅需要在 `src/icons` 目录下新建一个文件夹,然后将对应的 `svg` 图标放入其中即可。 +文件/目录使用小写字母、数字、下划线或连字符,首字符为字母;SVG 必须位于分包内。允许嵌套,例如 `business/orders/approved.svg` 对应 `business/orders/approved`。不同分包允许同名文件。 +单色图标使用 `currentColor`,有意留白用 `none`。品牌和插画保留原色,不保证 `color` 覆盖其所有颜色。避免包含内置脚本、事件处理器和外部资源。 -## 构建说明 +## 自动生成与注入 -`@spiriit/vite-plugin-svg-spritemap` 将图标打包为独立的带 hash 雪碧图。`RIcon` 使用标准 `href` 引用,开发和生产路径会跟随 Vite `base`,调用方仍然只需传递原有 `name`。 +- 新增、修改、删除或移动 SVG 时,开发服务自动检查并同步 `src/icons/manifest.ts`;增加或删除整个分包时自动重启开发服务。 +- `pnpm dev`、`build`、`dev-build`、`report` 和 `check` 都先自动生成清单;直接调用 Vite 时也由插件在启动/构建阶段同步。`typecheck` 与 `icons:check` 继续保持只读。也可单独运行 `pnpm icons:generate`。将更新后的清单与 SVG 一起维护。生成文件由项目 Prettier 配置格式化,模板同时遵守 ESLint 的声明空行规则。 +- `pnpm icons:check` 检查清单是否与目录一致,`pnpm typecheck` 和 `pnpm check` 会执行它。请修改生成脚本,不手工维护联合类型。 +- 每个顶层分包输出独立带 hash 的 SVG 雪碧图。生成的分包地址由 Spritemap 插件转换为随 Vite base 的开发/生产路径,`RIcon` 根据 name 的包名选择地址,再引用包含完整路径的 symbol ID。 +- `/svg-icons` 提供分包筛选、路径搜索和点击复制完整 TSX 用法。 -图标名称全局唯一,即使分在不同目录也不能重复。预览页的文件扫描放在独立 `.ts` 文件中,避免 Vite 8 对 `import.meta.glob` 与 JSX 混用的扫描限制;上游修复后可重新评估这一拆分。 +旧版本缓存里的裸 Logo 或菜单图标名在读取边界通过 `resolveIconName` 迁移;仅当文件名唯一时转换。新代码必须使用完整路径,不为裸名放宽组件类型。 diff --git a/src/icons/directional/adjustment.svg b/src/icons/action/adjustment.svg similarity index 100% rename from src/icons/directional/adjustment.svg rename to src/icons/action/adjustment.svg diff --git a/src/icons/tip/close.svg b/src/icons/action/close.svg similarity index 100% rename from src/icons/tip/close.svg rename to src/icons/action/close.svg diff --git a/src/icons/directional/close_left.svg b/src/icons/action/close_left.svg similarity index 100% rename from src/icons/directional/close_left.svg rename to src/icons/action/close_left.svg diff --git a/src/icons/directional/close_right.svg b/src/icons/action/close_right.svg similarity index 100% rename from src/icons/directional/close_right.svg rename to src/icons/action/close_right.svg diff --git a/src/icons/tip/export_excel.svg b/src/icons/action/export_excel.svg similarity index 100% rename from src/icons/tip/export_excel.svg rename to src/icons/action/export_excel.svg diff --git a/src/icons/directional/lock.svg b/src/icons/action/lock.svg similarity index 100% rename from src/icons/directional/lock.svg rename to src/icons/action/lock.svg diff --git a/src/icons/tip/more.svg b/src/icons/action/more.svg similarity index 100% rename from src/icons/tip/more.svg rename to src/icons/action/more.svg diff --git a/src/icons/tip/mouse.svg b/src/icons/action/mouse.svg similarity index 100% rename from src/icons/tip/mouse.svg rename to src/icons/action/mouse.svg diff --git a/src/icons/tip/print.svg b/src/icons/action/print.svg similarity index 100% rename from src/icons/tip/print.svg rename to src/icons/action/print.svg diff --git a/src/icons/tip/enter.svg b/src/icons/directional/enter.svg similarity index 100% rename from src/icons/tip/enter.svg rename to src/icons/directional/enter.svg diff --git a/src/icons/logo/login_bg.svg b/src/icons/illustration/login_bg.svg similarity index 100% rename from src/icons/logo/login_bg.svg rename to src/icons/illustration/login_bg.svg diff --git a/src/icons/index.ts b/src/icons/index.ts new file mode 100644 index 00000000..45c6f7fc --- /dev/null +++ b/src/icons/index.ts @@ -0,0 +1,16 @@ +import { iconNames, isIconName } from './manifest' +import type { IconName } from './manifest' + +export { iconNames, iconPackages, isIconName } from './manifest' +export type { IconName, IconPackage } from './manifest' + +// 仅用于读取旧版缓存。存在多个同名图标时不猜测所属分包。 +export function resolveIconName(value: unknown): IconName | undefined { + if (isIconName(value)) return value + + if (typeof value !== 'string' || value.includes('/')) return + + const matches = iconNames.filter((name) => name.endsWith(`/${value}`)) + + return matches.length === 1 ? matches[0] : void 0 +} diff --git a/src/icons/tip/axios.svg b/src/icons/logo/axios.svg similarity index 100% rename from src/icons/tip/axios.svg rename to src/icons/logo/axios.svg diff --git a/src/icons/manifest.ts b/src/icons/manifest.ts new file mode 100644 index 00000000..08a7cca1 --- /dev/null +++ b/src/icons/manifest.ts @@ -0,0 +1,76 @@ +// Generated by scripts/icons.mjs. Do not edit. +export const iconNames = [ + 'action/adjustment', + 'action/close', + 'action/close_left', + 'action/close_other', + 'action/close_right', + 'action/draggable', + 'action/export_excel', + 'action/fullscreen', + 'action/fullscreen_fold', + 'action/lock', + 'action/more', + 'action/mouse', + 'action/out', + 'action/print', + 'action/reload', + 'action/search', + 'action/setting', + 'action/shared', + 'directional/enter', + 'directional/expanded', + 'directional/left_arrow', + 'directional/resize_h', + 'directional/right_arrow', + 'directional/row_end', + 'directional/row_head', + 'illustration/login_bg', + 'logo/axios', + 'logo/github', + 'logo/google', + 'logo/office', + 'logo/ray', + 'logo/twitter', + 'navigation/dashboard', + 'navigation/echart', + 'navigation/menu', + 'navigation/other', + 'navigation/rely', + 'navigation/table', + 'status/error', + 'status/question', + 'system/dark', + 'system/language', + 'system/light', + 'system/system_os', +] as const + +export type IconName = (typeof iconNames)[number] + +export const iconPackages = [ + 'action', + 'directional', + 'illustration', + 'logo', + 'navigation', + 'status', + 'system', +] as const + +export type IconPackage = (typeof iconPackages)[number] + +export const iconSprites = { + action: '/__spritemap-action', + directional: '/__spritemap-directional', + illustration: '/__spritemap-illustration', + logo: '/__spritemap-logo', + navigation: '/__spritemap-navigation', + status: '/__spritemap-status', + system: '/__spritemap-system', +} as const + +const names: ReadonlySet = new Set(iconNames) + +export const isIconName = (value: unknown): value is IconName => + typeof value === 'string' && names.has(value) diff --git a/src/icons/tip/dashboard.svg b/src/icons/navigation/dashboard.svg similarity index 100% rename from src/icons/tip/dashboard.svg rename to src/icons/navigation/dashboard.svg diff --git a/src/icons/tip/echart.svg b/src/icons/navigation/echart.svg similarity index 100% rename from src/icons/tip/echart.svg rename to src/icons/navigation/echart.svg diff --git a/src/icons/tip/menu.svg b/src/icons/navigation/menu.svg similarity index 100% rename from src/icons/tip/menu.svg rename to src/icons/navigation/menu.svg diff --git a/src/icons/tip/other.svg b/src/icons/navigation/other.svg similarity index 100% rename from src/icons/tip/other.svg rename to src/icons/navigation/other.svg diff --git a/src/icons/tip/rely.svg b/src/icons/navigation/rely.svg similarity index 100% rename from src/icons/tip/rely.svg rename to src/icons/navigation/rely.svg diff --git a/src/icons/tip/table.svg b/src/icons/navigation/table.svg similarity index 100% rename from src/icons/tip/table.svg rename to src/icons/navigation/table.svg diff --git a/src/icons/tip/error.svg b/src/icons/status/error.svg similarity index 100% rename from src/icons/tip/error.svg rename to src/icons/status/error.svg diff --git a/src/icons/tip/question.svg b/src/icons/status/question.svg similarity index 100% rename from src/icons/tip/question.svg rename to src/icons/status/question.svg diff --git a/src/icons/template/dark.svg b/src/icons/system/dark.svg similarity index 87% rename from src/icons/template/dark.svg rename to src/icons/system/dark.svg index 1e247138..e487c057 100644 --- a/src/icons/template/dark.svg +++ b/src/icons/system/dark.svg @@ -1,4 +1,4 @@ - + + + {{ + header: () => , + sidebar: () => , + tabs: () => , + footer: () => , + default: () => , + }} + +``` + +插槽替换遵循当前模式与显隐设置:顶部导航模式无 sidebar,关闭标签/版权后不渲染相应区域。自定义内容需要自行处理请求取消与路由内容;未替换时沿用默认 Provider 和路由缓存。 + +布局的内容滚动引用仍为 `LAYOUT_CONTENT_REF`,侧栏引用为 `LAYOUT_SIDER_REF`;`useContentScroll` / `useSiderScroll` 在执行时读取当前引用,支持模式切换与组件重新挂载。 diff --git a/src/layout/components/LayoutSettings.tsx b/src/layout/components/LayoutSettings.tsx new file mode 100644 index 00000000..a6f743ad --- /dev/null +++ b/src/layout/components/LayoutSettings.tsx @@ -0,0 +1,118 @@ +import { useI18n } from '@/hooks' +import { useSettingActions, useSettingGetters } from '@/store' +import { getDefaultSettingConfig } from '@/store/modules/setting/constant' +import type { LayoutConfig } from '@/store/modules/setting/types' +import { + NButton, + NFlex, + NForm, + NFormItem, + NInputNumber, + NSelect, + NSwitch, +} from 'naive-ui' + +export default defineComponent({ + name: 'LayoutSettings', + props: { showDescription: { type: Boolean, default: true } }, + setup(props) { + const { t } = useI18n('layout') + const { getLayoutConfig } = useSettingGetters() + const { updateSettingState } = useSettingActions() + const text = (key: string) => t(key) + const modes = ['side', 'top', 'mixed'] as const + const update = (value: Partial) => + updateSettingState('layoutConfig', value) + + return () => ( + + {props.showDescription ? ( +

{text('description')}

+ ) : null} + + {modes.map((mode) => ( + update({ mode })} + > + + ))} + + + + ({ + value, + label: text(value), + }))} + onUpdateValue={(value: LayoutConfig['contentWidth']) => + update({ contentWidth: value }) + } + /> + + + { + if (value !== null) update({ contentMaxWidth: value }) + }} + /> + + + { + if (value !== null) update({ contentPadding: value }) + }} + /> + + + update({ fixedHeader })} + /> + + + update({ fixedFooter })} + /> + + + update({ ...getDefaultSettingConfig().layoutConfig })} + > + {text('reset')} + +
+ ) + }, +}) diff --git a/src/layout/components/Menu/components/SiderBarLogo/index.scss b/src/layout/components/Menu/components/SiderBarLogo/index.scss index 6bba540e..ccf43bda 100644 --- a/src/layout/components/Menu/components/SiderBarLogo/index.scss +++ b/src/layout/components/Menu/components/SiderBarLogo/index.scss @@ -1,19 +1,27 @@ .r-menu__logo { + width: 100%; height: $layoutHeaderHeight; + box-sizing: border-box; + border: 0; + border-bottom: 1px solid var(--r-line); + color: var(--r-text); + background: inherit; + font-size: 16px; + text-align: left; padding: 0 18px 0 24px; display: flex; flex-wrap: nowrap; justify-content: center; align-items: center; gap: 8px 12px; - font-weight: 600; + font-weight: 650; overflow: hidden; &.r-menu__logo-url { position: sticky; top: 0; cursor: pointer; - background-color: var(--n-color); + background-color: inherit; z-index: 20; } @@ -29,3 +37,9 @@ } } } + +.r-menu__logo-initial { + color: var(--r-theme-primary-color); + font-size: 18px; + font-weight: 600; +} diff --git a/src/layout/components/Menu/components/SiderBarLogo/index.tsx b/src/layout/components/Menu/components/SiderBarLogo/index.tsx index 28ba985d..3d0423ea 100644 --- a/src/layout/components/Menu/components/SiderBarLogo/index.tsx +++ b/src/layout/components/Menu/components/SiderBarLogo/index.tsx @@ -1,8 +1,9 @@ +import { resolveIconName } from '@/icons' import './index.scss' import { RIcon } from '@/components' import { useSettingGetters } from '@/store' import { isValueType, renderNode } from '@/utils' -import { NEllipsis, NGradientText, NTooltip } from 'naive-ui' +import { NEllipsis, NTooltip } from 'naive-ui' export const SIDER_BAR_LOGO = shallowRef() @@ -41,7 +42,7 @@ export default defineComponent({ if (typeof getSideBarLogo.value.icon === 'string') { return ( @@ -63,7 +64,9 @@ export default defineComponent({ const { sideBarLogo, collapsed, TemplateLogo, sideBarLogoClick } = this return sideBarLogo?.title ? ( -
{{ trigger: () => ( - + {sideBarLogo.title?.[0] || null} - + ), default: () => sideBarLogo.title, }} ) : null} - {sideBarLogo.title} - -
+ + ) : null }, }) diff --git a/src/layout/components/Menu/index.scss b/src/layout/components/Menu/index.scss index 28c7870a..dd46d3a8 100644 --- a/src/layout/components/Menu/index.scss +++ b/src/layout/components/Menu/index.scss @@ -6,10 +6,41 @@ } } -.r-template--light .app-menu__sider { - box-shadow: 2px 0 8px $layoutShadowColorLight; +.app-menu__sider { + border-inline-end: 1px solid var(--r-line); + box-shadow: none; + + .n-menu-item-content { + transition: color 0.18s ease; + } } -.r-template--dark .app-menu__sider { - box-shadow: 2px 0 8px $layoutShadowColorDark; +.app-menu__sider .r-menu__logo { + color: var(--n-text-color); + border-bottom-color: color-mix(in oklab, currentColor 15%, transparent); +} + +.app-menu__sider .r-menu__logo.r-menu__logo-url { + background-color: var(--n-color); +} + +.app-menu__sider .r-menu__logo-initial { + color: inherit; +} + +.app-menu__sider { + --r-primary-text: var(--n-text-color); + --r-selected-text: var(--n-text-color); +} + +.r-menu--app .n-menu-item-content--selected .n-menu-item-content-header { + font-weight: 600; +} + +@media (forced-colors: active) { + .r-menu--app .n-menu-item-content--selected, + .menu-tag__btn.n-button--primary-type { + outline: 1px solid Highlight; + outline-offset: -2px; + } } diff --git a/src/layout/components/Menu/index.tsx b/src/layout/components/Menu/index.tsx index c1f1fc3b..cf895b1a 100644 --- a/src/layout/components/Menu/index.tsx +++ b/src/layout/components/Menu/index.tsx @@ -1,110 +1,92 @@ import './index.scss' import { LAYOUT_SIDER_REF } from '@/app-config' -import { getVariableToRefs, setVariable } from '@/global-variable' import { useDevice } from '@/hooks' -import { useMenuActions, useMenuGetters, useSettingGetters } from '@/store' +import { + useMenuActions, + useMenuGetters, + useRuntimeActions, + useRuntimeGetters, + useSettingGetters, +} from '@/store' import type { AppMenuOption, NaiveMenuOptions } from '@/types' import { positionSelectedMenuItem } from '@/utils' import { NDrawer, NLayoutSider, NMenu } from 'naive-ui' import type { MenuInst } from 'naive-ui' +import type { PropType } from 'vue' import SiderBarLogo from './components/SiderBarLogo' export default defineComponent({ name: 'AppMenu', - setup() { - // 这里使用 shallowRef 而不是 useTemplateRef 是因为在这里有一个特殊情况,会导致一个 readonly 的警告 - const menuRef = shallowRef() - + props: { + options: { type: Array as PropType, default: void 0 }, + showLogo: { type: Boolean, default: true }, + }, + setup(props) { + const menuRef = shallowRef(null) const { changeMenuModelValue, collapsedMenu, updateMenuState } = useMenuActions() const { getMenuConfig } = useSettingGetters() const { getMenuOptions, getCollapsed, getMenuKey } = useMenuGetters() - const modelMenuKey = computed({ - get: () => { - /** - * - * @description - * 禁用该 eslint 规则,因为在 computed 中使用了异步操作。 - * 该规则只是为了避免异步的 computed get 获取值出现问题; - * 但是,在这里获取值的操作是同步行为,只是为了在获取值以后将对应菜单项展开; - * 所以,这里不会出现异步获取值的问题,所以可以禁用该规则。 - */ - // eslint-disable-next-line vue/no-async-in-computed-properties - setTimeout(() => { - showMenuOption() - positionSelectedMenuItem() - }, 300) - - return getMenuKey.value - }, - set: () => { - if (isTabletOrSmaller.value) { - setVariable('globalDrawerValue', false) - } - }, - }) - const { isTabletOrSmaller } = useDevice({ + const { globalDrawerValue } = useRuntimeGetters() + const { setRuntimeState } = useRuntimeActions() + const { isTabletOrSmaller, width } = useDevice({ observer: (isSmaller) => { - if (isSmaller) { - // 避免菜单折叠时,在小尺寸屏幕导致菜单显示不完整 - updateMenuState('collapsed', false) - } - }, - }) - const modelGlobalDrawerValue = computed({ - get: () => getVariableToRefs('globalDrawerValue').value, - set: (val) => { - setVariable('globalDrawerValue', val) + if (isSmaller) updateMenuState('collapsed', false) + else setRuntimeState('globalDrawerValue', false) }, }) - /** - * - * @description - * 手动展开当前激活菜单项。 - */ - const showMenuOption = () => { - const key = modelMenuKey.value + watch( + [getMenuKey, () => props.options, menuRef], + async () => { + await nextTick() - if (key !== void 0 && key !== null) { - nextTick(() => menuRef.value?.showOption?.(key)) - } - } + if (getMenuKey.value != null) + menuRef.value?.showOption(String(getMenuKey.value)) - const BasicMenu = () => ( + positionSelectedMenuItem() + }, + { flush: 'post' }, + ) + + const basicMenu = () => ( { - updateMenuState('collapsed', false) - }} - onCollapse={() => { - updateMenuState('collapsed', true) - }} + collapsed={isTabletOrSmaller.value ? false : getCollapsed.value} inverted={getMenuConfig.value.inverted} > - {getMenuConfig.value.menuSiderBarLogo ? ( + {props.showLogo && getMenuConfig.value.menuSiderBarLogo ? ( ) : null} { - changeMenuModelValue(key, op as unknown as AppMenuOption) + onUpdateValue={(key, option) => { + changeMenuModelValue(key, option as unknown as AppMenuOption) + + if (isTabletOrSmaller.value) + setRuntimeState('globalDrawerValue', false) }} accordion={getMenuConfig.value.accordion} iconSize={getMenuConfig.value.iconSize} @@ -113,27 +95,20 @@ export default defineComponent({ ) - return { - isTabletOrSmaller, - BasicMenu, - modelGlobalDrawerValue, - } - }, - render() { - const { isTabletOrSmaller, BasicMenu } = this - - return !isTabletOrSmaller ? ( - - ) : ( - - - - ) + return () => + isTabletOrSmaller.value ? ( + setRuntimeState('globalDrawerValue', value)} + placement="left" + displayDirective="show" + autoFocus={false} + > + {basicMenu()} + + ) : ( + basicMenu() + ) }, }) diff --git a/src/layout/components/MenuTag/index.scss b/src/layout/components/MenuTag/index.scss index 49c168a6..14f85986 100644 --- a/src/layout/components/MenuTag/index.scss +++ b/src/layout/components/MenuTag/index.scss @@ -20,30 +20,22 @@ $menuTagWrapperWidth: 76px; } } -// 激活标签页关闭按钮样式 .menu-tag .menu-tag__btn { - transition: - color 0.3s var(--n-bezier), - background-color 0.3s var(--n-bezier), - opacity 0.3s var(--n-bezier), - border-color 0.3s var(--n-bezier), - width 0.3s var(--n-bezier); + border-radius: 7px; + font-weight: 500; .n-button__icon { - opacity: 0; - width: 0; + width: var(--n-icon-size); height: var(--n-icon-size); - transition: all 0.3s var(--r-bezier); - margin-left: 0px; - transform: translateX(4px); + margin-left: 4px; + opacity: 0; + transition: opacity 0.18s ease; } - &:hover { - .n-button__icon { - opacity: 1; - width: var(--n-icon-size); - transition: all 0.3s var(--r-bezier); - } + &:hover .n-button__icon, + &:focus-visible .n-button__icon, + &.n-button--primary-type .n-button__icon { + opacity: 1; } } @@ -70,12 +62,10 @@ $menuTagWrapperWidth: 76px; animation: elementRotate 0.8s linear infinite; } -.r-template--light .menu-tag { - box-shadow: 0 2px 2px $layoutShadowColorLight; -} - -.r-template--dark .menu-tag { - box-shadow: 0 2px 2px $layoutShadowColorDark; +.menu-tag { + border-bottom: 1px solid var(--r-line); + box-shadow: none; + background: var(--r-surface); } .override-button__menu-tag { diff --git a/src/layout/components/MenuTag/index.tsx b/src/layout/components/MenuTag/index.tsx index fb57b368..ddd87759 100644 --- a/src/layout/components/MenuTag/index.tsx +++ b/src/layout/components/MenuTag/index.tsx @@ -1,27 +1,6 @@ -/** - * - * @description - * 操作说明: - * - 关闭全部: 关闭所有标签页,并且重定向至根页面 rootRoute.path - * - 关闭右侧: 关闭右侧所有标签,如果选中标签页与当前激活页不一致并且激活页在右侧,则会重定向至当前选中标签页 - * - 关闭左侧: 关闭左侧所有标签,如果选中标签页与当前激活页不一致并且激活页在左侧,则会重定向至当前选中标签页 - * - 关闭其他: 关闭其他所有标签,如果选中标签页与当前激活页不一致并且激活页在其中,则会重定向至当前选中标签页 - * - 关闭所有: 关闭所有标签页,并且重定向至 root page - * - * root path 标签不可被关闭。 - * 页面刷新后,仅会保留刷新前激活 key 的 tag 标签。 - * - * 注入 MENU_TAG_DATA 属性,用于动态更新 MenuTag 标签所在的位置。 - * - * 该模板中引入了 Root Path 概念,在 MenuTag 中除了关闭左右侧标签操作能主动移除 Root Tag 之外其余的操作都不允许。 - * - * outsideClick 方法优先级不如 contextmenu 事件高,所以可能会出现重复右键菜单时,闪烁问题; - * 虽然使用 throttle 方法进行优化,但是该问题本质并没有解决(v5.0.2 版本修复了该问题)。 - */ - +import { useRuntimeGetters } from '@/store' import './index.scss' import { RIcon, RMoreDropdown } from '@/components' -import { getVariableToRefs } from '@/global-variable' import { useAppRoot, useMaximize, useSiderBar, useSpinning } from '@/hooks' import { useMenuActions, useMenuGetters } from '@/store' import type { AppMenuOption, MenuTagOptions } from '@/types' @@ -65,22 +44,24 @@ export default defineComponent({ { label: '关闭当前页面', key: 'closeCurrentPage', - icon: () => , + icon: () => , }, { label: '最大化当前页面', key: 'maximizeLayoutContent', - icon: () => , + icon: () => ( + + ), }, { label: '刷新当前页面', key: 'reloadCurrentPage', - icon: () => , + icon: () => , }, { label: '新窗口打开', key: 'windowOpenTab', - icon: () => , + icon: () => , }, { type: 'divider', @@ -89,12 +70,12 @@ export default defineComponent({ { label: '关闭左侧标签页', key: 'closeLeft', - icon: () => , + icon: () => , }, { label: '关闭右侧标签页', key: 'closeRight', - icon: () => , + icon: () => , }, { type: 'divider', @@ -103,12 +84,14 @@ export default defineComponent({ { label: '关闭其他标签页', key: 'closeOther', - icon: () => , + icon: () => , }, { label: '关闭所有标签页', key: 'closeAll', - icon: () => , + icon: () => ( + + ), disabled: false, }, ]) @@ -162,7 +145,7 @@ export default defineComponent({ }) // 注入 tag 前缀 const MENU_TAG_DATA = 'menu_tag_data' - const globalMainLayoutLoad = getVariableToRefs('globalMainLayoutLoad') + const globalMainLayoutLoad = useRuntimeGetters().globalMainLayoutLoad // naive scrollbar 容器 class const naiveScrollbarContainerClass = 'n-scrollbar-container' // 缓存上一次的菜单 key @@ -464,7 +447,7 @@ export default defineComponent({ {{ icon: () => ( ( ( ( ( ( { - // 当处于小尺寸状态时,自动关闭搜索框 - if (val) { - modelShow.value = false - } - }, - }) const loading = ref(false) // 激活样式 class name const ACTIVE_CLASS = 'content-item--active' @@ -101,6 +84,16 @@ export default defineComponent({ preSearchElementIndex = searchElementIndex } + // 断点 observer 会同步执行,先初始化其调用的重置函数。 + const { isTabletOrSmaller } = useDevice({ + observer: (val) => { + // 当处于小尺寸状态时,自动关闭搜索框 + if (val) { + modelShow.value = false + } + }, + }) + // 按下 ctrl + k 或者 command + k 激活搜索栏 const registerArouseKeyboard = (e: KeyboardEvent) => { if (modelShow.value) { @@ -227,7 +220,7 @@ export default defineComponent({ } else if (typeof icon === 'function') { return } else { - return + return } } @@ -306,7 +299,7 @@ export default defineComponent({
{RenderPreIcon(menuOption.meta)}
{menuOption.breadcrumbLabel}
@@ -371,7 +364,7 @@ export default defineComponent({ onInput={fuzzySearchMenuOptions.bind(this)} > {{ - prefix: () => , + prefix: () => , }} ), diff --git a/src/layout/components/Search/GlobalSearchButton/index.tsx b/src/layout/components/Search/GlobalSearchButton/index.tsx index 0a2943e6..7eeeae5d 100644 --- a/src/layout/components/Search/GlobalSearchButton/index.tsx +++ b/src/layout/components/Search/GlobalSearchButton/index.tsx @@ -53,7 +53,7 @@ export default defineComponent({ style="margin-right: 16px" > {{ - icon: () => , + icon: () => , default: () => ( {$t('headerTooltip.Search')} diff --git a/src/layout/components/SiderBar/components/Breadcrumb/index.tsx b/src/layout/components/SiderBar/components/Breadcrumb/index.tsx index 3e20c563..f39dff79 100644 --- a/src/layout/components/SiderBar/components/Breadcrumb/index.tsx +++ b/src/layout/components/SiderBar/components/Breadcrumb/index.tsx @@ -1,12 +1,3 @@ -/** - * - * 顶部面包屑 - * - * 如果下拉菜单条目小于一条, 则不会触发下拉菜单 - * - * 添加 标签, 避免 Runtime directive used on component... 警告 - */ - import './index.scss' import { useDevice } from '@/hooks' import { useMenuActions, useMenuGetters } from '@/store' diff --git a/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSegment.tsx b/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSegment.tsx index c61fee3c..9041c9c1 100644 --- a/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSegment.tsx +++ b/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSegment.tsx @@ -13,17 +13,17 @@ export default defineComponent({ { label: '深色', key: 'dark', - icon: () => , + icon: () => , }, { label: '浅色', key: 'light', - icon: () => , + icon: () => , }, { label: '自动', key: 'auto', - icon: () => , + icon: () => , }, ] const modelAppTheme = computed({ diff --git a/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSwitch.tsx b/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSwitch.tsx index 4fa853a4..afc29306 100644 --- a/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSwitch.tsx +++ b/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSwitch.tsx @@ -44,8 +44,8 @@ export default defineComponent({ } > {{ - 'checked-icon': () => , - 'unchecked-icon': () => , + 'checked-icon': () => , + 'unchecked-icon': () => , checked: () => '亮', unchecked: () => '暗', }} diff --git a/src/layout/components/SiderBar/components/SettingDrawer/index.tsx b/src/layout/components/SiderBar/components/SettingDrawer/index.tsx index a0748f67..45b61015 100644 --- a/src/layout/components/SiderBar/components/SettingDrawer/index.tsx +++ b/src/layout/components/SiderBar/components/SettingDrawer/index.tsx @@ -1,3 +1,5 @@ +import { useI18n } from '@/hooks' +import LayoutSettings from '@/layout/components/LayoutSettings' import './index.scss' import { RIcon, useModal } from '@/components' import { useMenuActions, useSettingActions, useSettingGetters } from '@/store' @@ -23,6 +25,7 @@ export default defineComponent({ name: 'SettingDrawer', props: drawerProps, setup() { + const { t } = useI18n() const { create: createModal } = useModal() const { changePrimaryColor, updateSettingState } = useSettingActions() const { @@ -72,8 +75,6 @@ export default defineComponent({ // @ts-ignore modelReactive[key] = value - console.log(value, key) - updateSettingState(key as keyof SettingState, value) }) @@ -85,6 +86,7 @@ export default defineComponent({ provide(SETTING_DRAWER_INJECT_KEY, modelReactive) return { + t, changePrimaryColor, getAppTheme, getPrimaryColorOverride, @@ -103,10 +105,13 @@ export default defineComponent({ {{ default: () => ( + ('layout.tab')}> + + - + @@ -121,7 +126,7 @@ export default defineComponent({ {{ - icon: () => , + icon: () => , default: () => '初始化配置', }} diff --git a/src/layout/components/SiderBar/components/SettingDrawer/segment-views/CustomMenu.tsx b/src/layout/components/SiderBar/components/SettingDrawer/segment-views/CustomMenu.tsx index fab84545..9c3f807d 100644 --- a/src/layout/components/SiderBar/components/SettingDrawer/segment-views/CustomMenu.tsx +++ b/src/layout/components/SiderBar/components/SettingDrawer/segment-views/CustomMenu.tsx @@ -33,7 +33,7 @@ export default defineComponent({ {{ - trigger: () => , + trigger: () => , default: () => '菜单更新是一个复杂、耗时的操作,请手动点击【更新菜单】按钮更新设置', }} diff --git a/src/layout/components/SiderBar/components/TooltipIcon/index.tsx b/src/layout/components/SiderBar/components/TooltipIcon/index.tsx index 3dc40f29..3bcd604d 100644 --- a/src/layout/components/SiderBar/components/TooltipIcon/index.tsx +++ b/src/layout/components/SiderBar/components/TooltipIcon/index.tsx @@ -1,3 +1,5 @@ +import type { IconName } from '@/icons' +import type { PropType } from 'vue' import './index.scss' import { RIcon } from '@/components' import { NTooltip, tooltipProps } from 'naive-ui' @@ -8,7 +10,7 @@ export default defineComponent({ props: { ...tooltipProps, iconName: { - type: String, + type: String as PropType, required: true, }, customClassName: { diff --git a/src/layout/components/SiderBar/index.scss b/src/layout/components/SiderBar/index.scss index a81ec76c..11b7420a 100644 --- a/src/layout/components/SiderBar/index.scss +++ b/src/layout/components/SiderBar/index.scss @@ -9,14 +9,16 @@ } } -.r-template--light .layout-header { - box-shadow: 0 1px 2px $layoutShadowColorLight; -} +.layout-header { + border-bottom: 1px solid var(--r-line); + box-shadow: none; -.r-template--dark .layout-header { - box-shadow: 0 1px 2px $layoutShadowColorDark; + .n-breadcrumb { + font-size: 13px; + } } .override-button__layout { padding: 0 9px; + border-radius: 8px; } diff --git a/src/layout/components/SiderBar/index.tsx b/src/layout/components/SiderBar/index.tsx index 0074a162..2f12e460 100644 --- a/src/layout/components/SiderBar/index.tsx +++ b/src/layout/components/SiderBar/index.tsx @@ -1,16 +1,8 @@ -/** - * - * 本来想通过写数据配置化的方式实现顶部的功能小按钮, 结果事实发现... - * 但是我又不想改, 就这样吧 - * - * 如果你希望自己 diy 一些东西,可以自己使用 computed 实现 - */ - +import { useRuntimeActions, useRuntimeGetters } from '@/store' import './index.scss' import AppAvatar from '@/app-components/app/AppAvatar' import { LOCAL_OPTIONS } from '@/app-config' import { RIcon } from '@/components' -import { getVariableToRefs, setVariable } from '@/global-variable' import { useDevice, useI18n } from '@/hooks' import { useSettingActions, useSettingGetters } from '@/store' import { NButton, NDropdown, NFlex, NLayoutHeader, NScrollbar } from 'naive-ui' @@ -50,7 +42,7 @@ export default defineComponent({ // 当前是否为平板或者更小的设备 const { isTabletOrSmaller } = useDevice() // 获取全局 drawer 的值 - const globalDrawerValue = getVariableToRefs('globalDrawerValue') + const globalDrawerValue = useRuntimeGetters().globalDrawerValue /** * @@ -95,7 +87,10 @@ export default defineComponent({ updateSettingState('lockScreenSwitch', true) }, menu: () => { - setVariable('globalDrawerValue', !globalDrawerValue.value) + useRuntimeActions().setRuntimeState( + 'globalDrawerValue', + !globalDrawerValue.value, + ) }, } @@ -113,6 +108,7 @@ export default defineComponent({ } return { + t, leftIconOptions, rightTooltipIconOptions, toolIconClick, @@ -144,15 +140,20 @@ export default defineComponent({ > {leftIconOptions.map((curr) => ( - + aria-label={this.t('layout.toggleMenu')} + onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)} + > + + ))} {getBreadcrumbSwitch ? : null} @@ -172,7 +173,14 @@ export default defineComponent({ quaternary size="medium" key={curr.name} - onClick={toolIconClick.bind(this, curr.name)} + aria-label={this.t( + curr.eventKey === 'setting' + ? 'headerTooltip.Setting' + : curr.eventKey === 'github' + ? 'headerTooltip.Github' + : 'headerTooltip.FullScreen', + )} + onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)} focusable={false} > @@ -185,12 +193,13 @@ export default defineComponent({ > ('layout.language')} class="override-button__layout" focusable={false} > diff --git a/src/layout/components/SiderBar/shared.ts b/src/layout/components/SiderBar/shared.ts index cd8f92ce..37a00d4c 100644 --- a/src/layout/components/SiderBar/shared.ts +++ b/src/layout/components/SiderBar/shared.ts @@ -81,7 +81,7 @@ export const createLeftIconOptions = (opts: IconOptionsFC) => { const notTableOrSmallerOptions: IconOptions[] = [] const tableOrSmallerOptions: IconOptions[] = [ { - name: 'menu', + name: 'navigation/menu', size: 18, eventKey: 'menu', }, @@ -105,23 +105,25 @@ export const createRightIconOptions = (opts: IconOptionsFC) => { const basicOptions: IconOptions[] = [ { - name: 'fullscreen', + name: 'action/fullscreen', size: 18, - eventKey: 'screen', + eventKey: 'fullscreen', }, { - name: 'github', + name: 'logo/github', size: 18, eventKey: 'github', }, { - name: 'setting', + name: 'action/setting', size: 18, eventKey: 'setting', }, ] const notTableOrSmallerOptions: IconOptions[] = [...basicOptions] - const tableOrSmallerOptions: IconOptions[] = [...basicOptions] + const tableOrSmallerOptions: IconOptions[] = basicOptions.filter( + (option) => option.eventKey === 'setting', + ) return isTabletOrSmaller!.value ? tableOrSmallerOptions diff --git a/src/layout/components/SiderBar/type.ts b/src/layout/components/SiderBar/type.ts index 7dd6795e..17647b97 100644 --- a/src/layout/components/SiderBar/type.ts +++ b/src/layout/components/SiderBar/type.ts @@ -1,3 +1,4 @@ +import type { IconName } from '@/icons' import type { DropdownOption } from 'naive-ui' import type { ComputedRef, Ref, VNode } from 'vue' @@ -15,7 +16,7 @@ export interface IconDropdownOptions extends GlobalRecordable { } export interface IconOptions { - name: string + name: IconName size?: number tooltip?: ComputedRef | string eventKey?: string diff --git a/src/layout/components/TopNavigation/index.tsx b/src/layout/components/TopNavigation/index.tsx new file mode 100644 index 00000000..c7221bb1 --- /dev/null +++ b/src/layout/components/TopNavigation/index.tsx @@ -0,0 +1,55 @@ +import { useI18n } from '@/hooks' +import { useMenuActions, useMenuGetters, useSettingGetters } from '@/store' +import type { AppMenuOption, NaiveMenuOptions } from '@/types' +import { NMenu } from 'naive-ui' +import { findMenuRoot, firstMenuLeaf } from '../../navigation' +import SiderBarLogo from '../Menu/components/SiderBarLogo' + +export default defineComponent({ + name: 'TopNavigation', + setup() { + const { t } = useI18n() + const { getMenuOptions, getMenuKey } = useMenuGetters() + const { getLayoutConfig, getMenuConfig } = useSettingGetters() + const { changeMenuModelValue } = useMenuActions() + const mixed = computed(() => getLayoutConfig.value.mode === 'mixed') + const options = computed(() => + mixed.value + ? getMenuOptions.value + .filter((option) => option.show !== false) + .map((option) => ({ ...option, children: void 0 })) + : getMenuOptions.value, + ) + const selected = computed(() => + mixed.value + ? findMenuRoot(getMenuOptions.value, String(getMenuKey.value))?.fullPath + : getMenuKey.value, + ) + const select = (key: string, option: AppMenuOption) => { + const root = mixed.value + ? getMenuOptions.value.find((item) => item.fullPath === key) + : option + const leaf = root && firstMenuLeaf(root) + + if (leaf) changeMenuModelValue(leaf.fullPath, leaf) + } + + return () => ( + + ) + }, +}) diff --git a/src/layout/default/ContentWrapper/index.scss b/src/layout/default/ContentWrapper/index.scss index d510cb37..8877c7ae 100644 --- a/src/layout/default/ContentWrapper/index.scss +++ b/src/layout/default/ContentWrapper/index.scss @@ -6,53 +6,13 @@ } } -.r-layout-full__viewer-content--maximize .layout-content__maximize-out { +.layout-content__maximize-out { position: fixed; - width: 80px; - height: 80px; - border-radius: 50%; - cursor: pointer; - z-index: 99; - right: -40px; - top: -40px; - @include flexCenter; - transition: - color 0.3s var(--r-bezier), - background-color 0.3s var(--r-bezier); - - & .r-icon { - transform: translate(-14px, 14px); - } + top: 12px; + right: 20px; + z-index: 1000; } -.r-template--light { - .layout-content__maximize-out { - background-color: #d5d3d1; - color: #44403c; - - &:hover { - color: #2c2a28; - background: #757473; - } - } -} - -.r-template--dark { - .layout-content__maximize-out { - background-color: #44403c; - color: #d5d3d1; - - &:hover { - color: #eae9e8; - background: #a19f9d; - } - } -} - -.r-template--dark .r-layout-full__viewer-content { - background-color: $layoutContentBackgroundColorDark; -} - -.r-template--light .r-layout-full__viewer-content { - background-color: $layoutContentBackgroundColorLight; +.r-layout-full__viewer-content { + background-color: var(--r-canvas); } diff --git a/src/layout/default/ContentWrapper/index.tsx b/src/layout/default/ContentWrapper/index.tsx index e030040a..100e6c24 100644 --- a/src/layout/default/ContentWrapper/index.tsx +++ b/src/layout/default/ContentWrapper/index.tsx @@ -1,23 +1,18 @@ -/** - * - * 使用 NSpin 组件实现 loading 效果 - * 默认添加 300ms 延迟 - */ - +import { useRuntimeGetters } from '@/store' import './index.scss' import AppRequestCancelerProvider from '@/app-components/provider/AppRequestCancelerProvider' import { LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE } from '@/app-config' import { RIcon, RTransitionComponent } from '@/components' -import { getVariable } from '@/global-variable' -import { useMaximize } from '@/hooks' +import { useI18n, useMaximize } from '@/hooks' import { useSettingGetters } from '@/store' -import { NSpin } from 'naive-ui' +import { NButton, NSpin } from 'naive-ui' import type { GlobalThemeOverrides } from 'naive-ui' export default defineComponent({ name: 'LayoutContentWrapper', setup() { const router = useRouter() + const { t } = useI18n() const { maximize } = useMaximize() const { getContentTransition } = useSettingGetters() @@ -29,16 +24,23 @@ export default defineComponent({ globalMainLayoutLoad, layoutContentMaximize, layoutContentSpinning, - } = getVariable() + } = useRuntimeGetters() const setupLayoutContentSpin = () => { - router.beforeEach(() => { + const removeBefore = router.beforeEach(() => { spinning.value = true }) - router.afterEach(() => { + const removeAfter = router.afterEach(() => { spinning.value = false }) + const removeError = router.onError(() => { + spinning.value = false + }) + + onScopeDispose(removeBefore) + onScopeDispose(removeAfter) + onScopeDispose(removeError) } if (LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE) { @@ -46,6 +48,7 @@ export default defineComponent({ } return { + t, globalMainLayoutLoad, spinning, themeOverridesSpin, @@ -69,7 +72,8 @@ export default defineComponent({ return ( {layoutContentMaximize ? ( -
{ maximize(false) }} > - -
+ +
) : null} {globalMainLayoutLoad ? ( diff --git a/src/layout/default/FooterWrapper/index.scss b/src/layout/default/FooterWrapper/index.scss index 86acdcd0..428c4fd7 100644 --- a/src/layout/default/FooterWrapper/index.scss +++ b/src/layout/default/FooterWrapper/index.scss @@ -1,13 +1,11 @@ .layout-footer-wrapper { - height: 48px; - text-align: center; - line-height: 48px; -} - -.r-template--dark .layout-footer-wrapper { - background-color: $layoutFooterBackgroundColorDark; -} - -.r-template--light .layout-footer-wrapper { - background-color: $layoutFooterBackgroundColorLight; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + border-top: 1px solid var(--r-line); + background: var(--r-surface); + color: var(--r-text-muted); + font-size: 12px; + letter-spacing: 0.01em; } diff --git a/src/layout/index.scss b/src/layout/index.scss index d48b2950..858530e1 100644 --- a/src/layout/index.scss +++ b/src/layout/index.scss @@ -2,36 +2,167 @@ position: fixed; inset: 0; - & .n-layout-scroll-container { - & .r-layout-full__viewer .n-layout-scroll-container { + .r-layout-full__viewer { + min-width: 0; + + > .n-layout-scroll-container { + display: flex; + flex-direction: column; overflow: hidden; - - & .r-layout-full__viewer-content { - height: var(--layout-content-height); - padding: 8px 16px; - - & .n-scrollbar-container { - height: 100%; - - & .n-scrollbar-content { - height: 100%; - } - } - - // 设置 content-wrapper 的样式 - .content-wrapper { - width: 100%; - height: 100%; - } - } + height: 100%; } } + + .r-layout-full__viewer-content { + flex: 1; + min-height: 0; + min-width: 0; + + > .n-scrollbar > .n-scrollbar-container { + height: 100%; + } + } + + .r-layout-content-inner { + box-sizing: border-box; + width: 100%; + max-width: var(--layout-content-max-width); + margin-inline: auto; + padding: var(--layout-content-padding); + min-height: 100%; + } + + .content-wrapper { + box-sizing: border-box; + width: 100%; + min-height: 100%; + } } -.r-template--light .r-layout-full__viewer-content { - box-shadow: 0 -1px 2px $layoutShadowColorLight; +.r-layout-top-navigation { + display: flex; + align-items: center; + min-width: 0; + padding-inline: 16px; + + .r-menu__logo { + flex-shrink: 0; + width: 200px; + } + + .n-menu { + flex: 1; + min-width: 0; + } } -.r-template--dark .r-layout-full__viewer-content { - box-shadow: 0 -1px 2px $layoutShadowColorDark; +.r-layout-content--maximized { + position: fixed !important; + inset: 0; + width: 100dvw !important; + height: 100dvh !important; +} + +.r-layout-settings { + container-type: inline-size; + + .n-form-item { + margin-block-end: 16px; + } +} + +.r-layout-presets .r-layout-preset { + flex: 1; + height: auto; + padding: 10px 4px; + + .n-button__content { + flex-direction: column; + gap: 8px; + } +} + +.r-layout-preview { + display: grid; + grid-template: 10px 30px / 14px 42px; + gap: 3px; + width: 59px; + + > span { + border-radius: 2px; + background: currentColor; + opacity: 0.25; + } + + &__aside { + grid-area: 1 / 1 / 3 / 2; + opacity: 0.65 !important; + } + + &__header { + grid-area: 1 / 2 / 2 / 3; + } + + &__body { + grid-area: 2 / 2 / 3 / 3; + } + + &--top { + .r-layout-preview__aside { + display: none; + } + .r-layout-preview__header { + grid-column: 1 / 3; + } + .r-layout-preview__body { + grid-column: 1 / 3; + } + } + + &--mixed .r-layout-preview__header { + opacity: 0.8; + } +} + +@container (max-width: 240px) { + .r-layout-presets { + flex-wrap: wrap !important; + } +} + +@media (max-width: 768px) { + .r-layout-full .r-layout-content-inner { + padding: min(var(--layout-content-padding), 16px); + } +} + +.r-layout-settings__hint { + color: var(--r-text-muted); + font-size: 12px; + line-height: 1.8; +} + +.r-layout-extension-description { + margin-block-end: 18px; + color: var(--r-text-secondary); + line-height: 1.8; +} + +.r-layout-presets .r-layout-preset { + padding: 18px 8px 14px; + border: 1px solid var(--r-line); + border-radius: 10px; + + &[aria-pressed='true'] { + border-color: currentColor; + box-shadow: 0 0 0 1px currentColor; + } +} + +.r-layout-preset__selected { + position: absolute; + inset-block-start: 5px; + inset-inline-end: 8px; + font-size: 12px; + font-weight: 600; } diff --git a/src/layout/index.tsx b/src/layout/index.tsx index f77b6abf..c71900eb 100644 --- a/src/layout/index.tsx +++ b/src/layout/index.tsx @@ -1,76 +1,149 @@ -/** - * - * 页面布局入口文件 - * - * 说明: - * - rayLayoutContentWrapperScopeSelector: 页面切换时重置滚动条注入 id(弃用) - * - * 该组件入口不做逻辑相关的处理, 仅做功能、组件、方法注入 - * 提供页面内 Layout 的一些注入(css vars 为主) - */ - import './index.scss' import useAppLockScreen from '@/app-components/app/AppLockScreen/appLockVar' import UnlockScreen from '@/app-components/app/AppLockScreen/components/UnlockScreen' import { LAYOUT_CONTENT_REF } from '@/app-config' +import { useDevice, useMaximize } from '@/hooks' import { layoutCssVars } from '@/layout/layout-css-vars' -import { useSettingGetters } from '@/store' +import { + useMenuGetters, + useRuntimeActions, + useRuntimeGetters, + useSettingGetters, +} from '@/store' +import { useEventListener } from '@vueuse/core' import { NLayout, NLayoutContent } from 'naive-ui' import Menu from './components/Menu' +import TopNavigation from './components/TopNavigation' import { ContentWrapper, FeatureWrapper, FooterWrapper, HeaderWrapper, } from './default' +import { findMenuRoot } from './navigation' export default defineComponent({ name: 'RLayout', - setup() { - const layoutSiderBarRef = shallowRef() // 顶部操作栏 shallowRef - const layoutMenuTagRef = shallowRef() // 标签页 shallowRef - const layoutFooterRef = shallowRef() // 底部版权 shallowRef - - const { getMenuTagSwitch, getCopyrightSwitch } = useSettingGetters() + setup(_, { slots }) { + const headerRef = shallowRef() + const tagsRef = shallowRef() + const footerRef = shallowRef() + const { getMenuTagSwitch, getCopyrightSwitch, getLayoutConfig } = + useSettingGetters() + const { getMenuOptions, getMenuKey } = useMenuGetters() + const { layoutContentMaximize, layoutContentMaximizeStyle } = + useRuntimeGetters() + const { setRuntimeState } = useRuntimeActions() + const { maximize } = useMaximize() + const { isTabletOrSmaller } = useDevice() const { getLockAppScreen } = useAppLockScreen() - const cssVarsRef = layoutCssVars([ - layoutSiderBarRef, - layoutMenuTagRef, - layoutFooterRef, - ]) + const cssVars = layoutCssVars([headerRef, tagsRef, footerRef]) + const mode = computed(() => + isTabletOrSmaller.value ? 'side' : getLayoutConfig.value.mode, + ) + const mixedChildren = computed( + () => + findMenuRoot( + getMenuOptions.value, + String(getMenuKey.value), + )?.children?.filter((option) => option.show !== false) ?? [], + ) - return { - getMenuTagSwitch, - cssVarsRef, - getLockAppScreen, - layoutSiderBarRef, - layoutMenuTagRef, - layoutFooterRef, - getCopyrightSwitch, + useEventListener(window, 'keydown', (event) => { + if (event.key === 'Escape' && layoutContentMaximize.value) maximize(false) + }) + onBeforeUnmount(() => setRuntimeState('layoutContentMaximize', false)) + + const header = () => ( +
+ {slots.header ? ( + slots.header() + ) : ( + <> + + {mode.value !== 'side' ? : null} + + )} +
+ ) + const tabs = () => + getMenuTagSwitch.value ? ( +
{slots.tabs?.() ?? }
+ ) : null + const footer = () => + getCopyrightSwitch.value ? ( +
{slots.footer?.() ?? }
+ ) : null + + return () => { + if (getLockAppScreen()) return + + const config = getLayoutConfig.value + const hasSider = + mode.value === 'side' || + (mode.value === 'mixed' && mixedChildren.value.length > 0) + + return ( + + {hasSider + ? (slots.sidebar?.() ?? ( + + )) + : null} + + {config.fixedHeader ? ( + <> + {header()} + {tabs()} + + ) : null} + + {!config.fixedHeader ? ( + <> + {header()} + {tabs()} + + ) : null} +
+ {slots.default?.() ?? } +
+ {!config.fixedFooter ? footer() : null} +
+ {config.fixedFooter ? footer() : null} +
+ + ) } }, - render() { - const { getMenuTagSwitch, cssVarsRef, getCopyrightSwitch } = this - const { getLockAppScreen } = this - - return !getLockAppScreen() ? ( - - - - - {getMenuTagSwitch ? : null} - - - - {getCopyrightSwitch ? : null} - - - ) : ( - - ) - }, }) diff --git a/src/layout/navigation.ts b/src/layout/navigation.ts new file mode 100644 index 00000000..147c9f61 --- /dev/null +++ b/src/layout/navigation.ts @@ -0,0 +1,25 @@ +import type { AppMenuOption } from '@/types' + +export function findMenuRoot( + options: AppMenuOption[], + key: string, +): AppMenuOption | undefined { + const contains = (option: AppMenuOption): boolean => + option.fullPath === key || !!option.children?.some(contains) + + return options.find((option) => option.show !== false && contains(option)) +} + +export function firstMenuLeaf( + option: AppMenuOption, +): AppMenuOption | undefined { + if (option.show === false) return + + if (!option.children?.length) return option + + for (const child of option.children) { + const leaf = firstMenuLeaf(child) + + if (leaf) return leaf + } +} diff --git a/src/locales/index.ts b/src/locales/index.ts index e185e0be..dce466fc 100644 --- a/src/locales/index.ts +++ b/src/locales/index.ts @@ -1,29 +1,26 @@ -/** - * - * 注册 `vue-i18n` - * - * 预设 `localeLanguage` 作为缓存 `key` - * - * 预设中文作为基础语言 - * - * `naive ui` 语言包切换 - * - * 注意: - * - 建议按照主流约定语言包命名 - */ - import { LOCAL_OPTIONS, SYSTEM_FALLBACK_LOCALE } from '@/app-config' import { getAppDefaultLanguage, getAppLocalMessages } from '@/locales/utils' import type { App } from 'vue' import { createI18n } from 'vue-i18n' import type { I18n, I18nOptions } from 'vue-i18n' -/** i18n 实例 */ -export let i18n: I18n +/** 已安装的国际化实例;热更新期间保留同一个实例。 */ +export let i18n: I18n | undefined = import.meta.hot?.data.i18n as + I18n | undefined + +if (import.meta.hot) { + import.meta.hot.dispose((data) => { + // 组件热更新不会重新安装 Vue 插件,保留语言和消息的原有引用。 + data.i18n = i18n + }) +} /** * - * 获取所有语言包,创建 i18n 实例 + * @description + * 加载本地语言包,并按缓存语言创建国际化实例。 + * + * @returns 尚未安装到应用的国际化实例 */ const createI18nOptions = async () => { const locale = getAppDefaultLanguage() @@ -44,9 +41,10 @@ const createI18nOptions = async () => { /** * - * @param app vue app instance + * @param app 需要注册国际化插件的 Vue 应用 * - * 注册 i18n,并且缓存实例 + * @description + * 安装国际化插件,并更新共享的国际化实例。 */ export const setupI18n = async (app: App) => { const i18nInstance = await createI18nOptions() diff --git a/src/locales/lang/en-US/dashboard.json b/src/locales/lang/en-US/dashboard.json new file mode 100644 index 00000000..c6194344 --- /dev/null +++ b/src/locales/lang/en-US/dashboard.json @@ -0,0 +1,31 @@ +{ + "title": "Your workspace is ready.", + "description": "Explore the components, layouts and tools that help you focus on building your application.", + "stateManagement": "Reactive state management", + "explore": "Explore the template", + "hooks": "Template Hooks", + "hooksDescription": "Interactive composable examples", + "layout": "Layout playground", + "layoutDescription": "Preview navigation and content layouts", + "icons": "SVG icon library", + "iconsDescription": "Packages and full-path completion", + "project": "Project overview", + "projectDescription": "A practical set of engineering defaults and development tools for a straightforward start to your application.", + "routing": "Routing & access", + "themeAndLocale": "Themes & locales", + "feedbackBefore": "Share your suggestions in", + "feedbackAfter": ".", + "author": "About the author", + "frameworks": "Frameworks", + "experience": "Experience", + "experienceValue": "A frontend learner with two and a half years of practice", + "bio": "Introduction", + "bioValue": "Work hard, take a break, and keep making things better.", + "linksTitle": "Documentation & learning resources", + "links": { + "notes": "Ray’s frontend notes", + "interviews": "Ray’s interview notes", + "docs": "Ray Template documentation", + "docsMirror": "Ray Template documentation (China)" + } +} diff --git a/src/locales/lang/en-US/hooks.json b/src/locales/lang/en-US/hooks.json new file mode 100644 index 00000000..79fd71c2 --- /dev/null +++ b/src/locales/lang/en-US/hooks.json @@ -0,0 +1,73 @@ +{ + "code": "View usage", + "templateIntro": "Template hooks: each example calls the real API. Theme, layout and home preferences are saved; use the corresponding reset actions to restore them.", + "webIntro": "Web and component hooks: interactive examples, reactive results and minimal usage snippets.", + "dark": "Dark", + "light": "Light", + "system": "System", + "toggle": "Toggle", + "spin": "Load for 800 ms", + "reload": "Remount current page", + "maximize": "Toggle content size (Esc to restore)", + "badgeLabel": "Badge label", + "show": "Show", + "hide": "Hide", + "update": "Update badge and icon", + "clearIcon": "Remove badge icon", + "watermarkText": "Watermark text", + "openWeb": "Open Web Hooks", + "openNested": "Open a nested menu", + "firstMenu": "Navigate to the first menu", + "useCurrentHome": "Use this page as home", + "restoreHome": "Restore dashboard home", + "closeOther": "Close other tabs", + "closeLeft": "Close tabs on the left", + "closeRight": "Close tabs on the right", + "closeCurrent": "Close current tab", + "closeAll": "Close all and return home", + "contentTop": "Scroll content to top", + "content300": "Scroll content to 300 px", + "siderTop": "Scroll sidebar to top", + "sider300": "Scroll sidebar to 300 px", + "smallScreen": "Tablet or phone (≤768 px)", + "desktop": "Desktop (>768 px)", + "pageTwo": "Go to page 2", + "pageSize20": "20 rows per page", + "reset": "Reset", + "date": "Date (YYYY-MM-DD)", + "refreshDate": "Refresh today’s range", + "updateQuery": "Update query parameters", + "openTemplate": "Open Template Hooks", + "captureTarget": "Local example content for element fullscreen, image capture and printing.", + "exitFullscreen": "Exit element fullscreen", + "toggleElementFullscreen": "Toggle element fullscreen", + "capture": "Generate PNG preview", + "capturePreview": "PNG capture of the example content", + "print": "Open print preview", + "rightClick": "Right-click here to open the menu. Click outside or press Esc to close.", + "stopped": "Stopped (reload the page to retry)", + "stop": "Stop listening and close menu", + "contextCopy": "Copy example", + "contextInspect": "Inspect coordinates", + "descriptions": { + "useTheme": "Switch themes and read the current theme. System mode keeps responding to OS theme changes.", + "useSpinning": "Control the content loading overlay or remount the current page. The latest reload controls when content returns.", + "useMaximize": "Maximize layout content. Pages, tab menus and restore controls share the same state. Esc restores it.", + "useBadge": "Show, update or hide a menu badge by path, including its icon.", + "useWatermark": "Update the global watermark and control visibility. An empty string keeps the previous text.", + "useAppNavigation": "Navigate by menu object, full path or zero-based top-level index. Returns an awaitable navigation result.", + "useAppRoot": "Read and update the home route, used when all tabs are closed.", + "useSiderBar": "Close tabs and their neighbors by path, index or tab object.", + "useContentScroll": "Obtain a scroll function in setup. Each call resolves the current layout instance.", + "useSiderScroll": "Scroll the current sidebar. Safely does nothing when top navigation has no sidebar.", + "useDevice": "Observe viewport size and apply a custom tablet breakpoint. Resize the window to see changes.", + "usePagination": "Bind pagination to Naive UI. Page-size changes reset the page; resetting also invokes the business callback.", + "useDayjs": "Format dates, calculate day differences, test exclusive ranges and obtain today’s boundaries.", + "useI18n": "Use namespaced or full translation keys. The settings store synchronizes locale across the app.", + "useVueRouter": "Access the same Router inside or outside setup, including its reactive current route.", + "useElementFullscreen": "Maximize an element with CSS. Exit or scope disposal restores its original styles.", + "useDomToImage": "Capture the area above. Configure a default format or override it in create. Errors appear below.", + "usePrint": "Pass an element ref to print-js. The button opens the browser’s print interface.", + "useContextmenuCoordinate": "Track right-click coordinates for NDropdown, with outside-click dismissal and complete listener cleanup." + } +} diff --git a/src/locales/lang/en-US/icons.json b/src/locales/lang/en-US/icons.json new file mode 100644 index 00000000..b44f0b28 --- /dev/null +++ b/src/locales/lang/en-US/icons.json @@ -0,0 +1,9 @@ +{ + "title": "SVG icon library", + "description": "Browse icons by package and click to copy their full-path usage. Icon edits automatically synchronize types and asset references.", + "search": "Search icon paths", + "allPackages": "All packages", + "copy": "Click an icon to copy TSX usage", + "empty": "No matching icons", + "packagesLabel": "packages" +} diff --git a/src/locales/lang/en-US/layout.json b/src/locales/lang/en-US/layout.json new file mode 100644 index 00000000..fef3c398 --- /dev/null +++ b/src/locales/lang/en-US/layout.json @@ -0,0 +1,24 @@ +{ + "title": "Layout playground", + "description": "Changes apply immediately and are saved automatically. Mixed navigation shows the current section’s children. Small screens use a drawer while retaining desktop preferences.", + "side": "Sidebar", + "top": "Top", + "mixed": "Mixed", + "contentWidth": "Content width", + "fluid": "Fluid", + "fixed": "Centered", + "maxWidth": "Maximum content width (px)", + "padding": "Content padding (px)", + "fixedHeader": "Fixed header", + "fixedFooter": "Fixed footer", + "reset": "Reset layout", + "current": "Current configuration", + "extension": "Extend the layout", + "slots": "Use header, sidebar, tabs, footer and default content slots. Update the Pinia configuration to switch layouts.", + "navigation": "Main navigation", + "restore": "Restore content size (Esc)", + "loading": "Loading", + "tab": "Layout", + "toggleMenu": "Open navigation menu", + "language": "Change language" +} diff --git a/src/locales/lang/en-US/menu.json b/src/locales/lang/en-US/menu.json index 8ef9d153..07029c18 100644 --- a/src/locales/lang/en-US/menu.json +++ b/src/locales/lang/en-US/menu.json @@ -30,6 +30,8 @@ "Table": "Table", "TableAutoHeight": "Table Auto Height", "TablePro": "Table Pro", - "TemplateHooks": "Template Api", - "scrollReveal": "Scroll Reveal" + "TemplateHooks": "Template Hooks", + "scrollReveal": "Scroll Reveal", + "LayoutDemo": "Layout playground", + "WebHooks": "Web Hooks" } diff --git a/src/locales/lang/en-US/showcase.json b/src/locales/lang/en-US/showcase.json new file mode 100644 index 00000000..fbdd4148 --- /dev/null +++ b/src/locales/lang/en-US/showcase.json @@ -0,0 +1,19 @@ +{ + "preview": "Interactive example", + "code": "View usage", + "copyCode": "Copy code", + "templateTitle": "Template Hooks", + "templateEyebrow": "COMPOSABLES / TEMPLATE", + "webTitle": "Web Hooks", + "webEyebrow": "COMPOSABLES / WEB", + "appearanceAndPage": "Appearance & page state", + "globalMarkers": "Global markers", + "navigationAndTabs": "Navigation & tabs", + "scrollControls": "Scroll controls", + "commonUtilities": "Common utilities", + "browserCapabilities": "Browser capabilities", + "layoutEyebrow": "WORKSPACE / LAYOUT", + "iconsEyebrow": "ASSETS / ICONS", + "livePreferences": "Live preview · Saved automatically", + "layoutControls": "Layout & display" +} diff --git a/src/locales/lang/zh-CN/dashboard.json b/src/locales/lang/zh-CN/dashboard.json new file mode 100644 index 00000000..9290a83b --- /dev/null +++ b/src/locales/lang/zh-CN/dashboard.json @@ -0,0 +1,31 @@ +{ + "title": "工作空间,准备就绪。", + "description": "从常用能力开始,探索组件、布局与工具,让业务开发更从容。", + "stateManagement": "响应式状态管理", + "explore": "探索模板能力", + "hooks": "模板 Hooks", + "hooksDescription": "交互示例与组合式能力", + "layout": "布局实验室", + "layoutDescription": "即时调整导航与内容显示", + "icons": "SVG 图标库", + "iconsDescription": "分包浏览与完整路径提示", + "project": "项目概览", + "projectDescription": "预设常用工程配置与开发工具,提供简洁、快速上手的业务开发起点。", + "routing": "路由与权限", + "themeAndLocale": "主题与国际化", + "feedbackBefore": "欢迎在", + "feedbackAfter": "中提出建议。", + "author": "关于作者", + "frameworks": "常用框架", + "experience": "开发经历", + "experienceValue": "练习时长两年半的小白前端搬砖师", + "bio": "个人介绍", + "bioValue": "努力搬砖、努力摸鱼,建设美丽家园。", + "linksTitle": "文档与学习资源", + "links": { + "notes": "Ray 的前端学习笔记", + "interviews": "Ray 的面试题总结", + "docs": "Ray Template 文档", + "docsMirror": "Ray Template 文档(国内)" + } +} diff --git a/src/locales/lang/zh-CN/hooks.json b/src/locales/lang/zh-CN/hooks.json new file mode 100644 index 00000000..1031e6be --- /dev/null +++ b/src/locales/lang/zh-CN/hooks.json @@ -0,0 +1,73 @@ +{ + "code": "查看用法", + "templateIntro": "模板 Hooks:每个示例都调用真实接口。主题、布局和首页偏好会自动保存,可通过相应按钮恢复。", + "webIntro": "Web 与组件 Hooks:交互演示、响应式结果和可复制的最小用法。", + "dark": "暗色", + "light": "亮色", + "system": "跟随系统", + "toggle": "切换", + "spin": "加载 800ms", + "reload": "重新挂载当前页面", + "maximize": "切换内容最大化(Esc 退出)", + "badgeLabel": "菜单标记内容", + "show": "显示", + "hide": "隐藏", + "update": "更新标记和图标", + "clearIcon": "移除标记图标", + "watermarkText": "水印内容", + "openWeb": "打开 Web Hooks", + "openNested": "跳转到嵌套菜单", + "firstMenu": "导航到第一个菜单", + "useCurrentHome": "将本页设为首页", + "restoreHome": "恢复仪表盘首页", + "closeOther": "关闭其他标签", + "closeLeft": "关闭左侧标签", + "closeRight": "关闭右侧标签", + "closeCurrent": "关闭当前标签", + "closeAll": "关闭全部并返回首页", + "contentTop": "内容滚动到顶部", + "content300": "内容滚动到 300px", + "siderTop": "侧栏滚动到顶部", + "sider300": "侧栏滚动到 300px", + "smallScreen": "平板或手机(≤768px)", + "desktop": "桌面(>768px)", + "pageTwo": "跳到第 2 页", + "pageSize20": "每页 20 条", + "reset": "重置", + "date": "日期(YYYY-MM-DD)", + "refreshDate": "刷新今天的范围", + "updateQuery": "更新查询参数", + "openTemplate": "打开模板 Hooks", + "captureTarget": "用于元素全屏、截图和打印的本地演示区域。", + "exitFullscreen": "退出元素全屏", + "toggleElementFullscreen": "切换元素全屏", + "capture": "生成 PNG 预览", + "capturePreview": "演示区域的 PNG 截图", + "print": "打开打印预览", + "rightClick": "在此右击打开菜单;点击外部或按 Esc 关闭。", + "stopped": "已停止监听(刷新页面可重试)", + "stop": "停止监听并关闭菜单", + "contextCopy": "复制示例", + "contextInspect": "查看坐标", + "descriptions": { + "useTheme": "切换明暗主题,读取当前主题;跟随系统后会持续响应系统主题变化。", + "useSpinning": "控制内容区加载动画,或通过卸载并重新挂载刷新当前页面。重复刷新以最后一次为准。", + "useMaximize": "将布局内容最大化,页面、标签菜单与退出按钮共享状态。支持 Esc 退出。", + "useBadge": "按菜单路径显示、更新和隐藏徽标,也可以更新标记图标。", + "useWatermark": "更新全局水印文本并控制显示。空字符串沿用上一次内容。", + "useAppNavigation": "支持菜单对象、完整路径和从 0 开始的一级菜单索引,返回可等待的导航结果。", + "useAppRoot": "读取和更新应用首页;关闭所有标签后会导航至此。", + "useSiderBar": "按路径、索引或标签对象关闭指定标签及其相邻标签。", + "useContentScroll": "在 setup 中获取滚动方法,执行时使用当前布局实例。", + "useSiderScroll": "滚动当前侧栏;顶部导航没有侧栏,调用时会安全忽略。", + "useDevice": "观察窗口尺寸并按自定义断点判断是否为平板或更小设备。缩放窗口查看结果。", + "usePagination": "将分页状态绑定至 Naive UI,切换每页条数会重置页码;重置会调用业务回调。", + "useDayjs": "格式化日期、计算天数差、检查开区间并获取今天的开始和结束。", + "useI18n": "支持命名空间和完整键名,语言通过设置 Store 同步到应用。", + "useVueRouter": "在 setup 内外访问同一个 Router 实例,保留响应式当前路由。", + "useElementFullscreen": "通过 CSS 最大化指定元素,退出或作用域销毁后恢复原有样式。", + "useDomToImage": "将上方区域转换为图片。配置默认格式,也可以调用 create 时覆盖格式;错误会显示在此。", + "usePrint": "将元素 ref 交给 print-js,按钮触发浏览器打印界面。", + "useContextmenuCoordinate": "记录右键坐标并驱动 NDropdown,支持关闭、外部点击和彻底停止监听。" + } +} diff --git a/src/locales/lang/zh-CN/icons.json b/src/locales/lang/zh-CN/icons.json new file mode 100644 index 00000000..c80ecdfe --- /dev/null +++ b/src/locales/lang/zh-CN/icons.json @@ -0,0 +1,9 @@ +{ + "title": "SVG 图标库", + "description": "按分包浏览图标,点击即可复制完整路径用法。图标变更会自动同步类型提示和资源引用。", + "search": "搜索图标路径", + "allPackages": "全部分包", + "copy": "点击图标复制 TSX 用法", + "empty": "没有匹配的图标", + "packagesLabel": "分包" +} diff --git a/src/locales/lang/zh-CN/layout.json b/src/locales/lang/zh-CN/layout.json new file mode 100644 index 00000000..0ffcedc5 --- /dev/null +++ b/src/locales/lang/zh-CN/layout.json @@ -0,0 +1,24 @@ +{ + "title": "布局实验室", + "description": "配置即时生效并自动保存。混合导航显示当前一级菜单的子菜单;窄屏自动使用抽屉导航,保留桌面偏好。", + "side": "侧边导航", + "top": "顶部导航", + "mixed": "混合导航", + "contentWidth": "内容宽度", + "fluid": "流式铺满", + "fixed": "定宽居中", + "maxWidth": "内容最大宽度(px)", + "padding": "内容间距(px)", + "fixedHeader": "固定顶栏", + "fixedFooter": "固定页脚", + "reset": "恢复默认布局", + "current": "当前布局配置", + "extension": "扩展布局", + "slots": "布局提供 header、sidebar、tabs、footer 和默认内容插槽。通过 Pinia 更新配置即可切换布局。", + "navigation": "主导航", + "restore": "退出内容最大化(Esc)", + "loading": "正在加载", + "tab": "布局", + "toggleMenu": "打开导航菜单", + "language": "切换语言" +} diff --git a/src/locales/lang/zh-CN/menu.json b/src/locales/lang/zh-CN/menu.json index 51e2a30b..0d5b506f 100644 --- a/src/locales/lang/zh-CN/menu.json +++ b/src/locales/lang/zh-CN/menu.json @@ -30,6 +30,8 @@ "Table": "表格", "TableAutoHeight": "自适应高度表格", "TablePro": "高级表格", - "TemplateHooks": "模板内置 Api", - "scrollReveal": "滚动动画" + "TemplateHooks": "模板 Hooks", + "scrollReveal": "滚动动画", + "LayoutDemo": "布局实验室", + "WebHooks": "Web Hooks" } diff --git a/src/locales/lang/zh-CN/showcase.json b/src/locales/lang/zh-CN/showcase.json new file mode 100644 index 00000000..67e04164 --- /dev/null +++ b/src/locales/lang/zh-CN/showcase.json @@ -0,0 +1,19 @@ +{ + "preview": "交互演示", + "code": "查看用法", + "copyCode": "复制代码", + "templateTitle": "模板 Hooks", + "templateEyebrow": "COMPOSABLES / TEMPLATE", + "webTitle": "Web Hooks", + "webEyebrow": "COMPOSABLES / WEB", + "appearanceAndPage": "外观与页面控制", + "globalMarkers": "全局标记", + "navigationAndTabs": "导航与标签", + "scrollControls": "滚动控制", + "commonUtilities": "通用工具", + "browserCapabilities": "浏览器能力", + "layoutEyebrow": "WORKSPACE / LAYOUT", + "iconsEyebrow": "ASSETS / ICONS", + "livePreferences": "即时预览 · 自动保存", + "layoutControls": "布局与显示" +} diff --git a/src/router/README.md b/src/router/README.md index 63d4fe28..050feb36 100644 --- a/src/router/README.md +++ b/src/router/README.md @@ -19,7 +19,7 @@ const demo: AppRouteRecordRaw = { meta: { /** t 方法是一个纯函数,为了配合 i18n ally 插件提示使用 */ i18nKey: t('menu.Demo'), - icon: 'demo', + icon: 'navigation/other', order: 0, }, children: [ @@ -29,7 +29,7 @@ const demo: AppRouteRecordRaw = { component: () => import('@/views/demo-child/index'), meta: { i18nKey: t('menu.DemoChild'), - icon: 'demo', + icon: 'navigation/other', order: 0, }, }, @@ -45,7 +45,7 @@ export default dashboard interface RouteMeta { order?: number i18nKey: string - icon?: string + icon?: IconName windowOpen?: string role?: string[] hidden?: boolean @@ -95,7 +95,7 @@ const demo = { name: 'MultiMenu', meta: { i18nKey: 'MultiMenu', - icon: 'table', + icon: 'navigation/table', }, children: [ { @@ -158,3 +158,5 @@ const transform = [ }, ] ``` + +图标使用分包路径 `IconName`,例如 `directional/resize_h`,详见 [图标类型与生成流程](../icons/A_README.md)。 diff --git a/src/router/app-route-modules.ts b/src/router/app-route-modules.ts index 15680774..12a320ec 100644 --- a/src/router/app-route-modules.ts +++ b/src/router/app-route-modules.ts @@ -1,22 +1,23 @@ -/** - * - * 描述: - * - 自动导入所有路由模块 - * - 平铺所有路由 - * - * modules 模块下每一个 ts 文件视为一个路由模块(route) - * 每个模块必须配置 meta 属性 - * 如果不设置 order 属性, 则会默认排在前面 - */ - import { combineRawRouteModules, expandRoutes, orderRoutes, } from '@/router/utils' -/** 获取所有被合并与排序的路由 */ +/** + * + * @description + * 收集并按 meta.order 排序路由模块。 + * + * @returns 合并后的路由记录列表 + */ export const getAppRawRoutes = () => orderRoutes(combineRawRouteModules()) -/** 获取所有平铺展开的路由 */ +/** + * + * @description + * 将模块路由展开为平铺记录。 + * + * @returns 平铺后的路由记录列表 + */ export const appExpandRoutes = () => expandRoutes(getAppRawRoutes()) diff --git a/src/router/constant/index.ts b/src/router/constant/index.ts index 226026e9..5bed6cc4 100644 --- a/src/router/constant/index.ts +++ b/src/router/constant/index.ts @@ -1,19 +1 @@ -/** - * - * default layout - * - * 默认布局, 统一使用该组件管理右侧现实内容区域展示 - * - * @example - * 使用示例: - * ``` - * { - * path: '/axios', - * name: 'Axios', - * component: LAYOUT, - * meta: { ... }, - * children: [ { ... } ] - * } - * ``` - */ export const LAYOUT = () => import('@/layout/default/ContentWrapper') diff --git a/src/router/modules/dashboard.ts b/src/router/modules/dashboard.ts index ffff3183..8156a2f8 100644 --- a/src/router/modules/dashboard.ts +++ b/src/router/modules/dashboard.ts @@ -7,7 +7,7 @@ const dashboard: AppRouteRecordRaw = { component: () => import('@/views/dashboard'), meta: { i18nKey: t('menu.Dashboard'), - icon: 'dashboard', + icon: 'navigation/dashboard', order: 0, }, } diff --git a/src/router/modules/demo/axios.ts b/src/router/modules/demo/axios.ts index 1477c53d..d4292a67 100644 --- a/src/router/modules/demo/axios.ts +++ b/src/router/modules/demo/axios.ts @@ -8,7 +8,7 @@ const axios: AppRouteRecordRaw = { component: () => import('@/views/demo/axios/index'), meta: { i18nKey: t('menu.Axios'), - icon: 'axios', + icon: 'logo/axios', order: 3, keepAlive: true, }, diff --git a/src/router/modules/demo/barcode.ts b/src/router/modules/demo/barcode.ts index f9b035f0..7d25dc2d 100644 --- a/src/router/modules/demo/barcode.ts +++ b/src/router/modules/demo/barcode.ts @@ -7,7 +7,7 @@ const barcode: AppRouteRecordRaw = { component: () => import('@/views/demo/barcode-demo'), meta: { i18nKey: t('menu.Barcode'), - icon: 'other', + icon: 'navigation/other', order: 2, extra: { label: 'new', diff --git a/src/router/modules/demo/cache-demo.ts b/src/router/modules/demo/cache-demo.ts index 02715891..998a360f 100644 --- a/src/router/modules/demo/cache-demo.ts +++ b/src/router/modules/demo/cache-demo.ts @@ -7,7 +7,7 @@ const cacheDemo: AppRouteRecordRaw = { component: () => import('@/views/demo/cache-demo/index'), meta: { i18nKey: t('menu.CacheDemo'), - icon: 'other', + icon: 'navigation/other', order: 3, }, } diff --git a/src/router/modules/demo/context-menu.ts b/src/router/modules/demo/context-menu.ts index acd160e5..4429ad6b 100644 --- a/src/router/modules/demo/context-menu.ts +++ b/src/router/modules/demo/context-menu.ts @@ -6,7 +6,7 @@ const contextMenu: AppRouteRecordRaw = { component: () => import('@/views/demo/context-menu/index'), meta: { i18nKey: t('menu.ContextMenu'), - icon: 'other', + icon: 'navigation/other', order: 2, }, } diff --git a/src/router/modules/demo/directive.ts b/src/router/modules/demo/directive.ts index 537be459..e84d817a 100644 --- a/src/router/modules/demo/directive.ts +++ b/src/router/modules/demo/directive.ts @@ -7,7 +7,7 @@ const directive: AppRouteRecordRaw = { component: () => import('@/views/demo/directive/index'), meta: { i18nKey: t('menu.Directive'), - icon: 'other', + icon: 'navigation/other', order: 2, extra: { label: 'ellipsis', diff --git a/src/router/modules/demo/draggable-card.ts b/src/router/modules/demo/draggable-card.ts index b25b0c4a..eaf0fc5c 100644 --- a/src/router/modules/demo/draggable-card.ts +++ b/src/router/modules/demo/draggable-card.ts @@ -7,7 +7,7 @@ const r: AppRouteRecordRaw = { component: () => import('@/views/demo/draggable-card'), meta: { i18nKey: t('menu.DraggableCard'), - icon: 'other', + icon: 'navigation/other', order: 2, extra: { label: 'drag', diff --git a/src/router/modules/demo/echart.ts b/src/router/modules/demo/echart.ts index 833a67f4..604226b6 100644 --- a/src/router/modules/demo/echart.ts +++ b/src/router/modules/demo/echart.ts @@ -7,7 +7,7 @@ const echart: AppRouteRecordRaw = { component: () => import('@/views/demo/echart/index'), meta: { i18nKey: t('menu.Echart'), - icon: 'echart', + icon: 'navigation/echart', order: 1, extra: { label: 'useChart', diff --git a/src/router/modules/demo/flow.ts b/src/router/modules/demo/flow.ts index 4a3f3d2e..f46ca2e8 100644 --- a/src/router/modules/demo/flow.ts +++ b/src/router/modules/demo/flow.ts @@ -7,7 +7,7 @@ const r: AppRouteRecordRaw = { component: () => import('@/views/demo/flow-demo'), meta: { i18nKey: t('menu.Flow'), - icon: 'other', + icon: 'navigation/other', order: 2, }, } diff --git a/src/router/modules/demo/form.ts b/src/router/modules/demo/form.ts index 6696bdf9..f196104c 100644 --- a/src/router/modules/demo/form.ts +++ b/src/router/modules/demo/form.ts @@ -7,7 +7,7 @@ const form: AppRouteRecordRaw = { component: () => import('@/views/demo/form'), meta: { i18nKey: t('menu.Form'), - icon: 'other', + icon: 'navigation/other', order: 2, extra: { label: 'useForm', diff --git a/src/router/modules/demo/iframe.ts b/src/router/modules/demo/iframe.ts index fe7209ce..6fcbbc53 100644 --- a/src/router/modules/demo/iframe.ts +++ b/src/router/modules/demo/iframe.ts @@ -5,7 +5,7 @@ const iframe: AppRouteRecordRaw = { path: '/iframe', component: () => import('@/views/demo/iframe/index'), meta: { - icon: 'other', + icon: 'navigation/other', order: 2, noLocalTitle: 'iframe', }, diff --git a/src/router/modules/demo/layout.ts b/src/router/modules/demo/layout.ts new file mode 100644 index 00000000..4a8b57a3 --- /dev/null +++ b/src/router/modules/demo/layout.ts @@ -0,0 +1,9 @@ +import { t } from '@/hooks/web/useI18n' +import type { AppRouteRecordRaw } from '@/router/types' + +export default { + path: '/layout-demo', + name: 'LayoutDemo', + component: () => import('@/views/demo/layout-demo'), + meta: { i18nKey: t('menu.LayoutDemo'), icon: 'navigation/menu', order: 1 }, +} satisfies AppRouteRecordRaw diff --git a/src/router/modules/demo/mock.ts b/src/router/modules/demo/mock.ts index 8b3fbe5c..2f0014e3 100644 --- a/src/router/modules/demo/mock.ts +++ b/src/router/modules/demo/mock.ts @@ -7,7 +7,7 @@ const mockDemo: AppRouteRecordRaw = { component: () => import('@/views/demo/mock-demo/index'), meta: { i18nKey: t('menu.Mock'), - icon: 'other', + icon: 'navigation/other', order: 3, keepAlive: false, extra: { diff --git a/src/router/modules/demo/modal.ts b/src/router/modules/demo/modal.ts index 5d440a01..e82f643e 100644 --- a/src/router/modules/demo/modal.ts +++ b/src/router/modules/demo/modal.ts @@ -7,7 +7,7 @@ const mockDemo: AppRouteRecordRaw = { component: () => import('@/views/demo/modal-demo/index'), meta: { i18nKey: t('menu.Modal'), - icon: 'other', + icon: 'navigation/other', order: 3, }, } diff --git a/src/router/modules/demo/multi-menu.ts b/src/router/modules/demo/multi-menu.ts index 9a90cafd..0fdd4b35 100644 --- a/src/router/modules/demo/multi-menu.ts +++ b/src/router/modules/demo/multi-menu.ts @@ -7,7 +7,7 @@ const multiMenu: AppRouteRecordRaw = { component: LAYOUT, meta: { i18nKey: t('menu.MultiMenu'), - icon: 'other', + icon: 'navigation/other', order: 4, extra: { label: 'cache', diff --git a/src/router/modules/demo/precision.ts b/src/router/modules/demo/precision.ts index f1f2ea42..4340ebd4 100644 --- a/src/router/modules/demo/precision.ts +++ b/src/router/modules/demo/precision.ts @@ -7,7 +7,7 @@ const precision: AppRouteRecordRaw = { component: () => import('@/views/demo/precision/index'), meta: { i18nKey: t('menu.CalculatePrecision'), - icon: 'other', + icon: 'navigation/other', order: 2, }, } diff --git a/src/router/modules/demo/qrcode.ts b/src/router/modules/demo/qrcode.ts index c46a6f9f..14c91bfb 100644 --- a/src/router/modules/demo/qrcode.ts +++ b/src/router/modules/demo/qrcode.ts @@ -7,7 +7,7 @@ const qrcode: AppRouteRecordRaw = { component: () => import('@/views/demo/qrcode/index'), meta: { i18nKey: t('menu.QRCode'), - icon: 'other', + icon: 'navigation/other', order: 2, }, } diff --git a/src/router/modules/demo/rely.ts b/src/router/modules/demo/rely.ts index f21cefd5..2e4931e0 100644 --- a/src/router/modules/demo/rely.ts +++ b/src/router/modules/demo/rely.ts @@ -7,7 +7,7 @@ const rely: AppRouteRecordRaw = { component: () => import('@/views/demo/rely/views/rely-about/index'), meta: { i18nKey: t('menu.RelyAbout'), - icon: 'rely', + icon: 'navigation/rely', order: 999, }, } diff --git a/src/router/modules/demo/router-demo.ts b/src/router/modules/demo/router-demo.ts index f5ab8098..d81eba6d 100644 --- a/src/router/modules/demo/router-demo.ts +++ b/src/router/modules/demo/router-demo.ts @@ -7,7 +7,7 @@ const routerDemo: AppRouteRecordRaw = { component: LAYOUT, meta: { i18nKey: t('menu.RouterDemo'), - icon: 'other', + icon: 'navigation/other', order: 3, }, children: [ diff --git a/src/router/modules/demo/scroll-reveal.ts b/src/router/modules/demo/scroll-reveal.ts index cc93f0b9..ae2b6412 100644 --- a/src/router/modules/demo/scroll-reveal.ts +++ b/src/router/modules/demo/scroll-reveal.ts @@ -1,9 +1,3 @@ -/** - * - * 由于还未找到如何解决 scrollReveal 插件问题 - * 所以暂时隐藏该页面 - */ - import { t } from '@/hooks/web/useI18n' import { LAYOUT } from '@/router/constant' import type { AppRouteRecordRaw } from '@/router/types' @@ -13,7 +7,7 @@ const scrollReveal: AppRouteRecordRaw = { component: () => import('@/views/demo/scroll-reveal/index'), meta: { i18nKey: t('menu.scrollReveal'), - icon: 'scroll_reveal', + icon: 'navigation/other', hidden: true, }, } diff --git a/src/router/modules/demo/segment.ts b/src/router/modules/demo/segment.ts index dfe243ec..689289ff 100644 --- a/src/router/modules/demo/segment.ts +++ b/src/router/modules/demo/segment.ts @@ -7,7 +7,7 @@ const segment: AppRouteRecordRaw = { component: () => import('@/views/demo/segment'), meta: { i18nKey: t('menu.Segment'), - icon: 'other', + icon: 'navigation/other', order: 3, extra: { label: 'segment', diff --git a/src/router/modules/demo/svg-icons.ts b/src/router/modules/demo/svg-icons.ts index 47095294..fe08a8dc 100644 --- a/src/router/modules/demo/svg-icons.ts +++ b/src/router/modules/demo/svg-icons.ts @@ -7,7 +7,7 @@ const previewSVGIcons: AppRouteRecordRaw = { component: () => import('@/views/demo/svg-icons/index'), meta: { i18nKey: t('menu.SvgIcon'), - icon: 'other', + icon: 'navigation/other', order: 3, }, } diff --git a/src/router/modules/demo/table-auto-height.ts b/src/router/modules/demo/table-auto-height.ts index e2518b0e..9d2d9e9b 100644 --- a/src/router/modules/demo/table-auto-height.ts +++ b/src/router/modules/demo/table-auto-height.ts @@ -8,7 +8,7 @@ const axios: AppRouteRecordRaw = { component: () => import('@/views/demo/table-auto-height'), meta: { i18nKey: t('menu.TableAutoHeight'), - icon: 'other', + icon: 'navigation/other', order: 3, extra: { label: 'new', diff --git a/src/router/modules/demo/table-pro.ts b/src/router/modules/demo/table-pro.ts index cc60c3ea..f4d1cf5f 100644 --- a/src/router/modules/demo/table-pro.ts +++ b/src/router/modules/demo/table-pro.ts @@ -7,7 +7,7 @@ const r: AppRouteRecordRaw = { component: () => import('@/views/demo/table-pro-demo'), meta: { i18nKey: t('menu.TablePro'), - icon: 'other', + icon: 'navigation/other', order: 2, extra: { label: 'TablePro', diff --git a/src/router/modules/demo/table.ts b/src/router/modules/demo/table.ts index b01d0f35..273c2823 100644 --- a/src/router/modules/demo/table.ts +++ b/src/router/modules/demo/table.ts @@ -7,7 +7,7 @@ const table: AppRouteRecordRaw = { component: () => import('@/views/demo/table/index'), meta: { i18nKey: t('menu.Table'), - icon: 'other', + icon: 'navigation/other', order: 2, extra: { label: 'useTable', diff --git a/src/router/modules/demo/template-hooks.ts b/src/router/modules/demo/template-hooks.ts index aa1a5025..dcd8f422 100644 --- a/src/router/modules/demo/template-hooks.ts +++ b/src/router/modules/demo/template-hooks.ts @@ -4,10 +4,11 @@ import type { AppRouteRecordRaw } from '@/router/types' const axios: AppRouteRecordRaw = { path: '/template-hooks', + name: 'TemplateHooks', component: () => import('@/views/demo/template-hooks/index'), meta: { i18nKey: t('menu.TemplateHooks'), - icon: 'other', + icon: 'navigation/other', order: 1, }, } diff --git a/src/router/modules/demo/web-hooks.ts b/src/router/modules/demo/web-hooks.ts new file mode 100644 index 00000000..27f1610a --- /dev/null +++ b/src/router/modules/demo/web-hooks.ts @@ -0,0 +1,9 @@ +import { t } from '@/hooks/web/useI18n' +import type { AppRouteRecordRaw } from '@/router/types' + +export default { + path: '/web-hooks', + name: 'WebHooks', + component: () => import('@/views/demo/hooks/web-hooks'), + meta: { i18nKey: t('menu.WebHooks'), icon: 'action/mouse', order: 1 }, +} satisfies AppRouteRecordRaw diff --git a/src/router/routes.ts b/src/router/routes.ts index a651f266..6ee7a587 100644 --- a/src/router/routes.ts +++ b/src/router/routes.ts @@ -33,7 +33,7 @@ export default [ component: () => import('@/views/error/views/Error404'), meta: { i18nKey: t('menu.Error'), - icon: 'error', + icon: 'status/error', hidden: true, sameLevel: true, }, diff --git a/src/router/types.ts b/src/router/types.ts index df5320e4..b41d9273 100644 --- a/src/router/types.ts +++ b/src/router/types.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable @typescript-eslint/no-explicit-any */ +import type { IconName } from '@/icons/manifest' import type { Recordable } from '@/types' import type { TagProps } from 'naive-ui' import type { DefineComponent, VNode } from 'vue' @@ -57,7 +58,7 @@ export interface AppRouteMeta { * 如果配置为 string,则会自动使用 RIcon 尝试获取 icons 包下的图标。 * VNode 类型,会直接使用传递图标渲染。 */ - icon?: string | VNode + icon?: IconName | VNode /** * * @description diff --git a/src/router/utils/expand-routes.ts b/src/router/utils/expand-routes.ts index 3f5103c4..6873a444 100644 --- a/src/router/utils/expand-routes.ts +++ b/src/router/utils/expand-routes.ts @@ -1,11 +1,3 @@ -/** - * - * 该功能基于 提供代码改进实现 - * - * 自动展开所有路由 - * 把所有路由提升为顶层路由 - */ - import type { AppRouteRecordRaw } from '@/router/types' import { cloneDeep } from 'lodash-es' diff --git a/src/router/utils/permission.ts b/src/router/utils/permission.ts index bd6e9c79..ce6f4dba 100644 --- a/src/router/utils/permission.ts +++ b/src/router/utils/permission.ts @@ -1,13 +1,17 @@ -/** - * 路由权限由 token、白名单和 meta.role 共同决定;实际后端仍须独立鉴权。 - * 使用返回值守卫,让 Router 5 管理重定向,避免在守卫内另起一次导航。 - */ import { APP_CATCH_KEY, WHITE_ROUTES } from '@/app-config' import { useAppRoot } from '@/hooks' import { getStorage, setStorage } from '@/utils' import type { Router } from 'vue-router' import { validRole } from './valid-role' +/** + * + * @param router 应用的 Router 实例 + * + * @description + * 注册 token、白名单与 meta.role 权限守卫,重定向返回值交给 Router 处理。 + * 前端守卫不能替代后端鉴权。 + */ export const permissionRouter = (router: Router) => { const { getRootPath } = useAppRoot() diff --git a/src/store/README.md b/src/store/README.md index 7ada6063..4826baa1 100644 --- a/src/store/README.md +++ b/src/store/README.md @@ -1,6 +1,6 @@ ## 描述 -> pinia store 仓库包。存放全局公共状态。如果不需要 pinia 但是又希望使用全局变量,可以使用 `global-variable` 管理数据。 +> 所有全局可变 UI 状态统一由 Pinia 管理,按用途分包,通过 `src/store/hooks` 暴露响应式 getters 和 actions。 ## 约束 @@ -29,7 +29,7 @@ export const piniaDemoStore = defineStore( persist: { key: 'piniaDemoStore', pick: ['demoRef'], - storage: sessionStorage | localStorage, + storage: localStorage, }, }, ) @@ -71,3 +71,22 @@ export { useDemoGetters, useMenuActions } from './modules/demo' ```ts import { useDemoGetters, useMenuActions } from '@/store' ``` + +## 运行时状态与布局偏好 + +- `runtime`:全局加载、移动抽屉、页面刷新、内容最大化和内容加载动画。通过 `useRuntimeGetters` / `useRuntimeActions` 读取和修改;不持久化,应用卸载时释放 Store 与计时器。 +- `lock-screen`:锁屏状态也归入 Pinia,保留历史布尔值格式、缓存 key 与跨标签页同步。 +- `setting.layoutConfig`:布局模式、内容宽度与间距、顶栏和页脚固定方式。通过现有 `useSettingGetters` / `useSettingActions` 操作,使用原有设置缓存 key。旧缓存补默认值,不清空历史偏好。 +- 删除了独立的 `global-variable` 包;原五个状态名保留在 runtime 中,调用方改为 Store hooks。新增全局状态继续按用途放入 `src/store/modules`,不在普通模块创建共享 reactive 单例。 + +```ts +import { useRuntimeActions, useRuntimeGetters } from '@/store' + +const { globalSpinning } = useRuntimeGetters() +const { setRuntimeState } = useRuntimeActions() +setRuntimeState('globalSpinning', true) +// 异步任务结束后,务必恢复加载状态。 +setRuntimeState('globalSpinning', false) +``` + +布局用法和插槽见 [布局说明](../layout/README.md)。 diff --git a/src/store/hooks/useLockScreenStore.ts b/src/store/hooks/useLockScreenStore.ts new file mode 100644 index 00000000..98934822 --- /dev/null +++ b/src/store/hooks/useLockScreenStore.ts @@ -0,0 +1,13 @@ +import { piniaLockScreenStore } from '../modules/lock-screen' + +export const useLockScreenGetters = () => { + const store = piniaLockScreenStore() + + return { getLocked: computed(() => store.locked) } +} + +export const useLockScreenActions = () => { + const { setLocked } = piniaLockScreenStore() + + return { setLocked } +} diff --git a/src/store/hooks/useRuntimeStore.ts b/src/store/hooks/useRuntimeStore.ts new file mode 100644 index 00000000..96c15c01 --- /dev/null +++ b/src/store/hooks/useRuntimeStore.ts @@ -0,0 +1,21 @@ +import { piniaRuntimeStore } from '../modules/runtime' + +// 临时 UI 状态不持久化;同一个 Pinia 实例共享,应用卸载后随 store 释放。 +export const useRuntimeGetters = () => { + const state = storeToRefs(piniaRuntimeStore()) + + return { + globalSpinning: readonly(state.globalSpinning), + globalDrawerValue: readonly(state.globalDrawerValue), + globalMainLayoutLoad: readonly(state.globalMainLayoutLoad), + layoutContentMaximize: readonly(state.layoutContentMaximize), + layoutContentSpinning: readonly(state.layoutContentSpinning), + layoutContentMaximizeStyle: readonly(state.layoutContentMaximizeStyle), + } +} + +export const useRuntimeActions = () => { + const { setRuntimeState, reloadContent } = piniaRuntimeStore() + + return { setRuntimeState, reloadContent } +} diff --git a/src/store/hooks/useSettingStore.ts b/src/store/hooks/useSettingStore.ts index d713d53d..991abeca 100644 --- a/src/store/hooks/useSettingStore.ts +++ b/src/store/hooks/useSettingStore.ts @@ -2,6 +2,7 @@ import { piniaSettingStore } from '../modules/setting' export const useSettingGetters = () => { const variable = piniaSettingStore() + const getLayoutConfig = computed(() => variable.layoutConfig) /** * @@ -120,6 +121,7 @@ export const useSettingGetters = () => { const getDynamicDocumentTitle = computed(() => variable.dynamicDocumentTitle) return { + getLayoutConfig, getDrawerPlacement, getPrimaryColorOverride, getAppTheme, diff --git a/src/store/index.ts b/src/store/index.ts index 725ea01c..25bdd222 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -1,14 +1,4 @@ -/** - * - * 模板约定不直接操作 store 实例,所有操作都应在 hooks 中二次封装的 getters, actions - * - * 持久化存储 pinia 数据 - * 但是不能正常持久化 function 属性 - * - * 官网地址: - * @see https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/ - */ - +import { disposePinia } from 'pinia' import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' import type { App } from 'vue' @@ -17,20 +7,21 @@ export * from './modules/setting' export * from './modules/menu' export * from './modules/signing' export * from './modules/keep-alive' +export * from './modules/runtime' +export * from './modules/lock-screen' // 导出 getters, actions export * from './hooks/useMenuStore' export * from './hooks/useSettingStore' export * from './hooks/useSigningStore' export * from './hooks/useKeepAliveStore' +export * from './hooks/useRuntimeStore' +export * from './hooks/useLockScreenStore' -/** - * - * 设置并且注册 pinia - * pinia 天生支持在非 setup 环境中使用,只要在调用时已经注册 - */ +// Store hooks 是业务访问入口;应用卸载时同时释放 Pinia 作用域及其订阅。 export const setupStore = (app: App) => { const store = createPinia() app.use(store) store.use(piniaPluginPersistedstate) + app.onUnmount(() => disposePinia(store)) } diff --git a/src/store/modules/lock-screen/index.ts b/src/store/modules/lock-screen/index.ts new file mode 100644 index 00000000..7f0f9b76 --- /dev/null +++ b/src/store/modules/lock-screen/index.ts @@ -0,0 +1,17 @@ +import { APP_CATCH_KEY } from '@/app-config' +import { useStorage } from '@vueuse/core' + +export const piniaLockScreenStore = defineStore('lock-screen', () => { + // 沿用历史布尔值格式与 key,并保留跨标签页 storage 同步。 + const locked = useStorage( + APP_CATCH_KEY.isAppLockScreen, + false, + window.localStorage, + { mergeDefaults: true }, + ) + const setLocked = (value: boolean) => { + locked.value = value + } + + return { locked, setLocked } +}) diff --git a/src/store/modules/menu/utils.ts b/src/store/modules/menu/utils.ts index 5113c09e..cfb86319 100644 --- a/src/store/modules/menu/utils.ts +++ b/src/store/modules/menu/utils.ts @@ -1,8 +1,7 @@ -/** 本方法感谢 的支持 */ - import { APP_CATCH_KEY } from '@/app-config' 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 { NTag } from 'naive-ui' @@ -12,12 +11,14 @@ import { piniaSettingStore } from '../setting' /** * - * @param node 当前节点 - * @param key 动态字段 - * @param value 匹配值 + * @param node 待检查的菜单节点 + * @param key 需要比较的属性 + * @param value 目标属性值 * * @description - * 检查是否为所需项。 + * 比较菜单节点的指定属性,原实现参考 https://yunkuangao.me/。 + * + * @returns 节点有效且指定属性匹配时返回 true */ const isMatch = ( node: AppMenuOption, @@ -150,10 +151,14 @@ export const createMenuIcon = (option: AppMenuOption) => { const { menuConfig } = piniaSettingStore() const { collapsed } = piniaMenuStore() + const name = resolveIconName(icon) + + if (!name) return + const _icon = h( RIcon, { - name: icon, + name, size: collapsed ? menuConfig.collapsedIconSize : menuConfig.iconSize, cursor: 'pointer', }, diff --git a/src/store/modules/runtime/index.ts b/src/store/modules/runtime/index.ts new file mode 100644 index 00000000..96a5fe84 --- /dev/null +++ b/src/store/modules/runtime/index.ts @@ -0,0 +1,45 @@ +export interface RuntimeState { + globalSpinning: boolean + globalDrawerValue: boolean + globalMainLayoutLoad: boolean + layoutContentMaximize: boolean + layoutContentSpinning: boolean + layoutContentMaximizeStyle: { + zIndex: number + backgroundColor?: string + transition?: string + } +} + +export const piniaRuntimeStore = defineStore('runtime', () => { + const state = reactive({ + globalSpinning: false, + globalDrawerValue: false, + globalMainLayoutLoad: true, + layoutContentMaximize: false, + layoutContentSpinning: false, + layoutContentMaximizeStyle: { zIndex: 999 }, + }) + let reloadTimer: ReturnType | undefined + + const setRuntimeState = ( + key: K, + value: RuntimeState[K], + ) => { + state[key] = value + } + + // 刷新会卸载发起调用的页面,计时器必须由 store 持有;重复刷新以最后一次为准。 + const reloadContent = (wait = 800) => { + clearTimeout(reloadTimer) + state.globalMainLayoutLoad = false + reloadTimer = setTimeout(() => { + state.globalMainLayoutLoad = true + reloadTimer = void 0 + }, wait) + } + + onScopeDispose(() => clearTimeout(reloadTimer)) + + return { ...toRefs(state), setRuntimeState, reloadContent } +}) diff --git a/src/store/modules/setting/constant.ts b/src/store/modules/setting/constant.ts index ee21e18a..5ccfb0ae 100644 --- a/src/store/modules/setting/constant.ts +++ b/src/store/modules/setting/constant.ts @@ -1,6 +1,7 @@ -import type { SettingState } from './types' +import type { LayoutConfig, SettingState } from './types' type OmitKeys = + | 'layoutConfig' | 'contentTransition' | 'watermarkSwitch' | 'keepAliveConfig' @@ -17,6 +18,14 @@ interface Config extends Pick {} // SettingDrawer 默认配置系统配置项 const defaultSettingConfig: Readonly = { + layoutConfig: { + mode: 'side', + contentWidth: 'fluid', + contentMaxWidth: 1200, + contentPadding: 16, + fixedHeader: true, + fixedFooter: true, + }, // 切换过渡效果 contentTransition: 'scale', // 水印开关 @@ -87,3 +96,49 @@ export const getDefaultSettingConfig = (): Readonly => { export const updateDefaultSettingConfig = (config: Partial) => { Object.assign(defaultSettingConfig, config) } + +export function normalizeLayoutConfig(value: unknown): LayoutConfig { + const defaults = defaultSettingConfig.layoutConfig + const config = value && typeof value === 'object' ? value : {} + const source = config as Partial + const numberInRange = ( + value: unknown, + fallback: number, + min: number, + max: number, + ) => + typeof value === 'number' && Number.isFinite(value) + ? Math.min(max, Math.max(min, value)) + : fallback + + return { + mode: + source.mode === 'side' || source.mode === 'top' || source.mode === 'mixed' + ? source.mode + : defaults.mode, + contentWidth: + source.contentWidth === 'fixed' || source.contentWidth === 'fluid' + ? source.contentWidth + : defaults.contentWidth, + contentMaxWidth: numberInRange( + source.contentMaxWidth, + defaults.contentMaxWidth, + 640, + 2560, + ), + contentPadding: numberInRange( + source.contentPadding, + defaults.contentPadding, + 0, + 48, + ), + fixedHeader: + typeof source.fixedHeader === 'boolean' + ? source.fixedHeader + : defaults.fixedHeader, + fixedFooter: + typeof source.fixedFooter === 'boolean' + ? source.fixedFooter + : defaults.fixedFooter, + } +} diff --git a/src/store/modules/setting/index.ts b/src/store/modules/setting/index.ts index 1a2fe840..1d693b03 100644 --- a/src/store/modules/setting/index.ts +++ b/src/store/modules/setting/index.ts @@ -1,12 +1,14 @@ import { APP_CATCH_KEY, APP_THEME, GLOBAL_CLASS_NAMES } from '@/app-config' import { useDayjs, useI18n } from '@/hooks' import type { LocalKey } from '@/hooks' +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 { usePreferredDark } from '@vueuse/core' import { cloneDeep, merge } from 'lodash-es' -import { getDefaultSettingConfig } from './constant' +import { getDefaultSettingConfig, normalizeLayoutConfig } from './constant' export const piniaSettingStore = defineStore( 'setting', @@ -16,6 +18,7 @@ export const piniaSettingStore = defineStore( } = APP_THEME const { locale } = useI18n() const { locale: dayjsLocal } = useDayjs() + const preferredDark = usePreferredDark() const settingState = reactive({ // 默认主题色 @@ -42,7 +45,7 @@ export const piniaSettingStore = defineStore( }, // 侧边栏设置 sideBarLogo: { - icon: 'ray', + icon: 'logo/ray', title: 'Ray Template', url: '/dashboard', jumpType: 'station', @@ -106,6 +109,16 @@ export const piniaSettingStore = defineStore( value: Partial, cb?: C, ) => { + if (key === 'layoutConfig') { + settingState.layoutConfig = normalizeLayoutConfig({ + ...settingState.layoutConfig, + ...(value as object), + }) + cb?.() + + return + } + updateObjectValue(settingState, key, value as V[T], cb) } @@ -125,6 +138,9 @@ export const piniaSettingStore = defineStore( * 该方法会在初始化时执行一次,之后会在切换主题色时执行。 */ watchEffect(() => { + if (settingState.appTheme === 'auto') + settingState._appTheme = preferredDark.value + settingState._appTheme ? (settingState.primaryColorOverride = merge( {}, @@ -157,6 +173,13 @@ export const piniaSettingStore = defineStore( key: APP_CATCH_KEY.appPiniaSettingStore, omit: ['lockScreenSwitch'], storage: window.localStorage, + afterHydrate: ({ store }) => { + store.layoutConfig = normalizeLayoutConfig(store.layoutConfig) + + if (typeof store.sideBarLogo?.icon === 'string') { + store.sideBarLogo.icon = resolveIconName(store.sideBarLogo.icon) + } + }, }, }, ) diff --git a/src/store/modules/setting/types.ts b/src/store/modules/setting/types.ts index cd32beb3..bf8a1c14 100644 --- a/src/store/modules/setting/types.ts +++ b/src/store/modules/setting/types.ts @@ -25,7 +25,17 @@ export interface AppRootRoute { path: string } +export interface LayoutConfig { + mode: 'side' | 'top' | 'mixed' + contentWidth: 'fluid' | 'fixed' + contentMaxWidth: number + contentPadding: number + fixedHeader: boolean + fixedFooter: boolean +} + export interface SettingState { + layoutConfig: LayoutConfig drawerPlacement: Placement primaryColorOverride: GlobalThemeOverrides appTheme: 'dark' | 'light' | 'auto' diff --git a/src/store/modules/signing/index.ts b/src/store/modules/signing/index.ts index 34e57d98..8c087a0a 100644 --- a/src/store/modules/signing/index.ts +++ b/src/store/modules/signing/index.ts @@ -1,13 +1,3 @@ -/** - * - * 出于便捷性考虑, 将用户部分信息存于 pinia 仓库 - * 可以存储: 头像, 权限, 以及基于你项目实际情况的一些附带信息 - * - * 使用 sessionStorage 缓存部分用户信息 - * - * 默认仅缓存 SigningCallback 属性 - */ - import { APP_CATCH_KEY } from '@/app-config' import { useSiderBar } from '@/hooks' import type { @@ -18,6 +8,7 @@ import type { import { removeStorage } from '@/utils' import { isEmpty } from 'lodash-es' +/** 登录状态仓库,使用 localStorage 持久化 signingCallback。 */ export const piniaSigningStore = defineStore( 'signing', () => { diff --git a/src/styles/base.scss b/src/styles/base.scss index e785554b..ca508655 100644 --- a/src/styles/base.scss +++ b/src/styles/base.scss @@ -1,6 +1,7 @@ @use '@/styles/animate.scss' as *; @use '@/styles/root.scss' as *; @use '@/styles/naive.scss' as *; +@use '@/styles/design-system.scss' as *; @use '@/styles/print-css.scss' as *; body, diff --git a/src/styles/design-system.scss b/src/styles/design-system.scss new file mode 100644 index 00000000..8ee2d851 --- /dev/null +++ b/src/styles/design-system.scss @@ -0,0 +1,71 @@ +:root { + --r-primary-text: var(--r-theme-primary-color); + --r-selected-text: var(--r-theme-primary-color); + --r-canvas: #f5f7fb; + --r-surface: #ffffff; + --r-surface-muted: #f7f9fc; + --r-surface-hover: #eef2f8; + --r-line: #e4e9f1; + --r-control-border: #8492a8; + --r-text: #1d2a3e; + --r-text-secondary: #52647c; + --r-text-muted: #617187; + --r-shadow-soft: 0 1px 2px rgb(25 43 74 / 3%), 0 6px 20px rgb(25 43 74 / 3%); + --r-radius: 12px; + --r-font-mono: 'SFMono-Regular', Consolas, 'Liberation Mono', monospace; + color-scheme: light; +} + +.r-template--dark { + --r-primary-text: var(--r-text-secondary); + --r-selected-text: var(--r-text); + --r-canvas: #101722; + --r-surface: #172131; + --r-surface-muted: #1c293b; + --r-surface-hover: #243247; + --r-line: #2c394d; + --r-control-border: #687b96; + --r-text: #e9eef7; + --r-text-secondary: #b3c0d3; + --r-text-muted: #a0b0c6; + --r-shadow-soft: 0 1px 2px rgb(0 0 0 / 10%), 0 8px 24px rgb(0 0 0 / 10%); + color-scheme: dark; +} + +@media (forced-colors: active) { + :root, + .r-template--dark { + --r-primary-text: CanvasText; + --r-selected-text: CanvasText; + --r-canvas: Canvas; + --r-surface: Canvas; + --r-surface-muted: Canvas; + --r-surface-hover: Canvas; + --r-line: CanvasText; + --r-control-border: ButtonText; + --r-text: CanvasText; + --r-text-secondary: CanvasText; + --r-text-muted: CanvasText; + --r-shadow-soft: none; + } +} + +:where(button, a, summary, [tabindex]):focus-visible { + outline: 2px solid var(--r-theme-primary-color); + outline-offset: 3px; +} + +@media (prefers-reduced-motion: reduce) { + .r-layout-full *, + .r-layout-full *::before, + .r-layout-full *::after { + scroll-behavior: auto !important; + animation-duration: 0.01ms !important; + transition-duration: 0.01ms !important; + } +} + +.r-template--dark .menu-tag .menu-tag__btn.n-button--primary-type, +.r-template--dark .r-layout-settings .r-layout-preset[aria-pressed='true'] { + color: var(--r-text); +} diff --git a/src/styles/naive.scss b/src/styles/naive.scss index 169368c7..bfb25390 100644 --- a/src/styles/naive.scss +++ b/src/styles/naive.scss @@ -5,14 +5,6 @@ height: 100%; } -// 拓展 AppMenu Item样式 -.r-menu--app:not(.n-menu--collapsed) - .n-menu-item-content.n-menu-item-content--selected:before, -.r-menu--app:not(.n-menu--collapsed) .n-menu-item-content:hover:before { - border-left: 4px solid var(--r-theme-primary-color); - transition: border-left 0.1s; -} - // 手动设置 AppMenu Item Header 样式,兼容 extra 的情况 .r-menu--app .n-menu-item-content.n-menu-item-content--selected diff --git a/src/types/modules/vite-custom-config.ts b/src/types/modules/vite-custom-config.ts index 5d8b6af5..296c97aa 100644 --- a/src/types/modules/vite-custom-config.ts +++ b/src/types/modules/vite-custom-config.ts @@ -1,3 +1,4 @@ +import type { IconName } from '@/icons' import type { Recordable } from '@/types' import type { GlobalThemeOverrides } from 'naive-ui' import type { @@ -9,7 +10,7 @@ import type { import type { VNode, VNodeChild } from 'vue' export interface LayoutSideBarLogo { - icon?: string | VNode + icon?: IconName | VNode title?: string url?: string jumpType?: 'station' | 'outsideStation' diff --git a/src/utils/c/constant.ts b/src/utils/c/constant.ts index 65cea0fd..95f2d528 100644 --- a/src/utils/c/constant.ts +++ b/src/utils/c/constant.ts @@ -1,6 +1,2 @@ -/** - * - * @description - * 约定加密 key。 - */ +/** 历史加解密格式使用的默认密钥。 */ export const CRYPTO_KEY = '4cP+dX5FI2EVYzln' diff --git a/src/utils/precision.ts b/src/utils/precision.ts index 9494f34b..2d25c4de 100644 --- a/src/utils/precision.ts +++ b/src/utils/precision.ts @@ -1,26 +1,9 @@ -/** - * - * 文档地址: - * - * Options 默认值 - * - symbol default: `$`(货币符号) - * - separator default: `,`(数字分隔符, demo: 1234.56 => '1,234.56') - * - decimal default: `.`(十进制分隔符, demo: 1.23 => '1.23') - * - precision default: `2`(精度保留位数) - * - pattern default: `!#`(!: 货币符号代替, #: 货币金额代替) - * - negativePattern default: `!#`(!: 货币符号代替, #: 货币金额代替) - * - format default: `null`(默认格式化方法替代, 看文档) - * - fromCents default: `false`(尊重精度选项) - * - errorOnInvalid default: `false`(传入 null undefined 直接抛出错误) - * - increment default: `null`(四舍五入增量值) - * - useVedic default: `false`(分组格式化值, demo: currency(1234567.89, { useVedic: true }).format() => '12,34,567.89') - */ - import { isValueType } from '@/utils' import currency from 'currency.js' import type { Options } from 'currency.js' import { cloneDeep } from 'lodash-es' +/** 金额运算接受的输入类型。 */ export type CurrencyArguments = string | number | currency export type OriginalValueType = 'string' | 'number' diff --git a/src/views/dashboard/index.scss b/src/views/dashboard/index.scss index 10428428..c59ac485 100644 --- a/src/views/dashboard/index.scss +++ b/src/views/dashboard/index.scss @@ -1,13 +1,170 @@ -.dashboard-layout { - & .n-card { - margin-top: 18px; +.r-dashboard { + container-type: inline-size; + display: flex; + flex-direction: column; + gap: 24px; + width: 100%; + max-width: 1360px; + margin-inline: auto; + padding-block: 8px 20px; - &:first-child { - margin-top: 0; - } - } - - & .dashboard-link { - text-decoration: none; + &__brand { + display: grid; + place-items: center; + width: 72px; + height: 72px; + border: 1px solid var(--r-line); + border-radius: 18px; + background: var(--r-surface); + box-shadow: var(--r-shadow-soft); + } +} + +.r-dashboard-stack { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; + + &__item { + display: flex; + flex-direction: column; + gap: 10px; + padding: 20px 24px; + border: 1px solid var(--r-line); + border-radius: 12px; + background: var(--r-surface); + } + span { + color: var(--r-text-secondary); + font-size: 12px; + } + strong { + color: var(--r-text); + font-family: var(--r-font-mono); + font-size: 21px; + font-weight: 600; + letter-spacing: -0.03em; + } + small { + color: var(--r-text-muted); + font-size: 11px; + } +} + +.r-dashboard-shortcuts { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 14px; +} + +.r-dashboard-shortcut { + display: flex; + align-items: center; + gap: 14px; + padding: 18px; + border: 1px solid var(--r-line); + border-radius: 10px; + color: var(--r-text); + background: var(--r-surface-muted); + text-decoration: none; + transition: + border-color 0.18s ease, + background-color 0.18s ease; + + &:hover { + border-color: var(--r-control-border); + background: var(--r-surface); + } + &__icon { + display: grid; + place-items: center; + width: 38px; + height: 38px; + flex-shrink: 0; + border: 1px solid var(--r-line); + border-radius: 9px; + color: var(--r-text-secondary); + background: var(--r-surface); + } + > span:nth-child(2) { + display: flex; + flex-direction: column; + gap: 5px; + min-width: 0; + } + strong { + font-size: 14px; + font-weight: 600; + } + small { + color: var(--r-text-muted); + font-size: 12px; + } + &__arrow { + margin-inline-start: auto; + transform: rotate(180deg); + color: var(--r-text-muted); + } +} + +.r-dashboard-info { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 20px; + align-items: start; + + &__intro { + color: var(--r-text-secondary); + line-height: 1.8; + } + &__feedback { + margin-block-start: 24px; + color: var(--r-text-muted); + font-size: 12px; + line-height: 1.8; + } + a { + color: var(--r-text); + text-underline-offset: 3px; + } +} + +.r-dashboard-features { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-block-start: 20px; + + span { + padding: 5px 10px; + border: 1px solid var(--r-line); + border-radius: 6px; + background: var(--r-surface-muted); + color: var(--r-text-secondary); + font-size: 11px; + } +} + +@container (min-width: 760px) { + .r-dashboard-stack { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + .r-dashboard-shortcuts { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .r-dashboard-info { + grid-template-columns: 1.1fr 1fr; + } +} + +@container (max-width: 600px) { + .r-dashboard-stack { + gap: 12px; + } + .r-dashboard-stack__item { + padding: 18px; + } + .r-dashboard__brand { + display: none; } } diff --git a/src/views/dashboard/index.tsx b/src/views/dashboard/index.tsx index 6e0ab7b8..be857936 100644 --- a/src/views/dashboard/index.tsx +++ b/src/views/dashboard/index.tsx @@ -1,129 +1,152 @@ import './index.scss' +import AppPageHeader from '@/app-components/app/AppPageHeader' import AppShareLink from '@/app-components/app/AppShareLink' import { RIcon } from '@/components' -import { - NCard, - NDescriptions, - NDescriptionsItem, - NFlex, - NH6, - NP, - NTag, - NText, -} from 'naive-ui' +import { useI18n } from '@/hooks' +import { useMenuGetters } from '@/store' +import { NCard, NDescriptions, NDescriptionsItem } from 'naive-ui' +import { RouterLink } from 'vue-router' -const Dashboard = defineComponent({ +export default defineComponent({ name: 'RDashboard', setup() { - const coverLetterOptions = [ - { - label: '掌握搬砖框架', - des: () => ( - - Vue3.x - React - - ), - }, - { - label: '从事搬砖时长', - des: () => ( - - 练习时长两年半的小白前端搬砖师 - - ), - }, - { - label: '个人', - des: () => ( - - - 努力搬砖、努力摸鱼, 建设美丽家园 - - ), - span: 2, - }, - { - label: '补充说明', - des: () => ( - - 如果有希望补充的功能可以在 - - GitHub - - 提一个 Issues - - ), - span: 2, - }, - ] + const { t } = useI18n('dashboard') + const text = (key: string) => t(key) + const { getMenuOptions } = useMenuGetters() const { dependencies, devDependencies } = __APP_CFG__.pkg - const technologyTagOptions = [ - { label: `Vue ${dependencies.vue}`, value: 'vue' }, - { label: `Vite ${devDependencies.vite}`, value: 'vite' }, - { label: `Pinia ${dependencies.pinia}`, value: 'pinia' }, + const stack = [ + { name: 'Vue', version: dependencies.vue, detail: 'Composition API' }, + { name: 'Vite', version: devDependencies.vite, detail: 'Rolldown' }, { - label: `TypeScript ${devDependencies.typescript} / TSX`, - value: 'typescript', + name: 'TypeScript', + version: devDependencies.typescript, + detail: 'TSX', + }, + { + name: 'Pinia', + version: dependencies.pinia, + detail: text('stateManagement'), }, ] + const destinations = [ + { + path: '/template-hooks', + icon: 'action/setting', + title: 'hooks', + description: 'hooksDescription', + }, + { + path: '/layout-demo', + icon: 'navigation/menu', + title: 'layout', + description: 'layoutDescription', + }, + { + path: '/svg-icons', + icon: 'directional/resize_h', + title: 'icons', + description: 'iconsDescription', + }, + ] as const + const shortcuts = computed(() => + destinations.filter((item) => + getMenuOptions.value.some( + (menu) => menu.fullPath === item.path && menu.show !== false, + ), + ), + ) - return { - coverLetterOptions, - technologyTagOptions, - } - }, - render() { - return ( - - - {{ - header: () => , - default: () => '当你看见这个页面后, 就说明项目已经启动成功了~', - }} - - - - {this.coverLetterOptions.map((curr) => ( - - {curr.des()} - - ))} - - - - 技术栈 - - - {this.technologyTagOptions.map((curr) => ( - - {curr.label} - + return () => ( +
+ + + + + +
+ {stack.map((item) => ( +
+ {item.name} + {item.version} + + {item.name === 'Pinia' ? text('stateManagement') : item.detail} + +
+ ))} +
+ {shortcuts.value.length ? ( + +
+ {shortcuts.value.map((item) => ( + + + + + + {text(item.title)} + {text(item.description)} + + + ))} - - - 项目介绍 - - 预设了最佳构建体验的配置与常用搬砖工具。意在提供一个简洁、快速上手的模板。 - +
+
+ ) : null} +
+ +

{text('projectDescription')}

+
+ Vue 3 + TSX + Naive UI + {text('routing')} + {text('themeAndLocale')} +
+ +
+ + + + Vue3.x / React + + + {text('experienceValue')} + + + {text('bioValue')} + + + +
+ + - - - - +
) }, }) - -export default Dashboard diff --git a/src/views/demo/components/DemoPage.tsx b/src/views/demo/components/DemoPage.tsx new file mode 100644 index 00000000..fa6a3adc --- /dev/null +++ b/src/views/demo/components/DemoPage.tsx @@ -0,0 +1,29 @@ +import './index.scss' +import AppPageHeader from '@/app-components/app/AppPageHeader' + +export default defineComponent({ + name: 'DemoPage', + props: { + title: { type: String, required: true }, + description: { type: String, default: '' }, + eyebrow: { type: String, default: 'RAY TEMPLATE' }, + meta: { type: String, default: '' }, + }, + setup(props, { slots }) { + return () => ( +
+ + {props.meta ? ( + {props.meta} + ) : null} + {slots.actions?.()} + +
{slots.default?.()}
+
+ ) + }, +}) diff --git a/src/views/demo/components/index.scss b/src/views/demo/components/index.scss new file mode 100644 index 00000000..bf44cdb9 --- /dev/null +++ b/src/views/demo/components/index.scss @@ -0,0 +1,82 @@ +.r-showcase-page { + container-type: inline-size; + width: 100%; + max-width: 1360px; + margin-inline: auto; + display: flex; + flex-direction: column; + gap: 28px; + padding-block: 8px 20px; +} + +.r-showcase-meta { + padding: 7px 12px; + border: 1px solid var(--r-line); + border-radius: 8px; + color: var(--r-text-secondary); + background: var(--r-surface); + font-size: 12px; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.r-showcase-content { + display: flex; + flex-direction: column; + gap: 24px; + min-width: 0; +} + +.r-demo-section-heading { + display: flex; + align-items: center; + gap: 12px; + color: var(--r-text-secondary); + font-size: 13px; + font-weight: 600; + line-height: 1.5; + + &::after { + content: ''; + flex: 1; + height: 1px; + background: var(--r-line); + } +} + +.r-hook-grid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 20px; + align-items: start; +} + +.r-layout-playground { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 24px; + align-items: start; +} + +.r-layout-playground__aside { + display: flex; + flex-direction: column; + gap: 20px; + min-width: 0; +} + +@container (min-width: 900px) { + .r-hook-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + + > :last-child:nth-child(odd) { + grid-column: 1 / -1; + } + } +} + +@container (min-width: 760px) { + .r-layout-playground { + grid-template-columns: minmax(300px, 0.9fr) minmax(0, 1.1fr); + } +} diff --git a/src/views/demo/hooks/HookExample.tsx b/src/views/demo/hooks/HookExample.tsx new file mode 100644 index 00000000..9c4a2fad --- /dev/null +++ b/src/views/demo/hooks/HookExample.tsx @@ -0,0 +1,51 @@ +import './index.scss' +import { RIcon } from '@/components' +import { useI18n } from '@/hooks' +import { NButton, NCard } from 'naive-ui' + +export default defineComponent({ + name: 'HookExample', + props: { + name: { type: String, required: true }, + description: { type: String, required: true }, + code: { type: String, required: true }, + }, + setup(props, { slots }) { + const { t } = useI18n('showcase') + + return () => ( + +
+ +

{props.name}

+ Hook +
+

{props.description}

+
+ {t('preview')} + {slots.default?.()} +
+
+ + + + {t('code')} + + TS / TSX + +
+ TypeScript + + {t('copyCode')} + +
+
+            {props.code}
+          
+
+
+ ) + }, +}) diff --git a/src/views/demo/hooks/index.scss b/src/views/demo/hooks/index.scss new file mode 100644 index 00000000..a817c019 --- /dev/null +++ b/src/views/demo/hooks/index.scss @@ -0,0 +1,181 @@ +.r-demo-code { + margin: 0; + padding: 16px 18px; + border: 1px solid var(--r-line); + border-radius: 8px; + color: var(--r-text-secondary); + background: var(--r-surface-muted); + white-space: pre-wrap; + overflow-wrap: anywhere; + font-family: var(--r-font-mono); + font-size: 12px; + line-height: 1.8; + tab-size: 2; +} + +.r-hook-example { + min-width: 0; + box-shadow: var(--r-shadow-soft); + + &__header { + display: flex; + align-items: center; + gap: 10px; + padding: 22px 24px 0; + + h2 { + min-width: 0; + color: var(--r-text); + font-family: var(--r-font-mono); + font-size: 15px; + font-weight: 600; + overflow-wrap: anywhere; + } + } + + &__symbol { + display: grid; + place-items: center; + width: 30px; + height: 30px; + flex-shrink: 0; + border-radius: 8px; + color: var(--r-text-secondary); + background: var(--r-surface-muted); + font-family: Georgia, serif; + font-size: 20px; + } + + &__type { + margin-inline-start: auto; + color: var(--r-text-muted); + font-size: 11px; + } + + &__description { + margin: 12px 24px 18px; + color: var(--r-text-secondary); + font-size: 13px; + line-height: 1.8; + } +} + +.r-hook-preview { + display: flex; + flex-direction: column; + align-items: stretch; + gap: 12px; + margin: 0 24px 20px; + padding: 16px; + border: 1px solid var(--r-line); + border-radius: 8px; + background: var(--r-surface-muted); + + &__label { + color: var(--r-text-muted); + font-size: 11px; + font-weight: 500; + } + + > code, + code:not(.r-demo-code code) { + overflow-wrap: anywhere; + font-family: var(--r-font-mono); + font-size: 12px; + } +} + +.r-hook-code { + border-top: 1px solid var(--r-line); + + summary { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 13px 24px; + color: var(--r-text-secondary); + font-size: 12px; + list-style: none; + cursor: pointer; + + > span:first-child { + display: flex; + align-items: center; + gap: 7px; + } + &::-webkit-details-marker { + display: none; + } + .r-icon { + transform: rotate(180deg); + transition: transform 0.18s ease; + } + } + + &[open] summary .r-icon { + transform: rotate(270deg); + } + &[open] summary { + border-bottom: 1px solid var(--r-line); + } + &__format { + color: var(--r-text-muted); + font-family: var(--r-font-mono); + font-size: 10px; + } + &__toolbar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 24px 0; + color: var(--r-text-muted); + font-size: 11px; + } + .r-demo-code { + margin: 10px 16px 16px; + border: 0; + } +} + +.r-hook-capture-target { + position: relative; + padding: 28px; + border: 1px solid var(--r-line); + border-radius: 12px; + background: var(--r-surface); + color: var(--r-text); + box-shadow: var(--r-shadow-soft); + + h2 { + margin-block-end: 10px; + font-size: 21px; + font-weight: 600; + } + p { + max-width: 64ch; + color: var(--r-text-secondary); + line-height: 1.8; + } + .r-hook-capture-target__stack { + margin-block-start: 16px; + font-size: 12px; + color: var(--r-text-muted); + } +} + +@container (max-width: 600px) { + .r-hook-example__header { + padding: 18px 18px 0; + } + .r-hook-example__description { + margin-inline: 18px; + } + .r-hook-preview { + margin-inline: 18px; + padding: 12px; + } + .r-hook-code summary { + padding-inline: 18px; + } +} diff --git a/src/views/demo/hooks/web-hooks.tsx b/src/views/demo/hooks/web-hooks.tsx new file mode 100644 index 00000000..4248ec55 --- /dev/null +++ b/src/views/demo/hooks/web-hooks.tsx @@ -0,0 +1,339 @@ +import { + useContextmenuCoordinate, + useDayjs, + useDevice, + useDomToImage, + useElementFullscreen, + useI18n, + usePagination, + usePrint, + useVueRouter, +} from '@/hooks' +import { useSettingActions } from '@/store' +import { + NAlert, + NButton, + NDropdown, + NFlex, + NInput, + NPagination, + NTag, + useThemeVars, +} from 'naive-ui' +import DemoPage from '../components/DemoPage' +import HookExample from './HookExample' + +export default defineComponent({ + name: 'WebHooks', + setup() { + const { t } = useI18n('hooks') + const text = (key: string) => t(key) + const { t: showcaseT } = useI18n('showcase') + const label = (key: string) => showcaseT(key) + const themeVars = useThemeVars() + const device = useDevice() + const dayjs = useDayjs() + const { router } = useVueRouter() + const { updateLocale: changeLocale } = useSettingActions() + const [pagination, pages] = usePagination(void 0, { + itemCount: 95, + pageSize: 10, + }) + const date = ref('2026-11-03') + const dayRange = ref(dayjs.getStartAndEndOfDay()) + const target = ref() + const fullscreen = useElementFullscreen(target) + const capture = useDomToImage(target, { imageType: 'png', cacheBust: true }) + const printer = usePrint(target, { type: 'html', targetStyles: ['*'] }) + const image = ref('') + const error = ref('') + const busy = ref(false) + const contextTarget = ref() + const context = useContextmenuCoordinate(contextTarget) + const contextStopped = ref(false) + const selected = ref('') + const rows = computed(() => { + const start = (pages.getPage() - 1) * pages.getPageSize() + + return Array.from( + { + length: Math.min( + pages.getPageSize(), + Math.max(0, pages.getItemCount() - start), + ), + }, + (_, index) => start + index + 1, + ) + }) + const createImage = async () => { + busy.value = true + error.value = '' + + try { + image.value = await capture.create() + } catch (cause) { + error.value = cause instanceof Error ? cause.message : String(cause) + } finally { + busy.value = false + } + } + const example = ( + name: string, + code: string, + children: () => JSX.Element, + ) => ( + + {children()} + + ) + + return () => ( + +

{label('commonUtilities')}

+
+ {example( + 'useDevice', + `const { width, height, isTabletOrSmaller } = useDevice({ media: 768 })\n// Refs update when the viewport changes; listeners are released with the scope.`, + () => ( + + + {device.width.value} × {device.height.value} + + + {device.isTabletOrSmaller.value + ? text('smallScreen') + : text('desktop')} + + + ), + )} + {example( + 'usePagination', + `const [pagination, { getPage, setPage, setPageSize, resetPagination }] = usePagination(loadRows, { itemCount: 95 })\n\n// Changing page size resets the page to 1.`, + () => ( + + + {rows.value.map((row) => ( + #{row} + ))} + +
+ +
+ + pages.setPage(2)}> + {text('pageTwo')} + + pages.setPageSize(20)}> + {text('pageSize20')} + + + {text('reset')} + + +
+ ), + )} + {example( + 'useDayjs', + `const { format, daysDiff, isDateInRange, getStartAndEndOfDay, isDayjs, locale } = useDayjs()\nformat('2026-11-03', { format: 'YYYY/MM/DD' })\ndaysDiff('2026-11-01', '2026-11-03')\nisDateInRange('2026-11-03', { start: '2026-11-01', end: '2026-11-30' })`, + () => ( + + { + date.value = value + }} + aria-label={text('date')} + /> +
+                  
+                    {JSON.stringify(
+                      {
+                        format: dayjs.format(date.value),
+                        daysDiff: dayjs.daysDiff('2026-11-01', date.value),
+                        inRange: dayjs.isDateInRange(date.value, {
+                          start: '2026-11-01',
+                          end: '2026-11-30',
+                        }),
+                        startOfDay: dayRange.value.formatStartOfDay,
+                        endOfDay: dayRange.value.formatEndOfDay,
+                      },
+                      null,
+                      2,
+                    )}
+                  
+                
+ { + dayRange.value = dayjs.getStartAndEndOfDay() + }} + > + {text('refreshDate')} + +
+ ), + )} + {example( + 'useI18n', + `const { t } = useI18n('hooks')\nt('webIntro')\nt('hooks.webIntro')\nconst { updateLocale } = useSettingActions()\nupdateLocale('en-US')`, + () => ( + + {text('webIntro')} + + changeLocale('zh-CN')}> + 简体中文 + + changeLocale('en-US')}> + English + + + + ), + )} + {example( + 'useVueRouter', + `const { router } = useVueRouter()\nrouter.currentRoute.value.fullPath\nrouter.replace({ path: '/web-hooks', query: { example: 'router' } })`, + () => ( + + + {router.currentRoute.value.fullPath} + + + + router.replace({ + path: '/web-hooks', + query: { example: 'router' }, + }) + } + > + {text('updateQuery')} + + router.push('/template-hooks')}> + {text('openTemplate')} + + + + ), + )} +
+

{label('browserCapabilities')}

+
+

Ray Template

+

{text('captureTarget')}

+

+ Vue 3 · TypeScript · Naive UI +

+ {fullscreen.isFullscreen.value ? ( + + {text('exitFullscreen')} + + ) : null} +
+
+ {example( + 'useElementFullscreen', + `const target = ref()\nconst { enter, exit, toggleFullscreen, isFullscreen } = useElementFullscreen(target)\n// CSS fullscreen: no browser permission required.\n
`, + () => ( + + {String(fullscreen.isFullscreen.value)} + + {text('toggleElementFullscreen')} + + + ), + )} + {example( + 'useDomToImage', + `const { create } = useDomToImage(target, { imageType: 'png' })\nconst png: string = await create()\nconst blob: Blob | null = await create('blob')`, + () => ( + + + {text('capture')} + + {error.value ? ( + {error.value} + ) : null} + {image.value ? ( + {text('capturePreview')} + ) : null} + + ), + )} + {example( + 'usePrint', + `const target = ref()\nconst { print } = usePrint(target, { type: 'html', targetStyles: ['*'] })\n// Call from a button click.`, + () => ( + {text('print')} + ), + )} + {example( + 'useContextmenuCoordinate', + `const { x, y, show, updateShow, stop } = useContextmenuCoordinate(target)\n\nstop() // Hides the menu and removes all listeners.`, + () => ( + +
{ + if (event.key === 'Escape') context.updateShow(false) + }} + > + {text('rightClick')} +
+ + x: {context.x.value}, y: {context.y.value}, show:{' '} + {String(context.show.value)} {selected.value} + + { + context.stop() + contextStopped.value = true + }} + > + {contextStopped.value ? text('stopped') : text('stop')} + + { + selected.value = String(key) + context.updateShow(false) + }} + onClickoutside={() => context.updateShow(false)} + /> +
+ ), + )} +
+ + ) + }, +}) diff --git a/src/views/demo/iframe/index.tsx b/src/views/demo/iframe/index.tsx index 03200bc3..0673bad5 100644 --- a/src/views/demo/iframe/index.tsx +++ b/src/views/demo/iframe/index.tsx @@ -1,11 +1,3 @@ -/** - * - * RIframe 组件使用示例 - * - * 具体使用参考 props 代码注释 - * 做了简单的一个组件封装, 希望有用 - */ - import { RIframe } from '@/components' import { NCard, NFlex } from 'naive-ui' diff --git a/src/views/demo/layout-demo.tsx b/src/views/demo/layout-demo.tsx new file mode 100644 index 00000000..4f2dc1f3 --- /dev/null +++ b/src/views/demo/layout-demo.tsx @@ -0,0 +1,43 @@ +import './hooks/index.scss' +import { useI18n } from '@/hooks' +import LayoutSettings from '@/layout/components/LayoutSettings' +import { useSettingGetters } from '@/store' +import { NCard } from 'naive-ui' +import DemoPage from './components/DemoPage' + +export default defineComponent({ + name: 'LayoutDemo', + setup() { + const { t } = useI18n('layout') + const { t: showcaseT } = useI18n('showcase') + const { getLayoutConfig } = useSettingGetters() + + return () => ( + ('title')} + description={t('description')} + eyebrow={showcaseT('layoutEyebrow')} + meta={showcaseT('livePreferences')} + > +
+ ('layoutControls')}> + + +
+ ('current')}> +
+                {JSON.stringify(getLayoutConfig.value, null, 2)}
+              
+
+ ('extension')}> +

{t('slots')}

+
+                {`const { updateSettingState } = useSettingActions()\n\nupdateSettingState('layoutConfig', {\n  mode: 'mixed',\n  contentWidth: 'fixed',\n})\n\n\n  {{\n    header: () => ,\n    footer: () => ,\n  }}\n`}
+              
+
+
+
+
+ ) + }, +}) diff --git a/src/views/demo/segment/index.tsx b/src/views/demo/segment/index.tsx index 8988e074..5e948fc8 100644 --- a/src/views/demo/segment/index.tsx +++ b/src/views/demo/segment/index.tsx @@ -66,17 +66,17 @@ export default defineComponent({ { label: '设置', key: 'setting', - icon: , + icon: , }, { label: '刷新', key: 'reload', - icon: , + icon: , }, { label: '搜索', key: 'search', - icon: , + icon: , popover: '我是搜索', }, ] diff --git a/src/views/demo/svg-icons/icons.ts b/src/views/demo/svg-icons/icons.ts deleted file mode 100644 index 243503b4..00000000 --- a/src/views/demo/svg-icons/icons.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Vite 8 的依赖扫描会将含 glob 的模块当作 JS;单独放在 TS 文件中避免保留的 JSX 被误解析。 -// 上游扫描器支持 JSX + import.meta.glob 后可合并回演示组件。 -export const iconNames = Object.keys(import.meta.glob('@/icons/**/*.svg')) - .map((path) => - path - .split('/') - .at(-1) - ?.replace(/\.svg$/, ''), - ) - .filter((name): name is string => Boolean(name)) diff --git a/src/views/demo/svg-icons/index.scss b/src/views/demo/svg-icons/index.scss index 44170c60..e07bb14c 100644 --- a/src/views/demo/svg-icons/index.scss +++ b/src/views/demo/svg-icons/index.scss @@ -1,10 +1,98 @@ +.r-icon-library { + &__toolbar { + display: flex; + flex-wrap: wrap; + gap: 12px; + } + &__search { + flex: 1; + min-width: min(240px, 100%); + } + &__filter { + width: 180px; + } + &__hint { + display: flex; + justify-content: space-between; + gap: 12px; + padding-block: 14px 24px; + color: var(--r-text-muted); + font-size: 12px; + } + &__group { + & + & { + margin-block-start: 28px; + } + > header { + display: flex; + align-items: center; + gap: 10px; + margin-block-end: 14px; + } + h2 { + color: var(--r-text-secondary); + font-family: var(--r-font-mono); + font-size: 12px; + font-weight: 600; + } + > header > span { + display: grid; + place-items: center; + min-width: 22px; + height: 20px; + border-radius: 5px; + color: var(--r-text-muted); + background: var(--r-surface-muted); + font-size: 10px; + } + } +} + +.pre-view-icons__grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(min(120px, 100%), 1fr)); + gap: 10px; +} + .pre-view-icons__card { - width: 120px; - height: 120px; - padding: 18px; + min-width: 0; + min-height: 104px; + padding: 18px 8px 14px; display: flex; + flex-direction: column; + gap: 14px; justify-content: center; align-items: center; - border: 1px solid var(--n-border-color); - border-radius: var(--n-border-radius); + border: 1px solid var(--r-line); + border-radius: 9px; + color: var(--r-text-secondary); + background: var(--r-surface-muted); + cursor: pointer; + transition: + background-color 0.18s ease, + border-color 0.18s ease; + + > span:last-child { + font-family: var(--r-font-mono); + font-size: 10px; + overflow-wrap: anywhere; + } + &:hover { + border-color: var(--r-control-border); + background: var(--r-surface); + color: var(--r-text); + } + &:focus-visible { + outline: 2px solid var(--r-theme-primary-color); + outline-offset: 2px; + } +} + +@container (max-width: 600px) { + .r-icon-library__filter { + width: 100%; + } + .pre-view-icons__grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } } diff --git a/src/views/demo/svg-icons/index.tsx b/src/views/demo/svg-icons/index.tsx index e19c4539..b091b1fc 100644 --- a/src/views/demo/svg-icons/index.tsx +++ b/src/views/demo/svg-icons/index.tsx @@ -1,46 +1,100 @@ import './index.scss' import { RIcon } from '@/components' -import { NCard, NFlex, NPopover } from 'naive-ui' -import { iconNames } from './icons' +import { useI18n } from '@/hooks' +import { iconNames, iconPackages } from '@/icons' +import { NCard, NEmpty, NInput, NSelect } from 'naive-ui' +import DemoPage from '../components/DemoPage' -const PreviewSVGIcons = defineComponent({ +export default defineComponent({ name: 'PreviewSVGIcons', setup() { - const icons = iconNames + const { t } = useI18n('icons') + const { t: showcaseT } = useI18n('showcase') + const query = ref('') + const selectedPackage = ref(null) + const filtered = computed(() => + iconNames.filter( + (name) => + (!selectedPackage.value || + name.startsWith(`${selectedPackage.value}/`)) && + name.includes(query.value.trim().toLowerCase()), + ), + ) + const groups = computed(() => + iconPackages + .map((name) => ({ + name, + icons: filtered.value.filter((icon) => icon.startsWith(`${name}/`)), + })) + .filter((group) => group.icons.length), + ) - return { - icons, - } - }, - render() { - return ( - - {{ - 'header-extra': () => '点击图标复制代码', - default: () => ( - - {this.icons.map((curr) => ( -
`} - key={curr} - > - - {{ - trigger: () => ( - - ), - default: () => curr, - }} - -
- ))} -
- ), - }} -
+ return () => ( + ('title')} + description={t('description')} + eyebrow={showcaseT('iconsEyebrow')} + meta={`${iconNames.length} SVG / ${iconPackages.length} ${t('packagesLabel')}`} + > + +
+ { + query.value = value + }} + placeholder={t('search')} + inputProps={{ 'aria-label': t('search') }} + clearable + > + {{ prefix: () => }} + + { + selectedPackage.value = value + }} + options={iconPackages.map((value) => ({ label: value, value }))} + clearable + placeholder={t('allPackages')} + /> +
+
+ {t('copy')} + + {filtered.value.length} / {iconNames.length} + +
+ {groups.value.map((group) => ( +
+
+

{group.name}

+ {group.icons.length} +
+
+ {group.icons.map((name) => ( + + ))} +
+
+ ))} + {!filtered.value.length ? ( + ('empty')} /> + ) : null} +
+
) }, }) - -export default PreviewSVGIcons diff --git a/src/views/demo/table-pro-demo.tsx b/src/views/demo/table-pro-demo.tsx index 218b2cd1..cd4e8479 100644 --- a/src/views/demo/table-pro-demo.tsx +++ b/src/views/demo/table-pro-demo.tsx @@ -400,14 +400,14 @@ export default defineComponent({ (this.collapseRef = true)} secondary> {{ default: () => '受控展开', - icon: () => , + icon: () => , }} ) : ( (this.collapseRef = false)} secondary> {{ default: () => '受控收起', - icon: () => , + icon: () => , }} ), diff --git a/src/views/demo/table/index.tsx b/src/views/demo/table/index.tsx index 3392f252..6793d609 100644 --- a/src/views/demo/table/index.tsx +++ b/src/views/demo/table/index.tsx @@ -354,7 +354,7 @@ const TableView = defineComponent({ {{ trigger: () => ( { diff --git a/src/views/demo/template-hooks/index.tsx b/src/views/demo/template-hooks/index.tsx index 8b55cc29..e4f27d58 100644 --- a/src/views/demo/template-hooks/index.tsx +++ b/src/views/demo/template-hooks/index.tsx @@ -1,227 +1,337 @@ import { RIcon } from '@/components' -import { getVariableToRefs } from '@/global-variable' import { useAppNavigation, + useAppRoot, useBadge, + useContentScroll, + useI18n, useMaximize, + useSiderBar, + useSiderScroll, useSpinning, useTheme, + useVueRouter, useWatermark, } from '@/hooks' -import { useSettingGetters } from '@/store' -import { NButton, NCard, NFlex, NInput } from 'naive-ui' +import { useMenuGetters, useRuntimeGetters, useSettingGetters } from '@/store' +import { useTimeoutFn } from '@vueuse/core' +import { NButton, NFlex, NInput, NTag } from 'naive-ui' +import DemoPage from '../components/DemoPage' +import HookExample from '../hooks/HookExample' export default defineComponent({ name: 'TemplateHooks', setup() { - const currentMenuOption = ref('') - const maximizeRef = getVariableToRefs('layoutContentMaximize') - const watermark = ref(useSettingGetters().getWatermarkConfig.value.content) - const badgeValue = ref('new') - + const { t } = useI18n('hooks') + const text = (key: string) => t(key) + const { t: showcaseT } = useI18n('showcase') + const label = (key: string) => showcaseT(key) + const { router } = useVueRouter() + const theme = useTheme() + const watermark = useWatermark() + const badge = useBadge() + const spinning = useSpinning() + const maximize = useMaximize() + const root = useAppRoot() + const tags = useSiderBar() const { navigationTo } = useAppNavigation() - const { maximize, isLayoutContentMaximized } = useMaximize() - const { reload, openSpin, closeSpin } = useSpinning() - const { - showWatermark, - hiddenWatermark, - setWatermarkContent, - toggleWatermark, - } = useWatermark() - const { darkTheme, lightTheme, toggleTheme, getAppTheme, syncSystemTheme } = - useTheme() - const { - hidden: badgeHidden, - show: badgeShow, - update: badgeUpdateLabel, - } = useBadge() + const contentScrollTo = useContentScroll() + const siderScrollTo = useSiderScroll() + const settings = useSettingGetters() + const { getMenuTagOptions } = useMenuGetters() + const runtime = useRuntimeGetters() + const badgeLabel = ref('new') + const watermarkText = ref(settings.getWatermarkConfig.value.content) + const { start: stopSpinLater } = useTimeoutFn(spinning.closeSpin, 800, { + immediate: false, + }) - return { - navigationTo, - reload, - currentMenuOption, - maximize, - maximizeRef, - openSpin, - closeSpin, - showWatermark, - hiddenWatermark, - setWatermarkContent, - watermark, - toggleWatermark, - darkTheme, - lightTheme, - toggleTheme, - getAppTheme, - isLayoutContentMaximized, - badgeHidden, - badgeShow, - badgeUpdateLabel, - badgeValue, - syncSystemTheme, - } - }, - render() { - const { - navigationTo, - reload, - maximize, - openSpin, - closeSpin, - showWatermark, - hiddenWatermark, - setWatermarkContent, - toggleWatermark, - darkTheme, - lightTheme, - toggleTheme, - getAppTheme, - isLayoutContentMaximized, - badgeHidden, - badgeShow, - badgeUpdateLabel, - syncSystemTheme, - } = this + onBeforeUnmount(spinning.closeSpin) + // 过渡期间组件仍可能渲染,操作目标保持为本示例页面。 + const currentPath = router.currentRoute.value.path + const current = () => currentPath + const hasCurrentTag = computed(() => + getMenuTagOptions.value.some((tag) => tag.fullPath === currentPath), + ) + const example = ( + name: string, + code: string, + children: () => JSX.Element, + ) => ( + + {children()} + + ) - return ( - - -

- hooks/template 包存放模板专属 hook - 方法。这里不做过多的赘述,可以查看文档具体描述。 -

-
- - - - - badgeHidden('/template-hooks')}> - 隐藏当前菜单标记 - - - badgeShow('/template-hooks', { - label: this.badgeValue, - }) - } - > - 显示当前菜单标记 - - - badgeUpdateLabel('/template-hooks', { - label: this.badgeValue, - }) - } - > - 更新当前菜单标记 - - { - badgeUpdateLabel('/template-hooks', { - label: this.badgeValue, - icon: , - }) - }} - > - 添加标记图标 - - { - badgeUpdateLabel('/template-hooks', { - label: this.badgeValue, - icon: void 0, - }) - }} - > - 隐藏标记图标 - - - - - - -

getAppTheme 获取当前主题色: {getAppTheme().themeLabel}

- - darkTheme()}>切换暗黑主题 - lightTheme()}>切换明亮主题 - syncSystemTheme()}>跟随主题 - toggleTheme()}>切换主题 - -
-
- - - { - setWatermarkContent(val) - }} - /> - - showWatermark()}>显示水印 - hiddenWatermark()}>隐藏水印 - toggleWatermark()}>切换水印 - - - - -

- 手动刷新内容区域,会使得当前路由页面内容强制重新加载(会执行完整的 - vue 生命周期)。默认 800ms 延迟。 -

-
- - { - reload() - }} - > - 刷新(强制刷新) - - { - openSpin() - - setTimeout(() => { - closeSpin() - }, 800) - }} - > - 触发加载动画(不强制刷新) - - -
- -

- isLayoutContentMaximized 检测当前内容区域是否最大化: - {isLayoutContentMaximized ? '最大化' : '正常尺寸'} -

- { - maximize(!this.maximizeRef, { - scrollToOptions: { - left: 0, - top: -9999, - }, - }) - }} - > - 最大化内容区域,并且滚动至顶部 - -
- -

- navigationTo - 参数为正整数时,会更具当前的菜单顺序进行自动导航匹配。但是此方法仅能导航一级菜单。并且如果导航菜单非根菜单项,会自动递归导航至一子菜单。 - 支持传入完整的菜单路径,如:/multi/multi-menu-one。 -

-
- navigationTo('/multi/multi-menu-one')}> - 跳转至多级菜单 - -
-
+ return () => ( + +

{label('appearanceAndPage')}

+
+ {example( + 'useTheme', + `const { darkTheme, lightTheme, toggleTheme, syncSystemTheme, getAppTheme } = useTheme()\ntoggleTheme()\ngetAppTheme().themeLabel`, + () => ( + + {theme.getAppTheme().themeI18nLabel} + {text('dark')} + {text('light')} + + {text('system')} + + {text('toggle')} + + ), + )} + {example( + 'useSpinning', + `const { openSpin, closeSpin, reload } = useSpinning()\nopenSpin()\n// Call closeSpin() when work finishes.\nreload(800)`, + () => ( + + { + spinning.openSpin() + stopSpinLater() + }} + > + {text('spin')} + + spinning.reload()}> + {text('reload')} + + {String(runtime.layoutContentSpinning.value)} + + ), + )} + {example( + 'useMaximize', + `const { maximize, isLayoutContentMaximized, toggleFullscreen } = useMaximize()\nmaximize(true, { scrollToOptions: { top: 0 } })\nmaximize(false)`, + () => ( + + {String(maximize.isLayoutContentMaximized.value)} + + {text('maximize')} + + + ), + )} +
+

{label('globalMarkers')}

+
+ {example( + 'useBadge', + `const { show, update, hidden } = useBadge()\nshow('/template-hooks', { label: 'new' })\nupdate('/template-hooks', { label: '3', type: 'warning' })\nhidden('/template-hooks')`, + () => ( + + { + badgeLabel.value = value + }} + aria-label={text('badgeLabel')} + /> + + + badge.show(current(), { label: badgeLabel.value }) + } + > + {text('show')} + + + badge.update(current(), { + label: badgeLabel.value, + icon: , + type: 'warning', + }) + } + > + {text('update')} + + badge.update(current(), { icon: void 0 })} + > + {text('clearIcon')} + + badge.hidden(current())}> + {text('hide')} + + + + ), + )} + {example( + 'useWatermark', + `const { setWatermarkContent, showWatermark, hiddenWatermark, toggleWatermark } = useWatermark()\nsetWatermarkContent('Ray Template')\nshowWatermark()`, + () => ( + + { + watermarkText.value = value + watermark.setWatermarkContent(value) + }} + aria-label={text('watermarkText')} + /> + + + {text('show')} + + + {text('hide')} + + + {text('toggle')} + + + + ), + )} +
+

{label('navigationAndTabs')}

+
+ {example( + 'useAppNavigation', + `const { navigationTo } = useAppNavigation()\nawait navigationTo('/web-hooks', { query: { from: 'hooks' } })\n// A zero-based index navigates to the first child of that section.\nawait navigationTo(0)`, + () => ( + + + navigationTo('/web-hooks', { query: { from: 'hooks' } }) + } + > + {text('openWeb')} + + navigationTo('/multi/multi-menu-one')}> + {text('openNested')} + + navigationTo(0)}> + {text('firstMenu')} + + + ), + )} + {example( + 'useAppRoot', + `const { getRootRoute, getRootPath, getRootName, setRootRoute } = useAppRoot()\nsetRootRoute({ name: 'TemplateHooks', path: '/template-hooks' })`, + () => ( + + {JSON.stringify(root.getRootRoute.value)} + + + root.setRootRoute({ + name: 'TemplateHooks', + path: '/template-hooks', + }) + } + > + {text('useCurrentHome')} + + + root.setRootRoute({ + name: 'Dashboard', + path: '/dashboard', + }) + } + > + {text('restoreHome')} + + + + ), + )} + {example( + 'useSiderBar', + `const { close, closeAll, closeLeft, closeRight, closeOther, getCurrentTagIndex } = useSiderBar()\ncloseOther('/template-hooks')`, + () => ( + + + {getMenuTagOptions.value + .map((tag) => tag.fullPath) + .join(' · ')} + + + tags.closeOther(current())}> + {text('closeOther')} + + tags.closeLeft(current())} + > + {text('closeLeft')} + + tags.closeRight(current())} + > + {text('closeRight')} + + tags.close(current())}> + {text('closeCurrent')} + + {text('closeAll')} + + + ), + )} +
+

{label('scrollControls')}

+
+ {example( + 'useContentScroll', + `const contentScrollTo = useContentScroll()\ncontentScrollTo({ top: 0, behavior: 'smooth' })\ncontentScrollTo(0, 300)`, + () => ( + + + contentScrollTo({ top: 0, behavior: 'smooth' }) + } + > + {text('contentTop')} + + contentScrollTo(0, 300)}> + {text('content300')} + + + ), + )} + {example( + 'useSiderScroll', + `const siderScrollTo = useSiderScroll()\nsiderScrollTo({ top: 0, behavior: 'smooth' })\nsiderScrollTo(0, 300)`, + () => ( + + siderScrollTo({ top: 0, behavior: 'smooth' })} + > + {text('siderTop')} + + siderScrollTo(0, 300)} + > + {text('sider300')} + + + ), + )} +
+
) }, }) diff --git a/src/views/error/PageResult/index.tsx b/src/views/error/PageResult/index.tsx index 159ae6c4..b667a173 100644 --- a/src/views/error/PageResult/index.tsx +++ b/src/views/error/PageResult/index.tsx @@ -1,11 +1,3 @@ -/** - * - * 错误页面 - * - * 基于 NResult 组件实现, 继承该组件所有 props 与 slots - * 可以当作一个组件使用, 也可以当作一个页面调用 - */ - import './index.scss' import { redirectRouterToDashboard } from '@/router/utils' import { useSettingGetters } from '@/store' diff --git a/src/views/login/components/QRCodeSigning/index.tsx b/src/views/login/components/QRCodeSigning/index.tsx index 7f1ffaea..58eca0c5 100644 --- a/src/views/login/components/QRCodeSigning/index.tsx +++ b/src/views/login/components/QRCodeSigning/index.tsx @@ -2,13 +2,6 @@ import './index.scss' import LOGO from '@/assets/images/ray.svg' import { Vue3NextQrcode } from 'vue3-next-qrcode' -/** - * - * 二维码登陆 - * - * 可以根据业务需求自行更改 - */ - const QRCodeSigning = defineComponent({ name: 'QRCodeSigning', setup() { diff --git a/src/views/login/components/SSOSigning/index.tsx b/src/views/login/components/SSOSigning/index.tsx index 3c6618e6..b0b3fc95 100644 --- a/src/views/login/components/SSOSigning/index.tsx +++ b/src/views/login/components/SSOSigning/index.tsx @@ -1,16 +1,10 @@ -/** - * - * SSO 单点登录模块组件 - * - * 按照需求自行增减 - */ - +import type { IconName } from '@/icons' import './index.scss' import { RIcon } from '@/components' import { NFlex, NPopover } from 'naive-ui' interface SSOSigningOptions { - icon: string + icon: IconName key: string tooltipLabel: string } @@ -18,19 +12,19 @@ interface SSOSigningOptions { const SSOSigning = defineComponent({ name: 'SSOSigning', setup() { - const ssoSigningOptions = [ + const ssoSigningOptions: SSOSigningOptions[] = [ { - icon: 'github', + icon: 'logo/github', key: 'github', tooltipLabel: 'Github登陆', }, { - icon: 'google', + icon: 'logo/google', key: 'google', tooltipLabel: 'Google登陆', }, { - icon: 'twitter', + icon: 'logo/twitter', key: 'twitter', tooltipLabel: 'Twitter登陆', }, diff --git a/src/views/login/index.tsx b/src/views/login/index.tsx index 4f8e3d75..ed6d4941 100644 --- a/src/views/login/index.tsx +++ b/src/views/login/index.tsx @@ -62,7 +62,7 @@ const Login = defineComponent({ >