feat(docs): add interactive API examples

This commit is contained in:
XiaoDaiGua-Ray 2026-11-04 15:02:26 +08:00
parent 8e8fe5ee7a
commit 40320207ac
62 changed files with 1699 additions and 210 deletions

View File

@ -94,6 +94,7 @@
"stylelint",
"unocss",
"VITE",
"vitepress",
"vueuse",
"WUJIE",
"zlevel"

View File

@ -0,0 +1,33 @@
import {
getStorage,
removeStorage,
setStorage,
} from '../../apps/admin/src/utils/cache'
import { useMemoryCache } from '../../apps/admin/src/utils/cache-backend'
it('keeps writes and bulk clears in the documentation example out of the real app storage', () => {
const key = 'ray:example-isolation-test'
localStorage.setItem(key, JSON.stringify('admin local'))
sessionStorage.setItem(key, JSON.stringify('admin session'))
try {
useMemoryCache()
expect(getStorage(key, 'localStorage')).toBeNull()
expect(getStorage(key, 'sessionStorage')).toBeNull()
setStorage(key, 'example local', 'localStorage')
setStorage(key, 'example session', 'sessionStorage')
expect(getStorage(key, 'localStorage')).toBe('example local')
expect(getStorage(key, 'sessionStorage')).toBe('example session')
removeStorage('__all__', 'all')
expect(getStorage(key, 'localStorage')).toBeNull()
expect(getStorage(key, 'sessionStorage')).toBeNull()
expect(localStorage.getItem(key)).toBe(JSON.stringify('admin local'))
expect(sessionStorage.getItem(key)).toBe(JSON.stringify('admin session'))
} finally {
localStorage.removeItem(key)
sessionStorage.removeItem(key)
}
})

13
apps/admin/example.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="noindex" />
<title>Ray Template 示例</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/documentation-example.tsx"></script>
</body>
</html>

View File

@ -1,23 +1,8 @@
import type { AppTheme } from '@/types/modules/vite-custom-config'
/** 明暗主题共用的菜单尺寸与前景色配置。 */
const menuThemeOverrides = {
itemHeight: '40px',
borderRadius: '8px',
itemTextColorActive: 'var(--r-selected-text)',
itemTextColorActiveHover: 'var(--r-selected-text)',
itemTextColorChildActive: 'var(--r-selected-text)',
itemTextColorChildActiveHover: 'var(--r-selected-text)',
itemTextColorActiveHorizontal: 'var(--r-selected-text)',
itemTextColorChildActiveHorizontal: 'var(--r-selected-text)',
itemTextColorHoverHorizontal: 'var(--r-selected-text)',
itemIconColorActive: 'var(--r-selected-text)',
itemIconColorActiveHover: 'var(--r-selected-text)',
itemIconColorChildActive: 'var(--r-selected-text)',
itemIconColorChildActiveHover: 'var(--r-selected-text)',
itemIconColorActiveHorizontal: 'var(--r-selected-text)',
itemIconColorChildActiveHorizontal: 'var(--r-selected-text)',
}
import {
rayPrimaryColor,
rayThemeOverrides,
} from '@ray-template/ui/theme-presets'
export const APP_THEME: AppTheme = {
/**
@ -35,12 +20,7 @@ export const APP_THEME: AppTheme = {
'#18a058',
],
// 系统主题色
appPrimaryColor: {
// 主题色
primaryColor: '#3b63d9',
// 主题辅助色(用于整体 hover、active 等之类颜色)
primaryFadeColor: 'rgba(59, 99, 217, 0.85)',
},
appPrimaryColor: rayPrimaryColor,
/**
*
* @description
@ -66,70 +46,7 @@ export const APP_THEME: AppTheme = {
* }
* ```
*/
appNaiveUIThemeOverrides: {
dark: {
common: {
borderRadius: '8px',
fontWeightStrong: '600',
lineHeight: '1.6',
heightMedium: '36px',
heightSmall: '30px',
baseColor: '#172131',
bodyColor: '#101722',
cardColor: '#172131',
modalColor: '#192638',
popoverColor: '#192638',
actionColor: '#1c293b',
textColor1: '#e9eef7',
textColor2: '#b3c0d3',
textColor3: '#a0b0c6',
placeholderColor: '#a0b0c6',
borderColor: '#687b96',
dividerColor: '#2c394d',
hoverColor: 'rgba(179, 192, 211, 0.08)',
},
Card: {
borderRadius: '12px',
titleFontSizeMedium: '16px',
paddingMedium: '20px 24px',
},
Menu: menuThemeOverrides,
Button: { fontWeight: '500' },
Tag: { borderRadius: '5px', textColorPrimary: 'var(--r-primary-text)' },
Layout: { siderColor: '#172131', headerColor: '#172131' },
},
light: {
common: {
borderRadius: '8px',
fontWeightStrong: '600',
lineHeight: '1.6',
heightMedium: '36px',
heightSmall: '30px',
baseColor: '#ffffff',
bodyColor: '#f5f7fb',
cardColor: '#ffffff',
modalColor: '#ffffff',
popoverColor: '#ffffff',
actionColor: '#f7f9fc',
textColor1: '#1d2a3e',
textColor2: '#52647c',
textColor3: '#617187',
placeholderColor: '#617187',
borderColor: '#8492a8',
dividerColor: '#e4e9f1',
hoverColor: 'rgba(82, 100, 124, 0.06)',
},
Card: {
borderRadius: '12px',
titleFontSizeMedium: '16px',
paddingMedium: '20px 24px',
},
Menu: menuThemeOverrides,
Button: { fontWeight: '500' },
Tag: { borderRadius: '5px', textColorPrimary: 'var(--r-primary-text)' },
Layout: { siderColor: '#ffffff', headerColor: '#ffffff' },
},
},
appNaiveUIThemeOverrides: rayThemeOverrides,
/**
*
* @description

View File

@ -0,0 +1,140 @@
import './styles/entry'
import AppNaiveGlobalProvider from '@/app-components/provider/AppNaiveGlobalProvider'
import AppStyleProvider from '@/app-components/provider/AppStyleProvider'
import AppWatermarkProvider from '@/app-components/provider/AppWatermarkProvider'
import { APP_THEME } from '@/app-config'
import { setupDayjs } from '@/dayjs'
import { setupDirectives } from '@/directives'
import { useI18n, useTheme } from '@/hooks'
import Layout from '@/layout'
import { setupI18n } from '@/locales'
import { router } from '@/router'
import {
getStaticAppRoutes,
setAppRouteModules,
} from '@/router/app-route-modules'
import { expandRoutes } from '@/router/utils/expand-routes'
import { useSettingActions, useSettingGetters } from '@/store'
import { useMemoryCache } from '@/utils/cache-backend'
import { exampleFocusKey } from '@/views/demo/hooks/example-focus'
import type { IconPackage } from '@ray-template/icons'
import { iconSprites } from '@ray-template/icons/manifest'
import { provideUiServices } from '@ray-template/ui/services'
import { RouterView } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
const examplePaths = new Set([
'/dashboard',
'/form',
'/modal-demo',
'/echart',
'/flow',
'/segment',
'/iframe',
'/draggable-card',
'/svg-icons',
'/directive',
'/template-hooks',
'/web-hooks',
'/multi',
'/precision',
'/cache-demo',
'/axios',
'/qrcode',
])
const params = new URLSearchParams(location.search)
const withLayout = params.get('layout') === '1'
const examples = [
...getStaticAppRoutes().filter(({ path }) => examplePaths.has(path)),
{
path: '/docs-core-utils',
name: 'DocsCoreUtils',
component: () => import('@/views/demo/docs-core-utils'),
meta: { i18nKey: 'menu.DocsCoreUtils', order: 8 },
},
{
path: '/docs-browser-utils',
name: 'DocsBrowserUtils',
component: () => import('@/views/demo/docs-browser-utils'),
meta: { i18nKey: 'menu.DocsBrowserUtils', order: 9 },
},
{
path: '/docs-storage-utils',
name: 'DocsStorageUtils',
component: () => import('@/views/demo/docs-storage-utils'),
meta: { i18nKey: 'menu.DocsStorageUtils', order: 10 },
},
]
const DocumentationExample = defineComponent({
name: 'DocumentationExample',
setup() {
const { t } = useI18n()
const { getAppTheme, getLocaleLanguage } = useSettingGetters()
provideUiServices({
dark: () => getAppTheme.value,
locale: () => getLocaleLanguage.value,
chartTheme: APP_THEME.echartTheme,
translate: t,
iconUrl: (name, prefix) =>
`${iconSprites[name.split('/')[0] as IconPackage]}#${prefix}-${name}`,
reportError: (message) => window.$message?.error(message),
})
return () => (
<AppNaiveGlobalProvider>
<AppStyleProvider />
<AppWatermarkProvider />
<RouterView />
</AppNaiveGlobalProvider>
)
},
})
async function mountExample() {
useMemoryCache()
const app = createApp(DocumentationExample)
app.use(createPinia())
await setupI18n(app)
setupDayjs()
setupDirectives(app)
const { updateLocale } = app.runWithContext(useSettingActions)
const { darkTheme, lightTheme } = app.runWithContext(useTheme)
updateLocale(params.get('lang') === 'en' ? 'en-US' : 'zh-CN')
if (params.get('theme') === 'dark') darkTheme()
else lightTheme()
router.removeRoute('RLogin')
router.removeRoute('RLayout')
setAppRouteModules(examples)
const routes = expandRoutes(examples) as unknown as RouteRecordRaw[]
if (withLayout) {
router.addRoute({ path: '/', component: Layout, children: routes })
} else {
for (const route of routes) router.addRoute(route)
}
router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/dashboard' })
app.use(router)
await router.isReady()
const focus = params.get('focus')
if (focus) {
app.provide(exampleFocusKey, {
path: router.currentRoute.value.path,
names: new Set(focus.split(',')),
})
}
app.mount('#app')
}
void mountExample()

View File

@ -0,0 +1,76 @@
{
"core": {
"complete": "Complete",
"initial": "New",
"pending": "Pending",
"failed": "Example operation failed",
"succeeded": "Example operation succeeded",
"title": "Core utility playground",
"intro": "Try different inputs and compare type checks, route matching, and object updates.",
"inputType": "Input type",
"text": "Text",
"thenable": "Object with a then method",
"asyncFn": "Async function",
"checkResult": "Type checks",
"errorCallbacks": "uuid · Error callbacks",
"idLength": "ID length",
"radix": "Alphabet size",
"generate": "Generate ID",
"identifier": "Identifier",
"simulateFailure": "Simulate failure",
"runSync": "Run synchronously",
"runAsync": "Run asynchronously",
"execution": "Execution result",
"pathAndObject": "equalRouterPath · Object updates",
"pathOne": "First path",
"pathTwo": "Second path",
"orderStatus": "Order status",
"merge": "Shallow merge status",
"shallowCopy": "Shallow copy result",
"dateAndEnvironment": "getDateByNaiveDatePicker · Environment",
"dateRange": "Date range",
"dateResult": "Selected or cleared value",
"environment": "Environment"
},
"browser": {
"title": "Browser utility playground",
"intro": "Try the utilities on a sample element and file.",
"dom": "DOM styles, classes, and queries",
"color": "Color",
"width": "Width",
"apply": "Apply",
"remove": "Remove",
"target": "Sample element",
"domResult": "Class, selector matches, inline styles, and prefixes",
"sidebarTop": "Scroll sidebar to the top",
"locateMenu": "Reveal the selected menu item",
"vue": "Vue callbacks, rendering, and scopes",
"renderZero": "Render zero",
"fallback": "Fallback",
"callBoth": "Run both callbacks",
"start": "Start watching",
"increment": "Increment",
"stop": "Stop and clean up",
"vueResult": "Current value, observed value, cleanup status, and callback order",
"files": "Files and printing",
"convert": "Convert the sample PNG",
"downloadPng": "Download PNG",
"downloadBlob": "Download a text Blob",
"print": "Print the sample element",
"fileResult": "Conversion or print result",
"matchingDataUrl": "Both conversions produce the same Data URL"
},
"storage": {
"initial": "Pending",
"title": "Storage keys and legacy data",
"intro": "Compare a storage namespace and a legacy AES JSON round trip.",
"prefix": "Storage key prefix",
"key": "Storage key",
"resultKey": "Resolved storage key",
"plainText": "Example plaintext",
"encrypt": "Encrypt example",
"decrypt": "Restore JSON",
"ciphertext": "Ciphertext",
"restored": "Restored"
}
}

View File

@ -9,6 +9,9 @@
"Doc": "Doc",
"DocLocal": "Doc (China)",
"DocLocalInside": "Documentation (embedded)",
"DocsCoreUtils": "Core utilities",
"DocsBrowserUtils": "Browser utilities",
"DocsStorageUtils": "Storage keys and legacy encryption",
"DraggableCard": "Draggable Card",
"Echart": "Chart",
"Error": "Error Page",

View File

@ -0,0 +1,76 @@
{
"core": {
"complete": "完成",
"initial": "新建",
"pending": "待处理",
"failed": "示例操作失败",
"succeeded": "示例操作完成",
"title": "基础工具实验",
"intro": "选择不同输入,比较类型判断、路径匹配和对象更新的结果。",
"inputType": "输入类型",
"text": "文本",
"thenable": "有 then 方法的对象",
"asyncFn": "async 函数",
"checkResult": "判定结果",
"errorCallbacks": "uuid · 错误回调",
"idLength": "标识长度",
"radix": "字符基数",
"generate": "生成标识",
"identifier": "标识",
"simulateFailure": "模拟失败",
"runSync": "同步执行",
"runAsync": "异步执行",
"execution": "执行结果",
"pathAndObject": "equalRouterPath · 对象更新",
"pathOne": "第一个路径",
"pathTwo": "第二个路径",
"orderStatus": "订单状态",
"merge": "浅合并状态",
"shallowCopy": "浅拷贝输出",
"dateAndEnvironment": "getDateByNaiveDatePicker · 当前环境",
"dateRange": "日期范围",
"dateResult": "清空和选中时的值",
"environment": "当前环境"
},
"browser": {
"title": "浏览器工具实验",
"intro": "操作独立的预览元素和示例文件,查看实际结果。",
"dom": "DOM 样式、类名与查询",
"color": "颜色",
"width": "宽度",
"apply": "应用",
"remove": "移除",
"target": "预览元素",
"domResult": "类名、查询、行内样式与前缀",
"sidebarTop": "侧栏回到顶部",
"locateMenu": "定位选中的菜单",
"vue": "Vue 回调、渲染与作用域",
"renderZero": "渲染数字零",
"fallback": "回退值",
"callBoth": "调用两个回调",
"start": "开始监听",
"increment": "计数加一",
"stop": "停止并清理",
"vueResult": "当前值、监听值、清理状态和回调顺序",
"files": "文件与打印",
"convert": "转换示例 PNG",
"downloadPng": "下载 PNG",
"downloadBlob": "下载文本 Blob",
"print": "打印预览元素",
"fileResult": "转换或打印结果",
"matchingDataUrl": "两种转换的 Data URL 一致"
},
"storage": {
"initial": "待处理",
"title": "缓存键与历史格式",
"intro": "比较缓存命名空间和旧版 AES JSON 的往返结果。",
"prefix": "缓存键前缀",
"key": "缓存键",
"resultKey": "实际缓存键",
"plainText": "示例明文",
"encrypt": "生成示例密文",
"decrypt": "还原 JSON",
"ciphertext": "密文",
"restored": "还原"
}
}

View File

@ -9,6 +9,9 @@
"Doc": "文档",
"DocLocal": "文档 (加速地址)",
"DocLocalInside": "文档(内嵌)",
"DocsCoreUtils": "基础工具",
"DocsBrowserUtils": "浏览器工具",
"DocsStorageUtils": "缓存键与兼容加密",
"DraggableCard": "拖拽卡片",
"Echart": "可视化",
"Error": "错误页",

View File

@ -1,9 +1,5 @@
import App from './App'
import '@/styles/base.scss' // 初始化一些基础样式
import './app-components/provider/provider.scss' // 初始化 provider 包注入组件样式
import 'vue3-next-qrcode/es/style.css' // vue3-next-qrcode 样式
import 'virtual:uno.css'
import './styles/entry'
import type { App as AppType } from 'vue'
import { setupRayTemplateCore } from './__ray-template'
import { installAutocompleteDefaults } from './app-components/provider/AppAutocompleteDefaults'

View File

@ -1,4 +1,5 @@
import { APP_CATCH_KEY } from '@/app-config'
import { getStorageInstance } from '@/utils/cache-backend'
import { useStorage } from '@vueuse/core'
export const piniaLockScreenStore = defineStore('lock-screen', () => {
@ -6,7 +7,7 @@ export const piniaLockScreenStore = defineStore('lock-screen', () => {
const locked = useStorage(
APP_CATCH_KEY.isAppLockScreen,
false,
window.localStorage,
getStorageInstance('localStorage'),
{ mergeDefaults: true },
)
const setLocked = (value: boolean) => {

View File

@ -0,0 +1,4 @@
import './base.scss'
import '../app-components/provider/provider.scss'
import 'vue3-next-qrcode/es/style.css'
import 'virtual:uno.css'

View File

@ -0,0 +1,35 @@
const memoryStorage = (): Storage => {
const entries = new Map<string, string>()
return {
get length() {
return entries.size
},
key: (index) => Array.from(entries.keys())[index] ?? null,
getItem: (key) => entries.get(key) ?? null,
setItem: (key, value) => {
entries.set(key, value)
},
removeItem: (key) => {
entries.delete(key)
},
clear: () => entries.clear(),
}
}
let exampleStorage:
{ localStorage: Storage; sessionStorage: Storage } | undefined
export function useMemoryCache() {
exampleStorage = {
localStorage: memoryStorage(),
sessionStorage: memoryStorage(),
}
}
export const getStorageInstance = (
type: 'localStorage' | 'sessionStorage' = 'sessionStorage',
): Storage =>
type === 'localStorage'
? (exampleStorage?.localStorage ?? window.localStorage)
: (exampleStorage?.sessionStorage ?? window.sessionStorage)

View File

@ -1,8 +1,6 @@
import type { RemoveStorageFC, StorageLike, StorageOptions } from '@/types'
import { prefixCacheKey } from './app/prefix-cache-key'
const getStorageInstance = (type: StorageLike = 'sessionStorage'): Storage =>
type === 'localStorage' ? window.localStorage : window.sessionStorage
import { getStorageInstance } from './cache-backend'
const getKeyWithPrefix = (key: string, options?: StorageOptions): string =>
options?.prefix

View File

@ -0,0 +1,244 @@
import { useI18n, useSiderScroll } from '@/hooks'
import {
arrayBufferToBase64Image,
autoPrefixStyle,
call,
colorToRgba,
completeSize,
downloadAnyFile,
downloadBase64File,
effectDispose,
fileToBase64,
hasClass,
positionSelectedMenuItem,
printDom,
queryElements,
removeClass,
removeStyle,
renderNode,
setClass,
setStyle,
unrefElement,
watchEffectWithTarget,
} from '@/utils'
import { NButton, NCard, NFlex, NInput, NSwitch } from 'naive-ui'
import { effectScope } from 'vue'
import DemoPage from './components/DemoPage'
import DemoResult from './components/DemoResult'
const png =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j9x0AAAAASUVORK5CYII='
export default defineComponent({
name: 'DocsBrowserUtils',
setup() {
const { t } = useI18n('docsExamples')
const text = (key: string) => t<string>(key)
const target = ref<HTMLElement>()
const result = ref('')
const color = ref('#3b63d9')
const size = ref('150')
const zero = ref(true)
const log = ref<string[]>([])
const count = ref(0)
const observed = ref<number>()
const cleaned = ref(false)
const running = ref(false)
const dataUrl = ref('')
const fileResult = ref('')
const scrollSidebar = useSiderScroll()
let scope: ReturnType<typeof effectScope> | undefined
const change = (apply: boolean) => {
const node = unrefElement(target)
if (!node) return
const actionScope = effectScope()
actionScope.run(() => {
if (apply) {
setClass(node, 'docs-utility-marked')
setStyle(node, {
color: colorToRgba(color.value, 1, '#3b63d9'),
width: completeSize(size.value),
})
} else {
removeClass(node, 'docs-utility-marked')
removeStyle(node, ['color', 'width'])
}
result.value = JSON.stringify(
{
hasClass: hasClass(node, 'docs-utility-marked').value,
matched: queryElements('attr:data-docs-utility')?.length,
style: node.getAttribute('style'),
prefixes: autoPrefixStyle('transform'),
},
null,
2,
)
})
actionScope.stop()
}
const start = () => {
if (running.value) return
scope = effectScope()
cleaned.value = false
running.value = true
scope.run(() => {
watchEffectWithTarget(() => {
observed.value = count.value
})
effectDispose(() => {
cleaned.value = true
running.value = false
})
})
}
const stop = () => scope?.stop()
onScopeDispose(stop)
const convert = async () => {
try {
const bytes = Uint8Array.from(atob(png), (char) => char.charCodeAt(0))
dataUrl.value = arrayBufferToBase64Image(bytes.buffer)
const data = await fileToBase64(
new File([bytes], 'ray-example.png', { type: 'image/png' }),
)
fileResult.value =
data === dataUrl.value ? text('browser.matchingDataUrl') : data
} catch (error) {
fileResult.value = String(error)
}
}
return () => (
<DemoPage
title={text('browser.title')}
description={text('browser.intro')}
>
<div class="r-demo-grid">
<NCard title={text('browser.dom')}>
<NFlex>
<NInput
v-model:value={color.value}
aria-label={text('browser.color')}
/>
<NInput
v-model:value={size.value}
aria-label={text('browser.width')}
/>
<NButton onClick={() => change(true)}>
{text('browser.apply')}
</NButton>
<NButton onClick={() => change(false)}>
{text('browser.remove')}
</NButton>
</NFlex>
<p ref={target} data-docs-utility="">
{text('browser.target')}
</p>
<DemoResult label={text('browser.domResult')}>
<pre>{result.value}</pre>
</DemoResult>
<NFlex>
<NButton onClick={() => scrollSidebar(0, 0)}>
{text('browser.sidebarTop')}
</NButton>
<NButton onClick={positionSelectedMenuItem}>
{text('browser.locateMenu')}
</NButton>
</NFlex>
</NCard>
<NCard title={text('browser.vue')}>
<NFlex align="center">
<NSwitch
v-model:value={zero.value}
aria-label={text('browser.renderZero')}
/>
<span>
{renderNode(zero.value ? 0 : null, {
defaultElement: text('browser.fallback'),
})()}
</span>
<NButton
onClick={() => {
log.value = []
call(
[
(n: number) => log.value.push(`A:${n}`),
(n: number) => log.value.push(`B:${n}`),
],
count.value,
)
}}
>
{text('browser.callBoth')}
</NButton>
</NFlex>
<NFlex>
<NButton disabled={running.value} onClick={start}>
{text('browser.start')}
</NButton>
<NButton onClick={() => count.value++}>
{text('browser.increment')}
</NButton>
<NButton disabled={!running.value} onClick={stop}>
{text('browser.stop')}
</NButton>
</NFlex>
<DemoResult label={text('browser.vueResult')}>
<code>
{JSON.stringify({
count: count.value,
observed: observed.value,
cleaned: cleaned.value,
calls: log.value,
})}
</code>
</DemoResult>
</NCard>
<NCard title={text('browser.files')}>
<NFlex>
<NButton onClick={convert}>{text('browser.convert')}</NButton>
<NButton
disabled={!dataUrl.value}
onClick={() =>
downloadBase64File(dataUrl.value, 'ray-example.png')
}
>
{text('browser.downloadPng')}
</NButton>
<NButton
onClick={() =>
downloadAnyFile(
new Blob(['Ray Template\n'], { type: 'text/plain' }),
'ray-example.txt',
)
}
>
{text('browser.downloadBlob')}
</NButton>
<NButton
onClick={async () => {
fileResult.value = String(await printDom(target))
}}
>
{text('browser.print')}
</NButton>
</NFlex>
<DemoResult label={text('browser.fileResult')}>
{fileResult.value}
</DemoResult>
</NCard>
</div>
</DemoPage>
)
},
})

View File

@ -0,0 +1,203 @@
import { useI18n } from '@/hooks'
import {
callWithAsyncErrorHandling,
callWithErrorHandling,
detectOperatingSystem,
equalRouterPath,
getAppEnvironment,
getDateByNaiveDatePicker,
isAsyncFunction,
isPromise,
isValueType,
removeDuplicateKeys,
updateObjectValue,
uuid,
} from '@/utils'
import {
NButton,
NCard,
NDatePicker,
NFlex,
NInput,
NInputNumber,
NSelect,
NSwitch,
} from 'naive-ui'
import DemoPage from './components/DemoPage'
import DemoResult from './components/DemoResult'
export default defineComponent({
name: 'DocsCoreUtils',
setup() {
const { t } = useI18n('docsExamples')
const text = (key: string) => t<string>(key)
const kind = ref<'text' | 'thenable' | 'async'>('thenable')
const length = ref<number | null>(8)
const radix = ref<number | null>(36)
const generated = ref('')
const fail = ref(false)
const errorResult = ref('')
const first = ref('/orders/?page=1')
const second = ref('/orders#details')
const field = ref(text('core.pending'))
const range = ref<[number, number] | null>(null)
const row = reactive<{ order: { id?: string; status: string } }>({
order: { id: 'ORD-001', status: text('core.initial') },
})
const { MODE, DEV, PROD } = getAppEnvironment()
const sample = computed(() => {
if (kind.value === 'async') return async () => text('core.complete')
if (kind.value === 'thenable')
return { then: () => text('core.complete') }
return text('core.complete')
})
const generate = () => {
generated.value =
callWithErrorHandling(
() => uuid(length.value ?? 0, radix.value ?? 36),
(error: Error) => {
generated.value = error.message
},
) ?? generated.value
}
const handleError = (error: Error) => {
errorResult.value = error.message
}
const run = async (asyncMode: boolean) => {
const execute = () => {
if (fail.value) throw new Error(text('core.failed'))
return text('core.succeeded')
}
const result = asyncMode
? await callWithAsyncErrorHandling(async () => execute(), handleError)
: callWithErrorHandling(execute, handleError)
if (result) errorResult.value = result
}
return () => (
<DemoPage title={text('core.title')} description={text('core.intro')}>
<div class="r-demo-grid">
<NCard title="isValueType · isPromise · isAsyncFunction">
<NSelect
aria-label={text('core.inputType')}
options={[
{ label: text('core.text'), value: 'text' },
{ label: text('core.thenable'), value: 'thenable' },
{ label: text('core.asyncFn'), value: 'async' },
]}
v-model:value={kind.value}
/>
<DemoResult label={text('core.checkResult')}>
<pre>
{JSON.stringify(
{
String: isValueType(sample.value, 'String'),
Function: isValueType(sample.value, 'Function'),
isPromise: isPromise(sample.value),
isAsyncFunction: isAsyncFunction(sample.value),
},
null,
2,
)}
</pre>
</DemoResult>
</NCard>
<NCard title={text('core.errorCallbacks')}>
<NFlex>
<NInputNumber
v-model:value={length.value}
min={0}
max={64}
aria-label={text('core.idLength')}
/>
<NInputNumber
v-model:value={radix.value}
min={1}
max={62}
aria-label={text('core.radix')}
/>
<NButton onClick={generate}>{text('core.generate')}</NButton>
</NFlex>
<DemoResult label={text('core.identifier')}>
{generated.value}
</DemoResult>
<NFlex align="center">
<NSwitch
v-model:value={fail.value}
aria-label={text('core.simulateFailure')}
/>{' '}
{text('core.simulateFailure')}
<NButton onClick={() => run(false)}>
{text('core.runSync')}
</NButton>
<NButton onClick={() => run(true)}>
{text('core.runAsync')}
</NButton>
</NFlex>
<DemoResult label={text('core.execution')}>
{errorResult.value}
</DemoResult>
</NCard>
<NCard title={text('core.pathAndObject')}>
<NFlex>
<NInput
v-model:value={first.value}
aria-label={text('core.pathOne')}
/>
<NInput
v-model:value={second.value}
aria-label={text('core.pathTwo')}
/>
<code>{String(equalRouterPath(first.value, second.value))}</code>
</NFlex>
<NFlex>
<NInput
v-model:value={field.value}
aria-label={text('core.orderStatus')}
/>
<NButton
onClick={() =>
updateObjectValue(row, 'order', {
status: field.value,
})
}
>
{text('core.merge')}
</NButton>
</NFlex>
<DemoResult label={text('core.shallowCopy')}>
<code>{JSON.stringify(removeDuplicateKeys(row))}</code>
</DemoResult>
</NCard>
<NCard title={text('core.dateAndEnvironment')}>
<NDatePicker
v-model:value={range.value}
type="daterange"
clearable
aria-label={text('core.dateRange')}
/>
<DemoResult label={text('core.dateResult')}>
<code>
{JSON.stringify(getDateByNaiveDatePicker(range.value, true))}
</code>
</DemoResult>
<DemoResult label={text('core.environment')}>
<code>
{JSON.stringify({
MODE,
DEV,
PROD,
os: detectOperatingSystem(),
})}
</code>
</DemoResult>
</NCard>
</div>
</DemoPage>
)
},
})

View File

@ -0,0 +1,70 @@
import { useI18n } from '@/hooks'
import { decrypt, encrypt, prefixCacheKey } from '@/utils'
import { NButton, NFlex, NInput } from 'naive-ui'
import DemoPage from './components/DemoPage'
import DemoResult from './components/DemoResult'
export default defineComponent({
name: 'DocsStorageUtils',
setup() {
const { t } = useI18n('docsExamples')
const text = (key: string) => t<string>(key)
const key = ref('order-filter')
const prefix = ref('orders:')
const input = ref(text('storage.initial'))
const ciphertext = ref('')
const restored = ref('')
const passphrase = 'ray-template-example-only'
const cacheKey = computed(() =>
prefixCacheKey(key.value, { customPrefix: prefix.value }),
)
return () => (
<DemoPage
title={text('storage.title')}
description={text('storage.intro')}
>
<NFlex>
<NInput
v-model:value={prefix.value}
aria-label={text('storage.prefix')}
/>
<NInput v-model:value={key.value} aria-label={text('storage.key')} />
</NFlex>
<DemoResult label={text('storage.resultKey')}>
<code>{cacheKey.value}</code>
</DemoResult>
<NInput
v-model:value={input.value}
aria-label={text('storage.plainText')}
/>
<NFlex>
<NButton
onClick={() => {
ciphertext.value = encrypt({ status: input.value }, passphrase)
restored.value = ''
}}
>
{text('storage.encrypt')}
</NButton>
<NButton
disabled={!ciphertext.value}
onClick={() => {
restored.value = JSON.stringify(
decrypt(ciphertext.value, passphrase),
)
}}
>
{text('storage.decrypt')}
</NButton>
</NFlex>
<DemoResult label={text('storage.ciphertext')}>
<code>{ciphertext.value}</code>
</DemoResult>
<DemoResult label={text('storage.restored')}>
<code>{restored.value}</code>
</DemoResult>
</DemoPage>
)
},
})

View File

@ -2,6 +2,7 @@ import './index.scss'
import { RIcon } from '@/components'
import { useI18n } from '@/hooks'
import { NButton, NCard } from 'naive-ui'
import { exampleFocusKey } from './example-focus'
export default defineComponent({
name: 'HookExample',
@ -12,40 +13,49 @@ export default defineComponent({
},
setup(props, { slots }) {
const { t } = useI18n('showcase')
const focus = inject(exampleFocusKey)
const route = focus && useRoute()
return () => (
<NCard tag="article" class="r-hook-example" contentStyle={{ padding: 0 }}>
<header class="r-hook-example__header">
<span class="r-hook-example__symbol" aria-hidden="true">
ƒ
</span>
<h2>{props.name}</h2>
<span class="r-hook-example__type">Hook</span>
</header>
<p class="r-hook-example__description">{props.description}</p>
<div class="r-hook-preview">
<span class="r-hook-preview__label">{t('preview')}</span>
{slots.default?.()}
</div>
<details class="r-hook-code">
<summary>
<span>
<RIcon name="directional/expanded" size={12} />
{t('code')}
return () =>
focus &&
focus.path === route?.path &&
!focus.names.has(props.name) ? null : (
<NCard
tag="article"
class="r-hook-example"
contentStyle={{ padding: 0 }}
>
<header class="r-hook-example__header">
<span class="r-hook-example__symbol" aria-hidden="true">
ƒ
</span>
<span class="r-hook-code__format">TS / TSX</span>
</summary>
<div class="r-hook-code__toolbar">
<span>TypeScript</span>
<NButton text size="tiny" v-copy={props.code}>
{t('copyCode')}
</NButton>
<h2>{props.name}</h2>
<span class="r-hook-example__type">Hook</span>
</header>
<p class="r-hook-example__description">{props.description}</p>
<div class="r-hook-preview">
<span class="r-hook-preview__label">{t('preview')}</span>
{slots.default?.()}
</div>
<pre class="r-demo-code">
<code>{props.code}</code>
</pre>
</details>
</NCard>
)
<details class="r-hook-code">
<summary>
<span>
<RIcon name="directional/expanded" size={12} />
{t('code')}
</span>
<span class="r-hook-code__format">TS / TSX</span>
</summary>
<div class="r-hook-code__toolbar">
<span>TypeScript</span>
<NButton text size="tiny" v-copy={props.code}>
{t('copyCode')}
</NButton>
</div>
<pre class="r-demo-code">
<code>{props.code}</code>
</pre>
</details>
</NCard>
)
},
})

View File

@ -0,0 +1,6 @@
import type { InjectionKey } from 'vue'
export const exampleFocusKey: InjectionKey<{
path: string
names: ReadonlySet<string>
}> = Symbol('exampleFocus')

View File

@ -60,6 +60,11 @@
}
}
.r-demo-section-heading:has(+ .r-hook-grid:empty),
.r-hook-grid:empty {
display: none;
}
.r-hook-preview {
display: flex;
flex-direction: column;

View File

@ -1,5 +1,5 @@
import vueJsx from '@vitejs/plugin-vue-jsx'
import { defineConfig } from 'vitepress'
import { defineConfig, postcssIsolateStyles } from 'vitepress'
import { writeLegacyRedirects } from './legacy.mts'
import { sidebar } from './sidebar.mts'
import { demo, repository, version } from './source.mts'
@ -21,7 +21,13 @@ export default defineConfig({
dedupe: ['vue'],
},
// 文档按容器尺寸排版,不沿用后台的设计稿单位转换。
css: { postcss: { plugins: [] } },
css: {
postcss: {
plugins: [
postcssIsolateStyles({ includeFiles: [/(?:base|vp-doc)\.css$/] }),
],
},
},
},
head: [
[

View File

@ -6,6 +6,21 @@
background: var(--vp-c-bg-soft);
}
.ray-admin-example-frame {
padding: 12px;
border: 1px solid var(--vp-c-divider);
border-radius: 12px;
background: var(--vp-c-bg-soft);
}
.ray-admin-example {
display: block;
inline-size: 100%;
border: 0;
border-radius: 6px;
background: var(--vp-c-bg);
}
.ray-demo-fields {
display: flex;
flex-wrap: wrap;
@ -26,7 +41,7 @@
font-weight: 600;
}
.ray-demo input:not([type='radio']) {
.ray-demo-input {
inline-size: 100%;
min-block-size: 40px;
padding-inline: 10px;
@ -35,11 +50,11 @@
background: var(--vp-c-bg);
}
.ray-demo input[aria-invalid='true'] {
.ray-demo-input[aria-invalid='true'] {
border-color: var(--vp-c-danger-1);
}
.ray-demo input:focus-visible {
.ray-demo-input:focus-visible {
outline: 2px solid var(--vp-c-brand-1);
outline-offset: 2px;
}
@ -47,10 +62,24 @@
.ray-demo-options {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 12px;
}
.ray-demo-options label {
.ray-demo-group {
min-inline-size: 0;
margin: 0 0 12px;
padding: 0;
border: 0;
}
.ray-demo-group > legend {
margin-block-end: 6px;
font-size: 14px;
font-weight: 600;
}
.ray-demo-native-options > label {
display: inline-flex;
min-block-size: 40px;
align-items: center;
@ -59,7 +88,7 @@
font-size: 14px;
}
.ray-demo-options input {
.ray-demo-native-options > label > input {
appearance: auto;
accent-color: var(--vp-c-brand-1);
}

View File

@ -24,3 +24,7 @@ pnpm docs:preview
- `.vitepress/`:主题、导航和旧路径映射。迁址保留的相对路径会在生产构建生成跳转页。
应用变更影响公开 API 时,同步更新对应文档和示例。示例直接使用 workspace 包的公开入口。外壳预览使用文档自己的内存路由和示例菜单。预览生产构建,检查导航、搜索、主题、窄屏、旧路径和受影响示例。
轻量示例直接在文档中运行。依赖后台上下文的示例嵌入同一版本的 `example.html`,只注册演示路由,缓存和 Store 状态留在该示例实例。Markdown 从实际运行的文件引用源码。开发时同时运行 `pnpm dev` 和 `pnpm docs:dev`;后台端口不是 9527 时,为文档开发服务器设置 `VITE_RAY_EXAMPLE_ORIGIN`(例如 `http://127.0.0.1:9528`)。
验收全部示例请运行 `pnpm pages:build`,然后用 `pnpm preview --outDir ../../dist/pages` 在同一地址预览后台和文档,打开 `/ray-template/docs/`。只运行 `pnpm docs:preview` 时,可预览文档和直接运行的轻量示例。

View File

@ -0,0 +1,49 @@
<template>
<div class="ray-admin-example-frame">
<iframe
class="ray-admin-example"
:src="src"
:title="title"
:height="height ?? 490"
loading="lazy"
/>
</div>
<p>
<a :href="src" target="_blank" rel="noopener">{{
lang.startsWith('en')
? 'Run this example in a new tab'
: '在新标签页运行此示例'
}}</a>
</p>
</template>
<script setup lang="ts">
import { useData, withBase } from 'vitepress'
import { computed } from 'vue'
const props = defineProps<{
path: string
title: string
layout?: boolean
height?: number
focus?: string
}>()
const { isDark, lang } = useData()
const adminBase = withBase('/').replace(/[^/]+\/$/, '')
const src = computed(() => {
const query = new URLSearchParams({
theme: isDark.value ? 'dark' : 'light',
lang: lang.value.startsWith('en') ? 'en' : 'zh-CN',
})
if (props.layout) query.set('layout', '1')
if (props.focus) query.set('focus', props.focus)
const server = import.meta.env.DEV
? import.meta.env.VITE_RAY_EXAMPLE_ORIGIN || 'http://127.0.0.1:9527'
: ''
return `${server}${adminBase}example.html?${query}#${props.path}`
})
</script>

View File

@ -0,0 +1,61 @@
<template>
<DemoFrame>
<div class="ray-demo">
<RCollapseGrid
:open="open"
:cols="2"
:collapsedRows="1"
:collapseToggleText="copy.toggle"
@update:open="(collapsed) => (open = !collapsed)"
>
<NGridItem v-for="field in fields" :key="field">
<NInput
v-model:value="filters[field]"
:placeholder="copy.fields[field]"
:aria-label="copy.fields[field]"
/>
</NGridItem>
<template #action>
<NButton type="primary" @click="submitted = { ...filters }">{{
copy.search
}}</NButton>
</template>
</RCollapseGrid>
<output class="ray-demo-result">{{ submitted ?? copy.hint }}</output>
</div>
</DemoFrame>
</template>
<script setup lang="ts">
import { RCollapseGrid } from '@ray-template/ui/collapse-grid'
import { NButton, NGridItem, NInput } from 'naive-ui'
import { useData } from 'vitepress'
import { computed, reactive, ref } from 'vue'
import DemoFrame from './DemoFrame.vue'
const fields = ['name', 'department', 'role', 'id'] as const
const filters = reactive({ name: '', department: '', role: '', id: '' })
const { lang } = useData()
const copy = computed(() =>
lang.value.startsWith('en')
? {
fields: {
name: 'Name',
department: 'Department',
role: 'Role',
id: 'ID',
},
toggle: ['Expand', 'Collapse'] as [string, string],
search: 'Search',
hint: 'Expand to show more filters.',
}
: {
fields: { name: '姓名', department: '部门', role: '岗位', id: '编号' },
toggle: ['展开', '收起'] as [string, string],
search: '查询',
hint: '展开后可填写更多条件',
},
)
const open = ref(false)
const submitted = ref<typeof filters>()
</script>

View File

@ -1,16 +1,19 @@
<template>
<div class="ray-demo">
<NButton v-debounce="{ wait: 500, func: increment }">
连续点击 / Click repeatedly
</NButton>
<output class="ray-demo-result">执行次数 / Calls: {{ calls }}</output>
</div>
<DemoFrame>
<div class="ray-demo">
<NButton v-debounce="{ wait: 500, func: increment }">
连续点击 / Click repeatedly
</NButton>
<output class="ray-demo-result">执行次数 / Calls: {{ calls }}</output>
</div>
</DemoFrame>
</template>
<script setup lang="ts">
import debounce from '@ray-template/directives/debounce'
import { NButton } from 'naive-ui'
import { ref } from 'vue'
import DemoFrame from './DemoFrame.vue'
const vDebounce = debounce()
const calls = ref(0)

View File

@ -0,0 +1,45 @@
<template>
<NConfigProvider
:theme="isDark ? darkTheme : undefined"
:themeOverrides="themeOverrides"
:locale="locale === 'zh-CN' ? zhCN : undefined"
:dateLocale="locale === 'zh-CN' ? dateZhCN : undefined"
>
<div class="vp-raw" :class="{ 'r-template--dark': isDark }" :lang="locale">
<slot />
</div>
</NConfigProvider>
</template>
<script setup lang="ts">
import '@ray-template/ui/theme.css'
import {
rayPrimaryColor,
rayThemeOverrides,
} from '@ray-template/ui/theme-presets'
import { darkTheme, dateZhCN, NConfigProvider, zhCN } from 'naive-ui'
import { useData } from 'vitepress'
import { computed } from 'vue'
const props = defineProps<{ dark?: boolean; locale?: 'zh-CN' | 'en' }>()
const { isDark: docsDark, lang } = useData()
const isDark = computed(() => props.dark ?? docsDark.value)
const locale = computed(
() => props.locale ?? (lang.value.startsWith('en') ? 'en' : 'zh-CN'),
)
const { primaryColor, primaryFadeColor } = rayPrimaryColor
const themeOverrides = computed(() => {
const preset = rayThemeOverrides[isDark.value ? 'dark' : 'light']
return {
...preset,
common: {
...preset.common,
primaryColor,
primaryColorHover: primaryFadeColor,
primaryColorPressed: primaryColor,
primaryColorSuppl: primaryFadeColor,
},
}
})
</script>

View File

@ -1,17 +1,22 @@
<template>
<div ref="preview" class="ray-demo fullscreen-demo">
<NButton @click="toggleFullscreen">
{{
isFullscreen ? '退出全屏 / Exit full screen' : '元素全屏 / Full screen'
}}
</NButton>
</div>
<DemoFrame>
<div ref="preview" class="ray-demo fullscreen-demo">
<NButton @click="toggleFullscreen">
{{
isFullscreen
? '退出全屏 / Exit full screen'
: '元素全屏 / Full screen'
}}
</NButton>
</div>
</DemoFrame>
</template>
<script setup lang="ts">
import { useElementFullscreen } from '@ray-template/composables/useElementFullscreen'
import { NButton } from 'naive-ui'
import { useTemplateRef } from 'vue'
import DemoFrame from './DemoFrame.vue'
const { isFullscreen, toggleFullscreen } = useElementFullscreen(
useTemplateRef('preview'),

View File

@ -0,0 +1,46 @@
<template>
<DemoFrame>
<div class="ray-demo">
<RMoreDropdown trigger="click" :options="options" @select="onSelect">
<NButton>{{ copy.more }}</NButton>
</RMoreDropdown>
<output class="ray-demo-result">{{ result || copy.hint }}</output>
</div>
</DemoFrame>
</template>
<script setup lang="ts">
import { RMoreDropdown } from '@ray-template/ui/more-dropdown'
import { NButton } from 'naive-ui'
import { useData } from 'vitepress'
import { computed, ref } from 'vue'
import DemoFrame from './DemoFrame.vue'
const { lang } = useData()
const copy = computed(() =>
lang.value.startsWith('en')
? {
edit: 'Edit',
copy: 'Duplicate',
archive: 'Archive',
more: 'More actions',
hint: 'Select an action.',
}
: {
edit: '编辑',
copy: '复制',
archive: '归档',
more: '更多操作',
hint: '请选择一项操作',
},
)
const options = computed(() => [
{ key: 'edit', label: copy.value.edit },
{ key: 'copy', label: copy.value.copy },
{ key: 'archive', label: copy.value.archive, disabled: true },
])
const result = ref('')
const onSelect = (key: string | number) => {
result.value = options.value.find((option) => option.key === key)?.label ?? ''
}
</script>

View File

@ -6,6 +6,7 @@
<input
:id="firstId"
v-model.trim="first"
class="ray-demo-input"
inputmode="decimal"
:aria-describedby="hintId"
:aria-invalid="!isDecimal(first)"
@ -16,6 +17,7 @@
<input
:id="secondId"
v-model.trim="second"
class="ray-demo-input"
inputmode="decimal"
:aria-describedby="hintId"
:aria-invalid="!isDecimal(second)"
@ -28,6 +30,8 @@
{{ copy.fixed }}:<code>{{ result.fixed }}</code>
<br />
{{ copy.native }}:<code>{{ result.native }}</code>
<br />
<code>isCurrency: {{ result.isFixed }} / {{ result.isNative }}</code>
</span>
<span v-else>{{ copy.invalid }}</span>
</output>
@ -35,7 +39,7 @@
</template>
<script setup lang="ts">
import { add } from '@ray-template/utils/precision'
import { add, isCurrency } from '@ray-template/utils/precision'
import { computed, ref, useId } from 'vue'
const props = defineProps<{ locale?: 'zh-CN' | 'en' }>()
@ -68,9 +72,14 @@ const isDecimal = (value: string) =>
const result = computed(() => {
if (!isDecimal(first.value) || !isDecimal(second.value)) return
const fixed = add(first.value, second.value)
const native = Number(first.value) + Number(second.value)
return {
fixed: add(first.value, second.value).toString(),
native: Number(first.value) + Number(second.value),
fixed: fixed.toString(),
native,
isFixed: isCurrency(fixed),
isNative: isCurrency(native),
}
})
</script>

View File

@ -6,6 +6,7 @@
<input
:id="textId"
v-model="text"
class="ray-demo-input"
maxlength="24"
:inputmode="format === 'EAN13' ? 'numeric' : 'text'"
:aria-describedby="hintId"
@ -14,7 +15,7 @@
</div>
<fieldset>
<legend>{{ copy.format }}</legend>
<div class="ray-demo-options">
<div class="ray-demo-options ray-demo-native-options">
<label
v-for="item in formats"
:key="item"

View File

@ -1,5 +1,5 @@
<template>
<NConfigProvider :theme="dark ? darkTheme : undefined">
<DemoFrame :dark="dark" :locale="locale">
<div
class="shell-demo"
:class="{ 'r-template--dark': dark }"
@ -50,11 +50,10 @@
</template>
</AdminShell>
</div>
</NConfigProvider>
</DemoFrame>
</template>
<script setup lang="ts">
import '@ray-template/ui/theme.css'
import {
AdminShell,
LayoutSettings,
@ -62,15 +61,10 @@ import {
ShellTopNavigation,
} from '@ray-template/admin-shell'
import type { LayoutConfig } from '@ray-template/admin-shell'
import {
darkTheme,
NButton,
NConfigProvider,
NLayoutSider,
NMenu,
} from 'naive-ui'
import { NButton, NLayoutSider, NMenu } from 'naive-ui'
import { computed, onMounted, ref } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import DemoFrame from './DemoFrame.vue'
const props = withDefaults(defineProps<{ locale?: 'zh-CN' | 'en' }>(), {
locale: 'zh-CN',

View File

@ -1,37 +1,18 @@
<template>
<NConfigProvider :theme="dark ? darkTheme : undefined">
<div
class="ray-demo table-demo"
:class="{ 'r-template--dark': dark }"
:lang="locale"
>
<fieldset>
<DemoFrame :dark="dark" :locale="locale">
<div class="ray-demo table-demo">
<fieldset class="ray-demo-group">
<legend>{{ copy.source }}</legend>
<div class="ray-demo-options">
<label :for="`${id}-local`">
<input
:id="`${id}-local`"
v-model="source"
type="radio"
:name="id"
value="local"
/>
{{ copy.local }}
</label>
<label :for="`${id}-remote`">
<input
:id="`${id}-remote`"
v-model="source"
type="radio"
:name="id"
value="remote"
/>
{{ copy.remote }}
</label>
<label :for="`${id}-virtual`">
<input :id="`${id}-virtual`" v-model="virtual" type="checkbox" />
{{ copy.virtual }}
</label>
<NRadioGroup
v-model:value="source"
:name="id"
:aria-label="copy.source"
>
<NRadio value="local">{{ copy.local }}</NRadio>
<NRadio value="remote">{{ copy.remote }}</NRadio>
</NRadioGroup>
<NCheckbox v-model:checked="virtual">{{ copy.virtual }}</NCheckbox>
</div>
</fieldset>
<NButton v-if="source === 'remote'" size="small" @click="failRequest">
@ -47,22 +28,24 @@
:data="source === 'local' ? rows : []"
:request="source === 'remote' ? request : undefined"
:virtualScroll="virtual"
:search="[{ key: 'name', label: copy.name }]"
:search="[
{ key: 'name', label: copy.name, placeholder: copy.searchName },
]"
columnStateKey="docs-demo"
autoHeight
/>
</div>
</NConfigProvider>
</DemoFrame>
</template>
<script setup lang="ts">
import '@ray-template/ui/theme.css'
import { provideUiServices } from '@ray-template/ui/services'
import { RTablePro } from '@ray-template/ui/table-pro'
import type { TableProInst, TableProRequest } from '@ray-template/ui/table-pro'
import { createStorage } from '@ray-template/utils/storage'
import { darkTheme, NButton, NConfigProvider } from 'naive-ui'
import { NButton, NCheckbox, NRadio, NRadioGroup } from 'naive-ui'
import { computed, ref, shallowRef, useId } from 'vue'
import DemoFrame from './DemoFrame.vue'
const props = withDefaults(
defineProps<{ dark?: boolean; locale?: 'zh-CN' | 'en' }>(),
@ -78,6 +61,7 @@ const copy = computed(() =>
fail: 'Simulate a request failure',
cancelled: 'Cancelled requests:',
name: 'Name',
searchName: 'Enter a name',
score: 'Score',
entry: 'Member',
}
@ -89,6 +73,7 @@ const copy = computed(() =>
fail: '模拟请求失败',
cancelled: '已取消请求:',
name: '姓名',
searchName: '请输入姓名',
score: '分数',
entry: '成员',
},
@ -174,14 +159,9 @@ const failRequest = () => {
--r-table-height: 460px;
}
.table-demo :deep(.n-data-table-table) {
display: table;
margin: 0;
overflow: visible;
}
.table-demo :deep(.n-data-table-tr) {
background: transparent;
border: 0;
.table-demo :deep(.n-radio-group) {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
}
</style>

View File

@ -1,7 +1,19 @@
# 接口、取消与 Mock
<script setup>
import AdminExample from '../examples/AdminExample.vue'
</script>
业务代码调用 `apps/admin/src/api` 中的函数,后者使用 `@/axios` 的 `request`。成功时实例直接解析为响应体 `T`,失败会拒绝;接口还包了一层业务响应时,由业务层继续解析。需要原始响应头或状态码时,使用保留完整响应的 Axios 实例。
## 交互示例
<AdminExample path="/axios" title="执行、取消和节流请求" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/axios/index.tsx
:::
## 接入请求和取消
```ts

View File

@ -2,6 +2,21 @@
这些组件按文件默认导入,例如 `import AppPageHeader from '@/app-components/app/AppPageHeader'`。它们依赖应用 Store、路由或 DOM,按默认 [App 挂载顺序](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/App.tsx)集成。
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
## 后台上下文示例
这个预览运行后台的工作台和布局。在侧栏进入「模板 Hooks」,可以切换主题、水印、布局加载和菜单状态。版本提示、请求取消等 Provider 属于应用初始化流程,接入顺序见下表。
<AdminExample path="/dashboard" title="后台工作台、布局与 Provider" layout />
::: details 查看预览入口与工作台源码
<<< @/../admin/src/documentation-example.tsx
<<< @/../admin/src/views/dashboard/index.tsx
:::
## 页面组件
| 组件 | 配置和注意事项 |

View File

@ -1,5 +1,9 @@
# RChart 与 useChart
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
`RChart` 接收 ECharts options,负责创建实例、更新主题、监听尺寸与清理。需要确定的容器高度;`height="100%"` 依赖父元素的高度。图表数据和 series 配置由页面管理。
```tsx
@ -26,6 +30,14 @@ export default defineComponent({
})
```
## 交互示例
<AdminExample path="/echart" title="图表渲染和更新" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/echart/index.tsx
:::
## 渲染、主题与更新
| 属性 | 默认 | 说明 |

View File

@ -1,7 +1,21 @@
# RCollapseGrid
<script setup>
import CollapseGridDemo from '../../examples/CollapseGridDemo.vue'
</script>
适合有多个条件的搜索表单。底层用 `NGrid` 渲染,子项必须是 `NGridItem`。使用 `cols`、`responsive`、`collapsedRows`、`xGap` 和 `yGap` 配置网格;未指定间距或传 `0` 时当前实现回退到 12。
## 交互示例
<ClientOnly>
<CollapseGridDemo />
</ClientOnly>
::: details 查看示例源码
<<< @/examples/CollapseGridDemo.vue
:::
| 属性 | 默认 | 说明 |
| -------------------- | ------------------ | ---------------------------------------------------------- |
| `open` | `false` | 展开状态,`true` 表示展开,`false` 表示收起。 |

View File

@ -1,5 +1,9 @@
# RDraggableCard
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
基于 Naive UI Card 和 Interact.js。卡片 Teleport 到应用创建的容器,不参加原父节点的普通布局流。设置标题后可拖动卡片头部,否则拖动内容区;组件没有开放改变尺寸的交互。
| 属性 | 默认 | 说明 |
@ -14,6 +18,14 @@
位置可用 `top-left`、`top-right`、`bottom-left`、`bottom-right`、`center`、`top-center`、`bottom-center`。替换 `defaultPosition` 引用会触发重定位;没有公开拖拽事件或位置持久化。选择器需要在布局中真实存在,容器应有明确尺寸。组件初始化会访问 `document`,仅在浏览器侧渲染。继承 Card 属性和插槽。
## 交互示例
<AdminExample path="/draggable-card" title="拖拽卡片和移动边界" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/draggable-card.tsx
:::
```tsx
import { RDraggableCard } from '@/components'

View File

@ -1,7 +1,19 @@
# RFlow 与 useFlow
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
`RFlow` 在自己的 DOM 容器中建立 LogicFlow。图数据用 `FlowGraphData` 表示,`nodes` 和 `edges` 为可选数组;`NodeConfig`、`EdgeConfig` 都要求稳定的 `id`,边的源和目标需指向存在的节点。
## 交互示例
<AdminExample path="/flow" title="流程图和只读切换" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/flow-demo.tsx
:::
```tsx
import { RFlow } from '@/components'
import type LogicFlow from '@logicflow/core'

View File

@ -1,5 +1,9 @@
# RForm 与 useForm
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
`RForm` 包装 Naive UI Form,并用 Spin 显示提交或查询状态。用 `NFormItem.path` 匹配 `model` 的字段,在输入组件上更新值。
```tsx
@ -47,6 +51,14 @@ export default defineComponent({
})
```
## 交互示例
<AdminExample path="/form" title="表单校验和重置" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/form/index.tsx
:::
## 属性与事件
除 `onSubmit` 外,继承 `NForm` 的公开属性。默认插槽传给 `NForm`。

View File

@ -1,7 +1,19 @@
# RIframe
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
`RIframe` 封装原生 iframe 和 Naive UI Spin。它适合嵌入允许被加载的页面,页面自身的 CSP、嵌入授权和同源策略仍生效。`load` 事件并不能证明业务内容加载成功。
## 交互示例
<AdminExample path="/iframe" title="嵌入页面和加载状态" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/iframe/index.tsx
:::
```tsx
import { RIframe } from '@/components'

View File

@ -1,5 +1,9 @@
# RModal 与弹窗
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
`RModal` 继承 Naive UI Modal 的 `show`、`preset`、关闭事件和插槽,增加预设宽度和全屏卡片。声明式弹窗通过 `show` / `onUpdateShow` 或 `v-model:show` 控制。
```tsx
@ -45,6 +49,14 @@ export default defineComponent({
宽度接受数字或 CSS 尺寸。`fullscreen` 让卡片占满窗口,正文在溢出时滚动;它不调用浏览器全屏。`default`、`header`、`footer` 等插槽依 Naive UI 预设处理,组件原样转发。
## 交互示例
<AdminExample path="/modal-demo" title="声明式与命令式弹窗" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/modal-demo/index.tsx
:::
## 命令式弹窗
`@/components` 的 `useModal()` 已弃用,兼容代码仍可通过 `create(options)` 和 `destroyAll()` 调用。`create` 返回 Naive UI 弹窗句柄,支持 `fullscreen`、`width`、`cardWidth`、`dialogWidth` 等兼容配置。新代码从 `naive-ui` 导入 `useModal`,在 `NModalProvider` 的后代调用;需要模板专用全屏样式时用声明式 `RModal`。提示用户确认危险操作时也可以用全局 [Dialog Provider](./app)。

View File

@ -1,7 +1,21 @@
# RMoreDropdown
<script setup>
import MoreDropdownDemo from '../../examples/MoreDropdownDemo.vue'
</script>
包装 `NDropdown`,为行操作提供默认的更多图标。`options`、`trigger`、`placement`、`onSelect(key, option)`、受控显隐等沿用 Naive UI Dropdown。
## 交互示例
<ClientOnly>
<MoreDropdownDemo />
</ClientOnly>
::: details 查看示例源码
<<< @/examples/MoreDropdownDemo.vue
:::
| 属性 | 默认 | 说明 |
| ---------- | --------------- | ------------------------------------- |
| `icon` | `'action/more'` | 类型为 `IconName`,使用完整分包路径。 |

View File

@ -1,7 +1,19 @@
# 二维码
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
Ray Template 直接使用 `vue3-next-qrcode` 的 `Vue3NextQrcode`,公开实例类型为 `QRCodeInst`。组件演示和登录扫码占位页分别使用它。
## 交互示例
<AdminExample path="/qrcode" title="二维码参数和预览" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/qrcode/index.tsx
:::
```tsx
import { NButton } from 'naive-ui'
import { defineComponent, ref } from 'vue'

View File

@ -1,5 +1,9 @@
# RTransitionComponent
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
`RTransitionComponent` 是模板的路由出口,组合 `RouterView`、`Transition`、`Suspense` 与 `KeepAlive`。它直接渲染匹配的路由组件,按 `route.fullPath` 标识实例;query 或 hash 的变化也可能换用不同实例。
| 属性 | 默认 | 说明 |
@ -10,6 +14,14 @@
`setting.keepAliveConfig` 控制全局启用、最大数量和排除名称。`KeepAlive.include` 来自 KeepAlive Store,加入队列的页面必须有与路由名一致的组件名。缓存队列的名称会保存到当前标签的 Session Storage,浏览器刷新仍会创建新组件实例。自定义布局插槽时,只在期望的路由层级放一个出口,避免重复渲染;过渡页面使用单根节点。
## 交互示例
<AdminExample path="/multi/multi-menu-one" title="路由过渡和页面缓存" layout />
::: details 查看示例源码
<<< @/../admin/src/views/demo/multi/views/multi-menu-one/index.tsx
:::
```tsx
import { RTransitionComponent } from '@/components'

View File

@ -1,5 +1,9 @@
# RSegment
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
`RSegment` 用 Naive UI Tabs 的 `segment` 模式渲染选项。通过 `value` 和 `onUpdateValue`(或 `v-model:value`)切换业务状态,`defaultValue` 可提供非受控初值。页面内容由调用方根据值渲染。
| 属性 | 默认 | 说明 |
@ -10,6 +14,14 @@
每项必填 `key: string \| number`、`label`(文本、VNode 或渲染类型)。可用 `disabled`、`icon`(VNode 或函数)、`popover`(文本或含 `label` 的 Naive UI Popover 配置)、`slots.default`。虽然类型提供 `displayDirective`,当前实现没有把该字段传给选项,不能用它控制面板挂载。组件固定 `type="segment"` 与动画,不支持 Tabs 的增删页签、位置、Pane 样式等被排除字段。
## 交互示例
<AdminExample path="/segment" title="分段选项和宽度" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/segment/index.tsx
:::
```tsx
import { RSegment, type RSegmentOptions } from '@/components'
import { defineComponent, ref } from 'vue'

View File

@ -1,11 +1,22 @@
# 指令
<script setup>
import AdminExample from '../examples/AdminExample.vue'
import DebounceDemo from '../examples/DebounceDemo.vue'
</script>
应用在 `main.ts` 调用 `setupDirectives(app)`。注册器查找 `packages/directives/src/modules/<name>/index.ts`,调用默认导出的工厂,将返回的 Vue Directive 以目录名注册。SFC 中可直接用 `v-<name>`;从文件名和源码进入可查各指令的绑定类型。
## 交互示例
在同一示例操作复制、节流、防抖、文本省略、波纹与禁用。下方防抖小例可以快速对照计数。
<AdminExample path="/directive" title="六种指令的交互示例" :height="550" />
::: details 查看完整指令示例源码
<<< @/../admin/src/views/demo/directive/index.tsx
:::
## v-copy
绑定要复制的字符串;绑定值改变时销毁并重建 ClipboardJS 实例,卸载时销毁。Ray Admin 注册时接入消息提示。独立使用 `createCopyDirective` 时可提供自己的结果回调。复制应由用户点击触发。数字等值请先显式转为字符串。

View File

@ -1,5 +1,17 @@
# 主题、语言和水印 Hooks
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
## 交互示例
<AdminExample path="/template-hooks" title="主题和水印" focus="useTheme,useWatermark" layout />
::: details 查看示例源码
<<< @/../admin/src/views/demo/template-hooks/index.tsx
:::
## useTheme
`useTheme()` 返回下列方法。颜色覆盖由设置 Store 和全局 Provider 一起管理。
@ -15,6 +27,12 @@
## useI18n
<AdminExample path="/web-hooks" title="切换示例语言并查看翻译" focus="useI18n" />
::: details 查看语言切换示例源码
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
`useI18n(namespace?)` 返回 `t(key, ...args)`、`locale(lang)` 和初始化时可用的 Vue I18n 全局能力。`useI18n('menu').t('Dashboard')` 与 `useI18n('menu').t('menu.Dashboard')` 指向同一翻译键。未指定命名空间时,裸字符串原样返回。初始化前,`t` 返回解析后的键;初始化后同一个翻译函数会读取最新实例。
`@/hooks` 还导出独立的 `t(key)`,它只返回原始键,可供路由元数据和翻译工具静态识别。切换整个应用语言用 `useSettingActions().updateLocale(lang)`,以同步 Day.js、组件库和持久化语言;直接调用 `useI18n().locale` 只操作 Vue I18n 和 HTML 语言属性。

View File

@ -1,9 +1,18 @@
# 窗口、全屏和日期
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
import FullscreenDemo from '../../examples/FullscreenDemo.vue'
</script>
## 交互示例
<AdminExample path="/web-hooks" title="窗口宽度和日期范围" focus="useDevice,useDayjs" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
## useDevice
`useDevice(options?)` 返回 `width`、`height` 引用及 `isTabletOrSmaller` 计算引用。默认条件为 `width <= 768`。`options.media` 自定义断点,其他窗口尺寸选项传给 VueUse `useWindowSize`。`observer(isSmaller, { width, height })` 会立即执行一次,此后窗口尺寸或断点判断变化时再次执行。它检测窗口宽度,无法识别设备型号;组件容器宽度请另用 CSS 或容器观察。

View File

@ -1,5 +1,17 @@
# 分页与右键菜单
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
## 交互示例
<AdminExample path="/web-hooks" title="分页和右键菜单" focus="usePagination,useContextmenuCoordinate" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
## usePagination
`usePagination(callback?, options?)` 返回只读元组 `[pagination, actions]`。`pagination` 是可传给 `NPagination` 或 `NDataTable` 的响应式配置。缺省页码 1、每页 10 条、开启页大小选择器,候选 `[10, 20, 50, 100]`。`options` 接受除主题和原更新回调之外的 Pagination props,另提供 `pageChange(page)`、`pageSizeChange(size)`。

View File

@ -1,7 +1,19 @@
# 布局与滚动 Hooks
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
本页 API 操作模板默认布局。替换布局内容或侧栏前,先确认[插槽和布局实例](../../guide/layout)仍在预期位置。
## 交互示例
<AdminExample path="/template-hooks" title="内容加载、最大化和滚动" focus="useMaximize,useSpinning,useContentScroll,useSiderScroll" layout />
::: details 查看示例源码
<<< @/../admin/src/views/demo/template-hooks/index.tsx
:::
## useMaximize
`useMaximize(defaults?)` 返回 `isLayoutContentMaximized`(`isFullscreen` 是同一状态的别名)、`maximize(full, options?)`、`toggleFullscreen()`。页面、标签菜单和退出按钮共享同一个 Pinia 状态。需要单独放大一个 DOM 元素时,使用 [useElementFullscreen](./browser#useelementfullscreen)。

View File

@ -1,9 +1,27 @@
# 导航与菜单
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
从 `@/hooks` 导入本页 API。菜单来源、权限和路由记录见[路由指南](../../guide/routing)。
## 交互示例
<AdminExample path="/template-hooks" title="导航、首页、标签和标记" focus="useAppNavigation,useAppRoot,useSiderBar,useBadge" layout />
::: details 查看示例源码
<<< @/../admin/src/views/demo/template-hooks/index.tsx
:::
## useVueRouter
<AdminExample path="/web-hooks" title="读取路由和更新查询参数" focus="useVueRouter" />
::: details 查看路由示例源码
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
`useVueRouter()` 返回 `{ router }`,指向模板的共享 Vue Router 实例。当前路由用 `router.currentRoute.value` 读取,`push`、`replace`、`back` 等行为由 Vue Router 提供。它可在 `setup` 外取得实例。初始化后再访问依赖实际路由匹配的状态。
```ts

View File

@ -1,5 +1,17 @@
# DOM 截图与打印
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
## 交互示例
<AdminExample path="/web-hooks" title="截图与打印" focus="useDomToImage,usePrint" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
## useDomToImage
`useDomToImage(target, options?)` 返回 `create(format?)`。调用时从元素、ref 或 getter 解析目标,缺省格式为 `jpeg`,`options.imageType` 设置默认值,单次 `create(format)` 优先。Promise 按格式推断返回值:

View File

@ -1,5 +1,9 @@
# SVG 图标
<script setup>
import AdminExample from '../examples/AdminExample.vue'
</script>
```tsx
import type { IconName } from '@ray-template/icons'
import { RIcon } from '@ray-template/ui/icon'
@ -11,6 +15,14 @@ const renderIcon = () => <RIcon name={name} size={24} />
`RIcon.name` 和路由 `meta.icon` 使用同一套完整分包名。将 SVG 加入 `packages/icons/src/<分包>`,例如 `packages/icons/src/business/orders/approved.svg` 对应 `business/orders/approved`。可在演示的 SVG 图标页面查找并复制用法。
## 交互示例
<AdminExample path="/svg-icons" title="搜索图标和复制名称" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/svg-icons/index.tsx
:::
## 添加和生成
1. 选择现有分包(如 `action`、`navigation`、`system`),或按业务新建分包。路径段使用小写字母、数字、下划线或连字符,且以字母开头。

View File

@ -4,7 +4,7 @@
import { useData } from 'vitepress'
import { defineAsyncComponent } from 'vue'
const { isDark } = useData()
const { isDark, lang } = useData()
const TableProDemo = defineAsyncComponent(() => import('../examples/TableProDemo.vue'))
</script>
@ -17,7 +17,7 @@ const TableProDemo = defineAsyncComponent(() => import('../examples/TableProDemo
试试切换数据来源、筛选和分页。远端模式下,快速切换页码或重复提交筛选可以中止前一次查询。触发模拟失败后,可以用表格内的按钮重试。
<ClientOnly>
<TableProDemo :dark="isDark" />
<TableProDemo :dark="isDark" :locale="lang.startsWith('en') ? 'en' : 'zh-CN'" />
</ClientOnly>
::: details 查看示例源码

View File

@ -1,5 +1,19 @@
# Vue 与浏览器工具
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
## 交互示例
更改示例元素的颜色和尺寸,查看类名、查询和样式的结果。还可以开始或停止 Vue 作用域,转换内置 PNG,下载样例文件或打开打印预览。
<AdminExample path="/docs-browser-utils" title="Vue、DOM 与文件工具" layout :height="570" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/docs-browser-utils.tsx
:::
## Vue 目标解析
`BasicTarget<T>` 可为元素、组件实例、ref、getter 或空值,`unrefElement(target, fallback?)` 在调用时解包;组件优先返回 `$el`。多根组件的 `$el` 未必是可操作的元素。截图、全屏、样式操作请优先绑定明确的原生 DOM ref。

View File

@ -3,9 +3,20 @@
从 `@/utils` 导入以下函数。基础能力的实现位于 `@/utils/core`,精度工具也可从 `@/utils/precision` 单独导入。
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
import PrecisionDemo from '../../examples/PrecisionDemo.vue'
</script>
## 基础工具交互示例
比较 PromiseLike 与 async 函数,试试同步和异步错误回调,或观察路径、日期范围和对象更新的结果。
<AdminExample path="/docs-core-utils" title="类型判断、标识、错误、路径和日期工具" />
::: details 查看基础工具示例源码
<<< @/../admin/src/views/demo/docs-core-utils.tsx
:::
## 类型、标识和错误处理
| API | 输入与返回 |
@ -53,6 +64,14 @@ export function loadOrReport<T>(
<<< @/examples/PrecisionDemo.vue
:::
后台的精度实验还能切换减法、乘法、除法以及按份分摊。
<AdminExample path="/precision" title="定点运算与金额分摊" />
::: details 查看完整精度示例源码
<<< @/../admin/src/views/demo/precision/index.tsx
:::
### API
| API | 行为 |

View File

@ -1,5 +1,17 @@
# 缓存与兼容加密
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
## 交互示例
<AdminExample path="/cache-demo" title="缓存的写入、读取和删除" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/cache-demo/index.tsx
:::
## Web Storage
默认使用 `sessionStorage`,传 `'localStorage'` 跨刷新保存。所有读写值按 JSON 序列化。类型参数仅影响 TypeScript,不能确认缓存格式。
@ -29,6 +41,14 @@ export const clearOrderFilter = () =>
## 兼容 AES JSON
下面的实验可以比较缓存键前缀,并用示例口令把一段 JSON 加密后还原。
<AdminExample path="/docs-storage-utils" title="缓存键与旧版 AES JSON" />
::: details 查看示例源码
<<< @/../admin/src/views/demo/docs-storage-utils.tsx
:::
`encrypt(data, key?)` 返回 JSON 密文,`decrypt(ciphertext, key?)` 解码。可用字符串口令或 CryptoJS `WordArray`,同一数据须使用同类型和内容的 key。字符串沿用 OpenSSL 兼容格式,原始密钥使用随机 IV,字符串序列化为 `IV:密文`。错误密文或密钥会记录错误并返回 `undefined`,无法 JSON 序列化的输入会使加密抛错。
`CRYPTO_KEY` 是应用公开的历史兼容常量。这个工具用于读取既有本地数据(如演示锁屏),不能保护服务端密钥或替代认证。迁移格式时先保留对历史密文的读取能力。

View File

@ -184,6 +184,12 @@ Ray Admin 的应用入口迁到 `apps/admin`,文档和应用经公开入口使
- 开发服务器的 `/api/list` 返回 HTTP 200。Chrome 生产预览验证了演示登录、导航偏好刷新恢复、图标和文档交互,覆盖 TablePro 取消及失败重试、外壳导航和主题、精度工具、条码、路由校验、防抖和全屏。检查了 93 个旧路径的目标和锚点,并生成 138 个旧站跳转页。
- Docker、无界宿主和远端 CI 未运行。旧站迁址需在 GitHub Pages 发布时另行验收。
## 2026-11-04 文档示例与后台主题联动
文档的组件预览复用后台的 Naive UI 明暗主题和语言配置。页内示例隔离 VitePress 正文样式,依赖后台上下文的示例由 Pages 同一次构建中的 `example.html` 运行。示例宿主只注册演示路由,使用内存缓存和独立 Store,文档直接引用运行的源码。
`pnpm harness verify` 通过 69 个测试文件的 294 个用例。合并产物核对了 22 个文档页中的 26 处内嵌入口和源码。Chrome 生产预览验证了 TablePro 样式、明暗主题、中文分页及失败重试,抽测了组件、指令、Hooks、工具交互和正常后台登录入口。桌面和 390px 预览中的边框内边距均为 12px。
## 参考资料
- [Node.js 26.13.0 LTS](https://nodejs.org/en/blog/release/v26.13.0)

View File

@ -5,6 +5,7 @@
"exports": {
".": "./src/index.ts",
"./theme.css": "./src/theme.css",
"./theme-presets": "./src/theme-presets.ts",
"./barcode": "./src/RBarcode/index.ts",
"./chart": "./src/RChart/index.ts",
"./collapse-grid": "./src/RCollapseGrid/index.ts",

View File

@ -0,0 +1,88 @@
/** 明暗主题共用的菜单尺寸与前景色配置。 */
const menuThemeOverrides = {
itemHeight: '40px',
borderRadius: '8px',
itemTextColorActive: 'var(--r-selected-text)',
itemTextColorActiveHover: 'var(--r-selected-text)',
itemTextColorChildActive: 'var(--r-selected-text)',
itemTextColorChildActiveHover: 'var(--r-selected-text)',
itemTextColorActiveHorizontal: 'var(--r-selected-text)',
itemTextColorChildActiveHorizontal: 'var(--r-selected-text)',
itemTextColorHoverHorizontal: 'var(--r-selected-text)',
itemIconColorActive: 'var(--r-selected-text)',
itemIconColorActiveHover: 'var(--r-selected-text)',
itemIconColorChildActive: 'var(--r-selected-text)',
itemIconColorChildActiveHover: 'var(--r-selected-text)',
itemIconColorActiveHorizontal: 'var(--r-selected-text)',
itemIconColorChildActiveHorizontal: 'var(--r-selected-text)',
}
export const rayPrimaryColor = {
primaryColor: '#3b63d9',
primaryFadeColor: 'rgba(59, 99, 217, 0.85)',
}
export const rayThemeOverrides = {
dark: {
common: {
borderRadius: '8px',
fontWeightStrong: '600',
lineHeight: '1.6',
heightMedium: '36px',
heightSmall: '30px',
baseColor: '#172131',
bodyColor: '#101722',
cardColor: '#172131',
modalColor: '#192638',
popoverColor: '#192638',
actionColor: '#1c293b',
textColor1: '#e9eef7',
textColor2: '#b3c0d3',
textColor3: '#a0b0c6',
placeholderColor: '#a0b0c6',
borderColor: '#687b96',
dividerColor: '#2c394d',
hoverColor: 'rgba(179, 192, 211, 0.08)',
},
Card: {
borderRadius: '12px',
titleFontSizeMedium: '16px',
paddingMedium: '20px 24px',
},
Menu: menuThemeOverrides,
Button: { fontWeight: '500' },
Tag: { borderRadius: '5px', textColorPrimary: 'var(--r-primary-text)' },
Layout: { siderColor: '#172131', headerColor: '#172131' },
},
light: {
common: {
borderRadius: '8px',
fontWeightStrong: '600',
lineHeight: '1.6',
heightMedium: '36px',
heightSmall: '30px',
baseColor: '#ffffff',
bodyColor: '#f5f7fb',
cardColor: '#ffffff',
modalColor: '#ffffff',
popoverColor: '#ffffff',
actionColor: '#f7f9fc',
textColor1: '#1d2a3e',
textColor2: '#52647c',
textColor3: '#617187',
placeholderColor: '#617187',
borderColor: '#8492a8',
dividerColor: '#e4e9f1',
hoverColor: 'rgba(82, 100, 124, 0.06)',
},
Card: {
borderRadius: '12px',
titleFontSizeMedium: '16px',
paddingMedium: '20px 24px',
},
Menu: menuThemeOverrides,
Button: { fontWeight: '500' },
Tag: { borderRadius: '5px', textColorPrimary: 'var(--r-primary-text)' },
Layout: { siderColor: '#ffffff', headerColor: '#ffffff' },
},
}

View File

@ -69,6 +69,14 @@ export default defineConfig(({ mode }) => {
...buildOptions(mode),
target: 'baseline-widely-available',
rolldownOptions: {
input: {
index: fileURLToPath(
new URL('./apps/admin/index.html', import.meta.url),
),
example: fileURLToPath(
new URL('./apps/admin/example.html', import.meta.url),
),
},
output: {
// 交由 Rolldown 按依赖图拆包,避免手动按 pnpm 目录分组造成循环依赖。
minify: {