diff --git a/.vscode/settings.json b/.vscode/settings.json index 68585d78..3d4ca2fa 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -94,6 +94,7 @@ "stylelint", "unocss", "VITE", + "vitepress", "vueuse", "WUJIE", "zlevel" diff --git a/__test__/cache/docs-example-storage.spec.ts b/__test__/cache/docs-example-storage.spec.ts new file mode 100644 index 00000000..8580f109 --- /dev/null +++ b/__test__/cache/docs-example-storage.spec.ts @@ -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) + } +}) diff --git a/apps/admin/example.html b/apps/admin/example.html new file mode 100644 index 00000000..4dcfd30b --- /dev/null +++ b/apps/admin/example.html @@ -0,0 +1,13 @@ + + + + + + + Ray Template 示例 + + +
+ + + diff --git a/apps/admin/src/app-config/design-config.ts b/apps/admin/src/app-config/design-config.ts index afa79334..3b72c5d6 100644 --- a/apps/admin/src/app-config/design-config.ts +++ b/apps/admin/src/app-config/design-config.ts @@ -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 diff --git a/apps/admin/src/documentation-example.tsx b/apps/admin/src/documentation-example.tsx new file mode 100644 index 00000000..8cf6da73 --- /dev/null +++ b/apps/admin/src/documentation-example.tsx @@ -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 () => ( + + + + + + ) + }, +}) + +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() diff --git a/apps/admin/src/locales/lang/en-US/docsExamples.json b/apps/admin/src/locales/lang/en-US/docsExamples.json new file mode 100644 index 00000000..072fe957 --- /dev/null +++ b/apps/admin/src/locales/lang/en-US/docsExamples.json @@ -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" + } +} diff --git a/apps/admin/src/locales/lang/en-US/menu.json b/apps/admin/src/locales/lang/en-US/menu.json index b1ca7c89..9bf8cc1a 100644 --- a/apps/admin/src/locales/lang/en-US/menu.json +++ b/apps/admin/src/locales/lang/en-US/menu.json @@ -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", diff --git a/apps/admin/src/locales/lang/zh-CN/docsExamples.json b/apps/admin/src/locales/lang/zh-CN/docsExamples.json new file mode 100644 index 00000000..c622357c --- /dev/null +++ b/apps/admin/src/locales/lang/zh-CN/docsExamples.json @@ -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": "还原" + } +} diff --git a/apps/admin/src/locales/lang/zh-CN/menu.json b/apps/admin/src/locales/lang/zh-CN/menu.json index e4b66786..bf656bb6 100644 --- a/apps/admin/src/locales/lang/zh-CN/menu.json +++ b/apps/admin/src/locales/lang/zh-CN/menu.json @@ -9,6 +9,9 @@ "Doc": "文档", "DocLocal": "文档 (加速地址)", "DocLocalInside": "文档(内嵌)", + "DocsCoreUtils": "基础工具", + "DocsBrowserUtils": "浏览器工具", + "DocsStorageUtils": "缓存键与兼容加密", "DraggableCard": "拖拽卡片", "Echart": "可视化", "Error": "错误页", diff --git a/apps/admin/src/main.ts b/apps/admin/src/main.ts index 05ad2e03..ee05cfe7 100644 --- a/apps/admin/src/main.ts +++ b/apps/admin/src/main.ts @@ -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' diff --git a/apps/admin/src/store/modules/lock-screen/index.ts b/apps/admin/src/store/modules/lock-screen/index.ts index 7f0f9b76..fc25847e 100644 --- a/apps/admin/src/store/modules/lock-screen/index.ts +++ b/apps/admin/src/store/modules/lock-screen/index.ts @@ -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) => { diff --git a/apps/admin/src/styles/entry.ts b/apps/admin/src/styles/entry.ts new file mode 100644 index 00000000..5f269e43 --- /dev/null +++ b/apps/admin/src/styles/entry.ts @@ -0,0 +1,4 @@ +import './base.scss' +import '../app-components/provider/provider.scss' +import 'vue3-next-qrcode/es/style.css' +import 'virtual:uno.css' diff --git a/apps/admin/src/utils/cache-backend.ts b/apps/admin/src/utils/cache-backend.ts new file mode 100644 index 00000000..57c7b02e --- /dev/null +++ b/apps/admin/src/utils/cache-backend.ts @@ -0,0 +1,35 @@ +const memoryStorage = (): Storage => { + const entries = new Map() + + 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) diff --git a/apps/admin/src/utils/cache.ts b/apps/admin/src/utils/cache.ts index 61c1c90c..179b9bb3 100644 --- a/apps/admin/src/utils/cache.ts +++ b/apps/admin/src/utils/cache.ts @@ -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 diff --git a/apps/admin/src/views/demo/docs-browser-utils.tsx b/apps/admin/src/views/demo/docs-browser-utils.tsx new file mode 100644 index 00000000..4dffd602 --- /dev/null +++ b/apps/admin/src/views/demo/docs-browser-utils.tsx @@ -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(key) + const target = ref() + const result = ref('') + const color = ref('#3b63d9') + const size = ref('150') + const zero = ref(true) + const log = ref([]) + const count = ref(0) + const observed = ref() + const cleaned = ref(false) + const running = ref(false) + const dataUrl = ref('') + const fileResult = ref('') + const scrollSidebar = useSiderScroll() + let scope: ReturnType | 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 () => ( + +
+ + + + + change(true)}> + {text('browser.apply')} + + change(false)}> + {text('browser.remove')} + + +

+ {text('browser.target')} +

+ +
{result.value}
+
+ + scrollSidebar(0, 0)}> + {text('browser.sidebarTop')} + + + {text('browser.locateMenu')} + + +
+ + + + + {renderNode(zero.value ? 0 : null, { + defaultElement: text('browser.fallback'), + })()} + + { + log.value = [] + call( + [ + (n: number) => log.value.push(`A:${n}`), + (n: number) => log.value.push(`B:${n}`), + ], + count.value, + ) + }} + > + {text('browser.callBoth')} + + + + + {text('browser.start')} + + count.value++}> + {text('browser.increment')} + + + {text('browser.stop')} + + + + + {JSON.stringify({ + count: count.value, + observed: observed.value, + cleaned: cleaned.value, + calls: log.value, + })} + + + + + + {text('browser.convert')} + + downloadBase64File(dataUrl.value, 'ray-example.png') + } + > + {text('browser.downloadPng')} + + + downloadAnyFile( + new Blob(['Ray Template\n'], { type: 'text/plain' }), + 'ray-example.txt', + ) + } + > + {text('browser.downloadBlob')} + + { + fileResult.value = String(await printDom(target)) + }} + > + {text('browser.print')} + + + + {fileResult.value} + + +
+
+ ) + }, +}) diff --git a/apps/admin/src/views/demo/docs-core-utils.tsx b/apps/admin/src/views/demo/docs-core-utils.tsx new file mode 100644 index 00000000..28b89f29 --- /dev/null +++ b/apps/admin/src/views/demo/docs-core-utils.tsx @@ -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(key) + const kind = ref<'text' | 'thenable' | 'async'>('thenable') + const length = ref(8) + const radix = ref(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 () => ( + +
+ + + +
+                {JSON.stringify(
+                  {
+                    String: isValueType(sample.value, 'String'),
+                    Function: isValueType(sample.value, 'Function'),
+                    isPromise: isPromise(sample.value),
+                    isAsyncFunction: isAsyncFunction(sample.value),
+                  },
+                  null,
+                  2,
+                )}
+              
+
+
+ + + + + {text('core.generate')} + + + {generated.value} + + + {' '} + {text('core.simulateFailure')} + run(false)}> + {text('core.runSync')} + + run(true)}> + {text('core.runAsync')} + + + + {errorResult.value} + + + + + + + {String(equalRouterPath(first.value, second.value))} + + + + + updateObjectValue(row, 'order', { + status: field.value, + }) + } + > + {text('core.merge')} + + + + {JSON.stringify(removeDuplicateKeys(row))} + + + + + + + {JSON.stringify(getDateByNaiveDatePicker(range.value, true))} + + + + + {JSON.stringify({ + MODE, + DEV, + PROD, + os: detectOperatingSystem(), + })} + + + +
+
+ ) + }, +}) diff --git a/apps/admin/src/views/demo/docs-storage-utils.tsx b/apps/admin/src/views/demo/docs-storage-utils.tsx new file mode 100644 index 00000000..b0d6c02d --- /dev/null +++ b/apps/admin/src/views/demo/docs-storage-utils.tsx @@ -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(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 () => ( + + + + + + + {cacheKey.value} + + + + { + ciphertext.value = encrypt({ status: input.value }, passphrase) + restored.value = '' + }} + > + {text('storage.encrypt')} + + { + restored.value = JSON.stringify( + decrypt(ciphertext.value, passphrase), + ) + }} + > + {text('storage.decrypt')} + + + + {ciphertext.value} + + + {restored.value} + + + ) + }, +}) diff --git a/apps/admin/src/views/demo/hooks/HookExample.tsx b/apps/admin/src/views/demo/hooks/HookExample.tsx index 9c4a2fad..bc7475ac 100644 --- a/apps/admin/src/views/demo/hooks/HookExample.tsx +++ b/apps/admin/src/views/demo/hooks/HookExample.tsx @@ -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 () => ( - -
- -

{props.name}

- Hook -
-

{props.description}

-
- {t('preview')} - {slots.default?.()} -
-
- - - - {t('code')} + return () => + focus && + focus.path === route?.path && + !focus.names.has(props.name) ? null : ( + +
+ - TS / TSX -
-
- TypeScript - - {t('copyCode')} - +

{props.name}

+ Hook + +

{props.description}

+
+ {t('preview')} + {slots.default?.()}
-
-            {props.code}
-          
-
-
- ) +
+ + + + {t('code')} + + TS / TSX + +
+ TypeScript + + {t('copyCode')} + +
+
+              {props.code}
+            
+
+ + ) }, }) diff --git a/apps/admin/src/views/demo/hooks/example-focus.ts b/apps/admin/src/views/demo/hooks/example-focus.ts new file mode 100644 index 00000000..450fd0f9 --- /dev/null +++ b/apps/admin/src/views/demo/hooks/example-focus.ts @@ -0,0 +1,6 @@ +import type { InjectionKey } from 'vue' + +export const exampleFocusKey: InjectionKey<{ + path: string + names: ReadonlySet +}> = Symbol('exampleFocus') diff --git a/apps/admin/src/views/demo/hooks/index.scss b/apps/admin/src/views/demo/hooks/index.scss index a817c019..1b838711 100644 --- a/apps/admin/src/views/demo/hooks/index.scss +++ b/apps/admin/src/views/demo/hooks/index.scss @@ -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; diff --git a/apps/docs/.vitepress/config.mts b/apps/docs/.vitepress/config.mts index be88230b..2eeebdc0 100644 --- a/apps/docs/.vitepress/config.mts +++ b/apps/docs/.vitepress/config.mts @@ -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: [ [ diff --git a/apps/docs/.vitepress/theme/demo.css b/apps/docs/.vitepress/theme/demo.css index c7b4d465..a360c43b 100644 --- a/apps/docs/.vitepress/theme/demo.css +++ b/apps/docs/.vitepress/theme/demo.css @@ -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); } diff --git a/apps/docs/README.md b/apps/docs/README.md index 9adc0505..32cf1b05 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -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` 时,可预览文档和直接运行的轻量示例。 diff --git a/apps/docs/examples/AdminExample.vue b/apps/docs/examples/AdminExample.vue new file mode 100644 index 00000000..cb7c54ee --- /dev/null +++ b/apps/docs/examples/AdminExample.vue @@ -0,0 +1,49 @@ +