feat: refine admin workflows for v6.0.3

Improve theme consistency, keyboard navigation, and reusable frontend components.
Harden fullstack initialization and expose scoped lint and Vitest commands.
This commit is contained in:
XiaoDaiGua-Ray 2026-12-01 11:04:13 +08:00
parent d3a2504d37
commit 911c403434
No known key found for this signature in database
110 changed files with 1886 additions and 426 deletions

View File

@ -2,6 +2,7 @@
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.enable": true,
"eslint.probe": [],
"eslint.validate": [
"javascript",
"javascriptreact",

View File

@ -27,7 +27,11 @@
},
"JSON": {
"formatter": "prettier",
"format_on_save": "on"
"format_on_save": "on",
"language_servers": ["!eslint", "..."]
},
"JSONC": {
"language_servers": ["!eslint", "..."]
},
"SCSS": {
"formatter": "prettier",
@ -44,7 +48,8 @@
},
"Markdown": {
"formatter": "prettier",
"format_on_save": "on"
"format_on_save": "on",
"language_servers": ["!eslint", "..."]
}
},
"lsp": {

View File

@ -7,6 +7,7 @@ A Vue 3 + TSX admin template with an admin application, a documentation site, an
- Prefer feature entry points for runtime imports. Follow the [runtime import boundaries](harness/README.md#runtime-import-boundaries) when adding exports or changing what loads at startup or on demand.
- Prefer supported component hooks for imperative actions. Bind the hook's registration callback when required and call its returned actions. Follow the [component action conventions](docs/curd-conventions.md#component-actions) for tables, forms, and modals.
- Use `void 0` for an undefined runtime value and `undefined` in type annotations. Use the recommended replacements for APIs marked `@deprecated`.
- Apply ESLint fixes with `pnpm lint:fix <file> [...]` on explicitly named files. Use Prettier for Markdown and JSON.
- For complex tasks, the lead agent may choose to use subagents under the [delegation guidelines](harness/README.md#using-subagents-when-useful), when the host supports them and current permissions allow it. Delegation needs no separate approval. The lead agent owns integration and final verification.
- Write agent guidance and internal engineering documentation in English. Preserve the intended languages of product copy and reader-facing documentation.
- Follow the [comment style](docs/comment-style.md) when adding or editing comments. Maintain both Chinese and English product copy. For visible behavior changes, use [browser verification](harness/README.md#browser-verification) only for affected pages, actions, and dimensions.

View File

@ -1,3 +1,24 @@
## 6.0.3
### Feats
- 新增简单标签管理和复杂项目管理示例,展示弹窗编辑、独立详情页、里程碑与草稿保护。官网补齐英文指南和组件参考。
- 四种主题的登录页、图标库和业务面板使用各自的配色和圆角。提高输入框和主按钮的对比度,简化窄屏用户页和表格工具栏。
- 全局搜索提示按回车将打开的页面。面包屑可用键盘操作,工作区支持跳至主内容,并区分内容区最大化与浏览器全屏。
- 根 `package.json` 提供各模块的 Vitest 命令和全量入口 `pnpm test:all`。
### Fixes
- 路由守卫拒绝离开编辑页时保留草稿、标签与缓存。键盘关闭最后一个标签后,焦点回到标签页操作按钮。
- TablePro 在等值查询条件下保留页码,图表在实例就绪后才开始深度监听。用户管理按部门 ID 构建组织树,独立图标宿主按名称加载 SVG,打印引擎随打印示例按需加载。
- 修复不同二进制请求体互相取消的问题。RIframe 将 `sandbox` 和 `referrerpolicy` 交给原生 iframe。
- 全栈初始化先检查 Redis,再执行数据库迁移。切换到外部服务会保存实际连接,Compose 支持设置 `REDIS_KEY_PREFIX`。
### Compatibility
- `pnpm lint:fix <文件路径>` 只修复显式指定的文件。ESLint 自动将内置 `undefined` 的运行时读取改成 `void 0`,类型中的 `undefined` 仍可使用。Markdown 和 JSON 走 Prettier。
- 从 Compose 切换到外部服务时,同时提供 `DATABASE_URL` 和 `REDIS_URL`。已有外部服务配置可更新其中一项。[全栈启动指南](apps/docs/guide/distributions.md)
## 6.0.2
### Feats

View File

@ -1,12 +1,76 @@
import * as adminApi from '@/api/admin'
import { AdminApiError } from '@/api/admin/client'
import { userOptionsSchema } from '@/api/admin/contracts'
import { router } from '@/router'
import { piniaSigningStore } from '@/store/modules/signing'
import UserManagement from '@/views/user-management'
import { useUserErrorMessage } from '@/views/user-management/error-message'
import { flushPromises, mount } from '@vue/test-utils'
import { NTree } from 'naive-ui'
import { safeParse } from 'valibot'
import setupMiniApp from '../utils/setupMiniApp'
it('indexes unordered departments in linear work and preserves the tree order', async () => {
const { app } = await setupMiniApp()
let parentReads = 0
const departments = Array.from({ length: 1000 }, (_, index) => ({
id: String(index),
name: `Team ${index}`,
get parentId() {
parentReads++
return index < 2 ? '999' : null
},
}))
vi.spyOn(adminApi, 'getUserOptions').mockResolvedValue({
departments,
roles: [],
})
const wrapper = mount(UserManagement, {
global: {
plugins: [router],
stubs: { RTablePro: true, Tree: true, RIcon: true },
},
})
try {
await flushPromises()
const tree = wrapper.getComponent(NTree)
const children = tree.props('data')![0].children!
expect(children).toHaveLength(998)
expect(children[0].key).toBe('2')
expect(children.at(-1)?.children?.map(({ label }) => label)).toEqual([
'Team 0',
'Team 1',
])
expect(tree.props('defaultExpandedKeys')).toEqual(['', '999'])
expect(parentReads).toBeLessThanOrEqual(departments.length * 2)
} finally {
wrapper.unmount()
app.unmount()
vi.restoreAllMocks()
}
})
it('accepts a deep valid department tree and rejects cycles and missing parents', () => {
const departments = Array.from({ length: 2000 }, (_, index) => ({
id: String(index),
name: String(index),
parentId: index ? String(index - 1) : null,
})).reverse()
const valid = () =>
safeParse(userOptionsSchema, { departments, roles: [] }).success
const root = departments.at(-1)!
expect(valid()).toBe(true)
root.parentId = '1999'
expect(valid()).toBe(false)
root.parentId = 'missing'
expect(valid()).toBe(false)
})
it('keeps the current list and selection context when opening and closing an editor', async () => {
localStorage.clear()
const { app } = await setupMiniApp()

View File

@ -6,6 +6,7 @@ import {
themeStyleOverrides,
themeStyles,
} from '../../packages/ui/src/theme-presets'
import { contrast } from '../utils/color-contrast'
const registeredThemes = getCustomEchartTheme()
const themes = new Map(registeredThemes.map(({ name, theme }) => [name, theme]))
@ -17,37 +18,6 @@ const variants = themeStyles.flatMap((style) =>
})),
)
const composite = (foreground: number[], background: number[]) =>
foreground
.slice(0, 3)
.map(
(channel, index) =>
channel * foreground[3] + background[index] * (1 - foreground[3]),
)
const luminance = (rgb: number[]) =>
rgb
.map((channel) => {
const value = channel / 255
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
})
.reduce(
(sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index],
0,
)
const contrast = (foreground: string, background: string, surface = '#fff') => {
// 暗色 Naive/Plain 文本和指示线含透明度;必须先与实际底色合成再计算对比度。
const back = composite(color.parse(background), color.parse(surface))
const front = composite(color.parse(foreground), back)
const [lighter, darker] = [luminance(front), luminance(back)].sort(
(a, b) => b - a,
)
return (lighter + 0.05) / (darker + 0.05)
}
it('registers every style in both modes with unique deterministic names', () => {
expect(registeredThemes).toHaveLength(themes.size)
expect([...themes.keys()]).toEqual(

View File

@ -1,7 +1,7 @@
import { flushPromises, mount } from '@vue/test-utils'
import { init } from 'echarts/core'
import type { ECharts } from 'echarts/core'
import { nextTick, ref } from 'vue'
import { nextTick, reactive, ref } from 'vue'
import { RChart, useChart } from '../../packages/ui/src/RChart'
import { USE_CHART_PROVIDER_KEY } from '../../packages/ui/src/RChart/src/config'
import { provideUiServices } from '../../packages/ui/src/services'
@ -223,24 +223,44 @@ it('defers offscreen initialization, even when the theme changes', async () => {
vi.stubGlobal('IntersectionObserver', Observer)
const dark = ref(false)
const value = ref(1)
const readValue = vi.fn(() => value.value)
const options = reactive({
series: [
{
data: [
{
get value() {
return readValue()
},
},
],
},
],
})
const wrapper = mount({
setup() {
provideUiServices({ dark: () => dark.value })
return () => <RChart theme="default" />
return () => <RChart theme="default" options={options} />
},
})
try {
await flushPromises()
dark.value = true
value.value = 2
await nextTick()
expect(init).not.toHaveBeenCalled()
expect(readValue).not.toHaveBeenCalled()
visible()
await flushPromises()
expect(charts[0].getOption()).toMatchObject({
series: [{ data: [{ value: 2 }] }],
})
expect(disconnect).toHaveBeenCalled()
expect(init).toHaveBeenLastCalledWith(
expect.anything(),

View File

@ -0,0 +1,43 @@
import { darkTheme, lightTheme } from 'naive-ui'
import {
themeStyleOverrides,
themeStyles,
} from '../../packages/ui/src/theme-presets'
import { contrast } from '../utils/color-contrast'
it.each(themeStyles)(
'%s keeps editable fields and primary buttons legible in both modes',
(style) => {
for (const mode of ['light', 'dark'] as const) {
const base = mode === 'light' ? lightTheme : darkTheme
const overrides = themeStyleOverrides[style][mode]
const common = { ...base.common, ...overrides.common }
const input = { ...base.Input.self!(common), ...overrides.Input }
const selection = {
...base.Select.peers!.InternalSelection.self!(common),
...overrides.InternalSelection,
}
const button = { ...base.Button.self!(common), ...overrides.Button }
for (const field of [input, selection]) {
expect(
contrast(field.placeholderColor, field.color, common.cardColor),
).toBeGreaterThanOrEqual(4.5)
expect(
contrast(field.border.replace(/^1px solid /, ''), common.cardColor),
).toBeGreaterThanOrEqual(3)
}
for (const [text, fill] of [
[button.textColorPrimary, button.colorPrimary],
[button.textColorHoverPrimary, button.colorHoverPrimary],
[button.textColorPressedPrimary, button.colorPressedPrimary],
[button.textColorFocusPrimary, button.colorFocusPrimary],
]) {
expect(contrast(text, fill, common.cardColor)).toBeGreaterThanOrEqual(
4.5,
)
}
}
},
)

View File

@ -59,6 +59,7 @@ it('applies the latest measured search column count on the next frame', async ()
expect(resizeSearch).toBeTypeOf('function')
expect(grid.props('cols')).toBe(1)
expect(grid.find('button[type="submit"]').exists()).toBe(false)
resizeSearch?.(864)
await nextTick()
@ -71,6 +72,7 @@ it('applies the latest measured search column count on the next frame', async ()
vi.advanceTimersToNextFrame()
await nextTick()
expect(grid.props('cols')).toBe(3)
expect(grid.find('button[type="submit"]').exists()).toBe(true)
} finally {
wrapper.unmount()
vi.unstubAllGlobals()

View File

@ -4,6 +4,7 @@ import type { DropdownOption } from 'naive-ui'
import { RTablePro, useTablePro } from '../../packages/ui/src/RTablePro'
import type { TableProRequest } from '../../packages/ui/src/RTablePro'
import * as csv from '../../packages/ui/src/RTablePro/src/csv'
import * as image from '../../packages/ui/src/RTablePro/src/image'
import * as printing from '../../packages/ui/src/RTablePro/src/printing'
const columns = [{ key: 'name', title: 'Name' }]
@ -58,6 +59,70 @@ it('hides print by default and groups secondary actions under one menu', async (
}
})
it('puts image copying in the named menu on narrow panels without pagination', async () => {
let resize: ((width: number) => void) | undefined
vi.stubGlobal(
'ResizeObserver',
class {
constructor(private readonly callback: ResizeObserverCallback) {}
observe(target: Element) {
if (target.matches('.r-table'))
resize = (width) =>
this.callback(
[
{
target,
contentRect: new DOMRect(0, 0, width, 200),
} as ResizeObserverEntry,
],
this,
)
}
disconnect() {}
unobserve() {}
},
)
const wrapper = mount(RTablePro, {
props: { columns, data, pagination: false },
})
try {
await flushPromises()
const menu = wrapper.getComponent(NDropdown)
const copyOption = () =>
menu.props('options')?.find(({ key }) => key === 'copy-image')
expect(resize).toBeTypeOf('function')
resize?.(390)
await flushPromises()
expect(copyOption()).toMatchObject({ label: 'Copy table image' })
await wrapper.setProps({ loading: true })
expect(copyOption()).toMatchObject({ disabled: true })
await wrapper.setProps({ loading: false })
const copy = vi.spyOn(image, 'copyTableImage').mockResolvedValue(void 0)
menu.vm.$emit('select', 'copy-image')
await flushPromises()
expect(copy).toHaveBeenCalledOnce()
expect(wrapper.find('button[aria-label="Copy table image"]').exists()).toBe(
false,
)
await wrapper.setProps({ showCopyImage: false })
expect(copyOption()).toBeUndefined()
await wrapper.setProps({ showCopyImage: true })
resize?.(960)
await flushPromises()
expect(copyOption()).toBeUndefined()
expect(wrapper.find('button[aria-label="Copy table image"]').exists()).toBe(
true,
)
} finally {
wrapper.unmount()
vi.unstubAllGlobals()
}
})
it('opts into menu printing and retains CSV formatting and output options', async () => {
const download = vi
.spyOn(csv, 'downloadTableCsv')

View File

@ -7,7 +7,7 @@ import type {
import { provideUiServices } from '@ray-template/ui/services'
import { flushPromises, mount } from '@vue/test-utils'
import { NDataTable, NDropdown, NPagination } from 'naive-ui'
import { defineComponent, h } from 'vue'
import { defineComponent, h, reactive } from 'vue'
import * as csv from '../../packages/ui/src/RTablePro/src/csv'
const columns = [{ title: 'Name', key: 'name' }]
@ -97,6 +97,34 @@ it('loads and paginates once per action, without rewriting the filter object', a
}
})
it('keeps the current page for equivalent filters and reloads after a nested filter changes', async () => {
const filter = reactive({ state: 'active' })
const request = vi.fn(async (_params: TableProParams) => response('Alice'))
const wrapper = mount(RTablePro, {
props: {
columns,
request,
params: { filter: { state: 'active' } },
tool: false,
},
})
try {
await flushPromises()
await (wrapper.vm as unknown as TableProInst).setPage(2)
await wrapper.setProps({ params: { filter } })
await flushPromises()
expect(request.mock.calls.map(([query]) => query.page)).toEqual([1, 2])
filter.state = 'disabled'
await flushPromises()
expect(request.mock.calls.map(([query]) => query.page)).toEqual([1, 2, 1])
expect(request.mock.lastCall?.[0].filter).toEqual({ state: 'disabled' })
} finally {
wrapper.unmount()
}
})
it('ignores stale data even if the loader ignores cancellation', async () => {
const first = Promise.withResolvers<TableProResult>()
const second = Promise.withResolvers<TableProResult>()

View File

@ -65,12 +65,17 @@ it('preserves SVG root paint when no sprite service is installed', async () => {
const wrapper = mount(RIcon, { props: { name: 'action/close_all' } })
try {
await vi.waitFor(() => expect(wrapper.find('svg rect').exists()).toBe(true))
await vi.dynamicImportSettled()
expect(wrapper.find('svg rect').exists()).toBe(true)
expect(wrapper.get('svg').attributes()).toMatchObject({
fill: 'none',
stroke: 'currentColor',
'stroke-width': '1.8',
})
await wrapper.setProps({ name: 'action/reload' })
await vi.dynamicImportSettled()
expect(wrapper.find('svg rect').exists()).toBe(false)
expect(wrapper.find('svg path').exists()).toBe(true)
} finally {
wrapper.unmount()
}
@ -107,12 +112,21 @@ it('moves segment focus past disabled choices and emits each change once', async
})
it('starts iframe loading for every source and exposes the same native element', async () => {
const wrapper = mount(RIframe, { props: { src: '/one.html' } })
const wrapper = mount(RIframe, {
props: { src: '/one.html', sandbox: '', referrerpolicy: 'no-referrer' },
attrs: { class: 'host-frame' },
})
try {
await nextTick()
const frame = wrapper.get('iframe')
expect(frame.attributes('sandbox')).toBe('')
expect(frame.attributes('referrerpolicy')).toBe('no-referrer')
expect(wrapper.element.classList.contains('host-frame')).toBe(true)
expect(wrapper.element.hasAttribute('sandbox')).toBe(false)
await wrapper.setProps({ sandbox: 'allow-forms' })
expect(frame.attributes('sandbox')).toBe('allow-forms')
await frame.trigger('load')
expect(wrapper.findComponent(NSpin).props('show')).toBe(false)
await wrapper.setProps({ src: '/two.html' })

View File

@ -384,3 +384,69 @@ it('updates neutral and status document titles when the language changes', async
await flushPromises()
expect(document.title).toContain('工作区已就绪')
})
it.each([
'close',
'closeAll',
'closeOther',
'closeRight',
'closeLeft',
] as const)(
'preserves active, cached and saved tags when the guard declines %s',
async (operation) => {
const paths =
operation === 'closeLeft'
? ['/orders', '/reports', '/private']
: ['/orders', '/private', '/reports']
for (const path of paths) await router.push(path)
if (operation === 'closeLeft') await router.push('/reports')
const before = {
paths: menu.menuTagOptions.map((tag) => tag.fullPath),
saved: getCatchMenuTagOptions(),
cached: [...piniaKeepAliveStore().keepAliveInclude],
}
router.beforeEach(() => false)
if (operation === 'closeAll') await actions.closeAll()
else if (operation === 'close') await actions.close('/reports')
else
await actions[operation](
operation === 'closeLeft' ? '/private' : '/orders',
)
expect(router.currentRoute.value.path).toBe('/reports')
expect(menu.menuKey).toBe('/reports')
expect(menu.menuTagOptions.map((tag) => tag.fullPath)).toEqual(before.paths)
expect(getCatchMenuTagOptions()).toEqual(before.saved)
expect(piniaKeepAliveStore().keepAliveInclude).toEqual(before.cached)
},
)
it('preserves a tab fixed while the close-all navigation is waiting', async () => {
await router.push('/orders')
await router.push('/reports')
const gate = Promise.withResolvers<boolean>()
const entered = Promise.withResolvers<void>()
router.beforeEach(() => {
entered.resolve()
return gate.promise
})
const close = actions.closeAll()
await entered.promise
expect(menu.menuTagOptions).toHaveLength(2)
menu.toggleMenuTagFixed('/orders')
gate.resolve(true)
await close
expect(router.currentRoute.value.path).toBe('/welcome')
expect(menu.menuTagOptions.map((tag) => tag.fullPath)).toEqual(['/orders'])
expect(getCatchMenuTagOptions().map((tag) => tag.fullPath)).toEqual([
'/orders',
])
})

View File

@ -5,6 +5,7 @@ import { h, nextTick, ref } from 'vue'
import type { Ref } from 'vue'
const state = vi.hoisted(() => ({
select: vi.fn(),
compact: null as unknown as Ref<boolean>,
icons: null as unknown as Ref<boolean>,
fallback: null as unknown as Ref<boolean>,
@ -16,7 +17,7 @@ vi.mock('@/hooks', () => ({
}))
vi.mock('@/store', () => ({
useMenuActions: () => ({ changeMenuModelValue: vi.fn() }),
useMenuActions: () => ({ changeMenuModelValue: state.select }),
useMenuGetters: () => ({ getBreadcrumbOptions: state.options }),
useSettingGetters: () => ({
getBreadcrumbIcon: state.icons,
@ -71,3 +72,39 @@ it('displays menu images and defaults to a fallback for the missing icon', async
wrapper.unmount()
}
})
it('opens sibling pages from the keyboard and closes after selection', async () => {
state.compact = ref(false)
state.icons = ref(false)
state.fallback = ref(false)
const monthly = option('/reports/monthly', 'Monthly')
state.options = ref([
{
...option('/reports', 'Reports'),
children: [monthly, option('/reports/yearly', 'Yearly')],
},
monthly,
])
const wrapper = mount(Breadcrumb, { attachTo: document.body })
try {
const trigger = wrapper.get<HTMLButtonElement>(
'button[aria-haspopup="menu"]',
)
trigger.element.focus()
await trigger.trigger('keydown', { key: 'ArrowDown' })
expect(trigger.attributes('aria-expanded')).toBe('true')
await trigger.trigger('keydown', { key: 'ArrowDown' })
await trigger.trigger('keydown', { key: 'Enter' })
expect(state.select).toHaveBeenCalledWith(
'/reports/monthly',
expect.objectContaining({ fullPath: '/reports/monthly' }),
)
expect(trigger.attributes('aria-expanded')).toBe('false')
expect(document.activeElement).toBe(trigger.element)
} finally {
wrapper.unmount()
}
})

View File

@ -120,6 +120,13 @@ it('does not navigate while composing and supports keyboard result focus and Ent
await wrapper.get('input').setValue('tablepro')
await flushPromises()
expect(wrapper.findAll('.global-search__destination')).toHaveLength(1)
expect(
wrapper.get('[data-enter-target] .global-search__destination').text(),
).toBe('Visible page')
expect(
document.getElementById(input.getAttribute('aria-describedby')!)
?.textContent,
).toContain('Visible page')
expect(wrapper.get('.global-search__destination').text()).toBe(
'Visible page',
)

View File

@ -256,7 +256,7 @@ it('applies a context command to the most recently right-clicked tag', async ()
await openContextMenu(2)
const command = [
...document.querySelectorAll('.n-dropdown-option-body'),
...document.querySelectorAll('.n-dropdown-option-body__label'),
].find((option) => option.textContent === 'closeCurrent')
expect(command).toBeDefined()
@ -271,7 +271,7 @@ it('keeps context commands tied to the selected page when the order changes', as
state.tags.value.reverse()
await nextTick()
const command = Array.from(
document.querySelectorAll('.n-dropdown-option-body'),
document.querySelectorAll('.n-dropdown-option-body__label'),
).find((option) => option.textContent === 'fix')
mouse(command!, 'click', 0)
@ -569,3 +569,19 @@ it('dismisses the context menu with Escape after switching tags', async () => {
await nextTick()
expect(contextDropdown().props('show')).toBe(false)
})
it('returns focus to tab actions after keyboard closing the final page', async () => {
state.tags.value.splice(1)
await nextTick()
state.close.mockImplementationOnce((index) => {
state.tags.value.splice(index, 1)
})
const tab = wrapper.get<HTMLButtonElement>('.menu-tag__tab')
tab.element.focus()
await tab.trigger('keydown', { key: 'Delete' })
await flushPromises()
expect(document.activeElement).toBe(
wrapper.get('button[aria-label="menuTag.actions"]').element,
)
})

View File

@ -44,6 +44,7 @@ it('offers a restore button for custom content and also exits with Escape', asyn
setActivePinia(pinia)
const runtime = piniaRuntimeStore()
const wrapper = shallowMount(Layout, {
attachTo: document.body,
global: {
renderStubDefaultSlot: true,
stubs: { RayAdminShell: false, NLayout: false, NLayoutContent: false },
@ -58,6 +59,8 @@ it('offers a restore button for custom content and also exits with Escape', asyn
expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe(
false,
)
await wrapper.get('.r-layout-skip').trigger('click')
expect(document.activeElement).toBe(wrapper.get('main').element)
runtime.setRuntimeState('layoutContentMaximize', true)
await nextTick()
expect(wrapper.find('[data-test="custom-content"]').exists()).toBe(true)

View File

@ -0,0 +1,36 @@
import { color } from 'echarts/core'
const composite = (foreground: number[], background: number[]) =>
foreground
.slice(0, 3)
.map(
(channel, index) =>
channel * foreground[3] + background[index] * (1 - foreground[3]),
)
const luminance = (rgb: number[]) =>
rgb
.map((channel) => {
const value = channel / 255
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
})
.reduce(
(sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index],
0,
)
export const contrast = (
foreground: string,
background: string,
surface = '#fff',
) => {
// 暗色 Naive/Plain 文本和指示线含透明度;必须先与实际底色合成再计算对比度。
const back = composite(color.parse(background), color.parse(surface))
const front = composite(color.parse(foreground), back)
const [lighter, darker] = [luminance(front), luminance(back)].sort(
(a, b) => b - a,
)
return (lighter + 0.05) / (darker + 0.05)
}

View File

@ -1,5 +1,5 @@
import { setupI18n } from '../../apps/admin/src/locales'
import { setupRouter } from '../../apps/admin/src/router'
import { router, setupRouter } from '../../apps/admin/src/router'
import { setupStore } from '../../apps/admin/src/store'
import { piniaSigningStore } from '../../apps/admin/src/store/modules/signing'
import Login from '../../apps/admin/src/views/login'
@ -26,6 +26,7 @@ const setupMiniApp = async (authenticated = false) => {
)
await setupRouter(app, authenticated, Login)
await router.isReady()
return {
app,

View File

@ -1,3 +1,5 @@
// @vitest-environment node
import { createHttpClient } from '@ray-template/http'
import RequestCanceler from '@ray-template/http/RequestCanceler'
import type { AppRawRequestConfig } from '@ray-template/http/types'
@ -44,6 +46,56 @@ it('compares repeated form fields, URL parameters and uploaded file identity whe
expect(anotherFile.aborted).toBe(true)
})
it('keeps independent binary uploads pending and cancels repeats of the same instance', async () => {
const pending: Array<() => void> = []
const adapter: AxiosAdapter = (config) =>
new Promise((resolve, reject) => {
pending.push(() =>
resolve({
data: 'ok',
status: 200,
statusText: 'OK',
headers: {},
config,
}),
)
config.signal?.addEventListener?.('abort', () =>
reject(new AxiosError('aborted', 'ERR_CANCELED', config)),
)
})
const { request, canceler } = createHttpClient({ axios: { adapter } })
const upload = (data: unknown) =>
request.post('/binary', data).catch((error: AxiosError) => error.code)
const bodies = [
new Blob(['a']),
new Blob(['b']),
new File(['a'], 'same.bin'),
new File(['b'], 'same.bin'),
new Uint8Array([1]).buffer,
new Uint8Array([2]).buffer,
new Uint8Array([1]),
new Uint8Array([1]),
new DataView(new ArrayBuffer(1)),
new DataView(new ArrayBuffer(1)),
new ReadableStream(),
new ReadableStream(),
]
const uploads = bodies.map(upload)
await vi.waitFor(() => expect(pending).toHaveLength(bodies.length))
expect(canceler.getPendingCount()).toBe(bodies.length)
const repeated = upload(bodies[0])
await vi.waitFor(() => expect(pending).toHaveLength(bodies.length + 1))
expect(await uploads[0]).toBe('ERR_CANCELED')
expect(canceler.getPendingCount()).toBe(bodies.length)
pending.forEach((finish) => finish())
expect(await Promise.all([...uploads.slice(1), repeated])).toEqual(
bodies.map(() => 'ok'),
)
expect(canceler.getPendingCount()).toBe(0)
})
it('isolates pending requests by client and leaves caller-owned signals intact', async () => {
const pending: Array<{ signal: unknown; finish: () => void }> = []
const adapter: AxiosAdapter = (config) =>

View File

@ -0,0 +1,85 @@
// @vitest-environment node
import { ESLint } from 'eslint'
const ruleId = 'ray-template/no-undefined'
const eslint = new ESLint({
fix: true,
ruleFilter: (rule) => rule.ruleId === ruleId,
overrideConfig: { languageOptions: { parserOptions: { project: false } } },
})
async function lint(source: string, extension = 'ts') {
const [result] = await eslint.lintText(source, {
filePath: `__test__/workspace/fixture.${extension}`,
})
expect(result.fatalErrorCount, result.messages[0]?.message).toBe(0)
return { code: result.output ?? source, messages: result.messages }
}
it.each([
[
'ts',
'let value: string | undefined = undefined\nvalue = undefined\nuse(undefined)\nvalue === undefined',
'let value: string | undefined = void 0\nvalue = void 0\nuse(void 0)\nvalue === void 0',
],
[
'ts',
'const options = { value: undefined, undefined }',
'const options = { value: void 0, undefined: void 0 }',
],
[
'tsx',
'const element = <Widget value={undefined} />',
'const element = <Widget value={void 0} />',
],
[
'vue',
'<script setup lang="ts">const value: undefined = undefined</script>',
'<script setup lang="ts">const value: undefined = void 0</script>',
],
[
'mjs',
'const result = []\nundefined?.method()',
'const result = []\n;(void 0)?.method()',
],
[
'mjs',
'if (enabled) undefined?.method()',
'if (enabled) (void 0)?.method()',
],
[
'mjs',
'const power = undefined ** 2\nconst result = new (undefined)()',
'const power = (void 0) ** 2\nconst result = new (void 0)()',
],
])('fixes runtime reads in %s from %s', async (extension, source, expected) => {
expect(await lint(source, extension)).toEqual({
code: expected,
messages: [],
})
})
it('preserves type keywords, type queries, literal keys, and member names', async () => {
const source =
'type Value = typeof undefined | undefined\n({ undefined: obj.undefined })'
expect(await lint(source)).toEqual({ code: source, messages: [] })
})
it.each([
['mjs', 'function read(undefined) { return undefined }'],
['mjs', 'undefined = 42'],
['cjs', 'delete undefined'],
['cjs', 'function read() { eval("var undefined = 42"); return undefined }'],
])('reports unsafe replacements in %s from %s', async (extension, source) => {
const { code, messages } = await lint(source, extension)
expect(code).toBe(source)
expect(messages.length).toBeGreaterThan(0)
expect(
messages.every((message) => message.ruleId === ruleId && !message.fix),
).toBe(true)
})

View File

@ -109,7 +109,7 @@
--boot-line: light-dark(#efeff5, #343438);
--boot-text: light-dark(#333639, #f0f0f0);
--boot-muted: light-dark(#666970, #b5b5b8);
--boot-accent: light-dark(#18a058, #63e2b7);
--boot-accent: light-dark(#137743, #63e2b7);
--boot-radius: 4px;
--boot-shadow: none;
}

View File

@ -2,7 +2,7 @@
"name": "@ray-template/admin",
"private": true,
"type": "module",
"version": "6.0.2",
"version": "6.0.3",
"dependencies": {
"@faker-js/faker": "10.6.0",
"@logicflow/core": "2.2.5",

View File

@ -20,4 +20,4 @@ const loadOrders = (signal: AbortSignal) =>
})
```
The canceller compares encoded URLSearchParams and ordered FormData entries, including file identity. Passing a signal or setting `cancelConfig.cancel` to `false` opts out of default cancellation. The person list demonstrates [forwarding TablePro's signal](../api/demo/mock/person.ts). `useRequest` wraps the same instance and must run within an active Vue effect scope.
The canceller compares encoded URLSearchParams and ordered FormData entries, including file identity. Raw files, blobs, array buffers, typed-array or DataView bodies, and readable streams are identified by instance. Reuse the same instance to replace an earlier pending upload. Passing a signal or setting `cancelConfig.cancel` to `false` opts out of default cancellation. The person list demonstrates [forwarding TablePro's signal](../api/demo/mock/person.ts). `useRequest` wraps the same instance and must run within an active Vue effect scope.

View File

@ -42,6 +42,6 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
- `usePagination` resets to the first option in the current `pagination.value.pageSizes` and supports Naive UI object options. Default option arrays are isolated between instances. Calling `setCallback()` removes the default callback.
- `useDomToImage` loads the rendering library on the first `create` call; import failures use the same error and cleanup callbacks as renderer failures.
- A disposed `useElementFullscreen` instance cannot enter again; create a fresh instance in a live scope when a target is remounted.
- `usePrint` unwraps its target when called. DOM targets print as HTML by default. Blob images and binary PDFs are converted first; callers can await the returned Promise.
- `usePrint` unwraps its target when called. DOM targets print as HTML by default. Blob images and binary PDFs are converted first; callers can await the returned Promise. The composables package marks its entry point and the Day.js locale registration as side-effectful so that unused hook re-exports do not load the print engine.
Screenshots and printing depend on real browsers. Happy DOM tests verify state and error handling; they do not replace native print-dialog or physical-output acceptance.

View File

@ -6,35 +6,6 @@ import { useVueRouter } from './useVueRouter'
export type CloseMenuTag = Key | MenuTagOptions
/**
*
* @param target 标签页对象、索引或路径
* @param fn 用于日志的调用方方法名
*
* @returns 当前标签列表中的对象和索引,找不到时返回 undefined。
*/
const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
const { getMenuTagOptions } = useMenuGetters()
const tags = getMenuTagOptions.value
const index =
typeof target === 'number'
? target
: tags.findIndex(
(tag) =>
tag.fullPath ===
(typeof target === 'string' ? target : target.fullPath),
)
if (!Number.isInteger(index) || index < 0 || index >= tags.length) {
console.warn(`[${fn}]: Could not find menu tag.`)
return
}
return { option: tags[index], index }
}
/**
*
* @returns 标签页检查与关闭方法;状态由共享菜单 Store 持有。
@ -42,23 +13,69 @@ const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
export function useSiderBar() {
const { getMenuTagOptions, getCurrentMenuOption } = useMenuGetters()
const { router } = useVueRouter()
const {
changeMenuModelValue,
spliceMenTagOptions,
setMenuTagOptions,
isMenuTagFixed,
} = useMenuActions()
const { setMenuTagOptions, isMenuTagFixed } = useMenuActions()
const canClose = (tag: MenuTagOptions) => !isMenuTagFixed(tag)
const closeWhere = (matches: (index: number) => boolean) => {
const current = getMenuTagOptions.value
const remaining = current.filter(
(tag, index) => !matches(index) || !canClose(tag),
)
if (remaining.length !== current.length) setMenuTagOptions(remaining, false)
/**
*
* @param target 标签页对象、索引或路径
* @param fn 用于日志的调用方方法名
*
* @returns 当前标签列表中的对象和索引,找不到时返回 undefined。
*/
const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
const tags = getMenuTagOptions.value
const index =
typeof target === 'number'
? target
: tags.findIndex(
(tag) =>
tag.fullPath ===
(typeof target === 'string' ? target : target.fullPath),
)
return remaining
if (!Number.isInteger(index) || index < 0 || index >= tags.length) {
console.warn(`[${fn}]: Could not find menu tag.`)
return
}
return { option: tags[index], index }
}
const closeTags = (
candidates: MenuTagOptions[],
destination?: string,
replace = false,
) => {
const closing = new Set(candidates.filter(canClose))
const commit = () => {
// 守卫等待期间,其他调用方可以打开、固定或替换标签;只移除本次选定且仍可关闭的项。
const current = getMenuTagOptions.value
const remaining = current.filter(
(tag) => !closing.has(tag) || !canClose(tag),
)
if (remaining.length !== current.length)
setMenuTagOptions(remaining, false)
}
if (!destination || router.currentRoute.value.fullPath === destination) {
commit()
return
}
const navigation = replace
? router.replace(destination)
: router.push(destination)
return navigation.then((failure) => {
if (!failure && router.currentRoute.value.fullPath === destination)
commit()
return failure
})
}
/**
@ -81,7 +98,10 @@ export function useSiderBar() {
const normal = normalMenuTagOption(target, 'checkCloseRight')
return (
!!normal && getMenuTagOptions.value.slice(normal.index + 1).some(canClose)
!!normal &&
getMenuTagOptions.value.some(
(tag, index) => index > normal.index && canClose(tag),
)
)
}
@ -95,7 +115,10 @@ export function useSiderBar() {
const normal = normalMenuTagOption(target, 'checkCloseLeft')
return (
!!normal && getMenuTagOptions.value.slice(0, normal.index).some(canClose)
!!normal &&
getMenuTagOptions.value.some(
(tag, index) => index < normal.index && canClose(tag),
)
)
}
@ -115,16 +138,15 @@ export function useSiderBar() {
const { index, option } = normal
const active = option.fullPath === getCurrentMenuOption.value?.fullPath
spliceMenTagOptions(index)
const tags = getMenuTagOptions.value
if (!getMenuTagOptions.value.length)
return router.replace(WELCOME_ROUTE_PATH)
if (tags.length === 1)
return closeTags([option], WELCOME_ROUTE_PATH, true)
if (active) {
const tag = getMenuTagOptions.value[Math.max(0, index - 1)]
return tag && changeMenuModelValue(tag.fullPath, tag)
}
return closeTags(
[option],
active ? (tags[index - 1] ?? tags[index + 1]).fullPath : void 0,
)
}
}
@ -137,11 +159,16 @@ export function useSiderBar() {
*/
const closeAll = () => {
const current = getCurrentMenuOption.value?.fullPath
const remaining = closeWhere(() => true)
const tags = getMenuTagOptions.value
const fixed = tags.filter(isMenuTagFixed)
if (remaining.some((tag) => tag.fullPath === current)) return
return router.replace(remaining[0]?.fullPath ?? WELCOME_ROUTE_PATH)
return closeTags(
tags,
fixed.some((tag) => tag.fullPath === current)
? void 0
: (fixed[0]?.fullPath ?? WELCOME_ROUTE_PATH),
true,
)
}
const closeForbiddenPage = () => {
@ -174,10 +201,12 @@ export function useSiderBar() {
const currentIndex = getCurrentTagIndex()
const current = getMenuTagOptions.value[currentIndex]
closeWhere((tagIndex) => tagIndex > index)
if (currentIndex > index && canClose(current))
return changeMenuModelValue(option.fullPath, option)
return closeTags(
getMenuTagOptions.value.slice(index + 1),
current && currentIndex > index && canClose(current)
? option.fullPath
: void 0,
)
}
}
@ -196,10 +225,12 @@ export function useSiderBar() {
const currentIndex = getCurrentTagIndex()
const current = getMenuTagOptions.value[currentIndex]
closeWhere((tagIndex) => tagIndex < index)
if (currentIndex >= 0 && currentIndex < index && canClose(current))
return changeMenuModelValue(option.fullPath, option)
return closeTags(
getMenuTagOptions.value.slice(0, index),
current && currentIndex < index && canClose(current)
? option.fullPath
: void 0,
)
}
}
@ -214,12 +245,14 @@ export function useSiderBar() {
const normal = normalMenuTagOption(target, 'closeOther')
if (normal) {
const { option, index } = normal
const { option } = normal
closeWhere((tagIndex) => tagIndex !== index)
if (getCurrentMenuOption.value?.fullPath !== option.fullPath)
return changeMenuModelValue(option.fullPath, option)
return closeTags(
getMenuTagOptions.value.filter((tag) => tag !== option),
getCurrentMenuOption.value?.fullPath === option.fullPath
? void 0
: option.fullPath,
)
}
}

View File

@ -101,7 +101,7 @@ export default defineComponent({
{
label: t('maximize'),
key: 'maximizeLayoutContent',
icon: () => <RIcon name="action/fullscreen" size="1em" />,
icon: () => <RIcon name="action/maximize-workspace" size="1em" />,
},
{
label: t('reload'),
@ -264,24 +264,35 @@ export default defineComponent({
? translate(tag.meta.i18nKey)
: tag.breadcrumbLabel || tag.fullPath
const closeCurrentMenuTag = (index: number, restoreFocus = false) => {
const closeCurrentMenuTag = async (index: number, restoreFocus = false) => {
const option = getMenuTagOptions.value[index]
if (!option || !canClose(option)) return
const focusIndex =
option.fullPath === getMenuKey.value ? Math.max(0, index - 1) : index
const wasActive = option.fullPath === getMenuKey.value
const failure = await close(index)
close(index)
if (
failure ||
!restoreFocus ||
getMenuTagOptions.value.some((tag) => tag.fullPath === option.fullPath)
)
return
if (restoreFocus) {
void nextTick(() => {
const tabs =
tagsRef.value?.querySelectorAll<HTMLButtonElement>('.menu-tag__tab')
await nextTick()
const tabs =
tagsRef.value?.querySelectorAll<HTMLButtonElement>('.menu-tag__tab')
const adjacent = tabs?.[Math.min(index, tabs.length - 1)]
const focus =
(wasActive
? tagsRef.value?.querySelector<HTMLButtonElement>(
'.menu-tag__tab[aria-current="page"]',
)
: adjacent) ??
adjacent ??
actionsButton.value
tabs?.[Math.min(focusIndex, tabs.length - 1)]?.focus()
})
}
focus?.focus()
}
// 菜单标签点击更新当前菜单激活项
@ -623,7 +634,7 @@ export default defineComponent({
title={$t('layout.maximize')}
onClick={() => this.maximize(true)}
>
<RIcon name="action/fullscreen" size={16} />
<RIcon name="action/maximize-workspace" size={16} />
</button>
<button
type="button"

View File

@ -1,11 +1,8 @@
import type { DragEvent } from '@interactjs/actions/drag/plugin'
import type { DropEvent } from '@interactjs/actions/drop/DropEvent'
import type { PointerEvent as InteractPointerEvent } from '@interactjs/pointer-events/PointerEvent'
import { useEventListener } from '@vueuse/core'
import { watch } from 'vue'
import type { Ref } from 'vue'
type Interact = typeof import('interactjs').default
type InteractApi = typeof import('interactjs').default
type Placement = 'before' | 'after'
type ClientPosition = Pick<PointerEvent, 'clientX' | 'clientY'>
@ -26,7 +23,7 @@ interface DropMarker {
interface Press {
down: PointerEvent
pointer: InteractPointerEvent
pointer: Interact.PointerEvent
row: HTMLElement
tab: HTMLElement
button: HTMLButtonElement
@ -44,7 +41,7 @@ interface Drag {
let activeTagDrags = 0
let previousDynamicDrop = false
const retainDynamicDrop = (interact: Interact) => {
const retainDynamicDrop = (interact: InteractApi) => {
// dynamicDrop 由同一个 interact.js 实例共享,最后一次标签拖动结束时恢复。
if (activeTagDrags === 0) {
previousDynamicDrop = interact.dynamicDrop() === true
@ -181,7 +178,7 @@ export function useTagReorder(
}
const bind = (
interact: Interact,
interact: InteractApi,
row: HTMLElement,
viewport: HTMLElement,
) => {
@ -218,7 +215,7 @@ export function useTagReorder(
}
const placementAt = (
event: DropEvent,
event: Interact.DropEvent,
x: number,
): DropMarker | undefined => {
const { target: tab, relatedTarget: source } = event
@ -271,7 +268,7 @@ export function useTagReorder(
draggableElement.parentElement === row,
overlap: 'pointer',
checker: (
event: DragEvent,
event: Interact.DragEvent,
_native,
over,
_zone,
@ -308,10 +305,10 @@ export function useTagReorder(
released.pageY < rect.bottom
)
},
ondropmove: (event: DropEvent) =>
ondropmove: (event: Interact.DropEvent) =>
mark(placementAt(event, event.dragEvent.clientX)),
ondragleave: () => mark(),
ondrop: (event: DropEvent) => {
ondrop: (event: Interact.DropEvent) => {
const released = drag?.release
if (!press || !released) return
@ -328,7 +325,7 @@ export function useTagReorder(
},
})
.pointerEvents({ ignoreFrom: CLOSE_SELECTOR })
.on('down', (pointer: InteractPointerEvent) => {
.on('down', (pointer: Interact.PointerEvent) => {
const event = pointer.originalEvent
const tab = pointer.currentTarget

View File

@ -98,6 +98,7 @@
}
}
&[data-enter-target],
&:has(> .global-search__destination:focus-visible) {
background: color-mix(
in srgb,
@ -252,3 +253,12 @@
--search-focus: Highlight;
}
}
.global-search__enter-hint {
position: absolute;
inline-size: 1px;
block-size: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}

View File

@ -28,6 +28,8 @@ export default defineComponent({
useNavigationHistoryActions()
const input = shallowRef<InputInst>()
const inputId = useId()
const enterHintId = useId()
const inputFocused = ref(false)
const searchValue = ref('')
const activeIndex = ref(0)
const rowButtons = new Map<string, HTMLButtonElement>()
@ -113,6 +115,10 @@ export default defineComponent({
groups.value.flatMap((group) => group.options),
)
const enterTarget = computed(() =>
inputFocused.value ? options.value[activeIndex.value] : void 0,
)
watch(options, () => {
activeIndex.value = 0
})
@ -240,14 +246,32 @@ export default defineComponent({
inputProps={{
id: inputId,
name: 'page-search',
'aria-describedby': enterHintId,
autocapitalize: 'off',
spellcheck: false,
}}
onFocus={() => {
inputFocused.value = true
}}
onBlur={() => {
inputFocused.value = false
}}
onKeydown={(event) => moveResult(event, true)}
clearable
>
{{ prefix: () => <RIcon name="action/search" size={18} /> }}
</NInput>
<span
id={enterHintId}
class="global-search__enter-hint"
role="status"
>
{enterTarget.value
? t('enterTarget', {
title: enterTarget.value.breadcrumbLabel,
})
: ''}
</span>
{storageUnavailable.value && (
<p class="global-search__hint" role="status">
{t('storageUnavailable')}
@ -273,6 +297,9 @@ export default defineComponent({
<li
key={option.fullPath}
class="global-search__item"
data-enter-target={
enterTarget.value === option ? '' : void 0
}
>
<button
type="button"

View File

@ -57,3 +57,27 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.layout-breadcrumb__trigger {
display: inline-flex;
align-items: center;
gap: 4px;
max-inline-size: 100%;
padding: 2px 4px;
border: 0;
border-radius: var(--r-control-radius);
color: var(--r-text-secondary);
background: transparent;
font: inherit;
cursor: pointer;
&:hover,
&[aria-expanded='true'] {
color: var(--r-text);
background: var(--r-surface-hover);
}
&:focus-visible {
outline: 2px solid var(--r-theme-primary-color);
}
}

View File

@ -15,24 +15,14 @@ export default defineComponent({
const { getBreadcrumbIcon, getBreadcrumbIconFallback } = useSettingGetters()
const { isTabletOrSmaller } = useDevice()
const dropdownSelect = (key: string | number, option: DropdownOption) => {
changeMenuModelValue(key, option as unknown as AppMenuOption)
const expanded = ref<string>()
const setExpanded = (path: string, open: boolean) => {
if (open) expanded.value = path
else if (expanded.value === path) expanded.value = void 0
}
/**
*
* @param option bread option
*
* 点击面包屑,如果包含子集,则允许点击更新页面
*/
const breadcrumbItemClick = (option: AppMenuOption) => {
if (!option.children?.length) {
const { meta = {} } = option
if (!meta.sameLevel) {
changeMenuModelValue(option.fullPath, option)
}
}
const dropdownSelect = (key: string | number, option: DropdownOption) => {
expanded.value = void 0
changeMenuModelValue(key, option as unknown as AppMenuOption)
}
const renderIcon = (option: Pick<AppMenuOption, 'icon'>) => {
@ -85,20 +75,59 @@ export default defineComponent({
<NBreadcrumb class="layout-breadcrumb">
<TransitionGroup name="breadcrumb" appear>
{trail.map((option) => (
<NBreadcrumbItem
key={option.fullPath}
onClick={() => breadcrumbItemClick(option)}
>
<NBreadcrumbItem key={option.fullPath} clickable={false}>
{option.children && option.children.length > 1 ? (
<NDropdown
trigger="hover"
show={expanded.value === option.fullPath}
onUpdateShow={(show) => setExpanded(option.fullPath, show)}
labelField="breadcrumbLabel"
keyField="fullPath"
options={option.children}
renderIcon={renderIcon}
onSelect={dropdownSelect}
>
{renderLabel(option, option === current)}
<button
type="button"
class="layout-breadcrumb__trigger"
aria-haspopup="menu"
aria-expanded={expanded.value === option.fullPath}
onClick={() =>
setExpanded(
option.fullPath,
expanded.value !== option.fullPath,
)
}
onKeydown={(event) => {
if (event.key === 'Tab')
setExpanded(option.fullPath, false)
if (
event.key === 'ArrowDown' &&
expanded.value !== option.fullPath
) {
event.preventDefault()
event.stopPropagation()
setExpanded(option.fullPath, true)
}
}}
>
{renderLabel(option, option === current)}
<RIcon name="directional/expanded" size="0.85em" />
</button>
</NDropdown>
) : option !== current &&
!option.children?.length &&
!option.meta.sameLevel ? (
<button
type="button"
class="layout-breadcrumb__trigger"
onClick={() =>
changeMenuModelValue(option.fullPath, option)
}
>
{renderLabel(option, false)}
</button>
) : (
renderLabel(option, option === current)
)}

View File

@ -90,6 +90,7 @@ export default defineComponent({
maximizedStyle={layoutContentMaximizeStyle.value}
contentRef={LAYOUT_CONTENT_REF}
restore={() => maximize(false)}
skipContentLabel={t('skipToContent')}
restoreLabel={t('restore')}
>
{{

View File

@ -24,6 +24,7 @@
"current": "Current configuration",
"extension": "Extend the layout",
"slots": "Use header, sidebar, tabs, footer and default content slots. Update the Pinia configuration to switch layouts.",
"skipToContent": "Skip to main content",
"navigation": "Main navigation",
"maximize": "Maximize content",
"restore": "Restore content size (Esc)",

View File

@ -11,6 +11,7 @@
"empty": "Search for a page and use the star to save a favorite.",
"storageUnavailable": "Your browser cannot save history right now. It remains available for this visit.",
"move": "Move",
"enterTarget": "Enter opens {title}",
"open": "Open",
"close": "Close"
}

View File

@ -1,6 +1,7 @@
{
"title": "User management",
"descriptionMock": "Manage members by organization. The online demo uses Mock APIs, with data saved in this browser.",
"descriptionMockCompact": "Demo data is saved in this browser.",
"descriptionServer": "Manage member profiles, roles and account status by organization.",
"organization": "Organization",
"createUser": "Add user",

View File

@ -24,6 +24,7 @@
"current": "当前布局配置",
"extension": "扩展布局",
"slots": "布局提供 header、sidebar、tabs、footer 和默认内容插槽。通过 Pinia 更新配置即可切换布局。",
"skipToContent": "跳至主内容",
"navigation": "主导航",
"maximize": "最大化内容区域",
"restore": "退出内容最大化(Esc)",

View File

@ -11,6 +11,7 @@
"empty": "搜索页面,并点击星标收藏常用入口。",
"storageUnavailable": "浏览器暂时无法保存记录,本次访问中仍可使用。",
"move": "切换",
"enterTarget": "按回车打开{title}",
"open": "打开",
"close": "关闭"
}

View File

@ -1,6 +1,7 @@
{
"title": "用户管理",
"descriptionMock": "按组织管理成员资料与状态。在线演示通过 Mock 接口读写,数据保存在当前浏览器。",
"descriptionMockCompact": "演示数据保存在当前浏览器。",
"descriptionServer": "按组织管理成员资料、角色与账号状态。",
"organization": "组织架构",
"createUser": "新增用户",

View File

@ -11,7 +11,7 @@
"Password": "密码",
"ShowPassword": "显示密码",
"HidePassword": "隐藏密码",
"RayTemplate": "构建你的中后台管理系统",
"RayTemplate": "构建你的\n中后台管理系统",
"TemplateDescription": "基于 Vue 3、TypeScript 和 Naive UI 的开源中后台管理模板。",
"OtherSignInOptions": "其他登录方式示例",
"Resources": "项目资源",

View File

@ -80,17 +80,6 @@ export default defineComponent({
<RIcon name="logo/ray" size={44} />
</span>
</AppPageHeader>
<div class="r-dashboard-stack">
{stack.map((item) => (
<article key={item.name} class="r-dashboard-stack__item">
<span>{item.name}</span>
<strong>{item.version}</strong>
<small>
{item.name === 'Pinia' ? text('stateManagement') : item.detail}
</small>
</article>
))}
</div>
{shortcuts.value.length ? (
<section aria-labelledby={shortcutsTitle}>
<h2 id={shortcutsTitle} class="r-dashboard__section-title">
@ -120,6 +109,17 @@ export default defineComponent({
</nav>
</section>
) : null}
<div class="r-dashboard-stack">
{stack.map((item) => (
<article key={item.name} class="r-dashboard-stack__item">
<span>{item.name}</span>
<strong>{item.version}</strong>
<small>
{item.name === 'Pinia' ? text('stateManagement') : item.detail}
</small>
</article>
))}
</div>
<div class="r-dashboard-info">
<NCard title={text('project')}>
<p class="r-dashboard-info__intro">{text('projectDescription')}</p>

View File

@ -12,7 +12,7 @@
.r-showcase-meta {
padding: 7px 12px;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-control-radius);
color: var(--r-text-secondary);
background: var(--r-surface);
font-size: 12px;
@ -146,7 +146,7 @@
min-height: 150px;
padding: 12px;
border: 1px solid var(--r-line);
border-radius: 10px;
border-radius: var(--r-radius);
background: #fff;
color: #182436;
overflow: auto;
@ -162,7 +162,7 @@
gap: 6px;
padding: 12px 14px;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-radius);
background: var(--r-surface-muted);
color: var(--r-text);
@ -192,7 +192,7 @@
min-height: 112px;
display: grid;
place-items: center;
border-radius: 8px;
border-radius: var(--r-radius);
background: var(--r-canvas);
span {
@ -200,7 +200,7 @@
block-size: 68px;
border: 1px solid var(--r-control-border);
border-block-start: 10px solid var(--r-theme-primary-color);
border-radius: 5px;
border-radius: var(--r-radius);
background: var(--r-surface);
}
@ -227,5 +227,5 @@
min-width: 0;
overflow: hidden;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-radius);
}

View File

@ -1,3 +1,4 @@
import './project-editor.scss'
import { useI18n } from '@/hooks/template/useI18n'
import { useRuntimeGetters } from '@/store/hooks/useRuntimeStore'
import { RForm } from '@ray-template/ui/form'
@ -159,11 +160,12 @@ export default defineComponent({
labelProps={{ for: field('summary') }}
>
<NInput
class="curd-project-editor__summary"
v-model:value={draft.value.summary}
inputProps={{ id: field('summary') }}
type="textarea"
maxlength={500}
autosize={{ minRows: 2, maxRows: 6 }}
autosize
/>
</NFormItem>
</NCard>

View File

@ -0,0 +1,5 @@
// 在 Naive UI 首次测量镜像之前设好行数边界,避免观察回调再次改变父容器高度。
.curd-project-editor__summary .n-input__textarea-mirror {
min-block-size: calc(2lh + 2 * var(--n-padding-vertical));
max-block-size: calc(6lh + 2 * var(--n-padding-vertical));
}

View File

@ -2,7 +2,7 @@
margin: 0;
padding: 16px 18px;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-radius);
color: var(--r-text-secondary);
background: var(--r-surface-muted);
white-space: pre-wrap;
@ -39,7 +39,7 @@
width: 30px;
height: 30px;
flex-shrink: 0;
border-radius: 8px;
border-radius: var(--r-control-radius);
color: var(--r-text-secondary);
background: var(--r-surface-muted);
font-family: Georgia, serif;
@ -73,7 +73,7 @@
margin: 0 24px 20px;
padding: 16px;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-radius);
background: var(--r-surface-muted);
&__label {
@ -147,7 +147,7 @@
position: relative;
padding: 28px;
border: 1px solid var(--r-line);
border-radius: 12px;
border-radius: var(--r-radius);
background: var(--r-surface);
color: var(--r-text);
box-shadow: var(--r-shadow-soft);

View File

@ -19,7 +19,7 @@
gap: 8px;
padding: 10px;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-control-radius);
background: var(--r-surface-muted);
overflow-wrap: anywhere;
}

View File

@ -40,7 +40,7 @@
place-items: center;
min-width: 22px;
height: 20px;
border-radius: 5px;
border-radius: var(--r-control-radius);
color: var(--r-text-muted);
background: var(--r-surface-muted);
font-size: 10px;
@ -64,8 +64,8 @@
justify-content: center;
align-items: center;
border: 1px solid var(--r-line);
border-radius: 9px;
color: var(--r-text-secondary);
border-radius: var(--r-control-radius);
color: var(--r-text);
background: var(--r-surface-muted);
cursor: pointer;
transition:
@ -73,17 +73,18 @@
border-color 0.18s ease;
> span:last-child {
color: var(--r-text-secondary);
font-family: var(--r-font-mono);
font-size: 10px;
font-size: 12px;
overflow-wrap: anywhere;
}
&:hover {
&:hover,
&:focus-visible {
border-color: var(--r-control-border);
background: var(--r-surface);
color: var(--r-text);
}
&:focus-visible {
outline: 2px solid var(--r-theme-primary-color);
outline: 2px solid var(--r-text);
outline-offset: 2px;
}
}

View File

@ -39,7 +39,7 @@
grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr);
grid-template-areas: 'story panel';
border: 1px solid var(--r-line);
border-radius: 20px;
border-radius: var(--r-radius);
overflow: clip;
background: var(--r-surface);
box-shadow: var(--r-shadow-soft);
@ -57,12 +57,11 @@
flex-direction: column;
justify-content: space-between;
gap: 44px;
color: #f1f7ff;
background:
radial-gradient(ellipse at 95% 88%, #204c7e, transparent 64%), #132743;
color: var(--r-text);
background-color: var(--r-surface-muted);
.login__eyebrow {
color: #9ce7ff;
color: var(--login-story-secondary, var(--r-text-secondary));
}
h2 {
@ -74,13 +73,28 @@
text-wrap: balance;
}
h2:lang(zh) {
max-width: none;
white-space: pre-line;
word-break: keep-all;
overflow-wrap: anywhere;
}
h2 + p {
max-width: 36ch;
color: #c6d7eb;
color: var(--login-story-secondary, var(--r-text-secondary));
line-height: 1.75;
}
}
&--modern &__story {
background-image: radial-gradient(
ellipse at 95% 88%,
color-mix(in srgb, var(--r-theme-primary-color) 24%, transparent),
transparent 66%
);
}
&__stack {
display: flex;
flex-wrap: wrap;
@ -90,8 +104,8 @@
margin: 24px 0 0;
li {
border: 1px solid #6983a3;
border-radius: 100px;
border: 1px solid color-mix(in srgb, currentColor 45%, transparent);
border-radius: var(--r-control-radius);
padding: 5px 12px;
font-size: 12px;
}
@ -107,7 +121,7 @@
background: repeating-radial-gradient(
circle,
transparent 0 29px,
rgb(156 231 255 / 20%) 30px 31px
color-mix(in srgb, currentColor 15%, transparent) 30px 31px
);
}
@ -154,6 +168,16 @@
}
}
.r-template--light .login--modern .login__story {
--login-story-secondary: color-mix(
in srgb,
var(--r-surface) 84%,
var(--r-text)
);
color: var(--r-surface);
background-color: var(--r-text);
}
@media (max-width: 760px) {
.login {
&__grid {

View File

@ -4,7 +4,7 @@ import AppShareLink from '@/app-components/app/AppShareLink'
import { LOCAL_OPTIONS } from '@/app-config'
import { useI18n } from '@/hooks'
import ThemeSwitch from '@/layout/components/SiderBar/components/SettingDrawer/components/ThemeSwitch'
import { useSettingActions } from '@/store'
import { useSettingActions, useSettingGetters } from '@/store'
import { navigateHorizontalChoice } from '@ray-template/composables/element'
import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDropdown, NFlex, NTab, NTabs } from 'naive-ui'
@ -23,6 +23,7 @@ export default defineComponent({
name: 'RLogin',
setup() {
const { updateLocale } = useSettingActions()
const { getThemeStyle } = useSettingGetters()
const { t } = useI18n('views.login.index')
const tabsValue = ref('signing')
const tabsId = useId()
@ -33,6 +34,7 @@ export default defineComponent({
return {
updateLocale,
getThemeStyle,
tabsValue,
tabsId,
copyright: __APP_CFG__.layout.copyright,
@ -43,7 +45,7 @@ export default defineComponent({
const copy = (key: string) => $t(`views.login.index.${key}`)
return (
<main class="login">
<main class={['login', `login--${this.getThemeStyle}`]}>
<header class="login__header">
<div class="login__brand">
<RIcon name="logo/ray" size={36} />

View File

@ -26,7 +26,7 @@
margin-block: 16px;
padding: 12px;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-radius);
summary {
cursor: pointer;
@ -75,7 +75,7 @@
max-height: 480px;
overflow: auto;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-radius);
li {
display: grid;

View File

@ -108,6 +108,30 @@
flex: none;
min-block-size: auto;
}
&--compact > .r-page-header {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 6px 10px;
.r-page-header__copy {
display: contents;
}
.r-page-header__eyebrow {
display: none;
}
.r-page-header__actions {
grid-area: 1 / 2;
gap: 6px;
}
.r-page-header__description {
grid-column: 1 / -1;
margin: 0;
}
}
&__identity {
display: grid;
gap: 4px;
@ -137,7 +161,7 @@
padding: 12px 16px;
background: var(--r-surface);
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: var(--r-radius);
}
}
.user-management__modal.n-card {

View File

@ -44,6 +44,8 @@ import type { DataTableColumn, DataTableColumns, TreeOption } from 'naive-ui'
import { useUserErrorMessage } from './error-message'
import UserEditor from './UserEditor'
const contractUrl = `${import.meta.env.BASE_URL}contracts/admin-api.json`
export default defineComponent({
name: 'UserManagement',
setup() {
@ -113,47 +115,50 @@ export default defineComponent({
void loadOptions()
const departmentLabel = (id: string) => {
const department = options.value?.departments.find(
(item) => item.id === id,
const organization = computed(() => {
const departments = options.value?.departments ?? []
const byId = new Map(
departments.map(({ id, name, labelKey }) => [
id,
{
key: id,
label: labelKey ? translate(labelKey) : name,
children: [] as TreeOption[],
},
]),
)
const root = {
key: '',
label: t('allUsers'),
children: [] as TreeOption[],
}
const expandedKeys = ['']
return department?.labelKey
? translate(department.labelKey)
: (department?.name ?? (id || t('allUsers')))
}
for (const { id, parentId } of departments) {
// 接口契约保证父节点存在;先建索引以支持子节点排在父节点之前。
const parent = parentId === null ? root : byId.get(parentId)!
if (parentId !== null && !parent.children.length)
expandedKeys.push(parentId)
parent.children.push(byId.get(id)!)
}
return { byId, tree: [root], expandedKeys }
})
const departmentLabel = (id: string) =>
organization.value.byId.get(id)?.label ?? (id || t('allUsers'))
const roleLabel = (value: string) => {
const role = options.value?.roles.find((item) => item.value === value)
return role?.labelKey ? translate(role.labelKey) : (role?.label ?? value)
}
const tree = computed(() => {
const visit = (parentId: string | null): TreeOption[] =>
(options.value?.departments ?? [])
.filter((item) => item.parentId === parentId)
.map((item) => ({
key: item.id,
label: departmentLabel(item.id),
children: visit(item.id),
}))
return [{ key: '', label: t('allUsers'), children: visit(null) }]
})
const renderOrganizationTree = () => (
<NTree
data={tree.value}
data={organization.value.tree}
blockLine
indent={12}
defaultExpandedKeys={[
'',
...(options.value?.departments ?? [])
.filter((item) =>
options.value?.departments.some(
(child) => child.parentId === item.id,
),
)
.map((item) => item.id),
]}
defaultExpandedKeys={organization.value.expandedKeys}
selectedKeys={[departmentId.value]}
onUpdateSelectedKeys={(keys) => {
departmentId.value = String(keys[0] ?? '')
@ -453,6 +458,10 @@ export default defineComponent({
}),
})
const canReset = computed(
() => apiMockEnabled && hasPermission('users:reset'),
)
return () => (
<section
ref={pageElement}
@ -468,7 +477,11 @@ export default defineComponent({
eyebrow="WORKSPACE / USERS"
title={t('title')}
description={t(
apiMockEnabled ? 'descriptionMock' : 'descriptionServer',
apiMockEnabled
? compact.value
? 'descriptionMockCompact'
: 'descriptionMock'
: 'descriptionServer',
)}
>
{hasPermission('users:create') && (
@ -482,22 +495,50 @@ export default defineComponent({
<RIcon name="action/add" /> {t('createUser')}
</NButton>
)}
{apiMockEnabled && hasPermission('users:reset') && (
<NButton secondary disabled={busy.value} onClick={reset}>
{t('reset')}
</NButton>
{compact.value ? (
<NDropdown
trigger="click"
options={[
...(canReset.value
? [{ key: 'reset', label: t('reset'), disabled: busy.value }]
: []),
{ key: 'contract', label: t('apiContract') },
]}
onSelect={(key) => {
if (key === 'contract')
window.open(contractUrl, '_blank', 'noopener,noreferrer')
else if (key === 'reset' && canReset.value && !busy.value)
reset()
}}
>
<NButton
secondary
aria-label={translate('appComponents.moreActions')}
aria-haspopup="menu"
>
<RIcon name="action/more" aria-hidden="true" />
</NButton>
</NDropdown>
) : (
<>
{canReset.value && (
<NButton secondary disabled={busy.value} onClick={reset}>
{t('reset')}
</NButton>
)}
<NButton
tag="a"
{...{
href: contractUrl,
target: '_blank',
rel: 'noreferrer',
}}
secondary
>
{t('apiContract')}
</NButton>
</>
)}
<NButton
tag="a"
{...{
href: `${import.meta.env.BASE_URL}contracts/admin-api.json`,
target: '_blank',
rel: 'noreferrer',
}}
secondary
>
{t('apiContract')}
</NButton>
</AppPageHeader>
<NSpin show={optionLoading.value}>
{optionError.value ? (

View File

@ -4,12 +4,12 @@
Switch styles under **Preferences → Appearance → Interface style**. Style is independent of light, dark, and system mode. Changes apply immediately, survive refresh, and are included in preference import and export.
| Style | Appearance |
| ---------------- | --------------------------------------------------------------------------------- |
| Naive UI default | Uses the component library's native tokens. |
| Modern | The default style. Ray blue, subdued backgrounds, moderate radii, and whitespace. |
| Material | Purple tones, larger radii, pill-shaped buttons, and layered surfaces. |
| Plain | Neutral gray, small radii, and flat surfaces. |
| Style | Appearance |
| ---------------- | ---------------------------------------------------------------------------------------------- |
| Naive UI default | Native control shapes and spacing, with an accessible green accent and clearer field outlines. |
| Modern | The default style. Ray blue, subdued backgrounds, moderate radii, and whitespace. |
| Material | Purple tones, larger radii, pill-shaped buttons, and layered surfaces. |
| Plain | Neutral gray, small radii, and flat surfaces. |
A manually selected primary color takes precedence over a preset and is retained when switching styles. Use **Use preset color** to restore the active preset's color. In light mode, solid buttons use white text and darken a custom button color as needed for readability. In dark mode, they choose black or white text based on the resolved fill. A translucent fill is composited over the current card background. New users, restored defaults, and legacy settings without a style use Modern. An explicitly chosen style survives refresh and import.

View File

@ -68,7 +68,7 @@ pnpm fullstack:setup --external
pnpm dev:full
```
`--external` skips starting Docker services and still runs migrations and initialization. It preserves an existing `apps/server/.env.local`. Process variables take precedence. Use a database dedicated to the project, since migration and initialization create or update its schema and data. Manage external services through their own deployment environment.
`--external` skips starting Docker services and still runs migrations and initialization. Setup checks the Redis connection before PostgreSQL migrations. To switch from Compose, supply both connection URLs. Setup saves them and the external service mode in `apps/server/.env.local`, preserving administrator credentials and the signing key. When already using external services, run `setup --external` with a new `DATABASE_URL` or `REDIS_URL` to change just that connection. Setup saves the supplied addresses for future shells and reuses the saved value for any omitted address. Use a database dedicated to the project, since migration and initialization create or update its schema and data. Manage external services through their own deployment environment.
### Create a real sign-in account {#创建真实登录账号}
@ -102,7 +102,7 @@ node scripts/fullstack.mjs up
The command creates private configuration, builds Admin and the API, starts PostgreSQL and Redis, applies migrations and initialization, and prints the local entry point after readiness. The host can build without preinstalled frontend dependencies. The default address is `http://127.0.0.1:8080/ray-template/`. Change it with `APP_PORT`. Stop services with `node scripts/fullstack.mjs stop` to keep the data volumes. For several isolated instances, assign each a distinct `RAY_COMPOSE_PROJECT`, host port, and `APP_PROXY_NETWORK`.
Nginx proxies same-origin `/api/` to the backend. The host port listens on loopback by default. Production disables demo features unless `APP_DEMO_ENABLED=true`. For an external HTTPS entry point, set `APP_ORIGINS` to the actual browser origin and `APP_SESSION_COOKIE_SECURE=true`, and serve `/ray-template/` and `/api/` on the same origin. The example Nginx overwrites forwarded headers. With an outer proxy, configure Nginx real IP to trust only the immediately upstream proxy and check that client-supplied forwarding headers cannot falsify the rate-limit address. If proxy subnets conflict, change `APP_PROXY_NETWORK`, for example to `172.30.68`. For containers using external data services, set correctly encoded `APP_DATABASE_URL` and `APP_REDIS_URL`. For local development with existing services, use `setup --external`.
Nginx proxies same-origin `/api/` to the backend. The host port listens on loopback by default. Production disables demo features unless `APP_DEMO_ENABLED=true`. For an external HTTPS entry point, set `APP_ORIGINS` to the actual browser origin and `APP_SESSION_COOKIE_SECURE=true`, and serve `/ray-template/` and `/api/` on the same origin. The example Nginx overwrites forwarded headers. With an outer proxy, configure Nginx real IP to trust only the immediately upstream proxy and check that client-supplied forwarding headers cannot falsify the rate-limit address. If proxy subnets conflict, change `APP_PROXY_NETWORK`, for example to `172.30.68`. For containers using external data services, set correctly encoded `APP_DATABASE_URL` and `APP_REDIS_URL`. Give each project a distinct `REDIS_KEY_PREFIX` when sharing an external Redis instance. For local development with existing services, use `setup --external`.
### Deployment verification for operators and agents {#给部署者和-ai-的验收清单}

View File

@ -43,6 +43,8 @@ Under **Preferences → Appearance → Interface display**, enable pill-shaped p
### Page tabs and breadcrumbs {#页面标签与面包屑}
- The first keyboard control skips navigation and focuses the main content. On desktop, focus a breadcrumb with a chevron and press Enter or Down to open its menu. Use the arrow keys and Enter to choose a page.
- If an editor asks whether to discard changes, choosing to stay preserves all affected tabs and their saved state. Closing the final tab with the keyboard moves focus to the tab actions button.
- Right-click a tab or open its actions menu to move it to the front or protect it. Moving a tab to the front places it at the left edge. Undoing this moves it to the start of the regular tab group. Protected tabs show a pin next to the title, hide the close button, and are protected from individual and bulk closing.
- Drag a tab, or focus it and use Shift + Left or Shift + Right to reorder it. While dragging, a preview follows the pointer and an insertion line marks the drop location. On touch screens, swipe the tab bar to scroll, or hold a tab and drag to reorder. Tabs promoted to the front and regular tabs reorder within their own groups. Order, promotion, and protection survive refresh within the current session.
- Breadcrumbs use the menu icons, including grouped SVG names and image VNodes on code-defined routes. The fallback is an outlined window icon. Narrow screens show the current path item and its icon.
@ -75,6 +77,6 @@ Place shared state by responsibility in `apps/admin/src/store/modules` and expos
## Recent pages and favorites {#最近访问和收藏}
Press Ctrl or Command + K on desktop to open search. Search by page name and click a star to add a favorite. With an empty query, it shows favorites and recent pages. Use the arrow keys, Enter, or Tab to operate it. Entries are scoped to the session user ID and restored on refresh. Clearing history keeps favorites. You can also clear the current account's recent pages after confirmation in **Preferences → General**. The cache stores only menu paths. Display resolves them against the current menus, permissions, and translations. On mobile, use the top bar's search button. The navigation drawer has a Close button. A width change preserves the desktop sidebar's collapse preference.
Press Ctrl or Command + K on desktop to open search. Search by page name and click a star to add a favorite. With an empty query, it shows favorites and recent pages. While the search field has focus, the highlighted result opens with Enter. Use the arrow keys to focus another result, or Tab to reach its favorite button. Entries are scoped to the session user ID and restored on refresh. Clearing history keeps favorites. You can also clear the current account's recent pages after confirmation in **Preferences → General**. The cache stores only menu paths. Display resolves them against the current menus, permissions, and translations. On mobile, use the top bar's search button. The navigation drawer has a Close button. A width change preserves the desktop sidebar's collapse preference.
When content should fill the workspace, reuse `--layout-content-height`, `RTablePro autoHeight`, and `--r-table-height`, or Naive UI's `NCard contentScrollable` or `NScrollbar`. Give the parent a definite height. Flex and grid children can use `min-block-size: 0` before hosting internal scrolling. The User Management page scrolls the left and right panels independently on desktop. At narrow widths, the page scrolls vertically, the organization tree has a height limit, and the table retains its own horizontal scrolling.

View File

@ -38,7 +38,7 @@ export function loadOrders(
}
```
The default canceler identifies duplicate requests by URL, method, query, and body. It compares the encoded parameter sequence for `URLSearchParams` and the ordered fields, text values, and file instances for `FormData`. The default layout cancels managed requests before the route updates. Callers that supply `signal` or set `cancelConfig.cancel: false` manage cancellation themselves. In the example above, TablePro owns the signal.
The default canceler identifies duplicate requests by URL, method, query, and body. It compares the encoded parameter sequence for `URLSearchParams` and the ordered fields, text values, and file instances for `FormData`. Raw files, blobs, buffers, typed-array views, and readable streams are identified by instance. Resending the same instance cancels its earlier pending request. The default layout cancels managed requests before the route updates. Callers that supply `signal` or set `cancelConfig.cancel: false` manage cancellation themselves. In the example above, TablePro owns the signal.
## Configuration and interceptors {#配置与拦截器}

View File

@ -9,6 +9,8 @@
| `pnpm harness context` | List task areas. Add `routing`, `table-pro`, or `docs` for implementation and verification pointers. |
| `pnpm harness verify table-pro` | Run targeted tests or project checks for the selected scope. |
| `pnpm harness verify all` | Run full checks and write a local report for integration risk or releases. |
| `pnpm test:<suite>` | Run a Vitest suite, such as `pnpm test:hooks`. |
| `pnpm test:all` | Run the complete Vitest suite once. |
| `pnpm typecheck` | Validate the icon manifest and check types for the application, Node configuration, and tests. |
| `pnpm dev-build` / `pnpm report` | Create a development build or static bundle report. |
| `pnpm build` / `pnpm preview` | Build and preview the admin artifact locally. |
@ -20,6 +22,10 @@
For routine changes, run the relevant test files or `pnpm harness verify <scope>`, then add formatting, ESLint, and type checks as the diff requires. Wording, comment, and maintainer documentation edits can use source review and formatting checks. Run `pnpm harness check` when indexes change. Run full checks once near completion for integration risk such as dependencies, public exports, or build configuration, or when a release or explicit request calls for them. Pages builds independently. The full local entry point is `pnpm check`.
The root `package.json` exposes a command for each suite directory under `__test__`. `pnpm test:utils` runs the utility suites together. Use `pnpm test:run <file>` to run an individual test file.
`pnpm lint` checks the entire workspace. Run `pnpm lint:fix <file> [...]` with individual code file paths to apply fixes. The fixer replaces reads of the built-in runtime `undefined` with `void 0` and keeps `undefined` in type positions. Use `pnpm exec prettier --check <file>` to check Markdown and JSON formatting.
Full checks cover the environment, Harness, API and package boundaries, icon synchronization, types, ESLint, Prettier, Vitest, and both admin and docs builds. `pnpm harness verify` with no scope still runs the full suite. Specify a scope for routine work. Harness saves command results in `.harness-local/runs/`. Browser acceptance runs separately from these commands.
Record browser checks for the affected behavior. Exercise the relevant page for interaction changes, add desktop and narrow widths for layout changes, check light and dark themes for color changes, and check both English and Chinese for copy or localization changes. For shared functionality, choose representative consumers with different usage. Logic, maintainer notes, and prose-only reader documentation can be verified without a browser. Once a check passes, rerun it only if a later change affects it.

View File

@ -22,15 +22,16 @@ export const renderReport = (url: string) => (
)
```
| Prop | Default | Description |
| ------------------------------------ | -------- | ------------------------------------------------------------------------------ |
| `src` | Required | iframe URL. If it comes from user input, enforce application-approved origins. |
| `width` / `height` | `'100%'` | CSS dimensions. Percentage heights depend on the parent. |
| `frameborder` | `0` | Template border style value. |
| `iframeWrapperClass` / `iframeClass` | None | Classes for the wrapper and native iframe. |
| `title` / `name` / `allow` | None | Native iframe attributes. Provide `title` for assistive technology. |
| `lazy` | `true` | `true` or `'lazy'` defers loading. `false` or `'eager'` loads eagerly. |
| `customSpinProps` | `{}` | NSpin configuration. Internal state controls `show`. |
| Prop | Default | Description |
| ------------------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `src` | Required | iframe URL. If it comes from user input, enforce application-approved origins. |
| `width` / `height` | `'100%'` | CSS dimensions. Percentage heights depend on the parent. |
| `frameborder` | `0` | Template border style value. |
| `iframeWrapperClass` / `iframeClass` | None | Classes for the wrapper and native iframe. |
| `title` / `name` / `allow` | None | Native iframe attributes. Provide `title` for assistive technology. |
| `sandbox` / `referrerpolicy` | None | Pass native embedding restrictions and referrer policy to the iframe. An empty sandbox string applies every sandbox restriction. |
| `lazy` | `true` | `true` or `'lazy'` defers loading. `false` or `'eager'` loads eagerly. |
| `customSpinProps` | `{}` | NSpin configuration. Internal state controls `show`. |
`onSuccess(iframe, event)` and `onError(event)` accept a callback or array. Each `src` change shows the spinner until `load` or `error`. The component ref exposes the native element as `iframe` and its compatibility alias `iframeInst`, both `null` before mounting. Vue already unwraps them. Additional slots go to Spin, and the iframe remains the default content.

View File

@ -33,6 +33,8 @@ The icon library copies TSX by default, such as `<RIcon name="action/search" />`
Production builds generate a separate hashed sprite per top-level group, loaded under the deployment base. Replace bare names in old source. Cached bare names are migrated only if the filename is unique.
An independent host loads each standalone SVG on demand by name and reuses it. The admin supplies its grouped sprites through `iconUrl`.
[Icon workflow and group map](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/icons/src/A_README.md)
## RIcon API

View File

@ -1,6 +1,6 @@
# Documentation and Source Versions {#文档与源码版本}
This site covers **Ray Template 6.0.2**. Ray Admin, the runnable examples, and the shared packages live in the same repository. Inline examples use workspace source at build time. Release builds pin source links to the corresponding commit.
This site covers **Ray Template 6.0.3**. Ray Admin, the runnable examples, and the shared packages live in the same repository. Inline examples use workspace source at build time. Release builds pin source links to the corresponding commit.
| Version | Source and documentation |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

View File

@ -54,6 +54,7 @@ const renderRemote = () => (
- Submitting search returns to page 1. Pass external filters in `params`, or use `submit(values)` from the `filters` slot for a custom form. Map sort and filter events into `params` for server-side processing.
- The default is 10 rows per page. Set `pageSize` or `pagination.pageSizes`, or disable pagination with `pagination={false}`. Disabling omits pagination fields. `bare pagination` enables only pagination on a bare table.
- Set the initial page with `pagination.defaultPage`. With `request`, TablePro owns the page, page size, and total. To manage remote data yourself, use `remote + data + pagination` and handle filter scope changes. In controlled mode, update the page and size in their callbacks. Search reset and instance actions invoke the corresponding callbacks.
- Replacing `params` with equivalent filters preserves the current page. Changing a filter value, including a nested reactive value, starts a new query on page one.
## Advanced search {#高级搜索}
@ -110,7 +111,7 @@ Use `defaultCollapsed`, `collapsedRows`, `maxColumns`, and field `span` for layo
Extend the table with `title`, `toolbar`, `tableFooter`, or `tableAction`. Use `error` for custom error content.
The toolbar separates application actions from built-in tools. In `request` mode it offers Refresh. Column settings, Copy table image, and fullscreen are direct actions. **More actions** contains density, striped rows, border, and CSV. Stripe and border icons remain visible, with a separate selection mark on the right. Density items use text and a selection mark. The default `size` is `medium` (Standard), shared by the menu and table. `small` selects Compact and `large` selects Comfortable. Use `showPrint` to add Print table. `tool={false}` hides built-in tools and retains the custom `toolbar` slot.
The toolbar separates application actions from built-in tools. In `request` mode it offers Refresh. Column settings and fullscreen are direct actions. Panels narrower than 600px place Copy table image in **More actions**. **More actions** contains density, striped rows, border, and CSV. Stripe and border icons remain visible, with a separate selection mark on the right. Density items use text and a selection mark. The default `size` is `medium` (Standard), shared by the menu and table. `small` selects Compact and `large` selects Comfortable. Use `showPrint` to add Print table. `tool={false}` hides built-in tools and retains the custom `toolbar` slot.
### `useTablePro`

View File

@ -4,12 +4,12 @@
在「偏好设置 → 外观 → 界面风格」切换。风格与浅色、深色、跟随系统独立;切换即时生效,刷新和偏好导入导出会保留选择。
| 风格 | 外观 |
| ------------- | -------------------------------------------- |
| Naive UI 默认 | 使用组件库原生 token |
| 现代化 | 默认风格:Ray 蓝、低饱和底色、适度圆角和留白 |
| Material | 紫色调、较大的圆角、胶囊按钮和分层表面 |
| 朴素 | 中性灰、小圆角和无阴影表面 |
| 风格 | 外观 |
| ------------- | -------------------------------------------------------- |
| Naive UI 默认 | 保留原生控件的形状和间距,使用更清晰的绿色主色和输入边框 |
| 现代化 | 默认风格:Ray 蓝、低饱和底色、适度圆角和留白 |
| Material | 紫色调、较大的圆角、胶囊按钮和分层表面 |
| 朴素 | 中性灰、小圆角和无阴影表面 |
手动选择的主题色优先于预设,并随风格保留。点击「使用风格默认色」可恢复当前风格的配色。浅色模式下,自定义主色的实心按钮使用白字,主题会适度加深过浅的按钮色以保持可读性。深色模式按实际填充色选择黑字或白字。半透明主色按当前主题卡片底色合成。新用户、恢复默认设置和缺少风格的历史配置都使用现代化。已有的显式风格选择会在刷新和导入时保留。

View File

@ -68,7 +68,7 @@ pnpm fullstack:setup --external
pnpm dev:full
```
`--external` 跳过 Docker 服务启动,仍执行迁移和初始化。已有 `apps/server/.env.local` 时保留该文件,进程环境优先。应使用为本项目准备的数据库;迁移和初始化会创建或更新本项目的数据结构。停止外部数据服务由其部署环境负责。
`--external` 跳过 Docker 服务启动,仍执行迁移和初始化。启动器先使用实际连接验证 Redis,再执行 PostgreSQL 迁移。从 Compose 切换时,须同时提供两条连接地址;启动器将连接和服务模式保存到 `apps/server/.env.local`,保留原有管理员凭据和签名密钥。已使用外部服务时,重新执行 `setup --external` 可以单独传入新的 `DATABASE_URL` 或 `REDIS_URL`。启动器保存新地址,未提供的地址沿用文件中的值,后续终端可以直接启动。应使用为本项目准备的数据库;迁移和初始化会创建或更新本项目的数据结构。停止外部数据服务由其部署环境负责。
### 创建真实登录账号
@ -102,7 +102,7 @@ node scripts/fullstack.mjs up
此命令创建私有配置、构建 Admin 和 API、启动 PostgreSQL 与 Redis、执行迁移和初始化,等服务就绪后打印本机入口。宿主机无需预先安装前端依赖。默认入口为 `http://127.0.0.1:8080/ray-template/`,可通过 `APP_PORT` 改端口。使用 `node scripts/fullstack.mjs stop` 停止服务,数据卷保留。多个隔离实例要为每份配置指定不同的 `RAY_COMPOSE_PROJECT`、宿主机端口和 `APP_PROXY_NETWORK`。
Nginx 将同源 `/api/` 转发给后端。默认只在回环地址暴露宿主机端口,生产模式关闭演示(可用 `APP_DEMO_ENABLED=true` 显式开启)。外部 HTTPS 入口设置 `APP_ORIGINS` 为实际浏览器来源、`APP_SESSION_COOKIE_SECURE=true`,保留同源的 `/ray-template/` 和 `/api/`。示例 Nginx 会覆盖转发头;如再接外层反代,应在 Nginx 的 real IP 设置中只信任实际上一跳,并验证转发头无法伪造限流地址。代理网段冲突时,修改 `APP_PROXY_NETWORK`(例如 `172.30.68`)。容器连接外部数据库或 Redis 时,用正确编码的 `APP_DATABASE_URL`、`APP_REDIS_URL` 指定目标;已有服务的本机开发走 `setup --external`。
Nginx 将同源 `/api/` 转发给后端。默认只在回环地址暴露宿主机端口,生产模式关闭演示(可用 `APP_DEMO_ENABLED=true` 显式开启)。外部 HTTPS 入口设置 `APP_ORIGINS` 为实际浏览器来源、`APP_SESSION_COOKIE_SECURE=true`,保留同源的 `/ray-template/` 和 `/api/`。示例 Nginx 会覆盖转发头;如再接外层反代,应在 Nginx 的 real IP 设置中只信任实际上一跳,并验证转发头无法伪造限流地址。代理网段冲突时,修改 `APP_PROXY_NETWORK`(例如 `172.30.68`)。容器连接外部数据库或 Redis 时,用正确编码的 `APP_DATABASE_URL`、`APP_REDIS_URL` 指定目标;多个项目使用同一个外部 Redis 时,为每个项目设置不同的 `REDIS_KEY_PREFIX`。已有服务的本机开发走 `setup --external`。
### 给部署者和 AI 的验收清单

View File

@ -43,6 +43,8 @@ updateSettingState('layoutConfig', {
### 页面标签与面包屑
- 键盘聚焦到布局的第一个控件时,可跳至主内容。桌面端聚焦带箭头的面包屑,按回车或 ↓ 打开菜单,再用方向键和回车选择页面。
- 若编辑器提示放弃更改,选择继续编辑会保留相关标签及其缓存。用键盘关闭最后一个标签后,焦点回到「标签页操作」。
- 右键点击标签或打开右侧「标签页操作」菜单,可置顶或固定标签。置顶将标签移至最左侧,取消置顶时移到普通标签组开头。固定后,标题左侧显示图钉,关闭按钮隐藏,标签受单个关闭和批量关闭保护。
- 直接拖动标签,或聚焦标签后按 Shift + ← 或 Shift + → 即可排序。拖动时标签副本跟随指针,插入线指示落点。触屏上滑动标签栏可滚动,按住标签再拖动可排序。置顶标签和普通标签各自组内排序。顺序、置顶和固定状态随当前会话刷新恢复。
- 面包屑复用菜单配置中的图标,支持 SVG 图标名和代码路由里的图片 VNode。缺少图标时使用线框窗口图标。窄屏显示当前路径项及其图标。
@ -75,6 +77,6 @@ updateSettingState('layoutConfig', {
## 最近访问和收藏
桌面搜索支持 Ctrl/Command + K。输入页面名称查找,点击星标收藏;空关键词时显示收藏与最近访问,方向键、回车和 Tab 可操作。记录按会话用户 id 隔离,刷新后恢复;清空记录保留收藏,也可在「偏好设置 → 通用」确认后清理当前账户的最近访问。缓存只存菜单路径,展示时重新依据当前菜单和权限筛选,语言切换沿用当前翻译。手机也可通过顶栏搜索按钮查询、收藏和打开页面;导航抽屉提供关闭按钮,切换屏幕宽度保留桌面侧栏的折叠偏好。
桌面搜索支持 Ctrl/Command + K。输入页面名称查找,点击星标收藏;空关键词时显示收藏与最近访问,输入时会高亮回车将打开的页面。用方向键聚焦其他结果,或用 Tab 移至收藏按钮。记录按会话用户 id 隔离,刷新后恢复;清空记录保留收藏,也可在「偏好设置 → 通用」确认后清理当前账户的最近访问。缓存只存菜单路径,展示时重新依据当前菜单和权限筛选,语言切换沿用当前翻译。手机也可通过顶栏搜索按钮查询、收藏和打开页面;导航抽屉提供关闭按钮,切换屏幕宽度保留桌面侧栏的折叠偏好。
内容页需要撑满工作区时,先复用布局的 `--layout-content-height`、`RTablePro autoHeight` 和 `--r-table-height`,以及 Naive UI 的 `NCard contentScrollable` / `NScrollbar`。父容器提供确定高度,Flex/Grid 子项设置 `min-block-size: 0` 后再承载内部滚动;单纯填充与滚动无需新增通用组件。用户管理页在桌面左右独立滚动;窄屏改为纵向页面滚动,组织树限制高度,表格保留局部横向滚动。

View File

@ -38,7 +38,7 @@ export function loadOrders(
}
```
默认取消器按 URL、方法、参数和请求体识别重复请求。`URLSearchParams` 比较编码后的参数序列,`FormData` 比较有序字段、文本值和文件实例。默认布局在路由更新前取消受管理的请求。调用方提供 `signal` 或设置 `cancelConfig.cancel: false` 时自行管理取消;示例中的信号由 TablePro 管理。
默认取消器按 URL、方法、参数和请求体识别重复请求。`URLSearchParams` 比较编码后的参数序列,`FormData` 比较有序字段、文本值和文件实例。直接上传的文件、Blob、缓冲区、类型化数组视图或可读流按实例识别。重复发送同一实例会取消前一次仍在进行的请求。默认布局在路由更新前取消受管理的请求。调用方提供 `signal` 或设置 `cancelConfig.cancel: false` 时自行管理取消;示例中的信号由 TablePro 管理。
## 配置与拦截器

View File

@ -9,6 +9,8 @@
| `pnpm harness context` | 查任务域;追加 `routing`、`table-pro`、`docs` 等查看实现与验证 |
| `pnpm harness verify table-pro` | 按域运行定向测试或项目检查 |
| `pnpm harness verify all` | 集成风险或发布时运行全量检查并生成本地报告 |
| `pnpm test:<模块>` | 运行指定 Vitest 模块,例如 `pnpm test:hooks` |
| `pnpm test:all` | 单次运行全部 Vitest 测试 |
| `pnpm typecheck` | 验证图标清单,检查应用、Node 配置和测试类型 |
| `pnpm dev-build` / `pnpm report` | 构建开发版,或输出静态打包报告 |
| `pnpm build` / `pnpm preview` | 构建并在本机验收产物 |
@ -20,6 +22,10 @@
日常修改先运行相关测试文件或 `pnpm harness verify <scope>`,再根据改动补充格式、ESLint 和类型检查。纯措辞、注释或维护文档修正可只检查内容和格式;索引变化加 `pnpm harness check`。依赖、公共导出、构建配置等集成风险、发布或明确要求时,才在任务收尾运行一次全量检查。Pages 发布独立运行构建,本地全量检查入口仍为 `pnpm check`。
根 `package.json` 按 `__test__` 中的测试目录提供模块命令。`pnpm test:utils` 一起运行各工具测试目录。单个文件可用 `pnpm test:run <文件>` 运行。
`pnpm lint` 检查整个工作区。自动修复用 `pnpm lint:fix <文件> [...]`,逐个指定要修复的代码文件。修复会将内置 `undefined` 的运行时读取改成 `void 0`,类型位置仍使用 `undefined`。Markdown 和 JSON 的格式用 `pnpm exec prettier --check <文件>` 检查。
全量检查包含环境、Harness、API 与包边界、图标同步、类型、ESLint、Prettier、Vitest,以及后台和文档构建。`pnpm harness verify` 省略 scope 时仍执行全量,日常使用应显式指定 scope。Harness 在 `.harness-local/runs/` 写命令结果,所有命令均不启动浏览器。
浏览器验收按影响范围单独记录:交互变化只操作对应页面,布局变化增加桌面和窄屏,颜色变化增加明暗主题,文案或国际化变化核对中英文。共享能力选择有差异的代表调用方;纯逻辑、维护文档和读者文档纯措辞修正无需浏览器。检查通过后,只重跑受后续修改影响的部分,无需遍历页面、语言、主题和视口的所有组合。

View File

@ -1,6 +1,6 @@
{
"name": "@ray-template/docs",
"version": "6.0.2",
"version": "6.0.3",
"private": true,
"type": "module",
"scripts": {

View File

@ -22,15 +22,16 @@ export const renderReport = (url: string) => (
)
```
| 属性 | 默认 | 说明 |
| ------------------------------------ | -------- | ---------------------------------------------------------- |
| `src` | 必填 | iframe 地址。接收用户输入时应由业务限制可嵌入来源。 |
| `width` / `height` | `'100%'` | CSS 尺寸。百分比高度依赖父级。 |
| `frameborder` | `0` | 模板边框样式变量。 |
| `iframeWrapperClass` / `iframeClass` | 无 | 外层容器与原生 iframe 的类名。 |
| `title` / `name` / `allow` | 无 | 原生 iframe 属性。`title` 用于辅助技术识别。 |
| `lazy` | `true` | `true` / `'lazy'` 延迟加载,`false` / `'eager'` 主动加载。 |
| `customSpinProps` | `{}` | NSpin 配置,`show` 由组件内状态覆盖。 |
| 属性 | 默认 | 说明 |
| ------------------------------------ | -------- | ------------------------------------------------------------------------------ |
| `src` | 必填 | iframe 地址。接收用户输入时应由业务限制可嵌入来源。 |
| `width` / `height` | `'100%'` | CSS 尺寸。百分比高度依赖父级。 |
| `frameborder` | `0` | 模板边框样式变量。 |
| `iframeWrapperClass` / `iframeClass` | 无 | 外层容器与原生 iframe 的类名。 |
| `title` / `name` / `allow` | 无 | 原生 iframe 属性。`title` 用于辅助技术识别。 |
| `sandbox` / `referrerpolicy` | 无 | 向原生 iframe 传入嵌入限制与来源策略。空字符串 `sandbox=""` 启用全部沙箱限制。 |
| `lazy` | `true` | `true` / `'lazy'` 延迟加载,`false` / `'eager'` 主动加载。 |
| `customSpinProps` | `{}` | NSpin 配置,`show` 由组件内状态覆盖。 |
`onSuccess(iframe, event)` 和 `onError(event)` 支持函数或回调数组。每次 `src` 变化都会重新显示 Spin,在 `load` / `error` 后关闭。组件 ref 上的 `iframe` 和兼容别名 `iframeInst` 都是原生 DOM 元素(尚未挂载时为 `null`);Vue 已自动解包,无需再访问 `.value`。额外插槽交给 Spin,但默认内容始终为 iframe。

View File

@ -33,6 +33,8 @@ const renderIcon = () => <RIcon name={name} />
生产时每个顶层分包生成独立、带 hash 的雪碧图,资源随部署 base 加载。迁移时直接改旧代码的裸名称;旧缓存仅当文件名唯一时自动转换。
独立宿主使用 `RIcon` 时,会按图标名称加载并复用 SVG。管理端通过 `iconUrl` 提供分包 spritemap。
[图标流程与分包表](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/icons/src/A_README.md)
## RIcon API

View File

@ -1,6 +1,6 @@
# 文档与源码版本
本站面向 **Ray Template 6.0.2**。Ray Admin、文档示例和共享包位于同一仓库。页内示例使用构建时同一工作区的包,发布构建的源码链接指向对应提交。
本站面向 **Ray Template 6.0.3**。Ray Admin、文档示例和共享包位于同一仓库。页内示例使用构建时同一工作区的包,发布构建的源码链接指向对应提交。
| 版本 | 源码与说明 |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

View File

@ -54,6 +54,7 @@ const renderRemote = () => (
- 搜索提交回到第 1 页。外部筛选用 `params`,复杂表单可从 `filters` 插槽调用 `submit(values)`。服务端排序和过滤由调用方将事件值映射进 `params`。
- 默认每页 10 条;用 `pageSize`、`pagination.pageSizes` 调整,或传 `pagination={false}` 关闭。关闭时不添加分页字段;`bare pagination` 可单独开启分页。
- 初始页用 `pagination.defaultPage`。远端模式下组件管理当前页、每页条数和总数;调用方已有自己的远端控制时可传 `remote + data + pagination`,并自行处理范围切换。受控分页由调用方在回调中更新页码和每页条数;搜索重置和实例操作都触发对应回调。
- 等值替换 `params` 保留当前页。修改筛选值(包括嵌套的响应式字段)会从第一页重新查询。
## 高级搜索
@ -110,7 +111,7 @@ const renderRemote = () => (
扩展表格区域可用 `title`、`toolbar`、`tableFooter`、`tableAction`;错误区域用 `error` 插槽。
工具栏分为业务操作与内置工具两组。`request` 模式提供刷新,列设置、复制图片和全屏为直接入口;密度、斑马纹、边框和 CSV 收入「更多操作」。斑马纹和边框的功能图标始终显示,选中状态在文字右侧单独标记;密度子菜单只保留文字和选中标记。TablePro 的 `size` 默认是 `medium`(标准),菜单与表格共用该值;传入 `small` 或 `large` 时分别选中紧凑或宽松。打印默认不显示,设置 `showPrint` 后才加入菜单。`tool={false}` 隐藏内置工具,保留自定义 `toolbar` 插槽。
工具栏分为业务操作与内置工具两组。`request` 模式提供刷新,列设置和全屏为直接入口,表格宽度小于 600px 时复制图片移入「更多操作」;密度、斑马纹、边框和 CSV 收入「更多操作」。斑马纹和边框的功能图标始终显示,选中状态在文字右侧单独标记;密度子菜单只保留文字和选中标记。TablePro 的 `size` 默认是 `medium`(标准),菜单与表格共用该值;传入 `small` 或 `large` 时分别选中紧凑或宽松。打印默认不显示,设置 `showPrint` 后才加入菜单。`tool={false}` 隐藏内置工具,保留自定义 `toolbar` 插槽。
### `useTablePro`

View File

@ -1,6 +1,6 @@
{
"name": "@ray-template/server",
"version": "6.0.2",
"version": "6.0.3",
"private": true,
"type": "module",
"scripts": {

View File

@ -0,0 +1,29 @@
import { createClient } from 'redis'
let client
try {
const url = new URL(process.env.REDIS_URL)
if (!['redis:', 'rediss:'].includes(url.protocol) || !url.hostname)
throw new Error('Invalid Redis URL.')
client = createClient({
url: process.env.REDIS_URL,
socket: {
connectTimeout: 3000,
socketTimeout: 3000,
reconnectStrategy: false,
},
})
client.on('error', () => {})
await client.connect()
await client.ping()
} catch {
console.error(
'Redis check failed. Verify REDIS_URL, credentials and service availability before retrying setup.',
)
process.exitCode = 1
} finally {
if (client?.isOpen) client.destroy()
}

View File

@ -13,6 +13,7 @@ import {
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { after, before, test } from 'node:test'
import { parseEnv } from 'node:util'
import {
accountProfileSchema,
loginResultSchema,
@ -557,6 +558,124 @@ test('profiles are self-scoped and credential changes revoke every prior session
assert.equal(JSON.stringify(audit).includes(password), false)
})
test('external setup verifies Redis and persists the connections used for migration', async () => {
const fixture = await mkdtemp(join(tmpdir(), 'ray-external-setup-'))
const file = join(fixture, 'apps/server/.env.local')
const steps = join(fixture, 'steps')
const saved =
'# keep this comment\nRAY_FULLSTACK_SERVICES=compose\nDATABASE_URL=postgresql://localhost/previous\nREDIS_URL=redis://localhost:6379\nADMIN_USERNAME=custom_admin\n'
const env = { ...process.env }
delete env.DATABASE_URL
delete env.REDIS_URL
const setup = (overrides: NodeJS.ProcessEnv = {}) =>
spawnSync(
process.execPath,
['scripts/fullstack.mjs', 'setup', '--external'],
{
cwd: fixture,
env: { ...env, ...overrides },
encoding: 'utf8',
timeout: 20000,
},
)
try {
await mkdir(join(fixture, 'scripts'))
await mkdir(join(fixture, 'apps/server/scripts'), { recursive: true })
await copyFile(
new URL('../../../scripts/fullstack.mjs', import.meta.url),
join(fixture, 'scripts/fullstack.mjs'),
)
const probe = new URL('../scripts/check-redis.mjs', import.meta.url)
await writeFile(
join(fixture, 'apps/server/scripts/check-redis.mjs'),
`import ${JSON.stringify(probe.href)}\n`,
)
await writeFile(
join(fixture, 'migrate.mjs'),
`import { appendFileSync, readFileSync } from 'node:fs'
import { parseEnv } from 'node:util'
const saved = parseEnv(readFileSync('apps/server/.env.local', 'utf8'))
if (['DATABASE_URL', 'REDIS_URL'].some((key) => saved[key] !== process.env[key])) process.exit(1)
appendFileSync('steps', 'migrate ')
`,
)
await writeFile(
join(fixture, 'package.json'),
JSON.stringify({
private: true,
scripts: {
'server:db:migrate': 'node migrate.mjs',
'server:db:seed': `node -e "require('node:fs').appendFileSync('steps', 'seed ')"`,
},
}),
)
await writeFile(steps, '')
const targets = {
DATABASE_URL: databaseUrl.toString(),
REDIS_URL: config.redisUrl,
}
const invalid = { ...targets, REDIS_URL: 'https://invalid.example' }
assert.equal(setup(invalid).status, 1)
await assert.rejects(readFile(file), { code: 'ENOENT' })
await writeFile(file, saved, { mode: 0o600 })
assert.equal(setup({ DATABASE_URL: targets.DATABASE_URL }).status, 1)
const rejected = setup(invalid)
assert.equal(rejected.status, 1)
assert.match(rejected.stderr, /Redis check failed/)
assert.equal(await readFile(file, 'utf8'), saved)
assert.equal(await readFile(steps, 'utf8'), '')
assert.equal(setup(targets).status, 0)
const updated = await readFile(file, 'utf8')
const settings = parseEnv(updated)
assert.ok(
settings.DATABASE_URL === targets.DATABASE_URL &&
settings.REDIS_URL === targets.REDIS_URL,
)
assert.equal(settings.RAY_FULLSTACK_SERVICES, 'external')
assert.equal(settings.ADMIN_USERNAME, 'custom_admin')
assert.ok(updated.startsWith('# keep this comment\n'))
const nextDatabase = new URL(targets.DATABASE_URL)
const nextRedis = new URL(targets.REDIS_URL)
nextDatabase.searchParams.set('application_name', 'next-external-setup')
nextRedis.searchParams.set('connection', 'next-external-setup')
for (const [key, target] of [
['DATABASE_URL', nextDatabase.href],
['REDIS_URL', nextRedis.href],
]) {
const result = setup({ [key]: target })
assert.equal(result.status, 0)
assert.ok(
result.stdout.includes(`Updated apps/server/.env.local (${key}).`),
)
assert.ok(!result.stdout.includes(target))
settings[key] = target
const persisted = parseEnv(await readFile(file, 'utf8'))
assert.ok(
Object.keys(settings).every(
(name) => persisted[name] === settings[name],
),
)
}
assert.equal(setup().status, 0)
assert.equal(await readFile(steps, 'utf8'), 'migrate seed '.repeat(4))
} finally {
await rm(fixture, { force: true, recursive: true })
}
})
test('the development launcher refuses a port already serving backend readiness', async () => {
const fixture = await mkdtemp(join(tmpdir(), 'ray-launcher-'))

View File

@ -4,6 +4,7 @@ x-server-environment: &server-environment
PORT: '3000'
DATABASE_URL: ${APP_DATABASE_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-ray_template}}
REDIS_URL: ${APP_REDIS_URL:-redis://:${REDIS_PASSWORD}@redis:6379}
REDIS_KEY_PREFIX: ${REDIS_KEY_PREFIX:-ray:production}
JWT_SECRET: ${JWT_SECRET:-}
SESSION_COOKIE_SECURE: ${APP_SESSION_COOKIE_SECURE:-false}
DEMO_ENABLED: ${APP_DEMO_ENABLED:-false}

View File

@ -40,6 +40,7 @@ const env = {
POSTGRES_PORT: String(postgresPort),
REDIS_PASSWORD: randomBytes(18).toString('base64url'),
REDIS_PORT: String(redisPort),
REDIS_KEY_PREFIX: project,
ADMIN_USERNAME: 'smoke_admin',
ADMIN_EMAIL: 'smoke-admin@example.test',
ADMIN_PASSWORD: password,
@ -179,7 +180,7 @@ try {
'redis',
'redis-cli',
'GET',
`ray:production:limit:login-ip:${digest}`,
`${project}:limit:login-ip:${digest}`,
],
true,
)

View File

@ -305,3 +305,9 @@ The assembled Pages preview verified demo sign-in, session restoration, chart, f
ESLint resolves `@deprecated` declarations in TypeScript, TSX, JavaScript scripts, and Vue script blocks through the workspace TypeScript projects. The [script lint project](../tsconfig.eslint-scripts.json) includes the JavaScript tooling. It lists the hidden Prettier config and the JavaScript entry points with paired declaration files explicitly. `no-undefined` still enforces `void 0` for runtime values. [ESLint configuration](../eslint.config.mjs) · [Deprecation rule](https://typescript-eslint.io/rules/no-deprecated/)
Local lint passed. Rule probes rejected deprecated calls, property reads, option keys, and TSX props. They accepted `void 0` and TypeScript's `undefined` type. The 624 frontend tests, type checks, documentation build, and both source distribution checks passed. The full Harness stopped at the existing InteractJS package boundary errors. [Tag reordering imports](../apps/admin/src/layout/components/MenuTag/use-tag-reorder.ts)
## 2026-12-01 Scoped ESLint fixes
`pnpm lint:fix` requires individual file paths. The local `ray-template/no-undefined` rule fixes value reads of the built-in binding and preserves TypeScript type positions. Shadowing bindings and writes require a manual edit. [Rule](../scripts/eslint-rules/no-undefined.mjs) · [Fix command](../scripts/lint-fix.mjs)
Workspace lint and the toolchain Harness passed. The scoped command fixed TS, TSX, and Vue script fixtures while preserving their type annotations and an unselected sibling file. The command rejected empty input and directories before writing. [Rule regressions](../__test__/workspace/no-undefined.spec.ts)

View File

@ -4,6 +4,7 @@ import vue from 'eslint-plugin-vue'
import { defineConfig, globalIgnores } from 'eslint/config'
import globals from 'globals'
import tseslint from 'typescript-eslint'
import noUndefined from './scripts/eslint-rules/no-undefined.mjs'
import autoImports from './unplugin/.eslintrc-auto-import.json' with { type: 'json' }
export default defineConfig([
@ -30,6 +31,7 @@ export default defineConfig([
...tseslint.configs.recommended,
...vue.configs['flat/recommended'],
],
plugins: { 'ray-template': { rules: { 'no-undefined': noUndefined } } },
languageOptions: {
ecmaVersion: 'latest',
parserOptions: {
@ -53,7 +55,7 @@ export default defineConfig([
},
},
rules: {
'no-undefined': ['error'],
'ray-template/no-undefined': 'error',
'@typescript-eslint/no-deprecated': 'error',
'@typescript-eslint/no-explicit-any': [
'error',

View File

@ -67,7 +67,7 @@ For example, a CSV escaping fix can use `pnpm test:run __test__/components/table
`verify` runs steps sequentially, stops at the first failure, and returns a nonzero exit code. It prints the path to `.harness-local/runs/<run>/report.json` on completion. Reports contain commands, outcomes, durations, runtime, and signals; each invocation has a separate record. Full reports represent `pnpm check` as one step; consult that run's terminal output for phase details. Invalid arguments or context, and forcibly interrupted runs, may produce no report. None of these CLI commands launches a browser. Passing command checks does not establish UI/UX acceptance.
The Pages workflow runs `pnpm pages:build` on Ubuntu 24.04 for every push to `main`, then publishes the `dist/pages` artifact to GitHub Pages. It also supports manual dispatch on `main` and runs independently of cross-platform checks. Local full verification uses `pnpm check` according to the rules above. Use `pnpm lint`, `pnpm format:check`, or `pnpm typecheck` separately to diagnose failures. `pnpm lint:fix` and `pnpm format` rewrite files. `pnpm check` synchronizes icon manifests and generates `dist/production`. Review generated diffs before delivery.
The Pages workflow runs `pnpm pages:build` on Ubuntu 24.04 for every push to `main`, then publishes the `dist/pages` artifact to GitHub Pages. It also supports manual dispatch on `main` and runs independently of cross-platform checks. Local full verification uses `pnpm check` according to the rules above. Use `pnpm lint`, `pnpm format:check`, or `pnpm typecheck` separately to diagnose failures. Use `pnpm lint:fix <file> [...]` to fix explicitly named code files and `pnpm exec prettier --check <files>` to check formatting. `pnpm check` synchronizes icon manifests and generates `dist/production`. Review generated diffs before delivery.
### Browser verification

View File

@ -11,6 +11,10 @@ Use this topic for dependencies, public exports, aliases, auto-imports, producti
Each workspace's `package.json#exports` defines its public exports. Compare Vite, TypeScript, and Vitest resolution when changing aliases. Update generated declarations through configuration. When publishing the combined site, check both the admin and documentation bases.
Run `pnpm test:<suite>` from the root for a single suite under `__test__`, such as `pnpm test:hooks`. `pnpm test:utils` runs the utility suites together. `pnpm test:all` runs all Vitest tests once. Use `pnpm test:run <path>` for an individual test file.
`pnpm lint` checks resolved `@deprecated` usages in TypeScript, TSX, JavaScript scripts, and Vue script blocks. ESLint uses the existing workspace TypeScript projects and the [script lint project](../../tsconfig.eslint-scripts.json). Use `void 0` for runtime values and `undefined` in type annotations.
Use `pnpm lint:fix <file> [...]` for autofixes. It requires existing individual file paths, rejects directories and patterns, and processes files covered by ESLint. The [local `ray-template/no-undefined` rule](../../scripts/eslint-rules/no-undefined.mjs) fixes reads of the built-in runtime value. Type positions keep `undefined`. Rename shadowing bindings by hand. Markdown and JSON are covered by Prettier. The commit hook runs the same lint fixer for staged code.
Targeted verification: `pnpm harness verify toolchain` runs package-boundary and type checks. For changes to dependencies, public exports, or build configuration, run `pnpm harness verify all` once at completion using the [verification scope](../README.md#choosing-the-verification-scope). Preview affected entry points when build artifacts or deployment paths change. Toolchain prose alone does not trigger these runtime checks. Passing targeted checks does not prove CI, Docker, or production publication succeeded.

View File

@ -73,7 +73,11 @@
"toolchain": {
"description": "Workspaces, public exports, type checking, Vite, builds, and CI",
"checks": ["packages:check", "typecheck"],
"tests": ["__test__/workspace/boundaries.spec.ts", "__test__/distribution/"]
"tests": [
"__test__/workspace/boundaries.spec.ts",
"__test__/workspace/no-undefined.spec.ts",
"__test__/distribution/"
]
},
"harness": {
"description": "Indexes, regression scope, verification commands, and local reports",

View File

@ -1,7 +1,7 @@
{
"name": "ray-template",
"private": true,
"version": "6.0.2",
"version": "6.0.3",
"type": "module",
"engines": {
"node": "^26.13.0",
@ -24,8 +24,28 @@
"test": "vitest",
"test:run": "vitest run",
"test:ui": "vitest --ui",
"test:all": "pnpm test:run",
"test:app": "pnpm test:run __test__/app/",
"test:axios": "pnpm test:run __test__/axios/",
"test:basic": "pnpm test:run __test__/basic/",
"test:cache": "pnpm test:run __test__/cache/",
"test:components": "pnpm test:run __test__/components/",
"test:distribution": "pnpm test:run __test__/distribution/",
"test:dom": "pnpm test:run __test__/dom/",
"test:element": "pnpm test:run __test__/element/",
"test:harness": "pnpm test:run __test__/harness/",
"test:hooks": "pnpm test:run __test__/hooks/",
"test:icons": "pnpm test:run __test__/icons/",
"test:layout": "pnpm test:run __test__/layout/",
"test:mock": "pnpm test:run __test__/mock/",
"test:precision": "pnpm test:run __test__/precision/",
"test:router": "pnpm test:run __test__/router/",
"test:utils": "pnpm test:run __test__/basic/ __test__/cache/ __test__/dom/ __test__/element/ __test__/precision/ __test__/utils-contracts/ __test__/vue/",
"test:utils-contracts": "pnpm test:run __test__/utils-contracts/",
"test:vue": "pnpm test:run __test__/vue/",
"test:workspace": "pnpm test:run __test__/workspace/",
"lint": "eslint . --max-warnings=0",
"lint:fix": "eslint . --fix --max-warnings=0",
"lint:fix": "node scripts/lint-fix.mjs",
"format": "prettier --write .",
"format:check": "prettier --check .",
"harness": "node harness/run.mjs",
@ -54,11 +74,11 @@
"fullstack:setup": "node scripts/fullstack.mjs setup"
},
"lint-staged": {
"*.{js,mjs,cjs,ts,tsx,vue}": [
"eslint --fix --max-warnings=0 --no-warn-ignored",
"*.{js,mjs,cjs,ts,mts,tsx,vue}": [
"node scripts/lint-fix.mjs",
"prettier --write"
],
"*.{json,css,scss,html,md,yml,yaml}": [
"*.{json,jsonc,css,scss,html,md,yml,yaml}": [
"prettier --write"
]
},

View File

@ -33,9 +33,11 @@ export const AdminShell = defineComponent({
default: void 0,
},
restore: { type: Function as PropType<() => void>, default: void 0 },
skipContentLabel: { type: String, default: 'Skip to main content' },
restoreLabel: { type: String, default: 'Restore layout' },
},
setup(props, { slots }) {
const mainRef = shallowRef<HTMLElement>()
const headerRef = shallowRef<HTMLElement>()
const tagsRef = shallowRef<HTMLElement>()
const footerRef = shallowRef<HTMLElement>()
@ -129,6 +131,14 @@ export const AdminShell = defineComponent({
},
]}
>
<button
type="button"
class="r-layout-skip"
hidden={props.maximized}
onClick={() => mainRef.value?.focus()}
>
{props.skipContentLabel}
</button>
{wideHeader ? header() : null}
<NLayout
class="r-layout-full__body"
@ -167,7 +177,7 @@ export const AdminShell = defineComponent({
}}
onClick={() => props.restore?.()}
>
<RIcon name="action/fullscreen_fold" size={18} />
<RIcon name="action/restore-workspace" size={18} />
</button>
) : null}
<NLayoutContent
@ -182,7 +192,12 @@ export const AdminShell = defineComponent({
{tabs()}
</>
) : null}
<main class="r-layout-content-inner" aria-busy={props.busy}>
<main
ref={mainRef}
tabindex={-1}
class="r-layout-content-inner"
aria-busy={props.busy}
>
{slots.default?.()}
</main>
{!config.fixedFooter ? footer() : null}

View File

@ -1,3 +1,22 @@
.r-layout-skip {
position: absolute;
inset-block-start: 0;
inset-inline-start: 8px;
z-index: 5;
transform: translateY(-120%);
padding: 8px 14px;
border: 1px solid var(--r-line);
border-radius: var(--r-control-radius);
background: var(--r-surface);
color: var(--r-text);
font: inherit;
&:focus {
transform: translateY(4px);
outline: 2px solid var(--r-theme-primary-color);
}
}
.r-shell-menu [role='menuitem'][tabindex]:focus-visible {
outline: 2px solid var(--r-theme-primary-color);
outline-offset: -2px;

View File

@ -48,21 +48,27 @@ export const userOptionsSchema = v.pipe(
)
return false
const connected = new Set<string>()
return departments.every((item) => {
const seen = new Set<string>()
let current: Department | undefined = item
while (current) {
while (current && !connected.has(current.id)) {
if (seen.has(current.id)) return false
seen.add(current.id)
if (current.parentId === null) return true
if (current.parentId === null) break
current = byId.get(current.parentId)
}
return false
if (!current) return false
for (const id of seen) connected.add(id)
return true
})
}, 'Departments must form a tree with unique identifiers.'),
)

View File

@ -2,6 +2,10 @@
"name": "@ray-template/composables",
"private": true,
"type": "module",
"sideEffects": [
"./src/index.ts",
"./src/useDayjs.ts"
],
"exports": {
".": "./src/index.ts",
"./usePrint": "./src/usePrint.ts",

View File

@ -231,6 +231,7 @@
"action/link",
"action/link-off",
"action/lock",
"action/maximize-workspace",
"action/minus",
"action/more",
"action/mouse",
@ -241,6 +242,7 @@
"action/print",
"action/redo",
"action/reload",
"action/restore-workspace",
"action/save",
"action/scan",
"action/search",

View File

@ -1,5 +1,12 @@
import type { AppRawRequestConfig, CancelerParams } from './types'
const opaqueBodyTags = new Set([
'[object Blob]',
'[object File]',
'[object ArrayBuffer]',
'[object ReadableStream]',
])
/**
*
* @description
@ -27,8 +34,23 @@ import type { AppRawRequestConfig, CancelerParams } from './types'
export default class RequestCanceler {
/** 待处理请求的 Map,key 为请求标识,value 为 AbortController */
private readonly pendingRequest = new Map<string, AbortController>()
private readonly fileIds = new WeakMap<File, number>()
private nextFileId = 0
private readonly pendingKeys = new WeakMap<
NonNullable<AppRawRequestConfig['signal']>,
string
>()
private readonly bodyIds = new WeakMap<object, number>()
private nextBodyId = 0
private bodyId(value: object) {
let id = this.bodyIds.get(value)
if (id === void 0) {
id = ++this.nextBodyId
this.bodyIds.set(value, id)
}
return id
}
private serializePart(value: unknown) {
if (
@ -38,23 +60,23 @@ export default class RequestCanceler {
return ['query', value.toString()]
if (typeof FormData !== 'undefined' && value instanceof FormData) {
const entries = Array.from(value, ([key, entry]) => {
if (typeof entry === 'string') return [key, entry]
// 文件同名且尺寸相同也可能有不同内容,只将同一文件实例视为相同。
let id = this.fileIds.get(entry)
if (id === void 0) {
id = ++this.nextFileId
this.fileIds.set(entry, id)
}
return [key, id]
})
const entries = Array.from(value, ([key, entry]) => [
key,
typeof entry === 'string' ? entry : this.bodyId(entry),
])
return ['form', entries]
}
// 二进制数据和流按实例区分,避免读取内容或逐字节序列化。
if (
value !== null &&
typeof value === 'object' &&
(ArrayBuffer.isView(value) ||
opaqueBodyTags.has(Object.prototype.toString.call(value)))
)
return ['opaque', this.bodyId(value)]
return JSON.stringify(value)
}
@ -137,6 +159,7 @@ export default class RequestCanceler {
config.signal = controller.signal
this.pendingRequest.set(requestKey, controller)
this.pendingKeys.set(controller.signal, requestKey)
}
}
@ -158,25 +181,23 @@ export default class RequestCanceler {
const controller = this.pendingRequest.get(requestKey)
if (controller) {
controller.abort()
this.pendingKeys.delete(controller.signal)
this.pendingRequest.delete(requestKey)
controller.abort()
}
}
releasePendingRequest(config: AppRawRequestConfig): void {
const key = this.generateRequestKey(config)
const controller = this.pendingRequest.get(key)
const { signal } = config
// Axios 可能转换请求体。用信号识别这一条请求,避免旧响应移除新请求。
if (controller?.signal === config.signal) {
if (!signal) return
// Axios 可能转换请求体,使用最初的 signal 直接定位这次请求。
const key = this.pendingKeys.get(signal)
if (key !== void 0) {
this.pendingKeys.delete(signal)
this.pendingRequest.delete(key)
} else if (config.signal) {
for (const [pendingKey, pending] of this.pendingRequest) {
if (pending.signal === config.signal) {
this.pendingRequest.delete(pendingKey)
break
}
}
}
}
@ -199,6 +220,7 @@ export default class RequestCanceler {
*/
cancelAllRequest(): void {
this.pendingRequest.forEach((controller) => {
this.pendingKeys.delete(controller.signal)
controller.abort()
})
this.pendingRequest.clear()

View File

@ -6,7 +6,7 @@
两批图标均由 ByteDance IconPark 发布,Copyright 2019-present Bytedance Inc.,采用 Apache 2.0 许可。[IconPark 上游项目](https://github.com/bytedance/IconPark) · [许可全文](LICENSE-ICONPARK)
The `action/close_all`, `action/pin`, `action/table-striped`, and `action/table-bordered` icons are original artwork in this repository, covered by its MIT license.
The `action/maximize-workspace`, `action/restore-workspace`, `action/close_all`, `action/pin`, `action/table-striped`, and `action/table-bordered` icons are original artwork in this repository, covered by its MIT license.
品牌标识沿用仓库已有的 SVG。不要将品牌标识与这批通用线性图标的来源或许可混用。

View File

@ -5,7 +5,8 @@
"exports": {
".": "./src/index.ts",
"./manifest": "./src/manifest.ts",
"./assets": "./src/assets.ts"
"./assets": "./src/assets.ts",
"./load-asset": "./src/load-asset.ts"
},
"rayTemplate": {
"runtime": "browser"

View File

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
<rect x="2.5" y="3" width="19" height="18" rx="2" />
<path d="M7 16l9-9m-5 0h5v5" />
</svg>

After

Width:  |  Height:  |  Size: 257 B

View File

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
<rect x="2.5" y="3" width="19" height="18" rx="2" />
<path d="M16 7l-7 7m5 0H9V9" />
</svg>

After

Width:  |  Height:  |  Size: 257 B

View File

@ -1,3 +1,4 @@
import { parseIconAsset } from './parse-asset'
import type { IconName } from './manifest'
const sources = import.meta.glob<string>('./**/*.svg', {
@ -7,21 +8,5 @@ const sources = import.meta.glob<string>('./**/*.svg', {
})
export function getIconAsset(name: IconName) {
const source = sources[`./${name}.svg`]
const svg = source?.match(/<svg\b([^>]*)>([\s\S]*)<\/svg>/i)
if (!svg) return
const paint = Object.fromEntries(
Array.from(
svg[1].matchAll(/\s((?:fill|stroke)(?:-[\w-]+)?|opacity|color|style|preserveAspectRatio)\s*=\s*(["'])([\s\S]*?)\2/g),
([, name, , value]) => [name, value],
),
)
return {
viewBox: svg[1].match(/viewBox=["']([^"']+)["']/i)?.[1],
body: svg[2],
paint,
}
return parseIconAsset(sources[`./${name}.svg`])
}

View File

@ -0,0 +1,24 @@
import type { IconName } from './manifest'
import { parseIconAsset } from './parse-asset'
const sources = import.meta.glob<string>('./**/*.svg', {
query: '?raw',
import: 'default',
})
const cache = new Map<IconName, NonNullable<ReturnType<typeof parseIconAsset>>>()
export async function loadIconAsset(name: IconName) {
const cached = cache.get(name)
if (cached) return cached
const load = sources[`./${name}.svg`]
if (!load) return
const asset = parseIconAsset(await load())
if (asset) cache.set(name, asset)
return asset
}

View File

@ -30,6 +30,7 @@ export const iconNames = [
'action/link',
'action/link-off',
'action/lock',
'action/maximize-workspace',
'action/minus',
'action/more',
'action/mouse',
@ -40,6 +41,7 @@ export const iconNames = [
'action/print',
'action/redo',
'action/reload',
'action/restore-workspace',
'action/save',
'action/scan',
'action/search',

View File

@ -0,0 +1,18 @@
export function parseIconAsset(source: string | undefined) {
const svg = source?.match(/<svg\b([^>]*)>([\s\S]*)<\/svg>/i)
if (!svg) return
const paint = Object.fromEntries(
Array.from(
svg[1].matchAll(/\s((?:fill|stroke)(?:-[\w-]+)?|opacity|color|style|preserveAspectRatio)\s*=\s*(["'])([\s\S]*?)\2/g),
([, name, , value]) => [name, value],
),
)
return {
viewBox: svg[1].match(/viewBox=["']([^"']+)["']/i)?.[1],
body: svg[2],
paint,
}
}

View File

@ -320,7 +320,7 @@ export default defineComponent({
watch(
[
() => props.watchOptions && renderRequest.value !== null,
() => props.watchOptions && instance.value,
() => props.watchDeep,
() => props.watchOptionsThrottleWait,
],
@ -345,7 +345,7 @@ export default defineComponent({
update.cancel()
})
},
{ immediate: true },
{ immediate: true, flush: 'sync' },
)
watch(
theme,

View File

@ -1,7 +1,8 @@
import { computed, defineComponent, onMounted, shallowRef } from 'vue'
import { computed, defineComponent, onMounted, shallowRef, watch } from 'vue'
import './index.scss'
import { completeSize } from '@ray-template/composables/element'
import { call } from '@ray-template/composables/vue'
import type { loadIconAsset } from '@ray-template/icons/load-asset'
import { useUiServices } from '../../services'
import props from './props'
@ -11,12 +12,32 @@ export default defineComponent({
setup(props) {
const { iconUrl } = useUiServices()
const symbolId = computed(() => iconUrl?.(props.name, props.prefix))
const assets = shallowRef<typeof import('@ray-template/icons/assets')>()
const asset = computed(() => assets.value?.getIconAsset(props.name))
const asset = shallowRef<Awaited<ReturnType<typeof loadIconAsset>>>()
onMounted(async () => {
if (!iconUrl) assets.value = await import('@ray-template/icons/assets')
})
if (!iconUrl) {
onMounted(() => {
watch(
() => props.name,
async (name, _, onCleanup) => {
let active = true
onCleanup(() => {
active = false
})
asset.value = void 0
const { loadIconAsset } =
await import('@ray-template/icons/load-asset')
if (!active) return
const next = await loadIconAsset(name)
if (active) asset.value = next
},
{ immediate: true },
)
})
}
const cssVars = computed(() => {
const cssVar = {

View File

@ -75,6 +75,8 @@ export default defineComponent({
class={['r-iframe__container', this.iframeClass]}
ref="iframeRef"
src={this.src}
sandbox={this.sandbox}
referrerpolicy={this.referrerpolicy}
allow={this.allow}
name={this.name}
title={this.title}

View File

@ -44,6 +44,8 @@ const props = {
type: String,
default: null,
},
sandbox: { type: String, default: void 0 },
referrerpolicy: { type: String as PropType<ReferrerPolicy>, default: void 0 },
name: {
/** iframe 定位嵌入的浏览上下文的名称 */
type: String,

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