feat: expand layout and route configuration

Add navigation presets, page transitions, and visual route editing.

Fix Segment sizing and loading placement. Add preference import and export.
This commit is contained in:
XiaoDaiGua-Ray 2026-11-04 11:17:27 +08:00
parent bd09fa6b18
commit 6f095b763e
47 changed files with 1351 additions and 339 deletions

View File

@ -1,7 +1,7 @@
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 { APP_CATCH_KEY, GLOBAL_CLASS_NAMES } 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'
@ -26,6 +26,16 @@ const menu = (
show,
})
const mountPersistedSettings = () => {
const pinia = createPinia().use(piniaPluginPersistedstate)
const app = createApp({ render: () => null }).use(pinia)
app.mount(document.createElement('div'))
setActivePinia(pinia)
return { pinia, app }
}
describe('layout preferences', () => {
it('adds defaults and bounds persisted or programmatic invalid values', () => {
expect(normalizeLayoutConfig(null)).toEqual(
@ -60,11 +70,7 @@ describe('layout preferences', () => {
menuTagSwitch: false,
}),
)
const pinia = createPinia().use(piniaPluginPersistedstate)
const app = createApp({ render: () => null }).use(pinia)
app.mount(document.createElement('div'))
setActivePinia(pinia)
const { pinia, app } = mountPersistedSettings()
try {
const store = piniaSettingStore()
@ -86,6 +92,80 @@ describe('layout preferences', () => {
}
})
it('restores the exported preferences through the existing store and persistence', async () => {
const { pinia, app } = mountPersistedSettings()
const store = piniaSettingStore()
const property = GLOBAL_CLASS_NAMES.rayTemplateThemePrimaryColor
const fadeProperty = GLOBAL_CLASS_NAMES.rayTemplateThemePrimaryFadeColor
const { style } = document.documentElement
try {
store.updateSettingState('layoutConfig', { mode: 'right' })
store.updateSettingState('appTheme', 'dark')
store.updateSettingState('watermarkConfig', { content: 'Portable' })
store.updateSettingState('keepAliveConfig', {
keepAliveExclude: ['Page'],
})
store.changePrimaryColor('#3468db')
const file = store.exportPreferences()
store.updateSettingState('layoutConfig', { mode: 'top' })
store.updateSettingState('appTheme', 'light')
store.updateSettingState('appRootRoute', { path: '/custom-home' })
store.changePrimaryColor('#000000')
store.importPreferences(JSON.stringify(file))
await nextTick()
expect(store.exportPreferences()).toEqual(file)
expect(store._appTheme).toBe(true)
expect(style.getPropertyValue(property)).toBe('#3468db')
expect(store.appRootRoute.path).toBe('/custom-home')
expect(file.preferences).not.toHaveProperty('appRootRoute')
expect(file.preferences).not.toHaveProperty('lockScreenSwitch')
expect(
JSON.parse(
localStorage.getItem(APP_CATCH_KEY.appPiniaSettingStore) ?? 'null',
),
).toMatchObject({ layoutConfig: { mode: 'right' }, appTheme: 'dark' })
} finally {
app.unmount()
disposePinia(pinia)
localStorage.removeItem(APP_CATCH_KEY.appPiniaSettingStore)
style.removeProperty(property)
style.removeProperty(fadeProperty)
}
})
it('does not change any preference when the file contains invalid settings', () => {
const pinia = createPinia()
setActivePinia(pinia)
const store = piniaSettingStore()
const before = store.exportPreferences()
try {
expect(() => store.importPreferences('{"routes": []}')).toThrow()
expect(() =>
store.importPreferences(JSON.stringify({ ...before, version: 2 })),
).toThrow()
expect(() =>
store.importPreferences(
JSON.stringify({
...before,
preferences: {
...before.preferences,
appTheme: 'dark',
menuConfig: { ...before.preferences.menuConfig, menuWidth: -1 },
},
}),
),
).toThrow()
expect(store.exportPreferences()).toEqual(before)
} finally {
disposePinia(pinia)
}
})
it('finds mixed navigation roots by nested leaf and skips hidden branches', () => {
const root = menu('/root', [
menu('/hidden', [], false),

View File

@ -65,3 +65,21 @@ it('offers a restore button for custom content and also exits with Escape', asyn
disposePinia(pinia)
}
})
it('moves the full navigation to the right without adding a second menu', () => {
const pinia = createPinia()
setActivePinia(pinia)
piniaSettingStore().updateSettingState('layoutConfig', { mode: 'right' })
const wrapper = shallowMount(Layout, {
global: { renderStubDefaultSlot: true, plugins: [router, pinia] },
})
try {
expect(wrapper.get('app-menu-stub').attributes('end')).toBe('true')
expect(wrapper.find('top-navigation-stub').exists()).toBe(false)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})

View File

@ -1,4 +1,8 @@
import { getStaticAppRoutes } from '@/router/app-route-modules'
import {
appExpandRoutes,
getAppRawRoutes,
getStaticAppRoutes,
} from '@/router/app-route-modules'
import {
exportRouteConfig,
parseRouteConfig,
@ -14,6 +18,26 @@ const parse = (routes: unknown[]) =>
parseRouteConfig(JSON.stringify({ version: 1, routes }))
describe('route configuration', () => {
it('keeps both management pages under the same admin-only menu', () => {
const root = getAppRawRoutes().find(
({ path }) => path === '/route-management',
)
const leaves = appExpandRoutes().filter(({ path }) =>
path.startsWith('/route-management/'),
)
expect(root?.children?.map(({ path }) => path)).toEqual(['visual', 'json'])
expect(leaves.map(({ path }) => path)).toEqual([
'/route-management/visual',
'/route-management/json',
])
for (const { meta } of leaves) {
expect(validRole(meta, 'admin')).toBe(true)
expect(validRole(meta, 'viewer')).toBe(false)
}
})
it('round-trips all bundled routes with their view IDs and metadata', () => {
const bundled = getStaticAppRoutes()
const config = exportRouteConfig(bundled)
@ -73,6 +97,11 @@ describe('route configuration', () => {
it.each([
[[{ ...page, path: '/route-management' }], /reserved/i],
[[{ ...page, path: '/ROUTE-MANAGEMENT/Visual' }], /reserved/i],
[
[{ ...page, path: '/reports', alias: '/route-management/json' }],
/reserved/i,
],
[[{ ...page, path: '/reports', name: 'RLogin' }], /reserved/i],
[[{ ...page, path: '/reports', component: 'missing' }], /unknown view/i],
[

View File

@ -22,3 +22,7 @@
## 动态路由与示例页交接
应用侧已准备好 [路由接入文档](../src/router/README.md)、[Schema](../src/router/config/schema.ts)、[Segment 说明](../src/components/RSegment/README.md) 和 [页面设计说明](ui-design.md)。应用提交可访问后,在站外的 `guide/routing.md` 补充来源切换、接口示例和版本校验,在组件参考中补充 `fitContent` 的选中态与过渡规则。站外截图使用更新后的登录页与管理页,并核对部署子路径。
布局与路由编辑器交付后,站外 `guide/layout.md` 补充右侧导航、通栏分组、减少动态效果和浮动退出按钮;`guide/routing.md` 增加可视化与 JSON 两个入口,明确可视化应用仅保存在当前浏览器;`reference/hooks/layout.md` 说明加载提示以可见内容区为基准。引用对应的应用提交后再验证文档站构建和预览。
站外 `guide/layout.md` 同步设置抽屉的偏好导入导出:JSON 只包含抽屉内偏好,校验通过后即时保存,独立于路由管理的 JSON 配置。

View File

@ -113,8 +113,7 @@ export const APP_CATCH_KEY = {
*
* @description
* 系统内容切换动画配置。
* 但是在配置的时候,会自动拼接一个 transform 前缀。
* 例如: transform-fade-bottom。
* 样式名在配置值后拼接 -transform,例如 fade-bottom-transform。
*/
export const CONTENT_TRANSITION_OPTIONS = [
{
@ -141,4 +140,6 @@ export const CONTENT_TRANSITION_OPTIONS = [
label: '底部消退',
value: 'fade-bottom',
},
{ label: '向上浮入', value: 'slide-up' },
{ label: '向左滑入', value: 'slide-left' },
]

View File

@ -4,4 +4,4 @@
在 Naive UI 2.45.3 中,选中态默认加粗。轨道使用内容宽度时,尤其是标签长短不同或带图标、提示时,切换选中态会改变轨道宽度。NTabs 的轨道 ResizeObserver 随即执行 `handleSegmentResize`,临时加上 `transition-disabled` 并强制同步胶囊位置。这个同步会让刚开始的位移动画跳到终点。
`fitContent` 模式固定各标签的字重,用颜色和胶囊标示选中态。内容过长时导航区可以横向滚动,避免撑破外层。轨道真正发生尺寸变化时继续让 NTabs 同步位置。减少动态效果偏好下取消胶囊过渡。
`fitContent` 模式按标签和轨道内边距的实际宽度排版,固定各标签的字重,用颜色和胶囊标示选中态。只有内容宽于可用空间时才横向滚动。轨道真正发生尺寸变化时继续让 NTabs 同步位置。减少动态效果偏好下取消胶囊过渡。

View File

@ -9,6 +9,8 @@
}
.n-tabs-rail {
box-sizing: border-box;
flex: none;
inline-size: max-content;
min-inline-size: 100%;
}
@ -19,6 +21,7 @@
// 选中前后字重相同,避免 intrinsic rail 触发 Naive UI 的无动画 resize 同步。
.n-tabs-tab {
inline-size: auto;
font-weight: var(--n-font-weight-strong);
}
}

View File

@ -1,5 +1,5 @@
<template>
<div>
<div class="r-route-transition">
<RouterView v-slot="{ Component, route }">
<template v-if="Component">
<Transition

View File

@ -29,6 +29,7 @@
- 组合式函数在 `setup` 或有效 effect scope 内创建,DOM 操作由用户事件或挂载后的回调触发。事件、订阅、动画帧随作用域清理。
- 全局 UI 状态由 Pinia `runtime` 管理,通过 `useRuntimeGetters` / `useRuntimeActions` 访问,不写入持久化缓存。
- `useSpinning().reload(wait)` 会卸载页面,恢复计时器由 runtime Store 持有;多个调用以最后一次刷新为准。
- 默认布局中的加载提示始终位于可见内容区中央,支持长页面与内容最大化。`reload` 立即显示提示,`openSpin` 持续超过 120ms 时显示,`closeSpin` 立即关闭手动加载提示。
- 两个滚动 Hook 可以在 setup 阶段创建,调用时才读取布局实例。无侧栏或未挂载时安全忽略。
- `useMaximize` 操作布局内容,多个调用方共享状态;`useElementFullscreen` 操作任意单个元素,其状态属于当前实例。二者均不调用浏览器 Fullscreen API。
- `navigationTo` 的索引从 0 开始;负数、小数、非有限数和越界索引不会导航。完整 URL 支持动态参数、query 和 hash;额外 query 参数可覆盖 URL 中的同名参数。成功调用返回 Router 导航 Promise。

View File

@ -7,10 +7,14 @@
- `side`:完整侧边菜单。
- `top`:完整顶部导航,Naive UI 处理横向溢出与子菜单。
- `mixed`:顶部一级导航,侧栏显示当前一级菜单的可见子菜单;单页菜单不占侧栏空间。
- `right`:完整侧边菜单放在内容右侧。
- `split`:固定顶栏横跨全宽,左侧只显示当前分组的子菜单。关闭固定顶栏时,顶部导航随内容滚动。
- ≤768px 自动使用完整菜单抽屉,不覆盖已保存的桌面模式。抽屉选中菜单后自动收起。
- 侧栏与抽屉的 Logo 固定在菜单上方;滚动条从菜单区域开始。菜单设置中的原生滚动条开关只作用于菜单列表。
- 内容支持流式铺满或定宽居中、640–2560px 最大宽度、0–48px 间距,以及顶栏/页脚固定或随内容滚动。标签和版权显隐沿用原设置。
- 最大化内容区与页面、标签菜单共享 Pinia 状态,退出按钮和 Esc 可恢复。
- 最大化内容区与页面、标签菜单共享 Pinia 状态。退出按钮浮在右上角,按 Esc 也可恢复。
- 内容加载以可见滚动视口为基准。重新挂载立即显示提示,短时手动加载延迟 120ms 后显示。顶栏、标签栏和页脚固定时不被遮罩覆盖。
- 「外观 → 页面切换动画」保留旧选项,并增加向上浮入和向左滑入。切换只动画化内容,系统启用减少动态效果时直接切换。
交互借鉴 [Vben 的布局偏好设置](https://doc.vben.pro/en/guide/essentials/settings.html),复用现有 Naive UI 组件,不引入第二套布局框架。
@ -30,6 +34,8 @@ updateSettingState('layoutConfig', {
配置属于 `setting` Store,沿用原有持久化 key;旧缓存自动补默认值并规范化范围,不清空用户偏好。`src/store/modules/setting/constant.ts` 管理默认值。恢复默认布局只重置 `layoutConfig`。
设置抽屉的五种布局预览固定一行,空间不足时可横向滚动。底部可将布局、外观、菜单、水印和通用偏好导出为 `ray-template-preferences.json`,或导入同格式文件。文件须通过版本和字段校验才会应用到当前浏览器,导入无需刷新。不包含登录、锁屏、路由配置或页面缓存数据。
需要替换区域时使用具名插槽:
```tsx

View File

@ -15,27 +15,27 @@
.r-layout-presets {
box-sizing: border-box;
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
max-inline-size: 300px;
padding: 6px;
> .r-layout-settings__hint {
grid-column: 1 / -1;
}
grid-auto-flow: column;
grid-auto-columns: minmax(72px, 1fr);
gap: 6px;
max-inline-size: min(100%, 410px);
padding: 5px;
overflow-x: auto;
}
.r-layout-preset {
position: relative;
box-sizing: border-box;
display: grid;
align-content: center;
place-items: center;
gap: 4px;
align-self: start;
min-inline-size: 0;
min-block-size: 0;
inline-size: 100%;
aspect-ratio: 1;
padding: 6px 4px;
block-size: 68px;
padding: 4px;
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
background: var(--r-surface-muted);
@ -68,12 +68,17 @@
}
}
.r-layout-preset__label {
font-size: 11px;
overflow-wrap: anywhere;
}
.r-layout-preview {
box-sizing: border-box;
display: grid;
grid-template: minmax(0, 1fr) minmax(0, 3fr) / minmax(0, 1fr) minmax(0, 3fr);
gap: 3px;
block-size: min(68%, 60px);
inline-size: min(65%, 37px);
max-inline-size: 100%;
aspect-ratio: 1;
padding: 4px;
@ -117,6 +122,30 @@
opacity: 0.65;
}
&--right {
grid-template-columns: minmax(0, 3fr) minmax(0, 1fr);
.r-layout-preview__aside {
grid-column: 2;
}
.r-layout-preview__header,
.r-layout-preview__body {
grid-column: 1;
}
}
&--split {
.r-layout-preview__header {
grid-column: 1 / -1;
opacity: 0.65;
}
.r-layout-preview__aside {
grid-row: 2;
}
}
&--mixed .r-layout-preview__header {
background: linear-gradient(
to bottom,

View File

@ -1,7 +1,10 @@
import './LayoutSettings.scss'
import { useI18n } from '@/hooks'
import { useSettingActions, useSettingGetters } from '@/store'
import { getDefaultSettingConfig } from '@/store/modules/setting/constant'
import {
getDefaultSettingConfig,
LAYOUT_MODES,
} from '@/store/modules/setting/constant'
import type { LayoutConfig } from '@/store/modules/setting/types'
import {
NButton,
@ -21,7 +24,6 @@ export default defineComponent({
const { getLayoutConfig } = useSettingGetters()
const { updateSettingState } = useSettingActions()
const text = (key: string) => t<string>(key)
const modes = ['side', 'top', 'mixed'] as const
const update = (value: Partial<LayoutConfig>) =>
updateSettingState('layoutConfig', value)
@ -30,8 +32,8 @@ export default defineComponent({
{props.showDescription ? (
<p class="r-layout-settings__hint">{text('description')}</p>
) : null}
<div class="r-layout-presets">
{modes.map((mode) => (
<div class="r-layout-presets" role="group" aria-label={text('tab')}>
{LAYOUT_MODES.map((mode) => (
<button
type="button"
class="r-layout-preset"
@ -49,6 +51,7 @@ export default defineComponent({
<span class="r-layout-preview__aside" />
<span class="r-layout-preview__body" />
</span>
<span class="r-layout-preset__label">{text(mode)}</span>
{getLayoutConfig.value.mode === mode ? (
<span class="r-layout-preset__selected" aria-hidden="true">
✓
@ -56,12 +59,12 @@ export default defineComponent({
) : null}
</button>
))}
{props.showDescription ? (
<p class="r-layout-settings__hint">
{text(`modeHint.${getLayoutConfig.value.mode}`)}
</p>
) : null}
</div>
{props.showDescription ? (
<p class="r-layout-settings__hint">
{text(`modeHint.${getLayoutConfig.value.mode}`)}
</p>
) : null}
<NForm labelPlacement="top" showFeedback={false}>
<NFormItem label={text('contentWidth')}>
<NSelect

View File

@ -8,6 +8,11 @@
border-inline-end: 1px solid var(--r-line);
&--end {
border-inline-end: 0;
border-inline-start: 1px solid var(--r-line);
}
.app-menu__body {
display: flex;
flex-direction: column;

View File

@ -20,6 +20,8 @@ export default defineComponent({
props: {
options: { type: Array as PropType<AppMenuOption[]>, default: void 0 },
showLogo: { type: Boolean, default: true },
end: Boolean,
inert: Boolean,
},
setup(props) {
const menuRef = shallowRef<MenuInst | null>(null)
@ -59,7 +61,8 @@ export default defineComponent({
const basicMenu = () => (
<NLayoutSider
class="app-menu__sider"
class={['app-menu__sider', { 'app-menu__sider--end': props.end }]}
{...{ inert: props.inert }}
showTrigger={!isTabletOrSmaller.value}
collapseMode={getMenuConfig.value.collapsedMode}
collapsedWidth={getMenuConfig.value.collapsedWidth}

View File

@ -10,6 +10,23 @@
padding: 12px clamp(12px, 3vw, 20px) 20px;
background: var(--r-canvas);
}
.r-settings-drawer__actions,
.r-settings-drawer__file-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.r-settings-drawer__actions {
inline-size: 100%;
justify-content: space-between;
}
.r-settings-drawer__file-actions {
justify-content: flex-end;
margin-inline-start: auto;
}
}
.r-settings-heading {

View File

@ -4,7 +4,9 @@ import { useI18n } from '@/hooks'
import LayoutSettings from '@/layout/components/LayoutSettings'
import { useMenuActions, useSettingActions } from '@/store'
import { getDefaultSettingConfig } from '@/store/modules/setting/constant'
import { PREFERENCE_FILE_LIMIT } from '@/store/modules/setting/preference-file'
import type { SettingState } from '@/store/modules/setting/types'
import { downloadAnyFile } from '@/utils/files'
import { cloneDeep, forIn } from 'lodash-es'
import {
drawerProps,
@ -34,8 +36,61 @@ export default defineComponent({
setup(props) {
const { t } = useI18n('preferences')
const { create } = useModal()
const { updateSettingState } = useSettingActions()
const { updateSettingState, exportPreferences, importPreferences } =
useSettingActions()
const { setupAppMenu } = useMenuActions()
const fileInput = useTemplateRef<HTMLInputElement>('preferenceFile')
const importing = ref(false)
const configError = (key: string) =>
window.$message.error(() => <span role="alert">{t(key)}</span>)
const exportConfig = async () => {
try {
const blob = new Blob(
[JSON.stringify(exportPreferences(), null, 2) + '\n'],
{ type: 'application/json' },
)
if (blob.size > PREFERENCE_FILE_LIMIT) {
configError('config.fileLimit')
return
}
await downloadAnyFile(blob, 'ray-template-preferences.json')
} catch {
configError('config.exportError')
}
}
const importConfig = async (event: Event) => {
const input = event.currentTarget as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file || importing.value) return
if (file.size > PREFERENCE_FILE_LIMIT) {
configError('config.fileLimit')
return
}
importing.value = true
try {
importPreferences(await file.text())
void setupAppMenu()
window.$message.success(() => (
<span role="status">{t('config.imported')}</span>
))
} catch {
configError('config.importError')
} finally {
importing.value = false
}
}
const reset = () =>
create({
@ -114,9 +169,29 @@ export default defineComponent({
</NTabs>
),
footer: () => (
<NButton type="warning" secondary onClick={reset}>
{t('reset')}
</NButton>
<div class="r-settings-drawer__actions">
<NButton type="warning" secondary onClick={reset}>
{t('reset')}
</NButton>
<div class="r-settings-drawer__file-actions">
<NButton onClick={exportConfig}>{t('config.export')}</NButton>
<NButton
type="primary"
secondary
loading={importing.value}
onClick={() => fileInput.value?.click()}
>
{t('config.import')}
</NButton>
<input
ref="preferenceFile"
type="file"
accept=".json,application/json"
hidden
onChange={importConfig}
/>
</div>
</div>
),
}}
</NDrawerContent>

View File

@ -13,7 +13,11 @@ export default defineComponent({
const { getMenuOptions, getMenuKey } = useMenuGetters()
const { getLayoutConfig, getMenuConfig } = useSettingGetters()
const { changeMenuModelValue } = useMenuActions()
const mixed = computed(() => getLayoutConfig.value.mode === 'mixed')
const mixed = computed(
() =>
getLayoutConfig.value.mode === 'mixed' ||
getLayoutConfig.value.mode === 'split',
)
const options = computed(() =>
mixed.value
? getMenuOptions.value

View File

@ -0,0 +1,61 @@
import './index.scss'
import { LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE } from '@/app-config'
import { useI18n } from '@/hooks'
import { useRuntimeGetters } from '@/store'
import { NSpin } from 'naive-ui'
export default defineComponent({
name: 'ContentLoading',
setup() {
const { t } = useI18n('layout')
const { globalMainLayoutLoad, layoutContentSpinning } = useRuntimeGetters()
const routePending = ref(false)
const visible = ref(false)
if (LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE) {
const router = useRouter()
const stop = () => (routePending.value = false)
onScopeDispose(
router.beforeEach(() => {
routePending.value = true
}),
)
onScopeDispose(router.afterEach(stop))
onScopeDispose(router.onError(stop))
}
watch(
[globalMainLayoutLoad, layoutContentSpinning, routePending],
([mounted, spinning, navigating], _, onCleanup) => {
if (!mounted) {
visible.value = true
} else if (!spinning && !navigating) {
visible.value = false
} else if (!visible.value) {
const timer = setTimeout(() => (visible.value = true), 120)
onCleanup(() => clearTimeout(timer))
}
},
{ immediate: true },
)
return () => (
<div
role="status"
class={[
'layout-content-loading',
{ 'layout-content-loading--visible': visible.value },
]}
>
{visible.value ? (
<div class="layout-content-loading__indicator">
<NSpin size="small" aria-hidden="true" />
<span>{t('loading')}</span>
</div>
) : null}
</div>
)
},
})

View File

@ -1,19 +1,35 @@
.layout-content-spin {
width: 100%;
height: 100%;
.content-wrapper {
overflow-x: clip;
min-inline-size: 0;
}
> .n-spin-content {
width: 100%;
height: 100%;
.layout-content-loading {
position: absolute;
inset: 0;
z-index: 2;
display: grid;
place-items: center;
pointer-events: none;
&--visible {
pointer-events: auto;
background: color-mix(in srgb, var(--r-canvas) 72%, transparent);
}
&__indicator {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
background: var(--r-surface);
color: var(--r-text);
}
}
.content-wrapper {
box-sizing: border-box;
width: 100%;
min-height: 100%;
&[v-cloak] {
@media (prefers-reduced-motion: reduce) {
.layout-content-loading .n-spin-body {
display: none;
}
}

View File

@ -1,82 +1,24 @@
import { useRuntimeGetters } from '@/store'
import './index.scss'
import AppRequestCancelerProvider from '@/app-components/provider/AppRequestCancelerProvider'
import { LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE } from '@/app-config'
import { RTransitionComponent } from '@/components'
import { useI18n } from '@/hooks'
import { useSettingGetters } from '@/store'
import { NSpin } from 'naive-ui'
import type { GlobalThemeOverrides } from 'naive-ui'
import { useRuntimeGetters, useSettingGetters } from '@/store'
export default defineComponent({
name: 'LayoutContentWrapper',
setup() {
const router = useRouter()
const { t } = useI18n()
const { globalMainLayoutLoad } = useRuntimeGetters()
const { getContentTransition } = useSettingGetters()
const spinning = ref(false)
const themeOverridesSpin: GlobalThemeOverrides['Spin'] = {
opacitySpinning: '0',
}
const { globalMainLayoutLoad, layoutContentSpinning } = useRuntimeGetters()
const setupLayoutContentSpin = () => {
const removeBefore = router.beforeEach(() => {
spinning.value = true
})
const removeAfter = router.afterEach(() => {
spinning.value = false
})
const removeError = router.onError(() => {
spinning.value = false
})
onScopeDispose(removeBefore)
onScopeDispose(removeAfter)
onScopeDispose(removeError)
}
if (LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE) {
setupLayoutContentSpin()
}
return {
t,
globalMainLayoutLoad,
spinning,
themeOverridesSpin,
getContentTransition,
layoutContentSpinning,
}
},
render() {
const {
globalMainLayoutLoad,
layoutContentSpinning,
spinning,
themeOverridesSpin,
getContentTransition,
} = this
return (
<NSpin
show={spinning || !globalMainLayoutLoad || layoutContentSpinning}
delay={300}
description={this.t('layout.loading')}
size="large"
themeOverrides={themeOverridesSpin}
class="layout-content-spin"
>
return () => (
<>
<AppRequestCancelerProvider />
{globalMainLayoutLoad ? (
{globalMainLayoutLoad.value ? (
<RTransitionComponent
class="content-wrapper"
transitionPropName={getContentTransition + '-transform'}
transitionPropName={`${getContentTransition.value}-transform`}
transitionAppear={false}
/>
) : null}
</NSpin>
</>
)
},
})

View File

@ -1,8 +1,16 @@
.r-layout-full {
position: fixed;
inset: 0;
display: flex;
flex-direction: column;
.r-layout-full__body {
flex: 1;
min-block-size: 0;
}
.r-layout-full__viewer {
block-size: 100%;
min-width: 0;
> .n-layout-scroll-container {
@ -19,11 +27,17 @@
flex-shrink: 0;
}
.r-layout-full__viewer-content {
.r-layout-content-viewport {
position: relative;
flex: 1;
min-height: 0;
min-width: 0;
min-block-size: 0;
min-inline-size: 0;
background: var(--r-canvas);
}
.r-layout-full__viewer-content {
block-size: 100%;
background: transparent;
> .n-scrollbar > .n-scrollbar-container {
height: 100%;
@ -50,49 +64,40 @@
}
}
.r-layout-content--maximized {
--layout-restore-height: 49px;
--layout-content-height: calc(100dvh - var(--layout-restore-height));
.r-layout-full .r-layout-content--maximized {
--layout-content-height: 100dvh;
position: fixed !important;
position: fixed;
inset: 0;
height: 100dvh !important;
.r-layout-header-region,
.r-layout-tabs-region,
.r-layout-footer-region {
display: none;
}
.r-layout-content-scroll {
padding-inline-end: 52px;
}
}
.r-layout-content-restore {
position: sticky;
inset-block-start: 0;
.r-layout-content-restore__button {
position: absolute;
inset-block-start: 10px;
inset-inline-end: 10px;
z-index: 3;
display: flex;
justify-content: flex-end;
flex: none;
padding: 8px max(12px, var(--layout-content-padding));
border-block-end: 1px solid var(--r-line);
display: grid;
place-items: center;
inline-size: 36px;
block-size: 36px;
border: 1px solid var(--r-control-border);
border-radius: 8px;
color: var(--r-text);
background: var(--r-surface);
cursor: pointer;
&__button {
display: inline-flex;
align-items: center;
gap: 8px;
min-block-size: 32px;
padding-inline: 10px;
border: 1px solid var(--r-control-border);
border-radius: 8px;
color: var(--r-text);
background: var(--r-surface-muted);
font-size: 13px;
font-weight: 550;
cursor: pointer;
&:hover {
background: var(--r-surface-hover);
}
&:hover {
background: var(--r-surface-hover);
}
}

View File

@ -22,6 +22,7 @@ import {
FooterWrapper,
HeaderWrapper,
} from './default'
import ContentLoading from './default/ContentWrapper/ContentLoading'
import { findMenuRoot } from './navigation'
export default defineComponent({
@ -33,8 +34,12 @@ export default defineComponent({
const { getMenuTagSwitch, getCopyrightSwitch, getLayoutConfig } =
useSettingGetters()
const { getMenuOptions, getMenuKey } = useMenuGetters()
const { layoutContentMaximize, layoutContentMaximizeStyle } =
useRuntimeGetters()
const {
globalMainLayoutLoad,
layoutContentSpinning,
layoutContentMaximize,
layoutContentMaximizeStyle,
} = useRuntimeGetters()
const { setRuntimeState } = useRuntimeActions()
const { maximize } = useMaximize()
const { t } = useI18n('layout')
@ -94,7 +99,11 @@ export default defineComponent({
) : (
<>
<HeaderWrapper />
{mode.value !== 'side' ? <TopNavigation /> : null}
{mode.value === 'top' ||
mode.value === 'mixed' ||
mode.value === 'split' ? (
<TopNavigation />
) : null}
</>
)}
</div>
@ -124,12 +133,26 @@ export default defineComponent({
if (getLockAppScreen()) return <UnlockScreen />
const config = getLayoutConfig.value
const grouped = mode.value === 'mixed' || mode.value === 'split'
const wideHeader = mode.value === 'split' && config.fixedHeader
const hasSider =
mode.value === 'side' ||
(mode.value === 'mixed' && mixedChildren.value.length > 0)
mode.value === 'right' ||
(grouped && mixedChildren.value.length > 0)
const sidebar = () =>
hasSider
? (slots.sidebar?.() ?? (
<Menu
options={grouped ? mixedChildren.value : void 0}
showLogo={!grouped}
end={mode.value === 'right'}
inert={layoutContentMaximize.value}
/>
))
: null
return (
<NLayout
<div
class="r-layout-full"
style={[
cssVars.value,
@ -141,42 +164,61 @@ export default defineComponent({
: '100%',
},
]}
hasSider
embedded
>
{hasSider
? (slots.sidebar?.() ?? (
<Menu
options={
mode.value === 'mixed' ? mixedChildren.value : void 0
}
showLogo={mode.value === 'side'}
/>
))
: null}
<NLayoutContent class="r-layout-full__viewer">
{config.fixedHeader ? (
<>
{header()}
{tabs()}
</>
) : null}
<NLayoutContent
ref={LAYOUT_CONTENT_REF}
class={[
'r-layout-full__viewer-content',
{ 'r-layout-content--maximized': layoutContentMaximize.value },
]}
style={
layoutContentMaximize.value
? layoutContentMaximizeStyle.value
: void 0
}
nativeScrollbar={false}
contentClass="r-layout-content-scroll"
>
{layoutContentMaximize.value ? (
<div class="r-layout-content-restore">
{wideHeader ? header() : null}
<NLayout
class="r-layout-full__body"
hasSider={hasSider}
siderPlacement={mode.value === 'right' ? 'right' : 'left'}
embedded
>
{mode.value !== 'right' ? sidebar() : null}
<NLayoutContent class="r-layout-full__viewer">
{config.fixedHeader ? (
<>
{!wideHeader ? header() : null}
{tabs()}
</>
) : null}
<div
class={[
'r-layout-content-viewport',
{
'r-layout-content--maximized': layoutContentMaximize.value,
},
]}
style={
layoutContentMaximize.value
? layoutContentMaximizeStyle.value
: void 0
}
>
<NLayoutContent
ref={LAYOUT_CONTENT_REF}
class="r-layout-full__viewer-content"
nativeScrollbar={false}
contentClass="r-layout-content-scroll"
>
{!config.fixedHeader ? (
<>
{header()}
{tabs()}
</>
) : null}
<main
class="r-layout-content-inner"
aria-busy={
!slots.default &&
(!globalMainLayoutLoad.value ||
layoutContentSpinning.value)
}
>
{slots.default?.() ?? <ContentWrapper />}
</main>
{!config.fixedFooter ? footer() : null}
</NLayoutContent>
{!slots.default ? <ContentLoading /> : null}
{layoutContentMaximize.value ? (
<button
type="button"
class="r-layout-content-restore__button"
@ -190,25 +232,15 @@ export default defineComponent({
}}
onClick={() => maximize(false)}
>
<RIcon name="action/out" size={16} />
{t('restoreButton')}
<RIcon name="action/fullscreen_fold" size={16} />
</button>
</div>
) : null}
{!config.fixedHeader ? (
<>
{header()}
{tabs()}
</>
) : null}
<main class="r-layout-content-inner">
{slots.default?.() ?? <ContentWrapper />}
</main>
{!config.fixedFooter ? footer() : null}
) : null}
</div>
{config.fixedFooter ? footer() : null}
</NLayoutContent>
{config.fixedFooter ? footer() : null}
</NLayoutContent>
</NLayout>
{mode.value === 'right' ? sidebar() : null}
</NLayout>
</div>
)
}
},

View File

@ -4,7 +4,11 @@
"side": "Sidebar",
"top": "Top",
"mixed": "Mixed",
"right": "Right sidebar",
"split": "Wide top",
"modeHint": {
"right": "The full menu moves to the right of the content.",
"split": "The fixed header spans the full width. The sidebar shows the active section. Turn off Fixed header to scroll it with the content.",
"side": "All menus live in the sidebar. Expand a section to see its submenus.",
"top": "All menus are available from the top bar. Submenus open in dropdowns.",
"mixed": "The top bar shows first-level menus. The sidebar appears when the current section has visible submenus."

View File

@ -39,5 +39,7 @@
"TableColumns": "Column preferences",
"TablePrinting": "Printing and custom regions",
"TableCustom": "Slots and instance methods",
"RouteManagement": "Route management"
"RouteManagement": "Route management",
"RouteManagementVisual": "Visual editor",
"RouteManagementJson": "JSON configuration"
}

View File

@ -4,6 +4,14 @@
"reset": "Restore defaults",
"resetDescription": "Restore the default layout, menu and general options.",
"cancel": "Cancel",
"config": {
"export": "Export settings",
"import": "Import settings",
"imported": "Settings imported and saved",
"importError": "Could not import settings. Choose a valid file exported by Ray Template.",
"exportError": "Could not export settings. Check your preferences and try again.",
"fileLimit": "The settings file must be 256 KiB or smaller."
},
"section": {
"layout": "Layout",
"appearance": "Appearance",
@ -28,6 +36,8 @@
"colorWeakness": "Color vision mode"
},
"transition": {
"slide-up": "Rise in",
"slide-left": "Slide in from right",
"none": "None",
"scale": "Scale in",
"fade-scale": "Scale and fade",

View File

@ -1,6 +1,6 @@
{
"eyebrow": "WORKSPACE / ROUTING",
"title": "Route management",
"title": "Route JSON configuration",
"description": "Switch route sources, preview the menu and validate page configuration as JSON.",
"active": "Active · {source}",
"fallback": "Load failed. Static routes are active.",
@ -34,5 +34,37 @@
"pagePath": "Route path",
"pageTitle": "Menu title",
"pageView": "View",
"addPage": "Add to configuration"
"addPage": "Add to configuration",
"visualTitle": "Visual route editor",
"visualDescription": "Select a menu item to edit its path, view and access rules.",
"visualDraft": "Local configuration draft",
"visualHint": "The draft starts with the active routes. Applying reloads the app and affects this browser only. Use JSON configuration for advanced fields such as aliases and view props.",
"validateDraft": "Validate",
"draftValid": "Configuration is valid",
"resetDraft": "Reload active configuration",
"resetConfirm": "Discard your draft changes and reload the active configuration?",
"addRoot": "Add top-level item",
"addChild": "Add child item",
"editNode": "Edit menu item",
"selectNode": "Select a menu item or add one.",
"moveUp": "Move up",
"moveDown": "Move down",
"deleteNode": "Delete",
"deleteConfirm": "Delete this item and its children from the draft?",
"i18nKey": "Title translation key",
"routeName": "Route name",
"redirectTarget": "Redirect target path",
"externalUrl": "External URL",
"routeIcon": "Icon name",
"roles": "Allowed roles",
"rolesHint": "Leave empty to allow all signed-in roles",
"literalTitle": "Menu title (without a translation key)",
"hidden": "Hide from menus",
"keepAlive": "Cache the page",
"kind": {
"page": "Page",
"group": "Menu group",
"redirect": "Redirect",
"external": "External link"
}
}

View File

@ -4,7 +4,11 @@
"side": "侧边导航",
"top": "顶部导航",
"mixed": "混合导航",
"right": "右侧导航",
"split": "通栏分组",
"modeHint": {
"right": "完整导航移到右侧,页面内容位于左侧。",
"split": "固定顶栏横跨全宽,侧栏显示当前分组的子菜单。关闭固定顶栏后,顶栏随内容滚动。",
"side": "各级菜单都在侧栏,展开分组即可查看子菜单。",
"top": "各级菜单都从顶栏进入,子菜单在下拉菜单中打开。",
"mixed": "顶栏显示一级菜单。有可见子菜单的分组会展开侧栏。"

View File

@ -39,5 +39,7 @@
"TableColumns": "列设置与缓存",
"TablePrinting": "打印与自定义区域",
"TableCustom": "插槽与实例操作",
"RouteManagement": "路由管理"
"RouteManagement": "路由管理",
"RouteManagementVisual": "可视化配置",
"RouteManagementJson": "JSON 配置"
}

View File

@ -4,6 +4,14 @@
"reset": "恢复默认设置",
"resetDescription": "将布局、菜单和通用选项恢复为默认值。",
"cancel": "取消",
"config": {
"export": "导出配置",
"import": "导入配置",
"imported": "配置已导入并保存",
"importError": "无法导入。请选择 Ray Template 导出的有效配置文件。",
"exportError": "无法导出当前配置,请检查设置后重试。",
"fileLimit": "配置文件不能超过 256 KiB。"
},
"section": {
"layout": "布局",
"appearance": "外观",
@ -28,6 +36,8 @@
"colorWeakness": "色弱模式"
},
"transition": {
"slide-up": "向上浮入",
"slide-left": "向左滑入",
"none": "无",
"scale": "缩放出现",
"fade-scale": "缩放淡出",

View File

@ -1,6 +1,6 @@
{
"eyebrow": "WORKSPACE / ROUTING",
"title": "路由管理",
"title": "路由 JSON 配置",
"description": "切换路由来源,预览并校验菜单和页面的 JSON 配置。",
"active": "当前生效 · {source}",
"fallback": "加载失败,已使用静态路由",
@ -34,5 +34,37 @@
"pagePath": "路由路径",
"pageTitle": "菜单标题",
"pageView": "页面组件",
"addPage": "添加到配置"
"addPage": "添加到配置",
"visualTitle": "路由可视化配置",
"visualDescription": "从菜单树选择一项,直接编辑它的路径、页面与访问规则。",
"visualDraft": "本机配置草稿",
"visualHint": "草稿从当前生效的路由开始。应用后会重新加载,仅在此浏览器生效;别名、组件参数等高级字段可在 JSON 配置中编辑。",
"validateDraft": "校验配置",
"draftValid": "校验通过",
"resetDraft": "重载生效配置",
"resetConfirm": "放弃草稿改动,重新读取当前生效的配置?",
"addRoot": "添加一级菜单",
"addChild": "添加子菜单",
"editNode": "编辑菜单项",
"selectNode": "从左侧选择一项,或添加菜单。",
"moveUp": "上移",
"moveDown": "下移",
"deleteNode": "删除",
"deleteConfirm": "从草稿中删除此项及其子菜单?",
"i18nKey": "标题翻译键",
"routeName": "路由名称",
"redirectTarget": "跳转目标路径",
"externalUrl": "外链地址",
"routeIcon": "图标名称",
"roles": "允许访问的角色",
"rolesHint": "留空允许所有已登录角色",
"literalTitle": "菜单标题(无翻译键时)",
"hidden": "从菜单隐藏",
"keepAlive": "缓存页面",
"kind": {
"page": "页面",
"group": "菜单分组",
"redirect": "重定向",
"external": "外部链接"
}
}

View File

@ -2,7 +2,10 @@
## 切换路由来源
登录后,从侧栏打开 **路由管理**(`/#/route-management`)。管理页由应用外壳注册,并使用 `admin` 角色守卫。可快速添加页面、编辑完整 JSON、从文件导入、校验和预览配置树,也可导出 JSON、标准 JSON Schema 和可用页面清单。
登录后,打开 **路由管理**。两个子页面均由应用外壳注册,使用相同的 `admin` 角色守卫。
- **可视化配置**(`/#/route-management/visual`):从当前生效的菜单树编辑页面、分组、重定向与外链,调整顺序、角色、显隐与缓存。可校验或导出草稿,也可应用并重新加载;应用仅在当前浏览器生效。已有别名、页面参数等高级字段会随草稿保留。
- **JSON 配置**(`/#/route-management/json`):管理静态、本机或后端来源,编辑或导入完整 JSON、校验和预览配置树,并导出 JSON、标准 JSON Schema 和可用页面清单。旧地址 `/#/route-management` 会跳转到这里。
| 来源 | 读取行为 | 应用方式 |
| --------- | -------------------------------------------- | ------------------------------------------ |

View File

@ -6,14 +6,26 @@ import { orderRoutes } from './utils/order-routes'
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,
},
children: [
{
path: 'visual',
name: 'RouteManagementVisual',
component: () => import('@/views/route-management/visual'),
meta: { i18nKey: 'menu.RouteManagementVisual' },
},
{
path: 'json',
name: 'RouteManagement',
component: () => import('@/views/route-management'),
meta: { i18nKey: 'menu.RouteManagementJson' },
},
],
}
export const getStaticAppRoutes = () => orderRoutes(combineRawRouteModules())

View File

@ -11,12 +11,16 @@ import { routeConfigSchema } from './schema'
import type { RouteConfig, RouteConfigRecord } from './schema'
import { findRouteView, findRouteViewId } from './views'
const reservedPaths = new Set(['/', ROUTE_MANAGEMENT_PATH])
const isReservedPath = (path: string) =>
path === '/' ||
path === ROUTE_MANAGEMENT_PATH ||
path.startsWith(`${ROUTE_MANAGEMENT_PATH}/`)
const reservedNames = new Set([
'rlogin',
'rlayout',
'rnotfound',
'routemanagement',
'routemanagementvisual',
'errorpage',
'raytemplatedoc',
])
@ -75,7 +79,7 @@ export function parseRouteConfig(text: string): RouteConfig {
const menuPath = path.toLowerCase()
if (menuPaths.has(menuPath) || reservedPaths.has(menuPath))
if (menuPaths.has(menuPath) || isReservedPath(menuPath))
fail('Duplicate or reserved menu path.')
menuPaths.add(menuPath)
@ -137,7 +141,7 @@ export function parseRouteConfig(text: string): RouteConfig {
)
fail(`Invalid path "${address}".`)
if (reservedPaths.has(key) || paths.has(key))
if (isReservedPath(key) || paths.has(key))
fail(`Duplicate or reserved path "${address}".`)
if (

View File

@ -4,3 +4,4 @@ export const NOT_FOUND_ROUTE_PATH = '/:catchAll(.*)'
export const DEFAULT_HOME_PATH = '/dashboard'
export const ROUTE_MANAGEMENT_PATH = '/route-management'
export const ROUTE_MANAGEMENT_JSON_PATH = `${ROUTE_MANAGEMENT_PATH}/json`

View File

@ -1,7 +1,11 @@
import Layout from '@/layout'
import type { RouteRecordRaw } from 'vue-router'
import { appExpandRoutes } from './app-route-modules'
import { NOT_FOUND_ROUTE_PATH } from './constant'
import {
NOT_FOUND_ROUTE_PATH,
ROUTE_MANAGEMENT_JSON_PATH,
ROUTE_MANAGEMENT_PATH,
} from './constant'
const legacyRedirects = [
{ path: '/tables', redirect: '/tables/basic' },
@ -31,6 +35,7 @@ export function getLayoutRoutes(): RouteRecordRaw[] {
({ path, redirect }) =>
!occupiedPaths.has(path) && occupiedPaths.has(redirect),
),
{ path: ROUTE_MANAGEMENT_PATH, redirect: ROUTE_MANAGEMENT_JSON_PATH },
{
path: NOT_FOUND_ROUTE_PATH,
name: 'RNotFound',

View File

@ -1,5 +1,3 @@
import type { AppRouteRecordRaw } from '@/router/types'
/**
*
* @param routes 路由模块表(route 表)
@ -11,7 +9,11 @@ import type { AppRouteRecordRaw } from '@/router/types'
* 如果为配置 order 属性, 则会自动按照前合并路由的顺序前后排序
* 如果 order 属性值相同, 则会按照路由名称进行排序
*/
export const orderRoutes = (routes: AppRouteRecordRaw[]) => {
export const orderRoutes = <
T extends { name?: string; meta?: { order?: number } },
>(
routes: T[],
) => {
return routes.toSorted((curr, next) => {
const order = (curr.meta?.order ?? 0) - (next.meta?.order ?? 0)

View File

@ -22,7 +22,7 @@ export const scrollViewToTop = (route: RouteLocationNormalized) => {
LAYOUT_CONTENT_REF.value?.scrollTo({
top: 0,
left: 0,
behavior: 'smooth',
behavior: 'instant',
})
}
}

View File

@ -149,6 +149,8 @@ export const useSettingActions = () => {
changePrimaryColor,
updateSettingState,
toggleColorWeakness,
exportPreferences,
importPreferences,
} = piniaSettingStore()
return {
@ -156,5 +158,7 @@ export const useSettingActions = () => {
changePrimaryColor,
updateSettingState,
toggleColorWeakness,
exportPreferences,
importPreferences,
}
}

View File

@ -16,6 +16,14 @@ type OmitKeys =
interface Config extends Pick<SettingState, OmitKeys> {}
export const LAYOUT_MODES = [
'side',
'top',
'mixed',
'right',
'split',
] as const satisfies readonly LayoutConfig['mode'][]
// SettingDrawer 默认配置系统配置项
const defaultSettingConfig: Readonly<Config> = {
layoutConfig: {
@ -112,10 +120,7 @@ export function normalizeLayoutConfig(value: unknown): LayoutConfig {
: fallback
return {
mode:
source.mode === 'side' || source.mode === 'top' || source.mode === 'mixed'
? source.mode
: defaults.mode,
mode: LAYOUT_MODES.find((mode) => mode === source.mode) ?? defaults.mode,
contentWidth:
source.contentWidth === 'fixed' || source.contentWidth === 'fluid'
? source.contentWidth

View File

@ -11,6 +11,7 @@ import { updateObjectValue } from '@/utils/update-object-value'
import { usePreferredDark } from '@vueuse/core'
import { cloneDeep, merge } from 'lodash-es'
import { getDefaultSettingConfig, normalizeLayoutConfig } from './constant'
import { createPreferenceFile, parsePreferenceFile } from './preference-file'
export const piniaSettingStore = defineStore(
'setting',
@ -128,6 +129,20 @@ export const piniaSettingStore = defineStore(
updateSettingState('colorWeakness', bool)
}
const exportPreferences = () => createPreferenceFile(settingState)
const importPreferences = (text: string) => {
const { primaryColor, ...preferences } = parsePreferenceFile(text)
Object.assign(settingState, preferences, {
_appTheme:
preferences.appTheme === 'auto'
? preferredDark.value
: preferences.appTheme === 'dark',
})
changePrimaryColor(primaryColor)
}
watch(
() => (settingState.appTheme === 'auto' ? preferredDark.value : void 0),
(systemDark) => {
@ -176,6 +191,8 @@ export const piniaSettingStore = defineStore(
changePrimaryColor,
updateSettingState,
toggleColorWeakness,
exportPreferences,
importPreferences,
}
},
{

View File

@ -0,0 +1,103 @@
import { APP_THEME, CONTENT_TRANSITION_OPTIONS } from '@/app-config'
import { pick } from 'lodash-es'
import * as v from 'valibot'
import { LAYOUT_MODES } from './constant'
import type { SettingState } from './types'
export const PREFERENCE_FILE_LIMIT = 256 * 1024
const flag = v.boolean()
const finite = v.pipe(v.number(), v.finite())
const size = v.pipe(finite, v.minValue(0))
const watermark = v.pipe(
v.strictObject({
content: v.string(),
cross: flag,
fontSize: finite,
lineHeight: finite,
width: finite,
height: finite,
xOffset: finite,
yOffset: finite,
xGap: finite,
yGap: finite,
rotate: finite,
}),
v.check(({ width, height, xGap, yGap }) =>
[width + xGap, height + yGap].every((edge) => edge > 0 && edge <= 4096),
),
)
const preferences = v.strictObject({
layoutConfig: v.strictObject({
mode: v.picklist(LAYOUT_MODES),
contentWidth: v.picklist(['fluid', 'fixed']),
contentMaxWidth: v.pipe(finite, v.minValue(640), v.maxValue(2560)),
contentPadding: v.pipe(finite, v.minValue(0), v.maxValue(48)),
fixedHeader: flag,
fixedFooter: flag,
}),
appTheme: v.picklist(['light', 'dark', 'auto']),
primaryColor: v.pipe(
v.string(),
v.maxLength(64),
v.regex(/^(?:#[\da-f]+|(?:rgba?|hsla?)\([\d.,%+\s/-]+\))$/i),
v.check((value) => {
const { style } = document.createElement('span')
style.color = value
return style.color !== ''
}),
),
contentTransition: v.picklist(
CONTENT_TRANSITION_OPTIONS.map(({ value }) => value),
),
drawerPlacement: v.picklist(['left', 'right']),
breadcrumbSwitch: flag,
menuTagSwitch: flag,
copyrightSwitch: flag,
colorWeakness: flag,
menuConfig: v.strictObject({
menuWidth: size,
collapsedWidth: size,
collapsedMode: v.picklist(['width', 'transform']),
collapsedIndent: size,
iconSize: size,
collapsedIconSize: size,
accordion: flag,
menuSiderBarLogo: flag,
inverted: flag,
nativeScrollbar: flag,
}),
watermarkSwitch: flag,
watermarkConfig: watermark,
dynamicDocumentTitle: flag,
keepAliveConfig: v.strictObject({
setupKeepAlive: flag,
maxKeepAliveLength: v.pipe(size, v.integer()),
keepAliveExclude: v.array(v.string()),
}),
})
const preferenceFile = v.strictObject({
format: v.literal('ray-template-preferences'),
version: v.literal(1),
preferences,
})
export function createPreferenceFile(state: SettingState) {
return v.parse(preferenceFile, {
format: 'ray-template-preferences',
version: 1,
preferences: {
...pick(state, Object.keys(preferences.entries)),
primaryColor:
state.primaryColorOverride.common?.primaryColor ??
APP_THEME.appPrimaryColor.primaryColor,
},
})
}
export function parsePreferenceFile(text: string) {
return v.parse(preferenceFile, JSON.parse(text)).preferences
}

View File

@ -26,7 +26,7 @@ export interface AppRootRoute {
}
export interface LayoutConfig {
mode: 'side' | 'top' | 'mixed'
mode: 'side' | 'top' | 'mixed' | 'right' | 'split'
contentWidth: 'fluid' | 'fixed'
contentMaxWidth: number
contentPadding: number

View File

@ -1,110 +1,73 @@
// 模糊匹配内容区域切换过渡动画包含: transform-leave-active 的 class
[class*='transform-leave-active'] {
position: absolute;
}
.r-route-transition {
.scale-transform-enter-active,
.fade-scale-transform-enter-active,
.fade-slide-transform-enter-active,
.fade-bottom-transform-enter-active,
.slide-up-transform-enter-active,
.slide-left-transform-enter-active {
transition:
opacity 180ms ease-out,
transform 180ms var(--r-bezier);
}
/* fade-slide-transform */
.fade-slide-transform-leave-active,
.fade-slide-transform-enter-active {
transition:
transform 0.48s var(--r-bezier),
opacity 0.48s var(--r-bezier);
}
.opacity-transform-enter-active {
transition: opacity 160ms ease-out;
}
.fade-slide-transform-enter-from {
opacity: 0;
transform: translateX(-30px);
}
.opacity-transform-leave-active,
.scale-transform-leave-active,
.fade-scale-transform-leave-active,
.fade-slide-transform-leave-active,
.fade-bottom-transform-leave-active {
transition: opacity 70ms ease-in;
pointer-events: none;
}
.fade-slide-transform-leave-to {
opacity: 0;
transform: translateX(30px);
}
.opacity-transform-enter-from,
.scale-transform-enter-from,
.fade-scale-transform-enter-from,
.fade-slide-transform-enter-from,
.fade-bottom-transform-enter-from,
.slide-up-transform-enter-from,
.slide-left-transform-enter-from,
.opacity-transform-leave-to,
.scale-transform-leave-to,
.fade-scale-transform-leave-to,
.fade-slide-transform-leave-to,
.fade-bottom-transform-leave-to {
opacity: 0;
}
/* scale-transform */
.scale-transform-enter-active {
transition:
transform 0.35s cubic-bezier(0.33, 1, 0.68, 1),
opacity 0.25s cubic-bezier(0.33, 1, 0.68, 1);
transition-delay: 0.25s;
}
.scale-transform-enter-from {
transform: scale(0.985);
}
.scale-transform-leave-active {
transition:
transform 0.35s cubic-bezier(0.32, 0, 0.67, 0),
opacity 0.25s ease-out;
}
.fade-scale-transform-enter-from {
transform: scale(1.015);
}
.scale-transform-enter-from {
opacity: 0;
transform: scale(0.95);
}
.fade-slide-transform-enter-from {
transform: translateX(-12px);
}
.scale-transform-leave-to {
opacity: 0;
transform: scale(1.03);
}
.fade-bottom-transform-enter-from {
transform: translateY(-10px);
}
/* opacity-transform */
.opacity-transform-leave-active,
.opacity-transform-enter-active {
transition: opacity 0.55s var(--r-bezier);
}
.slide-up-transform-enter-from {
transform: translateY(10px);
}
.opacity-transform-enter-from {
opacity: 0;
}
.slide-left-transform-enter-from {
transform: translateX(12px);
}
.opacity-transform-leave-to {
opacity: 0;
}
/* fade-bottom-transform */
.fade-bottom-transform-enter-active {
transition:
transform 0.35s cubic-bezier(0.33, 1, 0.68, 1),
opacity 0.25s cubic-bezier(0.33, 1, 0.68, 1);
transition-delay: 0.25s;
}
.fade-bottom-transform-leave-active {
transition:
transform 0.35s cubic-bezier(0.32, 0, 0.67, 0),
opacity 0.25s ease-out;
}
.fade-bottom-transform-enter-from {
opacity: 0;
transform: translateY(-15px);
}
.fade-bottom-transform-leave-to {
opacity: 0;
transform: translateY(15px);
}
/* fade-scale-transform */
.fade-scale-transform-enter-active {
transition:
transform 0.35s cubic-bezier(0.33, 1, 0.68, 1),
opacity 0.25s cubic-bezier(0.33, 1, 0.68, 1);
transition-delay: 0.25s;
}
.fade-scale-transform-leave-active {
transition:
transform 0.25s cubic-bezier(0.32, 0, 0.67, 0),
opacity 0.25s ease-out;
}
.fade-scale-transform-enter-from {
opacity: 0;
transform: scale(1.1);
}
.fade-scale-transform-leave-to {
opacity: 0;
transform: scale(0.85);
@media (prefers-reduced-motion: reduce) {
[class*='-transform-enter-active'],
[class*='-transform-leave-active'] {
transition: none;
}
}
}
@keyframes elementRotate {

View File

@ -0,0 +1,13 @@
export 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)
}

View File

@ -91,3 +91,33 @@
grid-template-columns: minmax(0, 2fr) minmax(240px, 1fr);
}
}
.route-management__tree {
max-block-size: 540px;
margin-block-start: 16px;
overflow: auto;
.n-tree-node-content__text {
overflow-wrap: anywhere;
}
}
.route-management__node-actions + .route-management__hint {
overflow-wrap: anywhere;
}
.route-management__fields {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 210px), 1fr));
gap: 0 16px;
.n-form-item {
min-inline-size: 0;
}
}
@container (min-width: 850px) {
.route-management__workspace--visual {
grid-template-columns: minmax(240px, 1fr) minmax(0, 1.6fr);
}
}

View File

@ -25,20 +25,7 @@ import {
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)
}
import { downloadJson } from './download-json'
export default defineComponent({
name: 'RouteManagement',

View File

@ -0,0 +1,433 @@
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 { RouteConfigRecord } from '@/router/config/schema'
import { routeSourceStatus, saveRouteSource } from '@/router/config/source'
import { findRouteView, routeViewCatalog } from '@/router/config/views'
import { joinRoutePath } from '@/router/utils/join-route-path'
import { orderRoutes } from '@/router/utils/order-routes'
import {
NAlert,
NButton,
NCard,
NDropdown,
NFlex,
NFormItem,
NInput,
NPopconfirm,
NSelect,
NSwitch,
NTag,
NTree,
} from 'naive-ui'
import type { TreeOption } from 'naive-ui'
import { downloadJson } from './download-json'
type Kind = 'page' | 'group' | 'redirect' | 'external'
const kinds: Kind[] = ['page', 'group', 'redirect', 'external']
const viewOptions = routeViewCatalog.map(({ id }) => ({ label: id, value: id }))
const getKind = (record: RouteConfigRecord): Kind =>
record.children
? 'group'
: record.component
? 'page'
: record.redirect !== void 0
? 'redirect'
: 'external'
export default defineComponent({
name: 'RouteManagementVisual',
setup() {
const { t } = useI18n('routeManagement')
const text = (key: string) => t<string>(key)
const { t: translate } = useI18n()
const records = ref<RouteConfigRecord[]>([])
const selected = ref<number>()
const expanded = ref<(string | number)[]>([])
const error = ref('')
const valid = ref(false)
const ids = new WeakMap<RouteConfigRecord, number>()
let sequence = 0
const id = useId()
const keyFor = (record: RouteConfigRecord) => {
const key = ids.get(record) ?? ++sequence
ids.set(record, key)
return key
}
const tree = computed(() => {
const entries = new Map<
number,
{
record: RouteConfigRecord
siblings: RouteConfigRecord[]
index: number
path: string
}
>()
const visit = (list: RouteConfigRecord[], parent = ''): TreeOption[] =>
list.map((record, index) => {
const key = keyFor(record)
const path = joinRoutePath(parent, record.path)
const { i18nKey, noLocalTitle } = record.meta
const label = i18nKey ? translate(i18nKey) : noLocalTitle
entries.set(key, { record, siblings: list, index, path })
return {
key,
label: `${label || text(`kind.${getKind(record)}`)} · ${path}`,
children: record.children && visit(record.children, path),
}
})
const options = visit(records.value)
return { entries, options }
})
const current = computed(() => tree.value.entries.get(selected.value ?? 0))
const clearResult = () => {
error.value = ''
valid.value = false
}
const report = (reason: unknown) => {
error.value = reason instanceof Error ? reason.message : String(reason)
valid.value = false
}
const load = () => {
try {
const config =
routeSourceStatus.config ?? exportRouteConfig(getStaticAppRoutes())
records.value = orderRoutes(structuredClone(config.routes))
selected.value = tree.value.options[0]?.key as number | undefined
expanded.value = []
clearResult()
} catch (reason) {
report(reason)
}
}
watch(records, clearResult, { deep: true })
load()
const validate = () => {
try {
const config = parseRouteConfig(
JSON.stringify({ version: 1, routes: records.value }),
)
valid.value = true
error.value = ''
return config
} catch (reason) {
report(reason)
}
}
const apply = () => {
const config = validate()
if (!config) return
try {
saveRouteSource('local', config)
} catch (reason) {
report(reason)
}
}
const add = (kind: Kind, parent?: RouteConfigRecord) => {
const list = parent?.children ?? records.value
const record: RouteConfigRecord = {
path: '',
meta: {},
}
if (kind === 'page') record.component = 'dashboard'
if (kind === 'group') {
record.component = 'layout'
record.children = []
}
if (kind === 'redirect') record.redirect = ''
if (kind === 'external') record.meta.windowOpen = ''
if (!parent && list.length)
record.meta.order = (list.at(-1)?.meta.order ?? 0) + 1
list.push(record)
selected.value = keyFor(list[list.length - 1])
if (parent && !expanded.value.includes(keyFor(parent)))
expanded.value.push(keyFor(parent))
}
const move = (offset: number) => {
if (!current.value) return
const { record, siblings, index } = current.value
const next = index + offset
if (next < 0 || next >= siblings.length) return
siblings.splice(index, 1)
siblings.splice(next, 0, record)
// 顶级菜单运行时按 order 排序,移动后让顺序与树一致。
if (siblings === records.value)
siblings.forEach((item, index) => (item.meta.order = index))
}
const remove = () => {
if (!current.value) return
const { siblings, index } = current.value
siblings.splice(index, 1)
const next = siblings[Math.min(index, siblings.length - 1)]
selected.value = next ? keyFor(next) : void 0
}
const input = (
field: string,
value: string,
update: (value: string) => void,
) => (
<NFormItem label={text(field)} labelProps={{ for: `${id}-${field}` }}>
<NInput
value={value}
inputProps={{ id: `${id}-${field}` }}
onUpdateValue={update}
/>
</NFormItem>
)
const addMenu = (label: string, parent?: RouteConfigRecord) => (
<NDropdown
trigger="click"
options={kinds.map((key) => ({ key, label: text(`kind.${key}`) }))}
onSelect={(key: Kind) => add(key, parent)}
>
<NButton secondary type="primary">
{text(label)}
</NButton>
</NDropdown>
)
const edit = (record: RouteConfigRecord) => {
const kind = getKind(record)
const meta = record.meta
const roles = meta.role ?? []
return (
<div class="route-management__fields">
{input('pagePath', record.path, (value) => (record.path = value))}
{input(
'literalTitle',
String(meta.noLocalTitle ?? ''),
(value) => (meta.noLocalTitle = value || void 0),
)}
{input(
'i18nKey',
meta.i18nKey ?? '',
(value) => (meta.i18nKey = value || void 0),
)}
{input(
'routeName',
record.name ?? '',
(value) => (record.name = value || void 0),
)}
{kind === 'page' && (
<NFormItem
label={text('pageView')}
labelProps={{ id: `${id}-view` }}
>
<NSelect
value={record.component}
options={viewOptions}
aria-labelledby={`${id}-view`}
filterable
onUpdateValue={(value: string) => {
record.component = value
if (meta.keepAlive) record.name = findRouteView(value)?.name
}}
/>
</NFormItem>
)}
{kind === 'redirect' &&
input(
'redirectTarget',
record.redirect ?? '',
(value) => (record.redirect = value),
)}
{kind === 'external' &&
input(
'externalUrl',
meta.windowOpen ?? '',
(value) => (meta.windowOpen = value),
)}
{input(
'routeIcon',
meta.icon ?? '',
(value) => (meta.icon = value || void 0),
)}
<NFormItem label={text('roles')} labelProps={{ id: `${id}-roles` }}>
<NSelect
multiple
filterable
tag
value={roles}
options={[...new Set(['admin', ...roles])].map((value) => ({
label: String(value),
value,
}))}
aria-labelledby={`${id}-roles`}
placeholder={text('rolesHint')}
onUpdateValue={(value: (string | number)[]) =>
(meta.role = value)
}
/>
</NFormItem>
<NFormItem label={text('hidden')}>
<NSwitch
value={!!meta.hidden}
aria-label={text('hidden')}
onUpdateValue={(value) => (meta.hidden = value)}
/>
</NFormItem>
{kind === 'page' && (
<NFormItem label={text('keepAlive')}>
<NSwitch
value={!!meta.keepAlive}
aria-label={text('keepAlive')}
onUpdateValue={(value) => {
meta.keepAlive = value
if (value && record.component)
record.name = findRouteView(record.component)?.name
}}
/>
</NFormItem>
)}
</div>
)
}
return () => (
<section class="route-management">
<AppPageHeader
eyebrow={text('eyebrow')}
title={text('visualTitle')}
description={text('visualDescription')}
>
<NTag type="info" bordered={false}>
{t('active', { source: text(routeSourceStatus.active) })}
</NTag>
</AppPageHeader>
{routeSourceStatus.error && (
<NAlert type="warning" title={text('fallback')}>
{routeSourceStatus.error}
</NAlert>
)}
<NCard title={text('visualDraft')}>
<p class="route-management__hint">{text('visualHint')}</p>
<NFlex align="center">
<NButton type="primary" onClick={apply}>
{text('apply')}
</NButton>
<NButton secondary onClick={validate}>
{text('validateDraft')}
</NButton>
<NButton
onClick={() => {
const config = validate()
if (config) downloadJson('routes.json', config)
}}
>
{text('export')}
</NButton>
<NPopconfirm onPositiveClick={load}>
{{
trigger: () => <NButton>{text('resetDraft')}</NButton>,
default: () => text('resetConfirm'),
}}
</NPopconfirm>
<span role="status">{valid.value ? text('draftValid') : ''}</span>
</NFlex>
{error.value && (
<NAlert
type="error"
title={text('invalid')}
class="route-management__tools"
>
<pre class="route-management__error">{error.value}</pre>
</NAlert>
)}
</NCard>
<div class="route-management__workspace route-management__workspace--visual">
<NCard title={text('preview')}>
{addMenu('addRoot')}
<NTree
class="route-management__tree"
blockLine
data={tree.value.options}
selectedKeys={selected.value === void 0 ? [] : [selected.value]}
v-model:expandedKeys={expanded.value}
onUpdateSelectedKeys={(keys) =>
(selected.value = keys[0] as number | undefined)
}
/>
</NCard>
<NCard title={text('editNode')}>
{current.value ? (
<>
<NFlex align="center" class="route-management__node-actions">
<NTag bordered={false}>
{text(`kind.${getKind(current.value.record)}`)}
</NTag>
{current.value.record.children &&
addMenu('addChild', current.value.record)}
<NButton
size="small"
disabled={current.value.index === 0}
onClick={() => move(-1)}
>
{text('moveUp')}
</NButton>
<NButton
size="small"
disabled={
current.value.index === current.value.siblings.length - 1
}
onClick={() => move(1)}
>
{text('moveDown')}
</NButton>
<NPopconfirm onPositiveClick={remove}>
{{
trigger: () => (
<NButton size="small" type="error" quaternary>
{text('deleteNode')}
</NButton>
),
default: () => text('deleteConfirm'),
}}
</NPopconfirm>
</NFlex>
<p class="route-management__hint">
<code>{current.value.path}</code>
</p>
{edit(current.value.record)}
</>
) : (
<p>{text('selectNode')}</p>
)}
</NCard>
</div>
</section>
)
},
})