feat(router): support configurable route sources and management

This commit is contained in:
XiaoDaiGua-Ray 2026-11-04 10:29:48 +08:00
parent 80e807759d
commit 30820d3031
59 changed files with 2078 additions and 914 deletions

View File

@ -0,0 +1,129 @@
import { getStaticAppRoutes } from '@/router/app-route-modules'
import {
exportRouteConfig,
parseRouteConfig,
toRuntimeRoutes,
} from '@/router/config/contract'
import { getRouteJsonSchema } from '@/router/config/json-schema'
import { expandRoutes } from '@/router/utils/expand-routes'
import { orderRoutes } from '@/router/utils/order-routes'
import { validRole } from '@/router/utils/valid-role'
const page = { component: 'dashboard', meta: {} }
const parse = (routes: unknown[]) =>
parseRouteConfig(JSON.stringify({ version: 1, routes }))
describe('route configuration', () => {
it('round-trips all bundled routes with their view IDs and metadata', () => {
const bundled = getStaticAppRoutes()
const config = exportRouteConfig(bundled)
const restored = toRuntimeRoutes(parseRouteConfig(JSON.stringify(config)))
expect(config.routes.length).toBeGreaterThan(10)
expect(exportRouteConfig(restored)).toEqual(config)
expect(expandRoutes(restored)).toEqual(expandRoutes(bundled))
})
it('exports a strict versioned schema with recursive menu definitions', () => {
const schema = getRouteJsonSchema()
expect(schema).toMatchObject({
$schema: 'https://json-schema.org/draft/2020-12/schema',
additionalProperties: false,
properties: {
version: { const: 1 },
routes: { items: { $ref: '#/$defs/route' } },
},
$defs: {
route: {
additionalProperties: false,
properties: {
children: { items: { $ref: '#/$defs/route' } },
meta: {
additionalProperties: false,
properties: { keepAlive: { type: 'boolean' } },
},
},
},
},
})
})
it('uses absolute child paths and applies every ancestor role to direct access', () => {
const config = parse([
{
path: '/private',
meta: { role: ['admin', 'editor'] },
children: [
{ ...page, path: '/absolute', meta: { role: ['editor'] } },
{ ...page, path: 'relative', alias: '/short' },
],
},
])
const [absolute, relative] = expandRoutes(toRuntimeRoutes(config))
expect(absolute.path).toBe('/absolute')
expect(relative.path).toBe('/private/relative')
expect(relative.alias).toBe('/short')
expect(validRole(absolute.meta, 'admin')).toBe(false)
expect(validRole(absolute.meta, 'editor')).toBe(true)
expect(validRole(relative.meta, 'viewer')).toBe(false)
})
it.each([
[[{ ...page, path: '/route-management' }], /reserved/i],
[[{ ...page, path: '/reports', name: 'RLogin' }], /reserved/i],
[[{ ...page, path: '/reports', component: 'missing' }], /unknown view/i],
[
[{ ...page, path: '/reports', meta: { icon: 'fake/icon' } }],
/unknown icon/i,
],
[
[{ ...page, path: '/reports', meta: { keepAlive: true } }],
/registered component name/i,
],
[
[{ ...page, path: '/dashboard', meta: { role: ['editor'] } }],
/all authenticated roles/i,
],
[
[{ path: '/external', meta: { windowOpen: 'javascript:alert(1)' } }],
/windowOpen/,
],
[[{ ...page, path: '/reports', props: { innerHTML: '<img>' } }], /props/],
[[{ ...page, path: '/reports', meta: { typo: true } }], /meta/],
[
[
{ ...page, path: '/a', alias: '/b' },
{ ...page, path: '/b' },
],
/duplicate/i,
],
[
[
{ path: '/a', redirect: '/b', meta: {} },
{ path: '/b', redirect: '/a', meta: {} },
],
/cycle/i,
],
[
[
{ ...page, path: '/:id', meta: { hidden: true } },
{ ...page, path: '/:item', meta: { hidden: true } },
],
/conflicting/i,
],
])('rejects invalid routes %j', (routes, message) => {
expect(() => parse(routes)).toThrow(message)
})
it('sorts missing order consistently and leaves the input in place', () => {
const first = { path: '/first', name: 'A', meta: {} }
const second = { path: '/second', name: 'B', meta: { order: 0 } }
const input = [second, first]
expect(orderRoutes(input)).toEqual([first, second])
expect(input).toEqual([second, first])
})
})

View File

@ -16,8 +16,8 @@ const setupMiniApp = async () => {
const [_, app] = renderHook(() => {})
setupStore(app)
setupRouter(app)
await setupI18n(app)
await setupRouter(app)
return {
app,

View File

@ -41,6 +41,7 @@
"@faker-js/faker": "10.6.0",
"@logicflow/core": "2.2.5",
"@logicflow/extension": "2.3.1",
"@valibot/to-json-schema": "1.8.0",
"@vueuse/core": "15.0.0",
"axios": "1.21.0",
"clipboard": "2.0.11",
@ -56,6 +57,7 @@
"pinia": "4.1.0",
"pinia-plugin-persistedstate": "4.7.1",
"print-js": "1.6.0",
"valibot": "1.5.0",
"vue": "3.5.44",
"vue-demi": "0.14.10",
"vue-hooks-plus": "2.4.3",

27
pnpm-lock.yaml generated
View File

@ -180,6 +180,9 @@ importers:
'@logicflow/extension':
specifier: 2.3.1
version: 2.3.1(@logicflow/core@2.2.5)
'@valibot/to-json-schema':
specifier: 1.8.0
version: 1.8.0(valibot@1.5.0(typescript@6.0.3))
'@vueuse/core':
specifier: 15.0.0
version: 15.0.0(vue@3.5.44(typescript@6.0.3))
@ -225,6 +228,9 @@ importers:
print-js:
specifier: 1.6.0
version: 1.6.0
valibot:
specifier: 1.5.0
version: 1.5.0(typescript@6.0.3)
vue:
specifier: 3.5.44
version: 3.5.44(typescript@6.0.3)
@ -1535,6 +1541,11 @@ packages:
peerDependencies:
vite: ^5.0.0-0 || ^6.0.0-0 || ^7.0.0-0 || ^8.0.0-0
'@valibot/to-json-schema@1.8.0':
resolution: {integrity: sha512-a0M+uwCuQZEPAo65NYkFSJ14O5c213KoSZmPdoCfuFvUhfULi4T2Z6Tpjv6lTVMW9RoLm74RpRAjNEa43KcN+g==}
peerDependencies:
valibot: ^1.5.0
'@vitejs/devtools-kit@0.7.6':
resolution: {integrity: sha512-VtnTo296ypQyksFcPgrUyDDxh/SuAa/18uWEitbODcJIu5eilMFQyaSzsLKgp0HQPsxo/Kfzbfl5gowNGfjwqQ==}
peerDependencies:
@ -3399,6 +3410,14 @@ packages:
resolution: {integrity: sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw==}
hasBin: true
valibot@1.5.0:
resolution: {integrity: sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ==}
peerDependencies:
typescript: '>=5'
peerDependenciesMeta:
typescript:
optional: true
vanilla-picker@2.12.3:
resolution: {integrity: sha512-qVkT1E7yMbUsB2mmJNFmaXMWE2hF8ffqzMMwe9zdAikd8u2VfnsVY2HQcOUi2F38bgbxzlJBEdS1UUhOXdF9GQ==}
@ -4845,6 +4864,10 @@ snapshots:
- ocache
- srvx
'@valibot/to-json-schema@1.8.0(valibot@1.5.0(typescript@6.0.3))':
dependencies:
valibot: 1.5.0(typescript@6.0.3)
'@vitejs/devtools-kit@0.7.6(cac@7.1.0)(crossws@0.4.17(srvx@1.0.8))(srvx@1.0.8)(vite@8.3.5(@types/node@26.6.6)(jiti@2.7.0)(sass@1.107.1)(yaml@2.9.1))':
dependencies:
'@devframes/hub': 1.3.0(crossws@0.4.17(srvx@1.0.8))(devframe@1.3.0(cac@7.1.0)(srvx@1.0.8))
@ -6706,6 +6729,10 @@ snapshots:
uuid@14.0.3: {}
valibot@1.5.0(typescript@6.0.3):
optionalDependencies:
typescript: 6.0.3
vanilla-picker@2.12.3:
dependencies:
'@sphinxxxx/color-conversion': 2.2.2

View File

@ -1,3 +1,5 @@
import { NOT_FOUND_ROUTE_PATH } from '@/router/constant'
import { validRole } from '@/router/utils/valid-role'
import { useMenuActions, useMenuGetters } from '@/store'
import { pickRouteRecordNormalizedConstant } from '@/store/modules/menu/constant'
import type { AppMenuOption, Key, MenuTagOptions } from '@/types'
@ -97,27 +99,29 @@ export function useSiderBar() {
// 关闭所有标签并且导航至 root path
const closeAll = () => {
const { getRootPath } = useAppRoot()
const {
router: { getRoutes },
} = useVueRouter()
const { router } = useVueRouter()
const home = router.resolve(getRootPath.value)
const record = home.matched.at(-1)
const findMenuOption = getRoutes().find(
(curr) => curr.path === getRootPath.value,
if (
!record ||
record.path === NOT_FOUND_ROUTE_PATH ||
record.redirect ||
!validRole(home.meta)
)
return
if (findMenuOption) {
spliceMenTagOptions(0, getMenuTagOptions.value.length)
const pickOption = pick(findMenuOption, pickRouteRecordNormalizedConstant)
const res = resolveOption(pickOption as unknown as AppMenuOption)
const option = resolveOption({
...(pick(
record,
pickRouteRecordNormalizedConstant,
) as unknown as AppMenuOption),
fullPath: home.path,
})
changeMenuModelValue(
res.path,
resolveOption({
...res,
fullPath: res.path,
}),
)
}
setMenuTagOptions(option, false)
return changeMenuModelValue(home.path, option, home.query)
}
// 目标标签页右侧所有标签页

View File

@ -3,12 +3,9 @@ import './index.scss'
import { RIcon } from '@/components'
import { useDevice } from '@/hooks'
import type { AppRouteMeta } from '@/router/types'
import { validMenuItemShow } from '@/router/utils'
import { useMenuActions } from '@/store'
import { useMenuActions, useMenuGetters } from '@/store'
import type { AppMenuOption } from '@/types'
import { queryElements, removeClass, setClass } from '@/utils'
import { useEventListener } from '@vueuse/core'
import { pick, throttle } from 'lodash-es'
import {
NCard,
NFlex,
@ -16,7 +13,6 @@ import {
NModal,
NResult,
NScrollbar,
NSpin,
NText,
} from 'naive-ui'
@ -30,8 +26,8 @@ export default defineComponent({
},
emits: ['update:show'],
setup(props, { emit }) {
const { changeMenuModelValue, resolveOption } = useMenuActions()
const { getRoutes } = useRouter()
const { changeMenuModelValue } = useMenuActions()
const { getMenuOptions } = useMenuGetters()
const modelShow = computed({
get: () => props.show,
@ -43,9 +39,35 @@ export default defineComponent({
}
},
})
const state = reactive({
searchValue: null,
searchOptions: [] as AppMenuOption[],
const searchValue = ref('')
const searchElementIndex = ref(0)
const visibleLeaves = computed(() => {
const leaves: AppMenuOption[] = []
const visit = (items: AppMenuOption[]) => {
for (const item of items) {
if (item.show === false) continue
if (item.children?.length) visit(item.children)
else leaves.push(item)
}
}
visit(getMenuOptions.value)
return leaves
})
const searchOptions = computed(() => {
const term = searchValue.value.trim().toLocaleLowerCase()
return term
? visibleLeaves.value.filter(({ breadcrumbLabel }) =>
breadcrumbLabel?.toLocaleLowerCase().includes(term),
)
: []
})
watch(searchOptions, () => {
searchElementIndex.value = 0
})
const helperTipOptions = [
{
@ -64,20 +86,9 @@ export default defineComponent({
plain: true,
},
]
// 初始化索引
let searchElementIndex = 0
// 缓存索引
let preSearchElementIndex = searchElementIndex
const loading = ref(false)
// 激活样式 class name
const ACTIVE_CLASS = 'content-item--active'
// 初始化一些值
const resetSearchSomeValue = () => {
state.searchOptions = []
state.searchValue = null
searchElementIndex = 0
preSearchElementIndex = searchElementIndex
searchValue.value = ''
searchElementIndex.value = 0
}
// 断点 observer 会同步执行,先初始化其调用的重置函数。
@ -105,106 +116,12 @@ export default defineComponent({
}
}
/**
*
* @param value 输入的搜索内容
*
* @description
* 根据输入值模糊检索菜单。
* 依赖 getRoutes() 获取的路由列表。
*/
const fuzzySearchMenuOptions = (value: string) => {
if (value) {
loading.value = true
} else {
loading.value = false
state.searchOptions = []
const searchItemClick = async (option: AppMenuOption) => {
if (!option.meta.windowOpen) modelShow.value = false
return
}
await changeMenuModelValue(option.fullPath, option)
const arr = getRoutes().reduce((pre, curr) => {
const pickOption = pick(curr, [
'children',
'meta',
'path',
'name',
]) as unknown as AppMenuOption
const res = resolveOption({
...pickOption,
fullPath: curr.path,
})
const { breadcrumbLabel } = res
// 是否模糊匹配字符、满足展示条件
if (
breadcrumbLabel
?.toLocaleLowerCase()
?.includes(value.toLocaleLowerCase()) &&
validMenuItemShow(res)
) {
pre.push(res)
}
return pre
}, [] as AppMenuOption[])
setTimeout(() => {
state.searchOptions = arr
nextTick().then(() => {
autoFocusingSearchItem()
})
loading.value = false
}, 300)
}
// 搜索结果项点击
const searchItemClick = (option: AppMenuOption) => {
if (option) {
const { meta } = option
// 如果配置站外跳转则不会关闭搜索框
if (meta.windowOpen) {
window.open(meta.windowOpen)
} else {
modelShow.value = false
changeMenuModelValue(option.fullPath, option)
setTimeout(positionSelectedMenuItem, 300)
}
}
}
// 自动聚焦检索项
const autoFocusingSearchItem = () => {
const currentOption = state.searchOptions[searchElementIndex] // 获取当前搜索项
const preOption = state.searchOptions[preSearchElementIndex] // 获取上一搜索项
if (currentOption) {
nextTick().then(() => {
const searchElementOptions = queryElements<HTMLElement>(
`attr:data_path="${currentOption.path}"`,
)
const preSearchElementOptions = preOption
? queryElements<HTMLElement>(`attr:data_path="${preOption?.path}"`)
: null
if (preSearchElementOptions?.length) {
const [el] = preSearchElementOptions
removeClass(el, ACTIVE_CLASS)
}
if (searchElementOptions?.length) {
const [el] = searchElementOptions
setClass(el, ACTIVE_CLASS)
}
})
}
if (!option.meta.windowOpen) positionSelectedMenuItem()
}
// 渲染搜索菜单前缀图标,如果没有则用 icon table 代替
@ -220,77 +137,43 @@ export default defineComponent({
}
}
// 更新索引
const updateIndex = (type: 'up' | 'down') => {
if (type === 'up') {
searchElementIndex -= 1
const registerChangeSearchElementIndex = (event: KeyboardEvent) => {
const { key } = event
if (searchElementIndex < 0) {
searchElementIndex = state.searchOptions.length - 1
}
if (!['ArrowUp', 'ArrowDown', 'Enter'].includes(key)) return
event.preventDefault()
event.stopPropagation()
const options = searchOptions.value
if (!options.length) return
if (key === 'Enter') {
const selected = options[searchElementIndex.value]
if (selected) void searchItemClick(selected)
return
}
if (type === 'down') {
searchElementIndex += 1
const offset = key === 'ArrowUp' ? -1 : 1
if (searchElementIndex >= state.searchOptions.length) {
searchElementIndex = 0
}
}
searchElementIndex.value =
(searchElementIndex.value + offset + options.length) % options.length
}
// 注册按键: 上、下、回车
const registerChangeSearchElementIndex = (e: KeyboardEvent) => {
const keyCode = e.key
if (
keyCode === 'ArrowUp' ||
keyCode === 'ArrowDown' ||
keyCode === 'Enter'
) {
e.preventDefault()
e.stopPropagation()
}
// 当初始化索引小于等于 0 时,缓存重置缓存索引
preSearchElementIndex = searchElementIndex <= 0 ? 0 : searchElementIndex
switch (keyCode) {
case 'ArrowUp':
updateIndex('up')
break
case 'ArrowDown':
updateIndex('down')
break
case 'Enter':
// eslint-disable-next-line no-case-declarations
const option = state.searchOptions[searchElementIndex]
if (option) {
searchItemClick(option)
}
break
default:
break
}
autoFocusingSearchItem()
}
const SearchItem = ({ menuOption }: { menuOption: AppMenuOption }) => (
const SearchItem = ({
menuOption,
active,
}: {
menuOption: AppMenuOption
active: boolean
}) => (
<NFlex
align="center"
class="content-item"
{...{
onClick: searchItemClick.bind(this, menuOption),
data_path: menuOption.path,
}}
class={['content-item', { 'content-item--active': active }]}
{...{ onClick: () => searchItemClick(menuOption) }}
>
<div class="content-item-icon">{RenderPreIcon(menuOption.meta)}</div>
<div class="content-item-label">{menuOption.breadcrumbLabel}</div>
@ -305,23 +188,22 @@ export default defineComponent({
useEventListener(window, 'keydown', registerArouseKeyboard)
return {
...toRefs(state),
searchValue,
searchOptions,
searchElementIndex,
modelShow,
helperTipOptions,
fuzzySearchMenuOptions: throttle(fuzzySearchMenuOptions, 300),
searchItemClick,
RenderPreIcon,
isTabletOrSmaller,
SearchItem,
loading,
registerChangeSearchElementIndex,
}
},
render() {
const { isTabletOrSmaller, searchOptions, loading } = this
const {
isTabletOrSmaller,
searchOptions,
searchElementIndex,
SearchItem,
fuzzySearchMenuOptions,
registerChangeSearchElementIndex,
} = this
@ -357,7 +239,6 @@ export default defineComponent({
size="large"
v-model:value={this.searchValue}
clearable
onInput={fuzzySearchMenuOptions.bind(this)}
>
{{
prefix: () => <RIcon name="action/search" size="24" />,
@ -366,33 +247,35 @@ export default defineComponent({
),
default: () => (
<NScrollbar>
<NSpin show={loading}>
{searchOptions.length ? (
<NFlex
vertical
size={[0, 6]}
class="global-search__card-content"
>
{searchOptions.map((curr, idx) => (
<SearchItem menuOption={curr} key={curr.fullPath} />
))}
</NFlex>
) : (
<NResult size="large" class="global-search__empty">
{{
icon: () => null,
default: () => (
<NFlex
justify="center"
class="global-search__empty-content"
>
<NText>没有搜索结果</NText>
</NFlex>
),
}}
</NResult>
)}
</NSpin>
{searchOptions.length ? (
<NFlex
vertical
size={[0, 6]}
class="global-search__card-content"
>
{searchOptions.map((curr, idx) => (
<SearchItem
menuOption={curr}
key={curr.fullPath}
active={idx === searchElementIndex}
/>
))}
</NFlex>
) : (
<NResult size="large" class="global-search__empty">
{{
icon: () => null,
default: () => (
<NFlex
justify="center"
class="global-search__empty-content"
>
<NText>没有搜索结果</NText>
</NFlex>
),
}}
</NResult>
)}
</NScrollbar>
),
action: () => (

View File

@ -38,5 +38,6 @@
"TableRemote": "Remote search and pagination",
"TableColumns": "Column preferences",
"TablePrinting": "Printing and custom regions",
"TableCustom": "Slots and instance methods"
"TableCustom": "Slots and instance methods",
"RouteManagement": "Route management"
}

View File

@ -0,0 +1,38 @@
{
"eyebrow": "WORKSPACE / ROUTING",
"title": "Route management",
"description": "Switch route sources, preview the menu and validate page configuration as JSON.",
"active": "Active · {source}",
"fallback": "Load failed. Static routes are active.",
"source": "Route source",
"static": "Static",
"local": "Local JSON",
"remote": "Backend",
"staticHint": "Use the TypeScript routes bundled with the app. Applying changes reloads the page.",
"localHint": "Validate and save the JSON in this browser. Applying changes reloads the page.",
"remoteHint": "Fetch JSON from the deployed endpoint at startup. If loading or validation fails, use static routes.",
"apply": "Apply and reload",
"manifest": "Route configuration",
"loadStatic": "Load static routes",
"loadRemote": "Fetch backend routes",
"import": "Import JSON",
"export": "Export JSON",
"editor": "Configuration JSON",
"validate": "Validate and preview",
"valid": "Valid · {count} records",
"editHint": "Validate to preview the route tree.",
"invalid": "Configuration validation failed",
"contract": "Input and output contract",
"contractHint": "Give the schema and view catalog to AI or backend developers. API responses, imports and exports use the same format.",
"views": "View catalog",
"preview": "Route tree preview",
"previewEmpty": "No records to preview.",
"group": "Menu group",
"external": "External link",
"fileLimit": "JSON files must be at most 256 KiB.",
"quickAdd": "Quick add page",
"pagePath": "Route path",
"pageTitle": "Menu title",
"pageView": "View",
"addPage": "Add to configuration"
}

View File

@ -38,5 +38,6 @@
"TableRemote": "远端查询与分页",
"TableColumns": "列设置与缓存",
"TablePrinting": "打印与自定义区域",
"TableCustom": "插槽与实例操作"
"TableCustom": "插槽与实例操作",
"RouteManagement": "路由管理"
}

View File

@ -0,0 +1,38 @@
{
"eyebrow": "WORKSPACE / ROUTING",
"title": "路由管理",
"description": "切换路由来源,预览并校验菜单和页面的 JSON 配置。",
"active": "当前生效 · {source}",
"fallback": "加载失败,已使用静态路由",
"source": "路由来源",
"static": "静态路由",
"local": "本机 JSON",
"remote": "后端接口",
"staticHint": "使用随应用发布的 TypeScript 路由。应用设置时会重新加载页面。",
"localHint": "校验并保存编辑器中的 JSON,仅在此浏览器生效。应用设置时会重新加载页面。",
"remoteHint": "每次启动从部署指定的接口读取 JSON。请求或校验失败时自动恢复到静态路由。",
"apply": "应用并重新加载",
"manifest": "路由配置",
"loadStatic": "载入静态配置",
"loadRemote": "读取后端配置",
"import": "导入 JSON",
"export": "导出 JSON",
"editor": "配置 JSON",
"validate": "校验并预览",
"valid": "校验通过 · {count} 项",
"editHint": "校验后可查看配置树。",
"invalid": "配置校验失败",
"contract": "输入与输出契约",
"contractHint": "将 Schema 与可用页面清单交给 AI 或后台开发者。接口响应、导入文件和导出文件使用同一格式。",
"views": "可用页面清单",
"preview": "配置树预览",
"previewEmpty": "当前没有可预览的记录。",
"group": "菜单分组",
"external": "外部链接",
"fileLimit": "JSON 文件上限为 256 KiB。",
"quickAdd": "快速添加页面",
"pagePath": "路由路径",
"pageTitle": "菜单标题",
"pageView": "页面组件",
"addPage": "添加到配置"
}

View File

@ -24,7 +24,7 @@ import { setupStore } from './store'
const setupPlugins = async (inst: AppType<Element>) => {
setupStore(inst)
await setupI18n(inst)
setupRouter(inst)
await setupRouter(inst)
setupDayjs()
setupDirectives(inst)
}
@ -76,9 +76,9 @@ const setupWujieTemplate = async () => {
* 作为主应用
* ----------------------------------------------------------------
* # 示例
* const setupTemplate = () => {
* const setupTemplate = async () => {
* const app = createApp(App)
* setupRouter(app)
* await setupRouter(app)
* ...
* }
* setupTemplate()

View File

@ -1,162 +1,66 @@
## router 拓展
# 路由、菜单与权限
## LAYOUT 说明
## 切换路由来源
> router modules 包中的路由模块会与菜单一一映射,也就是说,路由模块的配置结构会影响菜单的展示。当你有子菜单需要配置时,你需要使用该组件。
登录后,从侧栏打开 **路由管理**(`/#/route-management`)。管理页由应用外壳注册,并使用 `admin` 角色守卫。可快速添加页面、编辑完整 JSON、从文件导入、校验和预览配置树,也可导出 JSON、标准 JSON Schema 和可用页面清单。
```ts
import { t } from '@/hooks/web/useI18n'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
| 来源 | 读取行为 | 应用方式 |
| --------- | -------------------------------------------- | ------------------------------------------ |
| 静态路由 | 读取 [modules](modules) 下的 TypeScript 模块 | 选择静态路由并应用 |
| 本机 JSON | 读取当前浏览器保存的配置 | 导入文件或编辑 JSON,校验后应用 |
| 后端接口 | 启动时请求部署配置 `VITE_ROUTE_CONFIG_URL` | 选择后端接口并应用。接口地址随前端部署配置 |
const demo: AppRouteRecordRaw = {
/** 路由路径,如果为根菜单且无有菜单的时候可以配置为空字符串 */
path: '/demo',
/** views component name,必须与组件 name 属性匹配,否则缓存属性会失效 */
name: 'RDemo',
/** 这样配置后,就无须在 views 中重复写 <view-router /> 了 */
component: LAYOUT,
meta: {
/** t 方法是一个纯函数,为了配合 i18n ally 插件提示使用 */
i18nKey: t('menu.Demo'),
icon: 'navigation/other',
order: 0,
},
children: [
应用时重新加载页面,重新生成路由匹配、菜单和标签页。设置接口地址时,新浏览器默认选择后端接口。显式选择的来源保存在当前浏览器。接口异常、超时或配置校验失败时恢复静态路由,管理页显示失败原因。登录、管理页、404 由外壳保留。未配置 `/dashboard` 时补充内置首页。
## 后端与 AI 契约
部署时提供 `VITE_ROUTE_CONFIG_URL=/api/route-config`,或使用启用 CORS 的 HTTPS 地址。客户端请求 `GET`,接受 `application/json`,超时 5 秒。同源请求可用会话 Cookie。接口直接返回下方 JSON,导入、导出和接口响应使用同一结构。
```json
{
"version": 1,
"routes": [
{
path: '/demo-child',
name: 'RDemoChild',
component: () => import('@/views/demo-child/index'),
meta: {
i18nKey: t('menu.DemoChild'),
icon: 'navigation/other',
order: 0,
},
},
],
}
export default dashboard
```
## 类型
```ts
interface RouteMeta {
order?: number
i18nKey: string
icon?: IconName
windowOpen?: string
role?: string[]
hidden?: boolean
noLocalTitle?: string | number
ignoreAutoResetScroll?: boolean
keepAlive?: boolean
sameLevel?: boolean
dev?: string | string[]
}
```
## 说明
```
order: 菜单顺序,值越大越靠后。仅对顶层有效,子菜单该值无效
i18nKey: i18n 国际化 key, 会优先使用该字段
icon: icon 图标, 用于 Menu 菜单(依赖 RIcon 组件实现)
windowOpen: 超链接打开(新开窗口打开)
role: 权限表
hidden: 是否显示
noLocalTitle: 不使用国际化渲染 Menu Title
ignoreAutoResetScroll: 该页面内容区域自动初始化滚动条位置
keepAlive: 是否缓存该页面(需要配置 APP_KEEP_ALIVE setupKeepAlive 属性为 true 启用才有效)
sameLevel: 是否标记该路由为平级模式,如果标记为平级模式,会使路由菜单项隐藏。如果在含有子节点处,设置了该属性,会导致子节点全部被隐藏。并且该模块,在后续的使用 url 地址导航跳转时,如果在非当前路由层级层面跳转的该路由,会在当前的面包屑后面追加该模块的信息,触发跳转时,不会修改面包屑、标签页(优先级最高)
dev: 按照当前环境进行匹配(优先级最低)
```
### routerCopilot
> 该文件提供了一些辅助方法,让你更方便的做一些事情。系统其他地方引用了该方法,所以删除需谨慎。
### useVueRouter
> 二次封装了一个 router hook 方法,让你能够在 setup 环境之外使用 router。建议都使用该方法(useVueRouter)而不是 useRouter。
## 路由添加规则
- modules 中每一个 ts 文件视为一个路由模块
- path 以 `/` 开头则视为根路由
- 如果 path 为根路由,且不没有子级,则直接返回该路由
- 如果 path 为根路由,且不含有子级,则拼接完整 path 路径,然后返回最后一层路由
- 子级中不会存在 `/` 开头的情况(模板约定约束),如果存在则不用管,按照前三条逻辑执行代码,如果有误,由开发人员手动更改配置
```ts
const demo = {
path: '/multi',
name: 'MultiMenu',
meta: {
i18nKey: 'MultiMenu',
icon: 'navigation/table',
},
children: [
{
path: 'multi-menu-one',
name: 'MultiMenuOne',
meta: {
noLocalTitle: '多级菜单-1',
},
key: 'multi-menu-one',
breadcrumbLabel: '多级菜单-1',
show: true,
},
{
path: 'multi-menu-two',
name: 'MultiMenuTwo',
meta: {
noLocalTitle: '多级菜单-2',
},
children: [
"path": "/reports",
"component": "layout",
"meta": { "noLocalTitle": "Reports", "role": ["admin"], "order": 20 },
"children": [
{
path: 'sub-menu',
name: 'SubMenu',
meta: {
noLocalTitle: '多级菜单-2-1',
},
key: 'sub-menu',
breadcrumbLabel: '多级菜单-2-1',
show: true,
},
],
key: 'multi-menu-two',
breadcrumbLabel: '多级菜单-2',
show: true,
},
],
"path": "overview",
"name": "REchart",
"component": "demo/echart",
"meta": {
"i18nKey": "menu.Echart",
"icon": "navigation/echart",
"keepAlive": true
}
}
]
}
]
}
// 转换后
const transform = [
{
path: '/multi/multi-menu-one',
name: 'MultiMenuOne',
meta: {
noLocalTitle: '多级菜单-1',
},
key: 'multi-menu-one',
breadcrumbLabel: '多级菜单-1',
show: true,
},
{
path: '/multi/multi-menu-two/sub-menu',
name: 'SubMenu',
meta: {
noLocalTitle: '多级菜单-2-1',
},
key: 'sub-menu',
breadcrumbLabel: '多级菜单-2-1',
show: true,
},
]
```
图标使用分包路径 `IconName`,例如 `directional/resize_h`,详见 [图标类型与生成流程](../icons/A_README.md)。
| 字段 | 规则 |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `path`、`children` | 相对路径拼接到父组,绝对路径从根匹配。支持普通命名参数及可选参数,参数路由需设置 `hidden` 或 `sameLevel`。分组只参与菜单与权限 |
| `name`、`component` | 名称唯一。页面只能引用 [注册表](config/views.ts) 中的 ID。开启 `keepAlive` 时名称与该页面组件名一致 |
| `alias`、`redirect` | 支持叶子页的绝对别名和指向已配置页面的站内重定向。重定向的直接访问使用目标页权限 |
| `props` | `true` 将路由参数传给页面,也可传入 JSON 对象 |
| `meta.i18nKey`、`meta.noLocalTitle`、`meta.icon`、`meta.extra` | 翻译键优先于字面标题。图标使用 [IconName](../icons/manifest.ts)。标签可配置文案、翻译键、颜色、显隐及图标 |
| `meta.role`、`meta.hidden`、`meta.env`、`meta.sameLevel` | 父组和叶子的角色限制同时生效。隐藏、环境和平级模式影响菜单。平级模式在当前标签下追加面包屑 |
| `meta.keepAlive`、`meta.ignoreAutoResetScroll`、`meta.order`、`meta.windowOpen` | 控制叶子页缓存、滚动复位、顶层排序和 HTTP(S) 外部链接 |
[JSON Schema](config/schema.ts) 描述字段,Valibot 从同一份定义推导类型并校验结构,导出时使用官方转换器生成 JSON Schema。[校验与转换](config/contract.ts) 额外验证页面 ID、图标、参数冲突、保留地址和重定向环。最多 300 个记录、8 层、256 KiB。函数、VNode、路由钩子等代码能力使用 TypeScript 模块。路由角色控制前端菜单与导航,后端仍需验证业务 API 权限。
仓库内可直接导出 Schema 给后端或 AI 使用。
```sh
node --input-type=module -e "import {getRouteJsonSchema} from './src/router/config/json-schema.ts'; console.log(JSON.stringify(getRouteJsonSchema(), null, 2))"
```
## 扩展静态页面
新增页面时先在 [页面注册表](config/views.ts) 注册稳定 ID 和组件名,再从 `src/router/modules` 的路由记录用 `routeView(id)` 引用。静态模块默认导出一条记录。分组可以使用 `LAYOUT` 和 `children`,叶子在同一个应用布局中渲染。简体中文和英文菜单文案分别写入两份 `menu.json`。
系统配置和白名单见 [router-config.ts](../app-config/router-config.ts)。在 Vue setup 之外读取路由器时使用 `useVueRouter()`。变更后运行 `pnpm harness verify routing`,并核对菜单跳转、直达、刷新、切换来源、角色和缓存。

View File

@ -1,23 +1,42 @@
import {
combineRawRouteModules,
expandRoutes,
orderRoutes,
} from '@/router/utils'
import { DEFAULT_HOME_PATH, ROUTE_MANAGEMENT_PATH } from './constant'
import type { AppRouteRecordRaw } from './types'
import { combineRawRouteModules } from './utils/combine-raw-route-modules'
import { expandRoutes } from './utils/expand-routes'
import { orderRoutes } from './utils/order-routes'
/**
*
* @description
* 收集并按 meta.order 排序路由模块。
*
* @returns 合并后的路由记录列表
*/
export const getAppRawRoutes = () => orderRoutes(combineRawRouteModules())
const managementRoute: AppRouteRecordRaw = {
path: ROUTE_MANAGEMENT_PATH,
name: 'RouteManagement',
component: () => import('@/views/route-management'),
meta: {
i18nKey: 'menu.RouteManagement',
icon: 'action/setting',
role: ['admin'],
order: 100,
},
}
/**
*
* @description
* 将模块路由展开为平铺记录。
*
* @returns 平铺后的路由记录列表
*/
export const appExpandRoutes = () => expandRoutes(getAppRawRoutes())
export const getStaticAppRoutes = () => orderRoutes(combineRawRouteModules())
let activeRoutes: AppRouteRecordRaw[] | undefined
export function setAppRouteModules(routes: AppRouteRecordRaw[]) {
const fallback = getStaticAppRoutes().find(
({ path }) => path === DEFAULT_HOME_PATH,
)
const hasHome = expandRoutes(routes).some(
({ path }) => path === DEFAULT_HOME_PATH,
)
activeRoutes = orderRoutes(
hasHome || !fallback ? routes : [...routes, fallback],
)
}
export const getAppRawRoutes = () => [
...(activeRoutes ?? getStaticAppRoutes()),
managementRoute,
]
export const appExpandRoutes = () =>
expandRoutes(getAppRawRoutes()).filter(({ meta }) => !meta.windowOpen)

View File

@ -0,0 +1,255 @@
import { isIconName } from '@/icons/manifest'
import {
DEFAULT_HOME_PATH,
LAYOUT,
ROUTE_MANAGEMENT_PATH,
} from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
import { joinRoutePath } from '@/router/utils/join-route-path'
import { getDotPath, safeParse } from 'valibot'
import { routeConfigSchema } from './schema'
import type { RouteConfig, RouteConfigRecord } from './schema'
import { findRouteView, findRouteViewId } from './views'
const reservedPaths = new Set(['/', ROUTE_MANAGEMENT_PATH])
const reservedNames = new Set([
'rlogin',
'rlayout',
'rnotfound',
'routemanagement',
'errorpage',
'raytemplatedoc',
])
const configLimit = 256 * 1024
const asList = (value: string | string[] | undefined) =>
typeof value === 'string' ? [value] : (value ?? [])
export function parseRouteConfig(text: string): RouteConfig {
if (text.length > configLimit)
throw new Error('Route configuration exceeds 256 KiB.')
const input = JSON.parse(text)
let count = 0
const checkDepth = (routes: unknown, depth: number) => {
if (!Array.isArray(routes)) return
count += routes.length
if (count > 300 || depth > 8)
throw new Error('Use at most 300 routes and 8 menu levels.')
for (const item of routes) checkDepth(item?.children, depth + 1)
}
checkDepth(input?.routes, 1)
const result = safeParse(routeConfigSchema, input)
if (!result.success) {
throw new Error(
result.issues
.slice(0, 20)
.map((issue) => `${getDotPath(issue) ?? 'config'}: ${issue.message}`)
.join('\n'),
)
}
const config = result.output
const paths = new Map<string, RouteConfigRecord>()
const names = new Set(reservedNames)
const menuPaths = new Set<string>()
const matchPatterns = new Set<string>()
const visit = (
records: RouteConfigRecord[],
parent = '',
restricted = false,
) => {
for (const record of records) {
const { name, component, children, alias, redirect, props, meta } = record
const path = joinRoutePath(parent, record.path)
const fail = (message: string): never => {
throw new Error(`${path}: ${message}`)
}
const menuPath = path.toLowerCase()
if (menuPaths.has(menuPath) || reservedPaths.has(menuPath))
fail('Duplicate or reserved menu path.')
menuPaths.add(menuPath)
if (meta.windowOpen && !URL.canParse(meta.windowOpen))
fail('Invalid external URL.')
if (name) {
const key = name.toLowerCase()
if (names.has(key)) fail(`Duplicate or reserved name "${name}".`)
names.add(key)
}
for (const icon of [meta.icon, meta.extra?.icon]) {
if (icon && !isIconName(icon)) fail(`Unknown icon "${icon}".`)
}
if (children?.length) {
if (
(component && component !== 'layout') ||
alias ||
redirect ||
props !== void 0 ||
meta.windowOpen
)
fail('Groups accept layout, children and menu metadata.')
if (path.includes(':')) fail('Use static paths for menu groups.')
visit(children, path, restricted || !!meta.role?.length)
continue
}
const view = component && findRouteView(component)
if (component && !view) fail(`Unknown view "${component}".`)
if (
Number(!!component) + Number(!!redirect) + Number(!!meta.windowOpen) !==
1
)
fail('Specify exactly one view, redirect or external URL.')
if (props !== void 0 && !view) fail('Props require a view.')
if (meta.keepAlive && (!view || name !== view.name))
fail('keepAlive requires the registered component name.')
if (path.includes(':') && !meta.hidden && !meta.sameLevel)
fail('Parameterized paths must be hidden or sameLevel.')
for (const address of [path, ...asList(alias)]) {
const key = address.toLowerCase()
if (
key.split('/').some((segment) => segment === '.' || segment === '..')
)
fail(`Invalid path "${address}".`)
if (reservedPaths.has(key) || paths.has(key))
fail(`Duplicate or reserved path "${address}".`)
if (
key === DEFAULT_HOME_PATH &&
(address !== path ||
path !== DEFAULT_HOME_PATH ||
!view ||
restricted ||
meta.role?.length)
)
fail(
'/dashboard must be a view accessible to all authenticated roles.',
)
if (address !== path && (address.includes(':') || path.includes(':')))
fail('Aliases require a static page path.')
const pattern = key.replace(/:[a-z_]\w*/g, ':param')
if (matchPatterns.has(pattern))
fail(`Conflicting parameter pattern "${address}".`)
matchPatterns.add(pattern)
paths.set(key, record)
}
}
}
visit(config.routes)
for (const [path, record] of paths) {
let current = record
const visited = new Set<RouteConfigRecord>()
while (current.redirect) {
const next = paths.get(current.redirect.toLowerCase())
if (
visited.has(current) ||
!next ||
next.meta.windowOpen ||
current.redirect.includes(':')
) {
throw new Error(
`${path}: Redirects must reach a configured page without a cycle.`,
)
}
visited.add(current)
current = next
}
}
return config
}
export function toRuntimeRoutes(config: RouteConfig): AppRouteRecordRaw[] {
const toRoute = ({
component,
children,
meta,
...record
}: RouteConfigRecord): AppRouteRecordRaw =>
({
...record,
meta: meta as AppRouteRecordRaw['meta'],
component:
component === 'layout'
? LAYOUT
: component
? findRouteView(component)?.load
: void 0,
children: children?.map(toRoute),
}) as AppRouteRecordRaw
return config.routes.map(toRoute)
}
export function exportRouteConfig(routes: AppRouteRecordRaw[]): RouteConfig {
const toRecord = ({
path,
name,
meta,
component,
children,
props,
alias,
redirect,
}: AppRouteRecordRaw): RouteConfigRecord => {
const id = component === LAYOUT ? 'layout' : findRouteViewId(component)
if (component && !id)
throw new Error(
`${path}: Register the view in router/config/views.ts before exporting.`,
)
if (redirect && typeof redirect !== 'string')
throw new Error(`${path}: Export requires a string redirect.`)
return {
path,
name,
meta: meta as RouteConfigRecord['meta'],
component: id,
alias,
redirect,
props,
children: children?.map(toRecord),
}
}
return parseRouteConfig(
JSON.stringify({ version: 1, routes: routes.map(toRecord) }),
)
}

View File

@ -0,0 +1,9 @@
import { toJsonSchema } from '@valibot/to-json-schema'
import { routeConfigSchema, routeRecordSchema } from './schema.ts'
export const getRouteJsonSchema = () =>
toJsonSchema(routeConfigSchema, {
target: 'draft-2020-12',
definitions: { route: routeRecordSchema },
ignoreActions: ['check', 'finite'],
})

179
src/router/config/schema.ts Normal file
View File

@ -0,0 +1,179 @@
import * as v from 'valibot'
const text = v.pipe(v.string(), v.minLength(1), v.maxLength(256))
const finiteNumber = v.pipe(v.number(), v.finite())
const title = v.union([text, finiteNumber])
const icon = v.pipe(text, v.regex(/^[\w-]+\/[\w-]+$/))
const segment = '(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)'
const absolutePath = v.pipe(
text,
v.regex(new RegExp(`^/${segment}(?:/${segment})*$`)),
)
const unsafeProp =
/^(?:[oO][nN]|innerHTML$|outerHTML$|srcdoc$|__proto__$|constructor$|prototype$)/
const viewProps = v.pipe(
v.record(v.string(), v.unknown()),
v.check(
(value) => Object.keys(value).every((key) => !unsafeProp.test(key)),
'Unsafe view prop.',
),
v.metadata({ propertyNames: { not: { pattern: unsafeProp.source } } }),
)
const routeFields = {
path: v.pipe(
text,
v.regex(new RegExp(`^/?${segment}(?:/${segment})*$`)),
v.description(
'Absolute or relative child path. Supports named and optional parameters.',
),
),
name: v.optional(
v.pipe(
text,
v.regex(/^[A-Za-z_][\w.-]*$/),
v.description('Unique Vue Router name. Required for keepAlive.'),
),
),
component: v.optional(
v.pipe(
text,
v.description('Registered view ID. Use layout for a menu group.'),
),
),
alias: v.optional(
v.pipe(
v.union([
absolutePath,
v.pipe(v.array(absolutePath), v.minLength(1), v.maxLength(16)),
]),
v.description('Absolute alternative path(s) for a leaf.'),
),
),
redirect: v.optional(
v.pipe(
absolutePath,
v.description('Absolute path of another configured page.'),
),
),
props: v.optional(
v.pipe(
v.union([v.boolean(), viewProps]),
v.description('Pass route params (true) or a JSON object to the view.'),
),
),
meta: v.strictObject({
i18nKey: v.optional(
v.pipe(text, v.description('Translation key for the menu title.')),
),
noLocalTitle: v.optional(
v.pipe(title, v.description('Literal title if i18nKey is absent.')),
),
icon: v.optional(
v.pipe(icon, v.description('IconName from src/icons/manifest.ts.')),
),
role: v.optional(
v.pipe(
v.array(title),
v.maxLength(32),
v.description(
'Allowed roles. Omitted or empty means any authenticated role.',
),
),
),
hidden: v.optional(
v.pipe(
v.boolean(),
v.description(
'Hide from the menu. Direct navigation still uses the role guard.',
),
),
),
sameLevel: v.optional(
v.pipe(
v.boolean(),
v.description('Append a breadcrumb without replacing the current tab.'),
),
),
order: v.optional(
v.pipe(finiteNumber, v.description('Menu sort order at the top level.')),
),
env: v.optional(
v.pipe(
v.union([text, v.pipe(v.array(text), v.maxLength(16))]),
v.description('Vite mode(s) in which the menu item is visible.'),
),
),
windowOpen: v.optional(
v.pipe(
v.string(),
v.maxLength(2048),
v.regex(/^[Hh][Tt][Tt][Pp][Ss]?:\/\//),
v.description('Open this HTTP(S) URL in a new tab.'),
),
),
ignoreAutoResetScroll: v.optional(
v.pipe(
v.boolean(),
v.description('Keep the content scroll position on navigation.'),
),
),
keepAlive: v.optional(
v.pipe(
v.boolean(),
v.description(
'Keep the view mounted. name must match the registered view name.',
),
),
),
extra: v.optional(
v.pipe(
v.strictObject({
label: v.optional(title),
i18nLabel: v.optional(text),
icon: v.optional(icon),
show: v.optional(v.boolean()),
type: v.optional(
v.picklist([
'default',
'primary',
'info',
'success',
'warning',
'error',
]),
),
}),
v.description('Optional menu badge.'),
),
),
}),
}
type RouteFields = v.InferOutput<
v.StrictObjectSchema<typeof routeFields, undefined>
>
export type RouteConfigRecord = RouteFields & { children?: RouteConfigRecord[] }
export const routeRecordSchema: v.GenericSchema<RouteConfigRecord> =
v.strictObject({
...routeFields,
children: v.optional(
v.pipe(
v.array(v.lazy(() => routeRecordSchema)),
v.minLength(1),
v.maxLength(300),
),
),
})
export const routeConfigSchema = v.pipe(
v.strictObject({
version: v.literal(1),
routes: v.pipe(v.array(routeRecordSchema), v.maxLength(300)),
}),
v.title('Ray Template route configuration'),
)
export type RouteConfig = v.InferOutput<typeof routeConfigSchema>

View File

@ -0,0 +1,98 @@
import { APP_CATCH_KEY } from '@/app-config'
import type { RouteConfig } from './schema'
export type RouteSource = 'static' | 'local' | 'remote'
interface Preference {
source: RouteSource
local?: RouteConfig
}
const storageKey = 'rayRouteConfig.v1'
export const remoteRouteUrl = import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()
function readPreference(): Preference {
try {
const stored: unknown = JSON.parse(
localStorage.getItem(storageKey) ?? 'null',
)
if (
stored &&
typeof stored === 'object' &&
'source' in stored &&
(stored.source === 'static' ||
stored.source === 'local' ||
stored.source === 'remote')
) {
return stored as Preference
}
} catch {
// 损坏的浏览器偏好回退到部署默认值。
}
return { source: remoteRouteUrl ? 'remote' : 'static' }
}
const preference = readPreference()
export const routeSourceStatus: {
requested: RouteSource
active: RouteSource
error?: string
config?: RouteConfig
} = { requested: preference.source, active: 'static' }
export async function fetchRemoteRouteConfig(): Promise<RouteConfig> {
if (!remoteRouteUrl) throw new Error('VITE_ROUTE_CONFIG_URL is missing.')
const url = new URL(remoteRouteUrl, document.baseURI)
if (url.origin !== location.origin && url.protocol !== 'https:') {
throw new Error('The route endpoint must be same-origin or HTTPS.')
}
const { parseRouteConfig } = await import('./contract')
const response = await fetch(url, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(5000),
cache: 'no-cache',
redirect: 'error',
credentials: 'same-origin',
})
if (!response.ok)
throw new Error(`Route endpoint returned HTTP ${response.status}.`)
return parseRouteConfig(await response.text())
}
export async function loadRouteConfig(): Promise<RouteConfig | undefined> {
if (preference.source === 'static') return
try {
const config =
preference.source === 'remote'
? await fetchRemoteRouteConfig()
: (await import('./contract')).parseRouteConfig(
JSON.stringify(preference.local ?? null),
)
routeSourceStatus.active = preference.source
routeSourceStatus.config = config
return config
} catch (error) {
routeSourceStatus.error =
error instanceof Error ? error.message : String(error)
}
}
export function saveRouteSource(source: RouteSource, local = preference.local) {
localStorage.setItem(storageKey, JSON.stringify({ source, local }))
sessionStorage.removeItem(APP_CATCH_KEY.appMenuTagOptions)
sessionStorage.removeItem(APP_CATCH_KEY.appMenuKey)
sessionStorage.removeItem(APP_CATCH_KEY.appPiniaKeepAliveStore)
location.reload()
}

147
src/router/config/views.ts Normal file
View File

@ -0,0 +1,147 @@
const views = {
dashboard: { load: () => import('@/views/dashboard'), name: 'RDashboard' },
'demo/axios': {
load: () => import('@/views/demo/axios/index'),
name: 'RAxios',
},
'demo/barcode-demo': {
load: () => import('@/views/demo/barcode-demo'),
name: 'BarcodeDemo',
},
'demo/cache-demo': {
load: () => import('@/views/demo/cache-demo/index'),
name: 'CacheDemo',
},
'demo/context-menu': {
load: () => import('@/views/demo/context-menu/index'),
name: 'ContextMenuDemo',
},
'demo/directive': {
load: () => import('@/views/demo/directive/index'),
name: 'RDirective',
},
'demo/draggable-card': {
load: () => import('@/views/demo/draggable-card'),
name: 'DraggableCardDemo',
},
'demo/echart': {
load: () => import('@/views/demo/echart/index'),
name: 'REchart',
},
'demo/flow-demo': {
load: () => import('@/views/demo/flow-demo'),
name: 'RFlowDemo',
},
'demo/form': { load: () => import('@/views/demo/form'), name: 'RFormDemo' },
'demo/hooks/web-hooks': {
load: () => import('@/views/demo/hooks/web-hooks'),
name: 'WebHooks',
},
'demo/iframe': {
load: () => import('@/views/demo/iframe/index'),
name: 'IframeDemo',
},
'demo/layout-demo': {
load: () => import('@/views/demo/layout-demo'),
name: 'LayoutDemo',
},
'demo/modal-demo': {
load: () => import('@/views/demo/modal-demo/index'),
name: 'ModalDemo',
},
'demo/multi/views/multi-menu-one': {
load: () => import('@/views/demo/multi/views/multi-menu-one/index'),
name: 'MultiMenuOne',
},
'demo/multi/views/multi-menu-two/views/sub-menu-other': {
load: () =>
import('@/views/demo/multi/views/multi-menu-two/views/sub-menu-other/index'),
name: 'SubMenuOther',
},
'demo/multi/views/multi-menu-two/views/sub-menu/views/multi-menu-two-one': {
load: () =>
import('@/views/demo/multi/views/multi-menu-two/views/sub-menu/views/multi-menu-two-one/index'),
name: 'MultiMenuTwoOne',
},
'demo/precision': {
load: () => import('@/views/demo/precision/index'),
name: 'CalculatePrecision',
},
'demo/qrcode': {
load: () => import('@/views/demo/qrcode/index'),
name: 'RQRCodeDemo',
},
'demo/rely/views/rely-about': {
load: () => import('@/views/demo/rely/views/rely-about/index'),
name: 'RelyAbout',
},
'demo/router-demo/router-demo-detail': {
load: () => import('@/views/demo/router-demo/router-demo-detail/index'),
name: 'RouterDemoDetail',
},
'demo/router-demo/router-demo-home': {
load: () => import('@/views/demo/router-demo/router-demo-home/index'),
name: 'RouterDemoHome',
},
'demo/scroll-reveal': {
load: () => import('@/views/demo/scroll-reveal/index'),
name: 'ScrollReveal',
},
'demo/segment': {
load: () => import('@/views/demo/segment'),
name: 'SegmentDemo',
},
'demo/svg-icons': {
load: () => import('@/views/demo/svg-icons/index'),
name: 'PreviewSVGIcons',
},
'demo/tables/auto-height': {
load: () => import('@/views/demo/tables/auto-height'),
name: 'TableDemoAutoHeight',
},
'demo/tables/basic': {
load: () => import('@/views/demo/tables/basic'),
name: 'TableDemoBasic',
},
'demo/tables/columns': {
load: () => import('@/views/demo/tables/columns'),
name: 'TableDemoColumns',
},
'demo/tables/custom': {
load: () => import('@/views/demo/tables/custom'),
name: 'TableDemoCustom',
},
'demo/tables/printing': {
load: () => import('@/views/demo/tables/printing'),
name: 'TableDemoPrinting',
},
'demo/tables/remote': {
load: () => import('@/views/demo/tables/remote'),
name: 'TableDemoRemote',
},
'demo/template-hooks': {
load: () => import('@/views/demo/template-hooks/index'),
name: 'TemplateHooks',
},
}
export type RouteViewId = keyof typeof views
export const routeViewCatalog = Object.entries(views).map(([id, { name }]) => ({
id,
name,
}))
const viewIds = new Map(
Object.entries(views).map(([id, { load }]) => [load, id]),
)
export const routeView = (id: RouteViewId) => views[id].load
export const findRouteView = (id: string) =>
Object.hasOwn(views, id) ? views[id as RouteViewId] : void 0
export const findRouteViewId = (loader: unknown) =>
typeof loader === 'function'
? viewIds.get(loader as ReturnType<typeof routeView>)
: void 0

View File

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

View File

@ -1,26 +1,34 @@
import { scrollViewToTop, vueRouterRegister } from '@/router/utils'
import type { App } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import constantRoutes from './routes'
import { setAppRouteModules } from './app-route-modules'
import { loadRouteConfig } from './config/source'
import { constantRoutes, getLayoutRoutes } from './routes'
import { scrollViewToTop, vueRouterRegister } from './utils'
export const router = createRouter({
history: createWebHashHistory(),
routes: constantRoutes as unknown as RouteRecordRaw[],
routes: constantRoutes,
scrollBehavior: (to) => {
scrollViewToTop(to)
},
})
/**
*
* @param app vue instance
*
* @description
* 该方法用于注册 vue-router,并且初始化一些配置方法。
*/
export const setupRouter = (app: App<Element>) => {
app.use(router)
let initialize: Promise<void> | undefined
vueRouterRegister(router)
export async function setupRouter(app: App<Element>) {
initialize ??= (async () => {
const config = await loadRouteConfig()
if (config) {
const { toRuntimeRoutes } = await import('./config/contract')
setAppRouteModules(toRuntimeRoutes(config))
}
for (const route of getLayoutRoutes()) router.addRoute('RLayout', route)
vueRouterRegister(router)
})()
await initialize
app.use(router)
}

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const dashboard: AppRouteRecordRaw = {
path: '/dashboard',
component: () => import('@/views/dashboard'),
component: routeView('dashboard'),
meta: {
i18nKey: t('menu.Dashboard'),
icon: 'navigation/dashboard',

View File

@ -1,11 +1,12 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const axios: AppRouteRecordRaw = {
path: '/axios',
name: 'RAxios',
component: () => import('@/views/demo/axios/index'),
component: routeView('demo/axios'),
meta: {
i18nKey: t('menu.Axios'),
icon: 'logo/axios',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const barcode: AppRouteRecordRaw = {
path: 'barcode',
component: () => import('@/views/demo/barcode-demo'),
component: routeView('demo/barcode-demo'),
meta: {
i18nKey: t('menu.Barcode'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const cacheDemo: AppRouteRecordRaw = {
path: '/cache-demo',
component: () => import('@/views/demo/cache-demo/index'),
component: routeView('demo/cache-demo'),
meta: {
i18nKey: t('menu.CacheDemo'),
icon: 'navigation/other',

View File

@ -1,9 +1,10 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import type { AppRouteRecordRaw } from '@/router/types'
const contextMenu: AppRouteRecordRaw = {
path: '/context-menu',
component: () => import('@/views/demo/context-menu/index'),
component: routeView('demo/context-menu'),
meta: {
i18nKey: t('menu.ContextMenu'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const directive: AppRouteRecordRaw = {
path: '/directive',
component: () => import('@/views/demo/directive/index'),
component: routeView('demo/directive'),
meta: {
i18nKey: t('menu.Directive'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const r: AppRouteRecordRaw = {
path: '/draggable-card',
component: () => import('@/views/demo/draggable-card'),
component: routeView('demo/draggable-card'),
meta: {
i18nKey: t('menu.DraggableCard'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const echart: AppRouteRecordRaw = {
path: '/echart',
component: () => import('@/views/demo/echart/index'),
component: routeView('demo/echart'),
meta: {
i18nKey: t('menu.Echart'),
icon: 'navigation/echart',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const r: AppRouteRecordRaw = {
path: '/flow',
component: () => import('@/views/demo/flow-demo'),
component: routeView('demo/flow-demo'),
meta: {
i18nKey: t('menu.Flow'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const form: AppRouteRecordRaw = {
path: '/form',
component: () => import('@/views/demo/form'),
component: routeView('demo/form'),
meta: {
i18nKey: t('menu.Form'),
icon: 'navigation/other',

View File

@ -1,9 +1,10 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import type { AppRouteRecordRaw } from '@/router/types'
const iframe: AppRouteRecordRaw = {
path: '/iframe',
component: () => import('@/views/demo/iframe/index'),
component: routeView('demo/iframe'),
meta: {
icon: 'navigation/other',
order: 2,

View File

@ -1,9 +1,10 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import type { AppRouteRecordRaw } from '@/router/types'
export default {
path: '/layout-demo',
name: 'LayoutDemo',
component: () => import('@/views/demo/layout-demo'),
component: routeView('demo/layout-demo'),
meta: { i18nKey: t('menu.LayoutDemo'), icon: 'navigation/menu', order: 1 },
} satisfies AppRouteRecordRaw

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const mockDemo: AppRouteRecordRaw = {
path: '/modal-demo',
component: () => import('@/views/demo/modal-demo/index'),
component: routeView('demo/modal-demo'),
meta: {
i18nKey: t('menu.Modal'),
icon: 'navigation/other',

View File

@ -1,4 +1,5 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
@ -17,7 +18,7 @@ const multiMenu: AppRouteRecordRaw = {
{
path: 'multi-menu-one',
name: 'MultiMenuOne',
component: () => import('@/views/demo/multi/views/multi-menu-one/index'),
component: routeView('demo/multi/views/multi-menu-one'),
meta: {
noLocalTitle: '多级菜单-1',
keepAlive: true,
@ -34,8 +35,9 @@ const multiMenu: AppRouteRecordRaw = {
{
path: 'sub-menu-other',
name: 'SubMenuOther',
component: () =>
import('@/views/demo/multi/views/multi-menu-two/views/sub-menu-other/index'),
component: routeView(
'demo/multi/views/multi-menu-two/views/sub-menu-other',
),
meta: {
noLocalTitle: '多级菜单-2-1',
keepAlive: true,
@ -53,8 +55,9 @@ const multiMenu: AppRouteRecordRaw = {
{
path: 'sub-menu-one',
name: 'MultiMenuTwoOne',
component: () =>
import('@/views/demo/multi/views/multi-menu-two/views/sub-menu/views/multi-menu-two-one/index'),
component: routeView(
'demo/multi/views/multi-menu-two/views/sub-menu/views/multi-menu-two-one',
),
meta: {
noLocalTitle: '多级菜单-2-2-1',
keepAlive: true,

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const precision: AppRouteRecordRaw = {
path: '/precision',
component: () => import('@/views/demo/precision/index'),
component: routeView('demo/precision'),
meta: {
i18nKey: t('menu.CalculatePrecision'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const qrcode: AppRouteRecordRaw = {
path: '/qrcode',
component: () => import('@/views/demo/qrcode/index'),
component: routeView('demo/qrcode'),
meta: {
i18nKey: t('menu.QRCode'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const rely: AppRouteRecordRaw = {
path: 'rely-about',
component: () => import('@/views/demo/rely/views/rely-about/index'),
component: routeView('demo/rely/views/rely-about'),
meta: {
i18nKey: t('menu.RelyAbout'),
icon: 'navigation/rely',

View File

@ -1,4 +1,5 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
@ -13,16 +14,14 @@ const routerDemo: AppRouteRecordRaw = {
children: [
{
path: 'router-demo-home',
component: () =>
import('@/views/demo/router-demo/router-demo-home/index'),
component: routeView('demo/router-demo/router-demo-home'),
meta: {
noLocalTitle: '人员信息(平级模式)',
},
},
{
path: 'router-demo-detail',
component: () =>
import('@/views/demo/router-demo/router-demo-detail/index'),
component: routeView('demo/router-demo/router-demo-detail'),
meta: {
noLocalTitle: '信息详情',
sameLevel: true,

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const scrollReveal: AppRouteRecordRaw = {
path: '/scroll-reveal',
component: () => import('@/views/demo/scroll-reveal/index'),
component: routeView('demo/scroll-reveal'),
meta: {
i18nKey: t('menu.scrollReveal'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const segment: AppRouteRecordRaw = {
path: '/segment',
component: () => import('@/views/demo/segment'),
component: routeView('demo/segment'),
meta: {
i18nKey: t('menu.Segment'),
icon: 'navigation/other',

View File

@ -1,10 +1,11 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const previewSVGIcons: AppRouteRecordRaw = {
path: '/svg-icons',
component: () => import('@/views/demo/svg-icons/index'),
component: routeView('demo/svg-icons'),
meta: {
i18nKey: t('menu.SvgIcon'),
icon: 'navigation/other',

View File

@ -1,4 +1,5 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import type { AppRouteRecordRaw } from '@/router/types'
const tables: AppRouteRecordRaw = {
@ -12,37 +13,37 @@ const tables: AppRouteRecordRaw = {
{
path: 'basic',
name: 'TableDemoBasic',
component: () => import('@/views/demo/tables/basic'),
component: routeView('demo/tables/basic'),
meta: { i18nKey: t('menu.TableBasic') },
},
{
path: 'remote',
name: 'TableDemoRemote',
component: () => import('@/views/demo/tables/remote'),
component: routeView('demo/tables/remote'),
meta: { i18nKey: t('menu.TableRemote') },
},
{
path: 'auto-height',
name: 'TableDemoAutoHeight',
component: () => import('@/views/demo/tables/auto-height'),
component: routeView('demo/tables/auto-height'),
meta: { i18nKey: t('menu.TableAutoHeight') },
},
{
path: 'columns',
name: 'TableDemoColumns',
component: () => import('@/views/demo/tables/columns'),
component: routeView('demo/tables/columns'),
meta: { i18nKey: t('menu.TableColumns') },
},
{
path: 'printing',
name: 'TableDemoPrinting',
component: () => import('@/views/demo/tables/printing'),
component: routeView('demo/tables/printing'),
meta: { i18nKey: t('menu.TablePrinting') },
},
{
path: 'custom',
name: 'TableDemoCustom',
component: () => import('@/views/demo/tables/custom'),
component: routeView('demo/tables/custom'),
meta: { i18nKey: t('menu.TableCustom') },
},
],

View File

@ -1,11 +1,12 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import { LAYOUT } from '@/router/constant'
import type { AppRouteRecordRaw } from '@/router/types'
const axios: AppRouteRecordRaw = {
path: '/template-hooks',
name: 'TemplateHooks',
component: () => import('@/views/demo/template-hooks/index'),
component: routeView('demo/template-hooks'),
meta: {
i18nKey: t('menu.TemplateHooks'),
icon: 'navigation/other',

View File

@ -1,9 +1,10 @@
import { t } from '@/hooks/web/useI18n'
import { routeView } from '@/router/config/views'
import type { AppRouteRecordRaw } from '@/router/types'
export default {
path: '/web-hooks',
name: 'WebHooks',
component: () => import('@/views/demo/hooks/web-hooks'),
component: routeView('demo/hooks/web-hooks'),
meta: { i18nKey: t('menu.WebHooks'), icon: 'action/mouse', order: 1 },
} satisfies AppRouteRecordRaw

View File

@ -1,49 +1,46 @@
import { t } from '@/hooks/web/useI18n'
import Layout from '@/layout'
import type { RouteRecordRaw } from 'vue-router'
import { appExpandRoutes } from './app-route-modules'
import { NOT_FOUND_ROUTE_PATH } from './constant'
export default [
/**
*
* 首页(一般为 Login 页面)
* 整个模板默认导航地址
*/
{
path: '/',
name: 'RLogin',
component: () => import('@/views/login'),
},
/**
*
* App Layout 核心页面(一般为登陆后展示的页面)
*/
{
path: '/',
name: 'RLayout',
component: Layout,
children: [
...appExpandRoutes(),
{ path: '/tables', redirect: '/tables/basic' },
{ path: '/table', redirect: '/tables/basic' },
{ path: '/table-pro', redirect: '/tables/remote' },
{ path: '/mock-demo', redirect: '/tables/remote' },
{ path: '/table-auto-height', redirect: '/tables/auto-height' },
/**
*
* @description
* 404 页面一定要放在最后面,避免奇奇怪怪的问题。
*/
{
path: NOT_FOUND_ROUTE_PATH,
component: () => import('@/views/error/views/Error404'),
meta: {
i18nKey: t('menu.Error'),
icon: 'status/error',
hidden: true,
sameLevel: true,
},
},
],
},
const legacyRedirects = [
{ path: '/tables', redirect: '/tables/basic' },
{ path: '/table', redirect: '/tables/basic' },
{ path: '/table-pro', redirect: '/tables/remote' },
{ path: '/mock-demo', redirect: '/tables/remote' },
{ path: '/table-auto-height', redirect: '/tables/auto-height' },
]
export const constantRoutes: RouteRecordRaw[] = [
{ path: '/', name: 'RLogin', component: () => import('@/views/login') },
{ path: '/', name: 'RLayout', component: Layout },
]
export function getLayoutRoutes(): RouteRecordRaw[] {
const routes = appExpandRoutes()
const occupiedPaths = new Set(
routes.flatMap(({ path, alias }) => [
path.toLowerCase(),
...[alias ?? []].flat().map((entry) => entry.toLowerCase()),
]),
)
return [
...(routes as unknown as RouteRecordRaw[]),
...legacyRedirects.filter(
({ path, redirect }) =>
!occupiedPaths.has(path) && occupiedPaths.has(redirect),
),
{
path: NOT_FOUND_ROUTE_PATH,
name: 'RNotFound',
component: () => import('@/views/error/views/Error404'),
meta: {
i18nKey: 'menu.Error',
icon: 'status/error',
hidden: true,
sameLevel: true,
},
},
]
}

View File

@ -23,7 +23,7 @@ export interface AppMenuExtraOptions {
* @description
* 标签图标。
*/
icon?: VNode
icon?: IconName | VNode
/**
*
* @description
@ -72,6 +72,8 @@ export interface AppRouteMeta {
* 并且,该配置项优先级最高。
*/
role?: (string | number)[]
/** 展开菜单树后用于直接导航校验的父级权限。 */
ancestorRoles?: (string | number)[][]
/**
*
* @description
@ -180,7 +182,7 @@ interface BaseAppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
* @description
* 需要传递给组件的 props。
*/
props?: Recordable
props?: boolean | Recordable
/**
*
* @description

View File

@ -26,6 +26,13 @@ export const canSkipRoute = (
const skip = (skipOptions: LikeTemplateRouteOption[]): SkipReturnType => {
for (const curr of skipOptions) {
if (
curr.meta.hidden ||
curr.meta.sameLevel ||
('show' in curr && curr.show === false)
)
continue
if (
(!curr.children || curr.children.length === 0) &&
!curr.meta.windowOpen

View File

@ -1,50 +1,35 @@
import type { AppRouteRecordRaw } from '@/router/types'
import { cloneDeep } from 'lodash-es'
import type { AppRouteMeta, AppRouteRecordRaw } from '@/router/types'
import { joinRoutePath } from './join-route-path'
// 是否为根路由
const isRootPath = (path: string) => path[0] === '/'
export const expandRoutes = (routes: AppRouteRecordRaw[]) => {
const leaves: AppRouteRecordRaw[] = []
/**
*
* @param arr route modules
* @param result callback expand routes modules result
* @param path route path
* @returns callback expand routes modules result
*
* @remark 该方法会视 / 开头 path 为根路由
*/
const routePromotion = (
arr: AppRouteRecordRaw[],
result: AppRouteRecordRaw[] = [],
path = '',
) => {
if (!Array.isArray(arr)) {
return []
}
const visit = (
records: AppRouteRecordRaw[],
parentPath = '',
ancestors: AppRouteMeta[] = [],
) => {
for (const record of records) {
const path = joinRoutePath(parentPath, record.path)
for (const curr of arr) {
const newPath = path + (isRootPath(curr.path) ? curr.path : '/' + curr.path)
if (curr.children?.length) {
routePromotion(curr.children, result, newPath)
continue
} else {
result.push({
...curr,
path: newPath,
})
if (record.children?.length) {
visit(record.children, path, [...ancestors, record.meta])
} else {
leaves.push({
...record,
path,
meta: {
...record.meta,
ancestorRoles: ancestors.flatMap(({ role }) =>
role?.length ? [role] : [],
),
},
} as AppRouteRecordRaw)
}
}
}
return result
}
if (Array.isArray(routes)) visit(routes)
// 获取所有已展开的路由
export const expandRoutes = (arr: AppRouteRecordRaw[]) => {
if (!Array.isArray(arr)) {
return []
}
return routePromotion(cloneDeep(arr))
return leaves
}

View File

@ -0,0 +1,2 @@
export const joinRoutePath = (parent: string, path: string) =>
path.startsWith('/') ? path : `${parent.replace(/\/$/, '')}/${path}`

View File

@ -12,19 +12,9 @@ import type { AppRouteRecordRaw } from '@/router/types'
* 如果 order 属性值相同, 则会按照路由名称进行排序
*/
export const orderRoutes = (routes: AppRouteRecordRaw[]) => {
return routes.sort((curr, next) => {
const currOrder = curr.meta?.order ?? 1
const nextOrder = next.meta?.order ?? 0
return routes.toSorted((curr, next) => {
const order = (curr.meta?.order ?? 0) - (next.meta?.order ?? 0)
if (currOrder === nextOrder) {
// 如果两个路由的 order 值相同,则按照路由名进行排序
return curr.name
? next.name
? curr.name.localeCompare(next.name)
: -1
: 1
}
return currOrder - nextOrder
return order || (curr.name ?? '').localeCompare(next.name ?? '', 'en')
})
}

View File

@ -2,6 +2,7 @@ import { APP_CATCH_KEY, WHITE_ROUTES } from '@/app-config'
import { useAppRoot } from '@/hooks'
import { getStorage, setStorage } from '@/utils/cache'
import type { Router } from 'vue-router'
import { resolveLandingPath } from './resolve-landing-path'
import { validRole } from './valid-role'
/**
@ -13,8 +14,6 @@ import { validRole } from './valid-role'
* 前端守卫不能替代后端鉴权。
*/
export const permissionRouter = (router: Router) => {
const { getRootPath } = useAppRoot()
router.beforeEach((to) => {
const token = getStorage<string>(APP_CATCH_KEY.token, 'localStorage')
const isLogin = to.path === '/'
@ -27,12 +26,15 @@ export const permissionRouter = (router: Router) => {
typeof to.name === 'string' && WHITE_ROUTES.includes(to.name)
if (isLogin || (!isWhiteRoute && !validRole(to.meta))) {
const rootPath = getRootPath.value
const { getRootPath } = useAppRoot()
const rootPath = resolveLandingPath(router, getRootPath.value)
// 保留既有重定向时的缓存行为;若首页本身无权限,取消导航以免循环。
setStorage(APP_CATCH_KEY.appMenuKey, rootPath, 'localStorage')
return to.path === rootPath ? false : { path: rootPath, replace: true }
return to.fullPath === rootPath
? false
: { path: rootPath, replace: true }
}
return true

View File

@ -1,6 +1,7 @@
import { APP_CATCH_KEY } from '@/app-config'
import { useAppRoot, useVueRouter } from '@/hooks'
import { setStorage } from '@/utils/cache'
import { resolveLandingPath } from './resolve-landing-path'
/**
*
@ -15,7 +16,9 @@ export const redirectRouterToDashboard = (isReplace = true) => {
const { push, replace } = router
const { getRootPath } = useAppRoot()
setStorage(APP_CATCH_KEY.appMenuKey, getRootPath.value, 'localStorage')
const path = resolveLandingPath(router, getRootPath.value)
isReplace ? replace(getRootPath.value) : push(getRootPath.value)
setStorage(APP_CATCH_KEY.appMenuKey, path, 'localStorage')
return isReplace ? replace(path) : push(path)
}

View File

@ -0,0 +1,19 @@
import { DEFAULT_HOME_PATH, NOT_FOUND_ROUTE_PATH } from '@/router/constant'
import type { Router } from 'vue-router'
import { validRole } from './valid-role'
export function resolveLandingPath(router: Router, preferredPath: string) {
const home = router.resolve(preferredPath)
const record = home.matched.at(-1)
if (
home.path === '/' ||
!record ||
record.path === NOT_FOUND_ROUTE_PATH ||
record.redirect ||
(home.path !== DEFAULT_HOME_PATH && !validRole(home.meta))
)
return DEFAULT_HOME_PATH
return home.fullPath
}

View File

@ -1,38 +1,19 @@
import { SUPER_ADMIN } from '@/app-config'
import type { AppRouteMeta } from '@/router/types'
import { useSigningGetters } from '@/store'
import { piniaSigningStore } from '@/store'
/**
*
* @description
* 校验当前菜单项是否与权限匹配。
* 仅做对于 Meta Role 配置是否匹配做校验,不关心 Meta Hidden 属性。
*
* 如果为超级管理员,则会默认获取所有权限。
*
* true: 表示有权限
* false: 表示没有权限
*/
export const validRole = (meta: AppRouteMeta) => {
const { getSigningCallback } = useSigningGetters()
const { role: metaRole } = meta
export const validRole = (
{ role, ancestorRoles }: AppRouteMeta,
currentRole?: string | number,
) => {
if (!role?.length && !ancestorRoles?.length) return true
if (
SUPER_ADMIN?.length &&
SUPER_ADMIN.includes(getSigningCallback.value.role)
) {
return true
} else {
// 如果 role 为 undefined 或者空数组, 则认为该路由不做权限过滤
if (!metaRole || !metaRole?.length) {
return true
}
const userRole = currentRole ?? piniaSigningStore().signingCallback.role
// 判断是否含有该权限
if (metaRole) {
return metaRole.includes(getSigningCallback.value.role)
}
return true
}
return (
SUPER_ADMIN.includes(userRole) ||
((!role?.length || role.includes(userRole)) &&
(!ancestorRoles?.length ||
ancestorRoles.every((roles) => roles.includes(userRole))))
)
}

View File

@ -10,8 +10,6 @@ export const piniaKeepAliveStore = defineStore(
keepAliveInclude: [],
})
const getCurrentKeepAliveLength = () => state.keepAliveInclude.length
/**
*
* @param option current menu option
@ -21,28 +19,23 @@ export const piniaKeepAliveStore = defineStore(
* 如果当前可缓存项数量超过最大缓存数量,则移除第一个,添加最后一个。
*/
const setKeepAliveInclude = (option: AppMenuOption) => {
const length = getCurrentKeepAliveLength()
const {
name,
meta: { keepAlive },
} = option
const { maxKeepAliveLength } = piniaSettingStore().keepAliveConfig
if (keepAlive) {
if (
length < maxKeepAliveLength &&
!state.keepAliveInclude.includes(name)
) {
state.keepAliveInclude.push(name)
if (!keepAlive || !name || maxKeepAliveLength <= 0) return
return
}
const include = state.keepAliveInclude
if (length >= maxKeepAliveLength) {
state.keepAliveInclude.splice(0, 1)
state.keepAliveInclude.push(name)
}
}
if (include.at(-1) === name && include.length <= maxKeepAliveLength)
return
state.keepAliveInclude = [
...new Set(include.filter((key) => key !== name)),
name,
].slice(-maxKeepAliveLength)
}
// 获取当前缓存队列

View File

@ -2,6 +2,7 @@ import { APP_CATCH_KEY } from '@/app-config'
import { useI18n } from '@/hooks'
import { getAppRawRoutes } from '@/router/app-route-modules'
import { canSkipRoute, validMenuItemShow, validRole } from '@/router/utils'
import { joinRoutePath } from '@/router/utils/join-route-path'
import { useKeepAliveActions } from '@/store'
import type { MenuState } from '@/store/modules/menu/types'
import type { AnyFn, AppMenuOption, MenuTagOptions } from '@/types'
@ -10,14 +11,14 @@ import { equalRouterPath } from '@/utils/equal-router-path'
import { updateObjectValue } from '@/utils/update-object-value'
import { pick } from 'lodash-es'
import { NEllipsis } from 'naive-ui'
import type { LocationQuery } from 'vue-router'
import type { LocationQuery, RouteRecordNormalized } from 'vue-router'
import { piniaSigningStore } from '../signing'
import { pickRouteRecordNormalizedConstant } from './constant'
import {
createMenuExtra,
createMenuIcon,
getCatchMenuKey,
getCatchMenuTagOptions,
parseAndFindMatchingNodes,
updateDocumentTitle,
} from './utils'
@ -45,7 +46,7 @@ export const depthSearchAppMenu = (
export const piniaMenuStore = defineStore(
'menu',
() => {
const { push, getRoutes } = useRouter()
const { push, resolve } = useRouter()
const route = useRoute()
const { t } = useI18n()
const { setKeepAliveInclude } = useKeepAliveActions()
@ -58,7 +59,36 @@ export const piniaMenuStore = defineStore(
breadcrumbOptions: [], // 面包屑菜单
currentMenuOption: null, // 当前激活菜单项
})
const isSetupAppMenuLock = ref(true)
const signing = piniaSigningStore()
const menuIndex = new Map<
string,
{ option: AppMenuOption; parentPath: string }
>()
const cacheTags = () =>
setStorage(
APP_CATCH_KEY.appMenuTagOptions,
menuState.menuTagOptions.map(
({
name,
key,
path,
show,
meta,
breadcrumbLabel,
fullPath,
closeable,
}) => ({
name,
key,
path,
show,
meta,
breadcrumbLabel,
fullPath,
closeable,
}),
),
)
/**
*
@ -96,33 +126,20 @@ export const piniaMenuStore = defineStore(
const { meta } = option
const { i18nKey, noLocalTitle } = meta
// 设置 label, i18nKey 优先级最高
const label = computed(() => (i18nKey ? t(`${i18nKey}`) : noLocalTitle))
// 拼装菜单项,容错处理,兼容以前版本 key 选取为 path 的情况
const route = {
const getLabel = () =>
i18nKey ? t(i18nKey) : (noLocalTitle ?? option.name ?? option.path)
const resolved = {
...option,
key: option.fullPath,
label: () =>
h(NEllipsis, null, {
default: () => label.value,
}),
breadcrumbLabel: label.value,
} as AppMenuOption
// 合并 icon, extra
const attr: AppMenuOption = Object.assign({}, route, {
label: () => h(NEllipsis, null, { default: getLabel }),
get breadcrumbLabel() {
return String(getLabel())
},
icon: createMenuIcon(option),
extra: createMenuExtra(option),
})
// 如果当前菜单项与缓存菜单项相同,则更新当前菜单项
if (option.fullPath === getCatchMenuKey()) {
menuState.currentMenuOption = attr
}
// 验证菜单项是否显示
attr.show = validMenuItemShow(attr)
return attr
return Object.assign(resolved, { show: validMenuItemShow(resolved) })
}
/**
@ -135,9 +152,15 @@ export const piniaMenuStore = defineStore(
* 如果识别到为平级模式,则会自动追加一层面包屑。
*/
const setBreadcrumbOptions = (key: string | number) => {
menuState.breadcrumbOptions = unref(
parseAndFindMatchingNodes(menuState.options, 'fullPath', key),
)
const trail: AppMenuOption[] = []
let entry = menuIndex.get(String(key))
while (entry) {
trail.unshift(entry.option)
entry = menuIndex.get(entry.parentPath)
}
menuState.breadcrumbOptions = trail
}
/**
@ -161,217 +184,155 @@ export const piniaMenuStore = defineStore(
? menuState.menuTagOptions.push(...arr)
: (menuState.menuTagOptions = arr)
setStorage(APP_CATCH_KEY.appMenuTagOptions, menuState.menuTagOptions)
cacheTags()
}
/**
*
* @param key full path
* @param option menu tag option
*
* @description
* 设置当前标签项,如果不存在则追加。
*/
const setMenuTagOptionsWhenMenuValueChange = (
key: string | number,
option: AppMenuOption,
) => {
const tag = menuState.menuTagOptions.find((curr) => curr.fullPath === key)
const updateActiveMenu = (option: AppMenuOption) => {
setKeepAliveInclude(option)
updateDocumentTitle(option)
if (!tag) {
menuState.menuTagOptions.push(option as MenuTagOptions)
if (option.meta.sameLevel) {
if (
!menuState.breadcrumbOptions.some(({ key }) => key === option.key)
) {
menuState.breadcrumbOptions.push(option)
}
return
}
// 清理所有非根路径的标签页
menuState.menuTagOptions = menuState.menuTagOptions.filter((curr) =>
curr.fullPath?.startsWith('/'),
)
if (
!menuState.menuTagOptions.some(
({ fullPath }) => fullPath === option.fullPath,
)
) {
menuState.menuTagOptions.push(option)
cacheTags()
}
setStorage(APP_CATCH_KEY.appMenuTagOptions, menuState.menuTagOptions)
setBreadcrumbOptions(option.key)
if (!menuState.breadcrumbOptions.length)
menuState.breadcrumbOptions = [option]
menuState.currentMenuOption = option
if (menuState.menuKey !== option.key) {
menuState.menuKey = option.key
setStorage(APP_CATCH_KEY.appMenuKey, option.key)
}
}
/**
*
* @param key 菜单更新后的 key
* @param option 菜单当前 option 项
* @param query 路由参数
*
* @description
* 修改 `menu key` 后的回调函数。
* 修改后,缓存当前选择 key 并且存储标签页与跳转页面(router push 操作)。
*
* 如果 windowOpen 存在, 则直接打开新窗口,不会更新当前菜单状态,也不会做其他的操作。
* 如果 sameLevel 存在,则会追加一层面包屑,并不会触发菜单更新与标签页更新。
*
* 在执行更新操作后会做一些缓存操作。
*
* 该方法是整个模板的核心驱动: 菜单、标签页、面包屑、浏览器标题等等的更新方法。
*
* @example
* changeMenuModelValue('/dashboard',{ dashboard option }) // 跳转页面至 dashboard,并且更新菜单状态、标签页、面包屑、浏览器标题等等
* changeMenuModelValue('/dashboard', { dashboard option }, { id: 1 }) // 执行更新操作,并且传递参数
*/
const changeMenuModelValue = (
key: string | number,
option: AppMenuOption,
query?: LocationQuery,
) => {
const { meta } = option
if (option.meta.windowOpen) {
window.open(option.meta.windowOpen, '_blank', 'noopener,noreferrer')
if (meta.windowOpen) {
window.open(meta.windowOpen)
} else {
push({
path: String(key),
query,
})
const { sameLevel } = meta
// 更新缓存队列
setKeepAliveInclude(option)
// 更新浏览器标题
updateDocumentTitle(option)
// 如果不为 sameLevel,则会执行更新:覆盖更新面包屑、添加标签菜单、更新缓存
if (!sameLevel) {
// 更新标签菜单
setMenuTagOptionsWhenMenuValueChange(key, option)
// 更新面包屑
setBreadcrumbOptions(key)
menuState.menuKey = key
menuState.currentMenuOption = option
// 缓存菜单 key(sessionStorage)
setStorage(APP_CATCH_KEY.appMenuKey, key)
} else {
// 使用 pick 提取仅需要的字段,避免 vue 抛错空引用,导致性能损耗
const breadcrumbOption = pick(
resolveOption(option),
pickRouteRecordNormalizedConstant,
) as AppMenuOption
// 查看是否重复
const find = menuState.breadcrumbOptions.find(
(curr) => curr.key === breadcrumbOption.key,
)
// 如果未重复追加
if (!find) {
menuState.breadcrumbOptions.push({
...breadcrumbOption,
fullPath: String(breadcrumbOption.key),
})
}
}
}
}
/**
*
* @param path 路由地址
*
* @description
* 监听路由地址变化更新菜单状态。
*/
const updateMenuKeyWhenRouteUpdate = async (
path: string,
query: LocationQuery,
) => {
const [routePath] = path.split('?')
// 直接使用完整 url,检查是否在 routes 中
const findMenuOption = getRoutes().find((curr) => curr.path === routePath)
// 避免匹配根页面路由
if (
findMenuOption?.path === '/' ||
!findMenuOption?.path ||
findMenuOption?.path === '/login'
) {
return
}
if (findMenuOption) {
// 使用 pick 提取仅需要的字段,避免 vue 抛错空引用,导致性能损耗
const pickOption = pick(
findMenuOption,
pickRouteRecordNormalizedConstant,
) as unknown as AppMenuOption
const path = String(key)
changeMenuModelValue(
routePath,
resolveOption({
...pickOption,
fullPath: pickOption.path,
}),
query,
)
}
if (route.fullPath === path && !query) updateActiveMenu(option)
else return push({ path, query })
}
/**
*
* @description
* 初始化系统菜单列表,该方法仅执行一次。
* 会在初始化时拼接完整的 url 地址为 fullPath。
*
* 如果你需要手动更新菜单,可以在需要的时候调用该方法,即可刷新整个系统菜单。
*/
const setupAppMenu = () => {
return new Promise<void>((resolve) => {
const resolveRoutes = (routes: AppMenuOption[], parentPath: string) => {
const catchArr: AppMenuOption[] = []
const regex = /\/+/g
const optionForRoute = (path: string, matched: RouteRecordNormalized[]) => {
const record = matched.at(-1)
for (const curr of routes) {
let fullPath = `${
parentPath.endsWith('/') ? parentPath : parentPath + '/'
}${curr.path}`
if (!record || record.path === '/' || record.redirect) return
// 使用正则表达式替换重复的 '/'
fullPath = fullPath.replace(regex, '/')
const canonicalPath = record.aliasOf?.path ?? record.path
const menuOption = menuIndex.get(canonicalPath)?.option
if (curr.children?.length) {
curr.children = resolveRoutes(curr.children, fullPath)
} else if (!validRole(curr.meta)) {
continue
}
if (menuOption && !canonicalPath.includes(':')) return menuOption
catchArr.push(
resolveOption({
...curr,
fullPath,
}),
)
}
return catchArr
}
menuState.options = resolveRoutes(
getAppRawRoutes() as AppMenuOption[],
'',
)
const r =
menuState.currentMenuOption ||
(canSkipRoute(menuState.options) as AppMenuOption)
if (r) {
// 惰性更新面包屑,避免 sameLevel 模式下的面包屑被覆盖
if (!menuState.breadcrumbOptions.length) {
setBreadcrumbOptions(r.key)
}
setMenuTagOptionsWhenMenuValueChange(r.fullPath, r)
updateDocumentTitle(r)
}
resolve()
return resolveOption({
...(pick(
record,
pickRouteRecordNormalizedConstant,
) as unknown as AppMenuOption),
fullPath: path,
})
}
const setupAppMenu = async () => {
const currentRole = signing.signingCallback.role ?? ''
menuIndex.clear()
const resolveRoutes = (
routes: AppMenuOption[],
parentPath: string,
): AppMenuOption[] => {
const options: AppMenuOption[] = []
for (const curr of routes) {
if (!validRole(curr.meta, currentRole)) continue
const fullPath = joinRoutePath(parentPath, curr.path)
const children = curr.children?.length
? resolveRoutes(curr.children, fullPath)
: void 0
if (children && !children.length) continue
const option = resolveOption({ ...curr, fullPath, children })
menuIndex.set(fullPath, { option, parentPath })
options.push(option)
}
return options
}
menuState.options = resolveRoutes(
getAppRawRoutes() as AppMenuOption[],
'',
)
menuState.currentMenuOption = null
menuState.breadcrumbOptions = []
const restoredTags = menuState.menuTagOptions.flatMap(({ fullPath }) => {
if (typeof fullPath !== 'string' || !fullPath.startsWith('/')) return []
const restored = resolve(fullPath)
const record = restored.matched.at(-1)
if (!record || !validRole(record.meta, currentRole)) return []
const option = optionForRoute(restored.path, restored.matched)
return option && !option.meta.sameLevel && !option.meta.windowOpen
? [option]
: []
})
menuState.menuTagOptions = restoredTags
cacheTags()
const active = optionForRoute(route.path, route.matched)
if (!active || active.meta.sameLevel) {
const cached = menuIndex.get(String(menuState.menuKey))?.option
const first =
cached &&
!cached.children &&
cached.show !== false &&
!cached.meta.windowOpen
? cached
: canSkipRoute(menuState.options)
if (first) updateActiveMenu(first as AppMenuOption)
}
if (active) updateActiveMenu(active)
}
/**
*
* @param collapsed 折叠菜单开关
@ -395,39 +356,27 @@ export const piniaMenuStore = defineStore(
const spliceMenTagOptions = (idx: number, length = 1) => {
const r = menuState.menuTagOptions.splice(idx, length)
setStorage(APP_CATCH_KEY.appMenuTagOptions, menuState.menuTagOptions)
cacheTags()
return r
}
/**
*
* @description
* 初始化系统菜单列表。
* 该方法仅执行一次。
*/
const setupPiniaMenuStore = async () => {
if (!isSetupAppMenuLock.value) {
return
}
watch(() => signing.signingCallback.role, setupAppMenu, { immediate: true })
await setupAppMenu()
isSetupAppMenuLock.value = false
}
// 监听路由变化并且更新路由菜单与菜单标签
watch(
() => route.fullPath,
async (ndata, odata) => {
await setupPiniaMenuStore()
() => route.path,
(path) => {
const option = optionForRoute(path, route.matched)
if (ndata !== odata) {
await updateMenuKeyWhenRouteUpdate(ndata, route.query)
}
if (option) updateActiveMenu(option)
},
{
immediate: true,
)
watch(
() => menuState.currentMenuOption?.breadcrumbLabel,
() => {
if (menuState.currentMenuOption)
updateDocumentTitle(menuState.currentMenuOption)
},
)

View File

@ -150,23 +150,20 @@ export const createMenuIcon = (option: AppMenuOption) => {
return () => icon
}
const { menuConfig } = piniaSettingStore()
const { collapsed } = piniaMenuStore()
const settings = piniaSettingStore()
const menu = piniaMenuStore()
const name = resolveIconName(icon)
if (!name) return
const _icon = h(
RIcon,
{
return () =>
h(RIcon, {
name,
size: collapsed ? menuConfig.collapsedIconSize : menuConfig.iconSize,
size: menu.collapsed
? settings.menuConfig.collapsedIconSize
: settings.menuConfig.iconSize,
cursor: 'pointer',
},
{},
)
return () => _icon
})
}
/**
@ -204,46 +201,17 @@ export const createMenuExtra = (option: AppMenuOption) => {
strong: true,
}
// 渲染文案,优先级:i18nLabel > label
const renderLabel = () => {
if (i18nLabel) {
return t(i18nLabel)
}
if (label) {
return label
}
return null
}
// 如果没有文案,但是设置了 icon,则将 padding-right 设置为 0
const style = () => {
if ((icon && (i18nLabel || label)) || (!icon && (i18nLabel || label))) {
return null
}
return {
'padding-right': '0',
}
}
if (isValueType<object>(extra, 'Object')) {
return () => {
return h(
NTag,
{
...tagProps,
type: type || 'primary',
style: style(),
},
{
default: () => renderLabel(),
icon: () => icon,
},
)
}
}
return () =>
h(
NTag,
{ ...tagProps, type: type || 'primary' },
{
default: () => (i18nLabel ? t(i18nLabel) : label),
icon: icon
? () => (typeof icon === 'string' ? h(RIcon, { name: icon }) : icon)
: void 0,
},
)
}
/**
@ -274,10 +242,12 @@ export const getCatchMenuKey = () => {
* @returns 获取缓存的菜单标签页
*/
export const getCatchMenuTagOptions = () => {
return (
getStorage<AppMenuOption[]>(
APP_CATCH_KEY.appMenuTagOptions,
'sessionStorage',
) ?? []
const cached = getStorage<AppMenuOption[]>(
APP_CATCH_KEY.appMenuTagOptions,
'sessionStorage',
)
return Array.isArray(cached)
? cached.filter((item) => typeof item?.fullPath === 'string')
: []
}

View File

@ -0,0 +1,93 @@
.route-management {
max-width: 1360px;
margin-inline: auto;
display: grid;
gap: 20px;
container-type: inline-size;
&__workspace {
display: grid;
grid-template-columns: minmax(0, 1fr);
align-items: start;
gap: 20px;
> * {
min-width: 0;
}
}
&__add {
margin-block: 16px;
padding: 12px;
border: 1px solid var(--r-line);
border-radius: 8px;
summary {
cursor: pointer;
}
form {
display: grid;
gap: 12px;
margin-top: 12px;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr));
align-items: end;
}
}
&__tools {
margin-block: 12px;
}
&__hint,
&__contract p {
color: var(--r-text-secondary);
margin: 12px 0;
}
&__endpoint,
&__routes {
overflow-wrap: anywhere;
}
&__editor {
font-family: var(--r-font-mono);
font-size: 13px;
}
&__error {
max-height: 200px;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
&__routes {
list-style: none;
padding: 0;
max-height: 480px;
overflow: auto;
border: 1px solid var(--r-line);
border-radius: 8px;
li {
display: grid;
padding: 8px;
gap: 4px;
}
li + li {
border-top: 1px solid var(--r-line);
}
small {
color: var(--r-text-secondary);
}
}
}
@container (min-width: 850px) {
.route-management__workspace {
grid-template-columns: minmax(0, 2fr) minmax(240px, 1fr);
}
}

View File

@ -0,0 +1,402 @@
import './index.scss'
import AppPageHeader from '@/app-components/app/AppPageHeader'
import { useI18n } from '@/hooks'
import { getStaticAppRoutes } from '@/router/app-route-modules'
import { exportRouteConfig, parseRouteConfig } from '@/router/config/contract'
import type { RouteConfig } from '@/router/config/schema'
import {
fetchRemoteRouteConfig,
remoteRouteUrl,
routeSourceStatus,
saveRouteSource,
} from '@/router/config/source'
import type { RouteSource } from '@/router/config/source'
import { routeViewCatalog } from '@/router/config/views'
import { joinRoutePath } from '@/router/utils/join-route-path'
import {
NAlert,
NButton,
NCard,
NFlex,
NFormItem,
NInput,
NRadioButton,
NRadioGroup,
NSelect,
NTag,
} from 'naive-ui'
function downloadJson(filename: string, data: unknown) {
const url = URL.createObjectURL(
new Blob([JSON.stringify(data, null, 2) + '\n'], {
type: 'application/json',
}),
)
const link = document.createElement('a')
link.href = url
link.download = filename
link.click()
setTimeout(() => URL.revokeObjectURL(url), 1000)
}
export default defineComponent({
name: 'RouteManagement',
setup() {
const { t } = useI18n('routeManagement')
const source = ref<RouteSource>(routeSourceStatus.requested)
const draft = ref('')
const checked = shallowRef<RouteConfig>()
const error = ref('')
const busy = ref(false)
const file = useTemplateRef<HTMLInputElement>('file')
const editorId = useId()
const resultId = useId()
const pathId = useId()
const titleId = useId()
const viewId = useId()
const newPage = reactive({ path: '', title: '', component: 'dashboard' })
const viewOptions = routeViewCatalog.map(({ id }) => ({
label: id,
value: id,
}))
const report = (reason: unknown) => {
checked.value = void 0
error.value = reason instanceof Error ? reason.message : String(reason)
}
const setDraft = (config: RouteConfig) => {
draft.value = JSON.stringify(config, null, 2)
checked.value = config
error.value = ''
}
const loadStatic = () => {
try {
setDraft(exportRouteConfig(getStaticAppRoutes()))
} catch (reason) {
report(reason)
}
}
if (routeSourceStatus.config) setDraft(routeSourceStatus.config)
else loadStatic()
const validate = () => {
try {
const config = parseRouteConfig(draft.value)
checked.value = config
error.value = ''
return config
} catch (reason) {
report(reason)
}
}
const addPage = (event: Event) => {
event.preventDefault()
const config = validate()
if (!config) return
const page = {
path: newPage.path.trim(),
component: newPage.component,
meta: { noLocalTitle: newPage.title.trim() },
}
try {
setDraft(
parseRouteConfig(
JSON.stringify({ ...config, routes: [...config.routes, page] }),
),
)
newPage.path = ''
newPage.title = ''
source.value = 'local'
} catch (reason) {
report(reason)
}
}
const readFile = async (event: Event) => {
const input = event.currentTarget as HTMLInputElement
const selected = input.files?.[0]
if (!selected) return
try {
if (selected.size > 256 * 1024) throw new Error(t('fileLimit'))
draft.value = await selected.text()
source.value = 'local'
validate()
} catch (reason) {
report(reason)
} finally {
input.value = ''
}
}
const loadRemote = async () => {
busy.value = true
try {
setDraft(await fetchRemoteRouteConfig())
} catch (reason) {
report(reason)
} finally {
busy.value = false
}
}
const apply = () => {
const config = source.value === 'local' ? validate() : void 0
if (source.value === 'local' && !config) return
try {
saveRouteSource(source.value, config)
} catch (reason) {
report(reason)
}
}
const summary = computed(() => {
const entries: { path: string; component: string; depth: number }[] = []
const visit = (
records: RouteConfig['routes'],
parent = '',
depth = 0,
) => {
for (const route of records) {
const path = joinRoutePath(parent, route.path)
entries.push({
path,
component:
route.component ??
route.redirect ??
(route.children ? t('group') : t('external')),
depth,
})
if (route.children) visit(route.children, path, depth + 1)
}
}
if (checked.value) visit(checked.value.routes)
return entries
})
return () => (
<section class="route-management">
<AppPageHeader
eyebrow={t('eyebrow')}
title={t('title')}
description={t('description')}
>
<NTag
type={routeSourceStatus.error ? 'warning' : 'info'}
bordered={false}
>
{t('active', { source: t(routeSourceStatus.active) })}
</NTag>
</AppPageHeader>
{routeSourceStatus.error && (
<NAlert type="warning" title={t('fallback')}>
{routeSourceStatus.error}
</NAlert>
)}
<NCard title={t('source')}>
<NFlex align="center" justify="space-between">
<NRadioGroup v-model:value={source.value} aria-label={t('source')}>
<NRadioButton value="static">{t('static')}</NRadioButton>
<NRadioButton value="local">{t('local')}</NRadioButton>
<NRadioButton value="remote" disabled={!remoteRouteUrl}>
{t('remote')}
</NRadioButton>
</NRadioGroup>
<NButton
type="primary"
onClick={apply}
disabled={
busy.value || (source.value === 'remote' && !remoteRouteUrl)
}
>
{t('apply')}
</NButton>
</NFlex>
<p class="route-management__hint">{t(`${source.value}Hint`)}</p>
{remoteRouteUrl && (
<code class="route-management__endpoint">{remoteRouteUrl}</code>
)}
</NCard>
<div class="route-management__workspace">
<NCard title={t('manifest')}>
<NFlex class="route-management__tools">
<NButton size="small" onClick={loadStatic}>
{t('loadStatic')}
</NButton>
{remoteRouteUrl && (
<NButton size="small" loading={busy.value} onClick={loadRemote}>
{t('loadRemote')}
</NButton>
)}
<NButton size="small" onClick={() => file.value?.click()}>
{t('import')}
</NButton>
<input
ref="file"
type="file"
accept=".json,application/json"
hidden
onChange={readFile}
/>
<NButton
size="small"
onClick={() => {
const config = validate()
if (config) downloadJson('routes.json', config)
}}
>
{t('export')}
</NButton>
</NFlex>
<details class="route-management__add">
<summary>{t('quickAdd')}</summary>
<form onSubmit={addPage} autocomplete="off">
<NFormItem
label={t('pagePath')}
labelProps={{ for: pathId }}
showFeedback={false}
>
<NInput
v-model:value={newPage.path}
placeholder="/reports"
inputProps={{ id: pathId, required: true }}
/>
</NFormItem>
<NFormItem
label={t('pageTitle')}
labelProps={{ for: titleId }}
showFeedback={false}
>
<NInput
v-model:value={newPage.title}
inputProps={{ id: titleId, required: true }}
/>
</NFormItem>
<NFormItem
label={t('pageView')}
labelProps={{ id: viewId }}
showFeedback={false}
>
<NSelect
v-model:value={newPage.component}
options={viewOptions}
filterable
aria-labelledby={viewId}
/>
</NFormItem>
<NButton attrType="submit" secondary type="primary">
{t('addPage')}
</NButton>
</form>
</details>
<NFormItem
label={t('editor')}
labelProps={{ for: editorId }}
showFeedback={false}
>
<NInput
class="route-management__editor"
type="textarea"
value={draft.value}
rows={19}
inputProps={{
id: editorId,
spellcheck: false,
'aria-describedby': resultId,
}}
onUpdateValue={(value) => {
draft.value = value
checked.value = void 0
error.value = ''
}}
/>
</NFormItem>
<NFlex align="center" class="route-management__tools">
<NButton type="primary" secondary onClick={validate}>
{t('validate')}
</NButton>
<span id={resultId} role="status">
{checked.value
? t('valid', { count: summary.value.length })
: t('editHint')}
</span>
</NFlex>
{error.value && (
<NAlert type="error" title={t('invalid')}>
<pre class="route-management__error">{error.value}</pre>
</NAlert>
)}
</NCard>
<NCard title={t('contract')} class="route-management__contract">
<p>{t('contractHint')}</p>
<NFlex>
<NButton
size="small"
onClick={async () => {
try {
const { getRouteJsonSchema } =
await import('@/router/config/json-schema')
downloadJson(
'route-config.schema.json',
getRouteJsonSchema(),
)
} catch (reason) {
report(reason)
}
}}
>
JSON Schema
</NButton>
<NButton
size="small"
onClick={() =>
downloadJson('route-views.json', routeViewCatalog)
}
>
{t('views')}
</NButton>
</NFlex>
<h3>{t('preview')}</h3>
{summary.value.length > 0 ? (
<ul class="route-management__routes">
{summary.value.map(({ path, component, depth }, index) => (
<li
key={index}
style={{
paddingInlineStart: `${Math.min(depth, 4) * 12 + 8}px`,
}}
>
<code>{path}</code>
<small>{component}</small>
</li>
))}
</ul>
) : (
<p>{t('previewEmpty')}</p>
)}
</NCard>
</div>
</section>
)
},
})