feat: enhance template layouts, hooks, and icon workflow

Add interactive hook examples, shared Pinia runtime state, and configurable layouts.
Generate typed namespaced icons during development, HMR, and builds.
Refine the UI and establish project comment and design conventions.

Validation: typecheck, ESLint, 181 tests, and production build passed.
This commit is contained in:
XiaoDaiGua-Ray 2026-11-03 13:17:58 +08:00
parent 3c6a91b083
commit 39d2e82439
226 changed files with 4833 additions and 1836 deletions

View File

@ -21,6 +21,7 @@
- 网络调用从 `src/api` 进入 `src/axios`,不要绕过拦截器。Mock 位于 `mock`,不是生产后端或真实鉴权。
- 界面文本同时更新 `src/locales/lang/zh-CN` 与 `en-US`。检查明暗主题和窄屏;不要为修复构建随意删除样式或交互。
- 修改公共组件或工具前先查看调用方、类型、测试与导出;优先修共享根因,补有意义的回归用例。不得通过跳过测试、降低严格度或宽泛 `any` 掩盖问题。
- 新增或修改注释前阅读并遵循 [注释规范](docs/comment-style.md)。禁止在文件顶部或组件声明前写多行介绍,也不得将文件说明移动到首个函数或常量前;同一声明不堆叠多个 JSDoc。
- 注释解释接口契约或非显然原因,避免逐行复述。不要进行与任务无关的重构或新增抽象。
## AI 工作方式

View File

@ -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`.

View File

@ -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`。

View File

@ -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()
})
})

View File

@ -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)
})
})

View File

@ -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()
})
})

View File

@ -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<string>()
expectTypeOf(result).toEqualTypeOf<Blob | null>()
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)
})
})

View File

@ -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('')
})
})

View File

@ -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<string>
}
}
| 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<string>()
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')
})
})

View File

@ -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<LayoutInst | null>
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)
})
})

View File

@ -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)
}
})

View File

@ -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<typeof createPinia>
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)
})
})

View File

@ -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',
)
})
})

View File

@ -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<string, string> } =>
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'), '<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'), '<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)

107
__test__/icons/hmr.spec.ts Normal file
View File

@ -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<void>>(),
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<void>>().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<void>
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<void>
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')
})

View File

@ -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<IconProps['name']>().toEqualTypeOf<IconName>()
expectTypeOf<Extract<IconName, 'resize_h'>>().toEqualTypeOf<never>()
})
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, '<svg/>')
}
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()
})
})

View File

@ -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()
}
})

View File

@ -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)
}
})
})

View File

@ -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)
}
})

View File

@ -19,6 +19,8 @@ pnpm dev
Codex 自动读取根目录 `AGENTS.md`;Cursor、Copilot 和 Claude 的项目入口也指向同一份规则。新对话只需提供目标、影响页面或报错、预期行为、约束和验收条件,无需粘贴整个仓库。
编写或修改注释时统一遵循 [注释规范](comment-style.md),由 `AGENTS.md` 引入。组件说明放在 README 和示例页;函数契约、模块声明与内部逻辑使用各自规定的形式,不在工具适配文件重复维护规范。
## 命令契约
| 命令 | 用途与结果 |

View File

@ -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)。

56
docs/comment-style.md Normal file
View File

@ -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<void>` 和构造函数不写 `@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`、`/// <reference ... />`、`/* @__PURE__ */`。JSX 子节点使用 `{/* 说明 */}`;HTML、CSS 使用各自合法的定界符。
交付前检查注释位置、是否堆叠、参数名、标签顺序和内容真实性。注释规范不替代 ESLint、Prettier、类型检查或浏览器验收。

View File

@ -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)

24
docs/ui-design.md Normal file
View File

@ -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` 系统颜色回退、可见键盘焦点与减少动态效果设置。截图、颜色数值与浏览器检查不能互相替代,也不代表已验证全部最低版本设备。

View File

@ -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": {

4
scripts/icons.d.mts Normal file
View File

@ -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<void>

74
scripts/icons.mjs Normal file
View File

@ -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<string> = 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'))
}

View File

@ -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<AxiosTestResponse>({

View File

@ -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)。

View File

@ -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'

View File

@ -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,

View File

@ -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,
}
}

View File

@ -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;
}
}

View File

@ -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 () => (
<header class="r-page-header">
<div class="r-page-header__copy">
<p class="r-page-header__eyebrow">{props.eyebrow}</p>
<h1>{props.title}</h1>
{props.description ? (
<p class="r-page-header__description">{props.description}</p>
) : null}
</div>
{slots.default ? (
<div class="r-page-header__actions">{slots.default()}</div>
) : null}
</header>
)
},
})

View File

@ -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);
}
}
}

View File

@ -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 (
<NFlex>
{this.avatarOptions.map((curr) => (
<NTooltip key={curr.key}>
{{
trigger: () => (
<NAvatar
round
src={curr.icon}
style={['cursor: pointer']}
{...{
onClick: this.handleLinkClick.bind(this, curr),
}}
objectFit="cover"
size={24}
/>
),
default: () => curr.tooltip,
}}
</NTooltip>
))}
</NFlex>
<div class={['r-share-links', `r-share-links--${this.variant}`]}>
<div class="r-share-links__grid">
{this.avatarOptions.map((item) => (
<a
class="r-share-link"
href={item.src}
aria-label={this.t<string>(item.tooltip)}
title={this.t<string>(item.tooltip)}
target="_blank"
rel="noreferrer"
key={item.key}
>
<NAvatar round src={item.icon} size={24} />
<span>{this.t(item.tooltip)}</span>
<RIcon name="action/shared" size={13} />
</a>
))}
</div>
</div>
)
},
})

View File

@ -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,
})),
},
)

View File

@ -1,11 +1,3 @@
/**
*
* 路由更新前,取消上一路由所有请求
*
* 生命周期示意图:
* beforeRouteUpdate -> cancelAllRequest -> routeUpdate
*/
import { axiosCanceler } from '@/axios/utils/interceptor'
const AppRequestCancelerProvider = defineComponent({

View File

@ -1,9 +1,3 @@
/**
*
* 检测当前版本是否为最新版本
* 如果不是最新版本则弹出提示框,提示用户更新,点击确认后退出登录并且刷新资源
*/
import { APP_CATCH_KEY } from '@/app-config'
import { RModal } from '@/components'
import { useSigningActions } from '@/store'

View File

@ -1,13 +1,3 @@
/**
*
* 全局水印注入
*
* 该组件启用时,会在全局(包括首页)展示
* 如果你不希望在登录页显示,可以手动将该组件放置于 Layout 中
*
* 当然你也可以通过 useWatermark hook 自定义控制水印的显示以及内容
*/
import { useSettingGetters } from '@/store'
import { NWatermark } from 'naive-ui'

View File

@ -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' },
},
},
/**

View File

@ -1,9 +1,3 @@
/**
*
* 正则入口
* 系统公共正则, 配置在该文件中
*/
export const APP_REGEX: Record<string, RegExp> = {
/** css 尺寸单位匹配 */
cssUnit:

View File

@ -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: [

View File

@ -1,21 +1,6 @@
/**
*
* 响应拦截器入口
* 被注册方法执行时其实例能够保证获取到, 所以不需要做额外空判断
* 在内部执行方法中, 已经做了边界处理
*
* 提供两个工具方法, 方便类型推导
*
* 其中 injectResponseCanceler responseErrorCanceler 方法是注入的 axios response interceptor 方法
*/
import { injectResponseCanceler, responseErrorCanceler } from './plugins/cancel'
/**
*
* 注册响应拦截器
* 请注意执行顺序
*/
/** 响应拦截器注册列表,分别管理成功和失败分支。 */
export default {
// 响应正常
implementResponseInterceptorArray: [injectResponseCanceler],

View File

@ -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,

13
src/components/README.md Normal file
View File

@ -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 与示例页。

View File

@ -59,30 +59,6 @@ echartThemes.forEach((curr) => {
registerTheme(curr.name, curr.theme)
})
/**
*
* @description
* 基于 echarts 的图表组件。
*
* 让你仅需要关注 echarts options 的配置管理,而不需要关心 echarts 的初始化、销毁、主题切换等操作。
*
* 如果需要拓展配置项,进需要在使用该组件的时候使用 use 方法注册对应 chart 组件即可。
*
* @example
* <template>
* <RChart :options="options" @register="register" />
* </template>
*
* <script setup>
* import { RChart } from '@/components'
*
* import { useChart } from 'vue'
* import { ref } from 'vue'
*
* const [register, { ...Hooks }] = useChart()
* const options = ref({ ... })
* </script>
*/
export default defineComponent({
name: 'RChart',
props,

View File

@ -1,14 +1,3 @@
/**
*
* @author Ray <https://github.com/XiaoDaiGua-Ray>
*
* @date 2023-07-22
*
* @workspace ray-template
*
* @remark 今天也是元气满满撸代码的一天
*/
import type { ECharts } from 'echarts/core'
import type { CanvasRenderer } from 'echarts/renderers' // `echarts` 渲染器

View File

@ -1,13 +1,3 @@
/**
*
* <https://www.naiveui.com/zh-CN/dark/components/grid>
*
* 可折叠操作栏
* 可以结合表单或者表格使用,让你快捷的实现高级搜索功能
*
* 该组件完全基于 `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"
/>
</div>

View File

@ -3,5 +3,6 @@ import RIcon from './src/Icon'
import iconProps from './src/props'
export type IconProps = ExtractPublicPropTypes<typeof iconProps>
export type { IconName, IconPackage } from '@/icons/manifest'
export { RIcon, iconProps }

View File

@ -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 = {

View File

@ -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<IconName>,
required: true as const,
},
size: {
type: [Number, String],

View File

@ -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<IconName>,
default: 'action/more',
},
iconSize: {
type: Number,

View File

@ -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 = () => (
<RIcon name="draggable" size={14} cursor="grab" />
<RIcon name="action/draggable" size={14} cursor="grab" />
)
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: () => (
<NFlex style="padding-left: 32px;">
<RowIconRender
icon="row_head"
icon="directional/row_head"
title="固定在列首"
customClassName={
isLeftFixedActivated ? R_TABLE_C_TOOL_ICON_ACTIVE : ''
@ -141,7 +133,7 @@ export default defineComponent({
{{
trigger: () => (
<RIcon
name="resize_h"
name="directional/resize_h"
size={config.tableIconSize}
cursor="pointer"
customClassName={
@ -154,7 +146,7 @@ export default defineComponent({
}}
</NPopover>
<RowIconRender
icon="row_end"
icon="directional/row_end"
title="固定在列尾"
customClassName={
isRightFixedActivated ? R_TABLE_C_TOOL_ICON_ACTIVE : ''
@ -249,7 +241,7 @@ export default defineComponent({
{{
trigger: () => (
<RIcon
name="setting"
name="action/setting"
size={config.tableIconSize}
cursor="pointer"
customClassName="r-table__setting"

View File

@ -23,7 +23,7 @@ export default defineComponent({
return (
<RIcon
name="fullscreen"
name="action/fullscreen"
size={config.tableIconSize}
cursor="pointer"
onClick={() => {

View File

@ -40,7 +40,7 @@ export default defineComponent({
render() {
return (
<RIcon
name="print"
name="action/print"
size={config.tableIconSize}
cursor="pointer"
onClick={this.printTableClick.bind(this)}

View File

@ -69,7 +69,7 @@ export default defineComponent({
onUpdateValue={this.updatePopselectValue.bind(this)}
>
<RIcon
name="expanded"
name="directional/expanded"
size={config.tableIconSize}
cursor="pointer"
style="transform: rotate(270deg);"

View File

@ -55,7 +55,11 @@ export default defineComponent({
trigger="click"
onUpdateValue={this.updatePopselectValue.bind(this)}
>
<RIcon name="adjustment" size={config.tableIconSize} cursor="pointer" />
<RIcon
name="action/adjustment"
size={config.tableIconSize}
cursor="pointer"
/>
</NPopselect>
)
},

View File

@ -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',
})

View File

@ -23,12 +23,6 @@ export const collapseProps = Object.assign({}, formProps, {
},
})
/**
*
* @description
* 基于 RCollapseGrid 和 RForm 的折叠表单组件;
* 同样也继承了 RCollapseGrid 组件的缺点,必须使用 NFormItemGi, NGridItem 组件包裹表单项。
*/
export default defineComponent({
name: 'RCollapse',
props: collapseProps,

View File

@ -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)。

View File

@ -1,18 +1,3 @@
/**
*
* directive name: copy
*
* @description
* 该指令用于处理复制,使用的时候必须传递正确的 value 值。
*
* 指令基于 clipboard.js 实现。
*
* @example
* <template>
* <button v-copy="copyText">复制</button>
* </template>
*/
import type { CustomDirectiveFC } from '@/directives/types'
import ClipboardJS from 'clipboard'
import type { CopyElement } from './types'

View File

@ -1,22 +1,3 @@
/**
*
* directive name: debounce
*
* @description
*
* 该指令用于处理防抖,使用的时候必须传递正确的 func 值。
*
* 其中 trigger 和 wait 是可选的,trigger 默认为 click,wait 默认为 500。
*
* @example
* <template>
* <div v-debounce="{ func: () => console.log('debounce') }">这是一个防抖指令</div>
* </template>
* <template>
* <div v-debounce="{ func: () => console.log('debounce'), trigger: 'click', wait: 500 }">这是一个防抖指令</div>
* </template>
*/
import type { CustomDirectiveFC } from '@/directives/types'
import type { AnyFn } from '@/types'
import { useEventListener } from '@vueuse/core'

View File

@ -1,19 +1,3 @@
/**
*
* directive name: disabled
*
* @description
* 该指令用于处理元素的禁用状态,使用的时候必须传递正确的 value 值。
*
* 该方法依赖 r-template__directive--disabled 样式类,需要在全局样式中定义,
* 并且该指令仅仅是做了 css 样式层面的禁用效果,如果有需要,还需要在业务逻辑中做相应的处理。
*
* @example
* <template>
* <button v-disabled="true">这是一个禁用按钮</button>
* </template>
*/
import type { CustomDirectiveFC } from '@/directives/types'
import { removeClass, setClass } from '@/utils'

View File

@ -1,35 +1,14 @@
/**
*
* directive name: ellipsis
*
* @description
* 该指令用于处理文本溢出省略,使用的时候必须传递正确的 width 值。
*
* 其中 line 和 type 是可选的,line 默认为 1,type 默认为 block。
*
* @example
* <template>
* <div v-ellipsis="{ line: 2, width: 200 }">这是一段需要省略的文字</div>
* </template>
* <template>
* <div v-ellipsis="{ type: 'block', width: 200 }">这是一段需要省略的文字</div>
* </template>
*/
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

View File

@ -1,28 +1,3 @@
/**
*
* directive name: ripple
*
* @description
* 水波纹指令。
*
* 使用方式:
* @example
* <template>
* <button v-ripple>点击查看水波纹效果</button>
* </template>
* <template>
* <div
* style="height: 20px; line-height: 20px;text-align: center; border: 1px solid; padding: 6px;"
* v-ripple={[true, ['center']]}
* >
* 原生元素绑定水波纹效果,并且手动绑定 modifiers 为 center
* </div>
* </template>
*
* const DemoOne = () => <div v-ripple>hi</div>
* const DemoTwo = () => <div v-ripple={[true, ['circle']]}>hi</div>
*/
import './index.scss'
import type { CustomDirectiveFC } from '@/directives/types'
import type { RippleElement, RippleValue } from './types'

View File

@ -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',

View File

@ -1,21 +1,3 @@
/**
*
* directive name: throttle
*
* @description
* 该指令用于处理节流,使用的时候必须传递正确的 func 值。
*
* 其中 trigger 和 wait 是可选的,trigger 默认为 click,wait 默认为 500。
*
* @example
* <template>
* <div v-throttle="{ func: () => console.log('throttle') }">这是一个节流指令</div>
* </template>
* <template>
* <div v-throttle="{ func: () => console.log('throttle'), trigger: 'click', wait: 500 }">这是一个节流指令</div>
* </template>
*/
import type { CustomDirectiveFC } from '@/directives/types'
import type { AnyFn } from '@/types'
import { useEventListener } from '@vueuse/core'

View File

@ -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<demo value>
// 获取响应式变量
const yourGlobalValue = getVariableToRefs('yourGlobalValue') // Readonly<Ref<demo value>>
```
> 注意,避免滥用该模块。可能会导致管理不当引起内存泄漏。

View File

@ -1,3 +0,0 @@
export * from './variable'
export type * from './variable'

View File

@ -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<T> = {
[K in keyof T & string]: Readonly<Ref<T[K]>>
}
/**
*
* @param key variable key
* @param value variable value
* @param cb 设置完成后的回调函数
*
* 手动设置 variableState 的值
*
* @example
* setVariable('globalSpinning', true) // 设置全局加载状态为 true
* setVariable('globalSpinning', true, () => {}) // 设置全局加载状态为 true,并且在设置完成后执行回调函数
*/
export function setVariable<T extends VariableStateKey, FC extends AnyFn>(
key: T,
value: VariableState[T],
cb?: FC,
) {
updateObjectValue(variableState, key, value, cb)
}
/**
*
* @param key 目标值 key
*
* 返回目标值的响应式 ref
*
* @example
* getVariableToRefs('globalSpinning') // 返回 Ref<boolean>
*/
export function getVariableToRefs<K extends VariableStateKey>(key: K) {
return readonly(toRef<VariableState, K>(variableState, key))
}
/**
*
* @description
* 允许解构获取 variable 属性。并且返回一个只读的 ref。
*
* 该方法为了解决 getVariableToRefs 方法的解构问题,如果需要在一个地方获取很多 variable 属性,可以使用该方法。
*
* @example
* const { globalMainLayoutLoad } = getVariable()
*/
export function getVariable(): ReadonlyVariableState<typeof variableState> {
return {
...toRefs(readonly(variableState)),
}
}

39
src/hooks/README.md Normal file
View File

@ -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 测试验证状态与异常处理,不能替代原生打印界面或实际纸张输出验收。

View File

@ -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<MaybeElement>, (detectIframe) => {
clickOutside(detectIframe)
})
}
const cleanupOutside = onClickOutside(
target as MaybeElementRef<MaybeElement>,
(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),

View File

@ -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)
}
}

View File

@ -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

View File

@ -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
}

View File

@ -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<HTMLElement>
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),
}
}

View File

@ -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.`,
)

View File

@ -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
}

View File

@ -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<typeof useSpinning>

View File

@ -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)
}

View File

@ -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,

View File

@ -63,7 +63,10 @@ type Options<
*
* @default undefined
*/
created?: (result: DomToImageReturnType<ImageType>, element: T) => void
created?: (
result: DomToImageReturnType<DomToImageMethodKeys>,
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<T, ImageType> & HtmlToImageOptions
/**
@ -105,21 +108,21 @@ export type UseDomToImageOptions<
* 当然,你也可以不传递 imageType 参数,此时会使用 options.imageType,
* 如果都未传递,则默认使用 jpeg。
*
* 如果希望 created 获得准确的类型,可以给 useDomToImage 手动声明第二个类型参数;
* 或者就是在显式声明 options.imageType 参数。
* create 的返回类型跟随配置或本次传入的格式;created 可能接收覆盖格式后的结果,
* 因此应先用 typeof / instanceof 判断回调中的结果类型。
*
* @example
* const refDom = ref<HTMLElement>()
* 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<T>,
options?: UseDomToImageOptions<T, ImageType>,
@ -132,40 +135,30 @@ export const useDomToImage = <
imageType: _imageType,
} = options ?? {}
const run = <ImageType extends DomToImageMethodKeys = 'jpeg'>(
imageType?: ImageType,
): Promise<DomToImageReturnType<ImageType>> => {
return new Promise((resolve, reject) => {
const element = unrefElement(target)
const run = async <OutputType extends DomToImageMethodKeys = ImageType>(
imageType?: OutputType,
): Promise<DomToImageReturnType<OutputType>> => {
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<OutputType>
} catch (error) {
createdError?.(error instanceof Error ? error : new Error(String(error)))
throw error
} finally {
_finally?.(element)
}
}
return {

View File

@ -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?.()
}

View File

@ -5,7 +5,7 @@ export interface OverrideUseI18nReturnType extends Omit<
I18n['global'],
't' | 'locale'
> {
t: <T = unknown>(key: string, ...args: T[]) => T
t: <T = string>(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 = <T = string>(key: string, ...args: unknown[]): T => {
if (!key) return '' as T
if (!key.includes('.') && !namespace) return key as T
const fullKey = getI18nKey(namespace, key)
const instance = i18n
if (!instance) return fullKey as T
const nativeTranslate = instance.global.t as (
key: string,
...args: unknown[]
) => unknown
return nativeTranslate(fullKey, ...args) as T
}
const { 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

View File

@ -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
<svg fill="currentColor"></svg>
const name: IconName = 'directional/resize_h'
<RIcon name={name} size={24} />
```
## 使用方法
- 导入 `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` 迁移;仅当文件名唯一时转换。新代码必须使用完整路径,不为裸名放宽组件类型。

View File

Before

Width:  |  Height:  |  Size: 1018 B

After

Width:  |  Height:  |  Size: 1018 B

View File

Before

Width:  |  Height:  |  Size: 253 B

After

Width:  |  Height:  |  Size: 253 B

View File

Before

Width:  |  Height:  |  Size: 282 B

After

Width:  |  Height:  |  Size: 282 B

View File

Before

Width:  |  Height:  |  Size: 284 B

After

Width:  |  Height:  |  Size: 284 B

View File

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

View File

Before

Width:  |  Height:  |  Size: 1000 B

After

Width:  |  Height:  |  Size: 1000 B

View File

Before

Width:  |  Height:  |  Size: 935 B

After

Width:  |  Height:  |  Size: 935 B

View File

Before

Width:  |  Height:  |  Size: 930 B

After

Width:  |  Height:  |  Size: 930 B

View File

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

Before

Width:  |  Height:  |  Size: 254 B

After

Width:  |  Height:  |  Size: 254 B

View File

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 60 KiB

16
src/icons/index.ts Normal file
View File

@ -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
}

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

76
src/icons/manifest.ts Normal file
View File

@ -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<string> = new Set(iconNames)
export const isIconName = (value: unknown): value is IconName =>
typeof value === 'string' && names.has(value)

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