feat(ui): refine frontend interactions and add CURD examples

Protect route drafts and refine keyboard, responsive, and primary button behavior.

Add CURD workspace examples with tests and bilingual documentation.
This commit is contained in:
XiaoDaiGua-Ray 2026-11-27 14:51:46 +08:00
parent 474d75203c
commit d67e64d48c
No known key found for this signature in database
79 changed files with 3102 additions and 369 deletions

View File

@ -0,0 +1,45 @@
import { useMemoryCache } from '@/utils/cache-backend'
import {
createProjectDraft,
useProjects,
useTags,
} from '@/views/demo/curd/records'
import { beforeEach, describe, expect, it } from 'vitest'
describe('CURD demo records', () => {
beforeEach(useMemoryCache)
it('loads saved project milestones on a new page and removes them with the project', () => {
const projects = useProjects()
const draft = {
...createProjectDraft(),
name: 'Release review',
owner: 'Demo owner',
milestones: [
{ id: 'review', name: 'Check the release', outcome: 'Sign off' },
],
}
expect(projects.create(draft)).toBeUndefined()
const saved = useProjects()
const id = saved.rows.value.find(({ name }) => name === draft.name)!.id
expect(saved.find(id)).toMatchObject(draft)
expect(saved.update(id, { ...draft, name: 'Atlas portal' })).toBe(
'duplicate',
)
expect(useProjects().find(id)).toMatchObject(draft)
expect(saved.remove(id)).toBeUndefined()
expect(useProjects().find(id)).toBeUndefined()
expect(useProjects().update(id, draft)).toBe('missingRecord')
})
it('keeps an explicitly emptied tag list on reopen', () => {
const tags = useTags()
for (const { id } of tags.rows.value)
expect(tags.remove(id)).toBeUndefined()
expect(useTags().rows.value).toEqual([])
})
})

View File

@ -0,0 +1,60 @@
import { useRouteDraftGuard } from '@/views/route-management/use-draft-guard'
import { flushPromises, mount } from '@vue/test-utils'
import type { DialogOptions } from 'naive-ui'
import { defineComponent, h } from 'vue'
import { createMemoryHistory, createRouter, RouterView } from 'vue-router'
vi.mock('@/hooks', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
vi.mock('@/store', () => ({
useSigningGetters: () => ({ getSigningCallback: { value: { id: 'admin' } } }),
}))
it('keeps a dirty editor across a cancelled URL change and leaves after confirmation', async () => {
const warning = vi.fn((_options: DialogOptions) => ({ destroy: vi.fn() }))
vi.stubGlobal('$dialog', { warning })
const editor = defineComponent({
setup() {
useRouteDraftGuard(
() => true,
() => false,
)
return () => h('div', 'Draft editor')
},
})
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/editor', component: editor },
{ path: '/other', component: { render: () => h('div', 'Other view') } },
],
})
await router.push('/editor')
const wrapper = mount(RouterView, { global: { plugins: [router] } })
try {
const update = router.push('/editor?source=other')
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe('/editor')
warning.mock.lastCall?.[0].onAfterLeave?.()
await update
expect(router.currentRoute.value.fullPath).toBe('/editor')
const leave = router.push('/other')
await flushPromises()
const options = warning.mock.lastCall?.[0]
options?.onPositiveClick?.(new MouseEvent('click'))
options?.onAfterLeave?.()
await leave
expect(wrapper.text()).toBe('Other view')
expect(warning).toHaveBeenCalledTimes(2)
} finally {
wrapper.unmount()
vi.unstubAllGlobals()
}
})

View File

@ -44,6 +44,11 @@ it('submits the real login form with native credential fields and no demo shortc
expect(wrapper.text()).not.toMatch(/UseDemo|UseMember|UseManager/u)
await username.setValue('qa-account')
await password.setValue('qa-fixture-password')
await wrapper.get('button[aria-label="ShowPassword"]').trigger('click')
expect(password.attributes('type')).toBe('text')
expect(signing).not.toHaveBeenCalled()
await wrapper.get('button[aria-label="HidePassword"]').trigger('click')
expect(password.attributes('type')).toBe('password')
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(signing).toHaveBeenCalledExactlyOnceWith({

View File

@ -78,6 +78,28 @@ it('applies the latest measured search column count on the next frame', async ()
}
})
it('follows a measured collapse default until the user chooses a state', async () => {
const fields = [
{ key: 'name', label: 'Name' },
{ key: 'team', label: 'Team' },
]
const wrapper = mount(RTablePro, { props: { columns, search: { fields } } })
try {
const grid = wrapper.getComponent(NGrid)
expect(grid.props('collapsed')).toBe(false)
await wrapper.setProps({ search: { fields, defaultCollapsed: true } })
expect(grid.props('collapsed')).toBe(true)
await wrapper.get('button[aria-expanded="false"]').trigger('click')
await wrapper.setProps({ search: { fields, defaultCollapsed: false } })
await wrapper.setProps({ search: { fields, defaultCollapsed: true } })
expect(grid.props('collapsed')).toBe(false)
} finally {
wrapper.unmount()
}
})
it('labels compound picker triggers and both endpoints of a date range', async () => {
const fields: TableProSearchOptions['fields'] = [
{ key: 'created', type: 'dateRange', label: 'Created' },

View File

@ -271,7 +271,7 @@ it('clears even same-query rows on failure and when the request source changes',
}
})
it('shows a toast and the normal empty state without an inline alert, then allows retry', async () => {
it('shows a persistent request error with retry while preserving the ordinary empty slot', async () => {
const request = vi
.fn(async (_params: TableProParams) => response('Recovered', 1))
.mockRejectedValueOnce(new Error('offline'))
@ -299,14 +299,16 @@ it('shows a toast and the normal empty state without an inline alert, then allow
try {
await flushPromises()
expect(table.emitted('request-error')).toHaveLength(1)
expect(reportError).toHaveBeenCalledExactlyOnceWith(
"Couldn't load the data",
)
expect(reportError).not.toHaveBeenCalled()
expect(table.getComponent(NDataTable).props('pagination')).toBe(false)
expect(table.text()).toContain('Custom empty state')
expect(table.text()).not.toContain('Custom empty state')
expect(table.text()).toContain('Always visible notice')
expect(table.find('.n-alert').exists()).toBe(false)
await instance.reload()
expect(table.get('[role="alert"]').text()).toBe("Couldn't load the data")
await table
.findAll('button')
.find((item) => item.text() === 'Retry')!
.trigger('click')
await flushPromises()
expect(request.mock.calls.map(([params]) => params)).toEqual([{}, {}])
expect(table.text()).toContain('Recovered')
@ -317,6 +319,42 @@ it('shows a toast and the normal empty state without an inline alert, then allow
pageSize: null,
total: 1,
})
request.mockResolvedValueOnce({ data: [], total: 0 })
await instance.reload()
expect(table.text()).toContain('Custom empty state')
} finally {
wrapper.unmount()
}
})
it('offers a filter reset when a successful query returns no matches', async () => {
const request = vi.fn(async ({ name }: TableProParams) =>
name ? { data: [], total: 0 } : response('Member', 1),
)
const wrapper = mount(RTablePro, {
props: {
columns,
request,
pagination: false,
search: [{ key: 'name', label: 'Name' }],
},
})
const table = wrapper.vm as unknown as TableProInst
try {
await flushPromises()
table.setSearchValues({ name: 'missing' })
await table.submitSearch()
expect(wrapper.get('span[role="status"]').text()).toBe(
'No results match the filters',
)
await wrapper
.findAll('button')
.find((item) => item.text() === 'Reset filters')!
.trigger('click')
await flushPromises()
expect(request.mock.lastCall?.[0]).toEqual({})
expect(wrapper.text()).toContain('Member')
} finally {
wrapper.unmount()
}

View File

@ -86,7 +86,16 @@ it('does not navigate while composing and supports keyboard result focus and Ent
}
const menu = piniaMenuStore()
menu.options = [option('/visible', 'Visible page')]
menu.options = [
{
...option('/tables', 'Table examples'),
meta: { extra: { label: 'TablePro' } },
children: [
option('/visible', 'Visible page'),
option('/hidden', 'Hidden page', false),
],
},
]
const navigate = vi
.spyOn(menu, 'changeMenuModelValue')
.mockImplementation(() => void 0)
@ -108,8 +117,13 @@ it('does not navigate while composing and supports keyboard result focus and Ent
const input = wrapper.find('input').element as HTMLInputElement
expect(document.activeElement).toBe(input)
input.value = 'Visible'
input.dispatchEvent(new Event('input', { bubbles: true }))
await wrapper.get('input').setValue('tablepro')
await flushPromises()
expect(wrapper.findAll('.global-search__destination')).toHaveLength(1)
expect(wrapper.get('.global-search__destination').text()).toBe(
'Visible page',
)
await wrapper.get('input').setValue('Table examples')
await flushPromises()
expect(wrapper.findAll('.global-search__destination')).toHaveLength(1)
input.dispatchEvent(

View File

@ -294,7 +294,7 @@ describe('layout preferences', () => {
}
})
it('uses the contrast of each resolved button fill after importing an accent and switching modes', () => {
it('keeps light primary buttons white and resolves custom colors across modes', () => {
const pinia = createPinia()
setActivePinia(pinia)
@ -315,10 +315,18 @@ describe('layout preferences', () => {
try {
store.changePrimaryColor('#2d8cf0')
expect(store.themeOverrides.common?.primaryColor).toBe('#2d8cf0')
expect(store.themeOverrides.Button).toMatchObject({
colorPrimary: 'rgb(45, 140, 240)',
textColorPrimary: '#000',
textColorHoverPrimary: '#000',
colorPrimary: 'rgb(34, 112, 194)',
colorHoverPrimary: 'rgb(57, 121, 188)',
colorPressedPrimary: 'rgb(31, 106, 184)',
textColorPrimary: '#fff',
textColorHoverPrimary: '#fff',
textColorPressedPrimary: '#fff',
textColorFocusPrimary: '#fff',
borderPrimary: '1px solid rgb(34, 112, 194)',
textColorTextPrimary: 'rgb(34, 112, 194)',
textColorGhostPrimary: 'rgb(34, 112, 194)',
})
const primaryColor = 'hsla(0, 0%, 90%, 0.1)'
@ -342,7 +350,10 @@ describe('layout preferences', () => {
])
store.updateSettingState('appTheme', 'light')
pixels = [252, 252, 252, 255, 234, 234, 234, 255]
expect(store.themeOverrides.Button?.textColorPrimary).toBe('#000')
expect(store.themeOverrides.Button).toMatchObject({
colorPrimary: 'rgb(111, 111, 111)',
textColorPrimary: '#fff',
})
expect(paints.at(-3)).toBe('#ffffff')
store.changePrimaryColor()
expect(store.themeOverrides.Button?.textColorPrimary).toBeUndefined()

View File

@ -30,6 +30,7 @@ import type { RouteRecordRaw } from 'vue-router'
const examplePaths = new Set([
'/dashboard',
'/tables',
'/curd',
'/form',
'/modal-demo',
'/echart',
@ -135,6 +136,22 @@ async function mountExample() {
if (params.get('theme') === 'dark') darkTheme()
else lightTheme()
if (window.parent !== window && document.referrer) {
const parentOrigin = new URL(document.referrer).origin
window.addEventListener('message', ({ origin, source, data }) => {
if (
origin !== parentOrigin ||
source !== window.parent ||
data?.type !== 'ray-template:example-theme'
)
return
if (data.theme === 'dark') darkTheme()
else if (data.theme === 'light') lightTheme()
})
}
setAppRouteModules(examples)
const routes = [

View File

@ -19,6 +19,7 @@ export default defineComponent({
emits: ['update:show'],
setup(props, { emit }) {
const { t } = useI18n('navigationSearch')
const { t: translate } = useI18n()
const { changeMenuModelValue } = useMenuActions()
const { getMenuOptions } = useMenuGetters()
const { recentPaths, favoritePaths, storageUnavailable } =
@ -43,13 +44,27 @@ export default defineComponent({
},
})
const visibleLeaves = computed(() => {
const leaves: AppMenuOption[] = []
const visit = (items: AppMenuOption[]) => {
const leaves: { option: AppMenuOption; searchText: string }[] = []
const visit = (items: AppMenuOption[], trail = '') => {
for (const item of items) {
if (item.show === false) continue
if (item.children?.length) visit(item.children)
else leaves.push(item)
const badge = item.meta.extra
const badgeText =
badge?.show === false
? ''
: badge?.i18nLabel
? translate(badge.i18nLabel)
: (badge?.label ?? '')
const labels =
`${trail} ${item.breadcrumbLabel ?? ''} ${badgeText}`.trim()
if (item.children?.length) visit(item.children, labels)
else
leaves.push({
option: item,
searchText: labels.toLocaleLowerCase(),
})
}
}
@ -58,7 +73,10 @@ export default defineComponent({
return leaves
})
const menuByPath = computed(
() => new Map(visibleLeaves.value.map((item) => [item.fullPath, item])),
() =>
new Map(
visibleLeaves.value.map(({ option }) => [option.fullPath, option]),
),
)
const savedOptions = (paths: readonly string[]) =>
paths.flatMap((path) => {
@ -73,9 +91,9 @@ export default defineComponent({
return [
{
key: 'results',
options: visibleLeaves.value.filter((item) =>
item.breadcrumbLabel?.toLocaleLowerCase().includes(term),
),
options: visibleLeaves.value
.filter(({ searchText }) => searchText.includes(term))
.map(({ option }) => option),
},
]

View File

@ -1,7 +1,7 @@
import { useI18n, useTheme } from '@/hooks'
import { useSettingGetters } from '@/store'
import { RIcon } from '@ray-template/ui/icon'
import { NSwitch, NTooltip } from 'naive-ui'
import { NFlex, NSwitch } from 'naive-ui'
export default defineComponent({
name: 'ThemeSwitch',
@ -11,25 +11,21 @@ export default defineComponent({
const { lightTheme, darkTheme } = useTheme()
return () => (
<NTooltip>
{{
trigger: () => (
<NSwitch
value={getAppTheme.value}
aria-label={t('theme.darkMode')}
onUpdateValue={(dark) => (dark ? darkTheme() : lightTheme())}
>
{{
'checked-icon': () => <RIcon name="system/dark" size={14} />,
'unchecked-icon': () => <RIcon name="system/light" size={14} />,
checked: () => t('theme.dark'),
unchecked: () => t('theme.light'),
}}
</NSwitch>
),
default: () => t(getAppTheme.value ? 'theme.dark' : 'theme.light'),
}}
</NTooltip>
<NFlex align="center" wrap={false} size={6}>
<NSwitch
value={getAppTheme.value}
aria-label={t('theme.darkMode')}
onUpdateValue={(dark) => (dark ? darkTheme() : lightTheme())}
>
{{
'checked-icon': () => <RIcon name="system/dark" size={14} />,
'unchecked-icon': () => <RIcon name="system/light" size={14} />,
}}
</NSwitch>
<span aria-hidden="true">
{t(getAppTheme.value ? 'theme.dark' : 'theme.light')}
</span>
</NFlex>
)
},
})

View File

@ -10,12 +10,12 @@ import {
} from '@/store'
import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDropdown, NFlex, NLayoutHeader } from 'naive-ui'
import type { PropType } from 'vue'
import { useFullscreen } from 'vue-hooks-plus'
import {
Breadcrumb,
GlobalSearch,
GlobalSearchButton,
SettingDrawer,
TooltipIcon,
} from './components'
import {
@ -28,7 +28,10 @@ import type { IconEventMapOptions } from './type'
export default defineComponent({
name: 'AppSiderBar',
setup() {
props: {
onOpenSettings: { type: Function as PropType<() => void>, required: true },
},
setup(props) {
// 获取 setting 相关值
const { updateLocale, updateSettingState } = useSettingActions()
const { t } = useI18n()
@ -37,9 +40,7 @@ export default defineComponent({
document.getElementsByTagName('html')[0],
)
// 获取设置相关方法
const { getDrawerPlacement, getBreadcrumbSwitch } = useSettingGetters()
// 是否显示设置抽屉
const showSettings = ref(false)
const { getBreadcrumbSwitch } = useSettingGetters()
const accountMenuShown = ref(false)
const { getSigningCallback } = useSigningGetters()
// 是否展示全局搜索
@ -75,9 +76,7 @@ export default defineComponent({
search: () => {
globalSearchShown.value = true
},
setting: () => {
showSettings.value = true
},
setting: props.onOpenSettings,
github: () => {
window.open('https://github.com/XiaoDaiGua-Ray/ray-template')
},
@ -109,9 +108,7 @@ export default defineComponent({
leftIconOptions,
rightTooltipIconOptions,
toolIconClick,
showSettings,
updateLocale,
getDrawerPlacement,
getBreadcrumbSwitch,
globalSearchShown,
isTabletOrSmaller,
@ -120,12 +117,8 @@ export default defineComponent({
}
},
render() {
const {
rightTooltipIconOptions,
leftIconOptions,
getDrawerPlacement,
getBreadcrumbSwitch,
} = this
const { rightTooltipIconOptions, leftIconOptions, getBreadcrumbSwitch } =
this
const { toolIconClick, updateLocale } = this
return (
@ -191,7 +184,10 @@ export default defineComponent({
)}
{rightTooltipIconOptions.map((curr) => (
<NButton
class="override-button__layout"
class={[
'override-button__layout',
{ 'layout-header__settings': curr.eventKey === 'setting' },
]}
quaternary
size="medium"
key={curr.eventKey ?? curr.name}
@ -273,10 +269,6 @@ export default defineComponent({
</NDropdown>
</NFlex>
</NFlex>
<SettingDrawer
v-model:show={this.showSettings}
placement={getDrawerPlacement}
/>
</NLayoutHeader>
)
},

View File

@ -1,15 +1,16 @@
import SiderBar from '@/layout/components/SiderBar'
import { NFlex } from 'naive-ui'
import type { PropType } from 'vue'
export default defineComponent({
name: 'LayoutHeaderWrapper',
setup() {
return {}
props: {
onOpenSettings: { type: Function as PropType<() => void>, required: true },
},
render() {
return (
<NFlex size={[0, 0]}>
<SiderBar />
<SiderBar onOpenSettings={this.onOpenSettings} />
</NFlex>
)
},

View File

@ -6,6 +6,7 @@ import { useDevice, useI18n, useMaximize } from '@/hooks'
import { useMenuGetters, useRuntimeGetters, useSettingGetters } from '@/store'
import { AdminShell } from '@ray-template/admin-shell'
import Menu from './components/Menu'
import SettingDrawer from './components/SiderBar/components/SettingDrawer'
import TopNavigation from './components/TopNavigation'
import {
ContentWrapper,
@ -18,9 +19,14 @@ import { findMenuRoot } from './navigation'
export default defineComponent({
name: 'RLayout',
setup(_, { slots }) {
const { getMenuTagSwitch, getCopyrightSwitch, getLayoutConfig } =
useSettingGetters()
inheritAttrs: false,
setup(_, { attrs, slots }) {
const {
getMenuTagSwitch,
getCopyrightSwitch,
getLayoutConfig,
getDrawerPlacement,
} = useSettingGetters()
const { getMenuOptions, getMenuKey } = useMenuGetters()
const {
globalMainLayoutLoad,
@ -32,6 +38,24 @@ export default defineComponent({
const { t } = useI18n('layout')
const { isTabletOrSmaller } = useDevice()
const { getLockAppScreen } = useAppLockScreen()
const locked = computed(() => apiMockEnabled && getLockAppScreen())
const settingsShown = ref(false)
const shell = useTemplateRef<InstanceType<typeof AdminShell>>('shell')
const openSettings = () => {
settingsShown.value = true
}
const restoreSettingsFocus = () => {
const root = shell.value?.$el
if (root instanceof HTMLElement)
root
.querySelector<HTMLButtonElement>('.layout-header__settings')
?.focus({ preventScroll: true })
}
watch(locked, (value) => {
if (value) settingsShown.value = false
})
const mode = computed(() =>
isTabletOrSmaller.value ? 'side' : getLayoutConfig.value.mode,
)
@ -44,52 +68,63 @@ export default defineComponent({
)
return () => {
if (apiMockEnabled && getLockAppScreen()) return <UnlockScreen />
if (locked.value) return <UnlockScreen {...attrs} />
const grouped = mode.value === 'mixed' || mode.value === 'split'
return (
<AdminShell
layout={getLayoutConfig.value}
mode={mode.value}
groupedSidebar={mixedChildren.value.length > 0}
showTabs={getMenuTagSwitch.value}
showFooter={getCopyrightSwitch.value}
busy={
!slots.default &&
(!globalMainLayoutLoad.value || layoutContentSpinning.value)
}
maximized={layoutContentMaximize.value}
maximizedStyle={layoutContentMaximizeStyle.value}
contentRef={LAYOUT_CONTENT_REF}
restore={() => maximize(false)}
restoreLabel={t('restore')}
>
{{
header:
slots.header ??
(() => (
<>
<HeaderWrapper />
{mode.value === 'top' || grouped ? <TopNavigation /> : null}
</>
)),
sidebar:
slots.sidebar ??
(() => (
<Menu
options={grouped ? mixedChildren.value : void 0}
showLogo={!grouped}
end={mode.value === 'right'}
inert={layoutContentMaximize.value}
/>
)),
tabs: slots.tabs ?? (() => <FeatureWrapper />),
footer: slots.footer ?? (() => <FooterWrapper />),
default: slots.default ?? (() => <ContentWrapper />),
loading: slots.default ? void 0 : () => <ContentLoading />,
}}
</AdminShell>
<>
<AdminShell
{...attrs}
ref="shell"
layout={getLayoutConfig.value}
mode={mode.value}
groupedSidebar={mixedChildren.value.length > 0}
showTabs={getMenuTagSwitch.value}
showFooter={getCopyrightSwitch.value}
busy={
!slots.default &&
(!globalMainLayoutLoad.value || layoutContentSpinning.value)
}
maximized={layoutContentMaximize.value}
maximizedStyle={layoutContentMaximizeStyle.value}
contentRef={LAYOUT_CONTENT_REF}
restore={() => maximize(false)}
restoreLabel={t('restore')}
>
{{
header:
slots.header ??
(() => (
<>
<HeaderWrapper onOpenSettings={openSettings} />
{mode.value === 'top' || grouped ? <TopNavigation /> : null}
</>
)),
sidebar:
slots.sidebar ??
(() => (
<Menu
options={grouped ? mixedChildren.value : void 0}
showLogo={!grouped}
end={mode.value === 'right'}
inert={layoutContentMaximize.value}
/>
)),
tabs: slots.tabs ?? (() => <FeatureWrapper />),
footer: slots.footer ?? (() => <FooterWrapper />),
default: slots.default ?? (() => <ContentWrapper />),
loading: slots.default ? void 0 : () => <ContentLoading />,
}}
</AdminShell>
{!slots.header && (
<SettingDrawer
v-model:show={settingsShown.value}
placement={getDrawerPlacement.value}
onAfterLeave={restoreSettingsFocus}
/>
)}
</>
)
}
},

View File

@ -0,0 +1,61 @@
{
"tagsTitle": "Tags",
"tagsIntro": "Create and edit tags in a modal. Select a tag name to view its notes in a drawer.",
"projectsTitle": "Projects",
"projectsIntro": "Filter projects by name and status. Open a project page to view or edit its details and milestones.",
"name": "Name",
"tagNote": "Notes",
"projectName": "Project name",
"owner": "Owner",
"status": "Status",
"planned": "Planned",
"active": "In progress",
"completed": "Completed",
"summary": "Project summary",
"overview": "Overview",
"milestones": "Milestones",
"milestoneName": "Milestone name",
"milestoneOutcome": "Expected outcome",
"milestoneNumber": "Milestone {number}",
"removeMilestoneNumber": "Remove milestone {number}",
"addMilestone": "Add milestone",
"removeMilestone": "Remove",
"noMilestones": "No milestones yet",
"actions": "Actions",
"search": "Search",
"clearFilters": "Clear filters",
"noTags": "No tags yet",
"noProjects": "No projects yet",
"noMatches": "No projects match these filters",
"create": "Create",
"createTag": "Create tag",
"editTag": "Edit tag",
"tagDetail": "Tag details",
"createProject": "Create project",
"editProject": "Edit {name}",
"projectDetail": "Project details",
"editorIntro": "Add project information and any milestones. Save to apply your changes.",
"backToProjects": "Back to projects",
"edit": "Edit",
"saveChanges": "Save changes",
"cancel": "Cancel",
"close": "Close",
"delete": "Delete",
"deleteTitle": "Confirm deletion",
"deleteTag": "Delete “{name}”? This action is permanent.",
"deleteProject": "Delete “{name}” and all its milestones? This action is permanent.",
"saved": "Saved",
"deleted": "Deleted",
"nameRequired": "Enter a name",
"ownerRequired": "Enter an owner",
"milestoneRequired": "Enter a milestone name",
"checkFields": "Review the indicated fields and try again.",
"duplicate": "This name is already in use. Choose a different name.",
"saveFailed": "Could not write the example data to this browser. Try again.",
"missingRecord": "Record unavailable",
"missingHelp": "The project may have been deleted or may belong to another demo session.",
"discardTitle": "Discard unsaved changes?",
"discardMessage": "Your edits will be lost when you leave.",
"discard": "Discard changes",
"keepEditing": "Keep editing"
}

View File

@ -32,6 +32,8 @@
"profile": "Profile",
"name": "Name",
"age": "Age",
"decreaseAge": "Decrease age",
"increaseAge": "Increase age",
"date": "Date of birth",
"gender": "Gender",
"female": "Female",

View File

@ -4,6 +4,12 @@
"CacheDemo": "Cache Utils Demo",
"CalculatePrecision": "Precision",
"ContextMenu": "Right Click Menu",
"CurdExamples": "CURD examples",
"CurdTags": "Tags · Simple",
"CurdProjects": "Projects · Complex",
"CurdProjectCreate": "Create project",
"CurdProjectDetail": "Project details",
"CurdProjectEdit": "Edit project",
"Dashboard": "Home",
"DemoComponents": "Component examples",
"DemoAssets": "Icons and codes",

View File

@ -22,6 +22,8 @@
"valid": "Valid · {count} records",
"editHint": "Validate to preview the route tree.",
"invalid": "Configuration validation failed",
"jsonSyntax": "Invalid JSON. Check the double quotes, commas, and matching brackets.",
"jsonSyntaxAt": "Invalid JSON near line {line}, column {column}. Check the double quotes, commas, and brackets there.",
"contract": "Input and output contract",
"contractHint": "Give the schema and view catalog to AI or backend developers. API responses, imports and exports use the same format.",
"views": "View catalog",
@ -42,7 +44,10 @@
"validateDraft": "Validate",
"draftValid": "Configuration is valid",
"resetDraft": "Reload configuration",
"resetConfirm": "Discard your draft changes and reload the saved configuration?",
"discardTitle": "Unsaved route draft",
"discardPrompt": "Continuing discards these changes. Return to the editor to keep working or export the draft.",
"keepEditing": "Keep editing",
"discardChanges": "Discard changes",
"addRoot": "Add top-level item",
"addChild": "Add child item",
"editNode": "Edit menu item",

View File

@ -50,6 +50,7 @@
"optionsFailed": "Could not load organizations and roles",
"retry": "Retry",
"viewNamed": "View details for {name}",
"moreNamed": "More actions for {name}",
"editNamed": "Edit {name}",
"deleteNamed": "Delete {name}",
"enableNamed": "Enable {name}",

View File

@ -2,12 +2,15 @@
"Register": "Register",
"PageTitle": "Sign in - Ray Admin",
"Signing": "Sign in",
"SignInMethods": "Sign-in options",
"QRCodeSigning": "QR code",
"NamePlaceholder": "please enter user name",
"PasswordPlaceholder": "please enter password",
"Login": "Sign in",
"Name": "User Name",
"Password": "User Password",
"ShowPassword": "Show password",
"HidePassword": "Hide password",
"RayTemplate": "Build your next admin dashboard",
"TemplateDescription": "Open-source Vue 3 admin dashboard template with TypeScript and Naive UI.",
"OtherSignInOptions": "More sign-in examples",

View File

@ -0,0 +1,61 @@
{
"tagsTitle": "标签管理",
"tagsIntro": "用弹窗创建或编辑标签。点击标签名称,在抽屉里查看备注。",
"projectsTitle": "项目管理",
"projectsIntro": "按名称和状态筛选项目。打开独立页面查看详情,或编辑项目与里程碑。",
"name": "名称",
"tagNote": "备注",
"projectName": "项目名称",
"owner": "负责人",
"status": "状态",
"planned": "计划中",
"active": "进行中",
"completed": "已完成",
"summary": "项目说明",
"overview": "基本信息",
"milestones": "里程碑",
"milestoneName": "里程碑名称",
"milestoneOutcome": "预期成果",
"milestoneNumber": "里程碑 {number}",
"removeMilestoneNumber": "移除里程碑 {number}",
"addMilestone": "添加里程碑",
"removeMilestone": "移除",
"noMilestones": "暂无里程碑",
"actions": "操作",
"search": "查询",
"clearFilters": "清除筛选",
"noTags": "暂无标签",
"noProjects": "暂无项目",
"noMatches": "没有符合筛选条件的项目",
"create": "创建",
"createTag": "新增标签",
"editTag": "编辑标签",
"tagDetail": "标签详情",
"createProject": "新增项目",
"editProject": "编辑项目「{name}」",
"projectDetail": "项目详情",
"editorIntro": "填写项目信息,并按需添加里程碑。保存后才会应用这些变更。",
"backToProjects": "返回项目列表",
"edit": "编辑",
"saveChanges": "保存更改",
"cancel": "取消",
"close": "关闭",
"delete": "删除",
"deleteTitle": "确认删除",
"deleteTag": "确定删除标签「{name}」?此操作无法撤销。",
"deleteProject": "确定删除项目「{name}」及其全部里程碑?此操作无法撤销。",
"saved": "已保存",
"deleted": "已删除",
"nameRequired": "请输入名称",
"ownerRequired": "请输入负责人",
"milestoneRequired": "请输入里程碑名称",
"checkFields": "请检查有提示的字段后重新提交。",
"duplicate": "此名称已被使用,请换一个名称。",
"saveFailed": "无法写入当前浏览器的演示数据,请重试。",
"missingRecord": "找不到这条记录",
"missingHelp": "该项目可能已删除,或属于另一个演示会话。",
"discardTitle": "放弃未保存的更改?",
"discardMessage": "离开后,本次编辑的内容将丢失。",
"discard": "放弃更改",
"keepEditing": "继续编辑"
}

View File

@ -32,6 +32,8 @@
"profile": "档案",
"name": "姓名",
"age": "年龄",
"decreaseAge": "减少年龄",
"increaseAge": "增加年龄",
"date": "出生日期",
"gender": "性别",
"female": "女",

View File

@ -4,6 +4,12 @@
"CacheDemo": "缓存工具函数",
"CalculatePrecision": "数字精度",
"ContextMenu": "右键菜单",
"CurdExamples": "CURD 示例",
"CurdTags": "标签管理 · 简单",
"CurdProjects": "项目管理 · 复杂",
"CurdProjectCreate": "新增项目",
"CurdProjectDetail": "项目详情",
"CurdProjectEdit": "编辑项目",
"Dashboard": "首页",
"DemoComponents": "组件示例",
"DemoAssets": "图标与编码",

View File

@ -22,6 +22,8 @@
"valid": "校验通过 · {count} 项",
"editHint": "校验后可查看配置树。",
"invalid": "配置校验失败",
"jsonSyntax": "JSON 格式有误。请检查双引号、逗号和括号是否配对。",
"jsonSyntaxAt": "第 {line} 行、第 {column} 列附近的 JSON 格式有误。请检查该处的双引号、逗号和括号。",
"contract": "输入与输出契约",
"contractHint": "将 Schema 与可用页面清单交给 AI 或后台开发者。接口响应、导入文件和导出文件使用同一格式。",
"views": "可用页面清单",
@ -42,7 +44,10 @@
"validateDraft": "校验配置",
"draftValid": "校验通过",
"resetDraft": "重新读取配置",
"resetConfirm": "放弃草稿改动,重新读取已保存的配置?",
"discardTitle": "路由草稿尚未保存",
"discardPrompt": "继续会放弃本次修改。你可以返回编辑器继续修改或导出草稿。",
"keepEditing": "继续编辑",
"discardChanges": "放弃修改",
"addRoot": "添加一级菜单",
"addChild": "添加子菜单",
"editNode": "编辑菜单项",

View File

@ -50,6 +50,7 @@
"optionsFailed": "组织和角色加载失败",
"retry": "重试",
"viewNamed": "查看 {name} 的详情",
"moreNamed": "{name} 的更多操作",
"editNamed": "编辑 {name}",
"deleteNamed": "删除 {name}",
"enableNamed": "启用 {name}",

View File

@ -2,12 +2,15 @@
"Register": "注册",
"PageTitle": "登录 - Ray Admin",
"Signing": "登录",
"SignInMethods": "登录方式",
"QRCodeSigning": "二维码",
"NamePlaceholder": "请输入用户名",
"PasswordPlaceholder": "请输入密码",
"Login": "登录",
"Name": "用户名",
"Password": "密码",
"ShowPassword": "显示密码",
"HidePassword": "隐藏密码",
"RayTemplate": "构建你的中后台管理系统",
"TemplateDescription": "基于 Vue 3、TypeScript 和 Naive UI 的开源中后台管理模板。",
"OtherSignInOptions": "其他登录方式示例",

View File

@ -20,6 +20,26 @@ const views = {
load: () => import('@/views/demo/context-menu/index'),
name: 'ContextMenuDemo',
},
'demo/curd/tags': {
load: () => import('@/views/demo/curd/tags'),
name: 'CurdTags',
},
'demo/curd/projects': {
load: () => import('@/views/demo/curd/projects'),
name: 'CurdProjects',
},
'demo/curd/project-create': {
load: () => import('@/views/demo/curd/project-create'),
name: 'CurdProjectCreate',
},
'demo/curd/project-detail': {
load: () => import('@/views/demo/curd/project-detail'),
name: 'CurdProjectDetail',
},
'demo/curd/project-edit': {
load: () => import('@/views/demo/curd/project-edit'),
name: 'CurdProjectEdit',
},
'demo/directive': {
load: () => import('@/views/demo/directive/index'),
name: 'RDirective',

View File

@ -106,6 +106,7 @@ export const piniaSettingStore = defineStore(
accent.primaryColor,
accent.primaryColorHover ?? accent.primaryColor,
surface,
mode,
),
},
}),

View File

@ -3,15 +3,17 @@
* @param primary 用户选择的主色
* @param hover 悬停与聚焦状态的主色
* @param surface 当前风格和明暗模式的卡片底色
* @param mode 当前明暗模式
*
* @description
* 用浏览器解析 CSS 颜色,并把半透明填充合成在主题底色上。按钮使用同一不透明色,
* 使文字对比度不受按钮下方实际页面内容影响。
* 在主题底色上解析自定义主色。浅色实心按钮沿用白字,需要时加深填充色;
* 深色按钮按实际填充色选取对比度更高的文字色。
*/
export function primaryButtonColors(
primary: string,
hover: string,
surface: string,
mode: 'light' | 'dark',
) {
const canvas = document.createElement('canvas')
@ -30,35 +32,71 @@ export function primaryButtonColors(
}
const pixels = context.getImageData(0, 0, 2, 1).data
const colors = (index: number) => {
const colors = (index: number, whiteTextContrast?: number) => {
const rgb = Array.from(pixels.slice(index, index + 3))
const [r, g, b] = rgb.map((byte) => {
const channels = rgb.map((byte) => {
const channel = byte / 255
return channel <= 0.04045
? channel / 12.92
: ((channel + 0.055) / 1.055) ** 2.4
})
const [r, g, b] = channels
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
const blackContrast = (luminance + 0.05) / 0.05
const whiteContrast = 1.05 / (luminance + 0.05)
let fill = rgb
if (whiteTextContrast !== void 0 && whiteContrast < whiteTextContrast) {
const scale = (1.05 / whiteTextContrast - 0.05) / luminance
fill = channels.map((channel) => {
const linear = channel * scale
const srgb =
linear <= 0.0031308
? linear * 12.92
: 1.055 * linear ** (1 / 2.4) - 0.055
return Math.floor(srgb * 255)
})
}
return {
fill: `rgb(${rgb.join(', ')})`,
text: blackContrast >= whiteContrast ? '#000' : '#fff',
fill: `rgb(${fill.join(', ')})`,
text:
whiteTextContrast !== void 0 || whiteContrast > blackContrast
? '#fff'
: '#000',
}
}
const normal = colors(0)
const active = colors(4)
// 默认态预留对比度余量,让悬停提亮后仍满足白字可读性。
const light = mode === 'light'
const normal = colors(0, light ? 5 : void 0)
const active = colors(4, light ? 4.5 : void 0)
const pressed = light ? colors(0, 5.5) : normal
return {
colorPrimary: normal.fill,
colorPressedPrimary: normal.fill,
colorPressedPrimary: pressed.fill,
colorHoverPrimary: active.fill,
colorFocusPrimary: active.fill,
textColorPrimary: normal.text,
textColorPressedPrimary: normal.text,
textColorPressedPrimary: pressed.text,
textColorHoverPrimary: active.text,
textColorFocusPrimary: active.text,
...(light && {
borderPrimary: `1px solid ${normal.fill}`,
borderHoverPrimary: `1px solid ${active.fill}`,
borderPressedPrimary: `1px solid ${pressed.fill}`,
borderFocusPrimary: `1px solid ${active.fill}`,
textColorGhostPrimary: normal.fill,
textColorGhostHoverPrimary: active.fill,
textColorGhostPressedPrimary: pressed.fill,
textColorGhostFocusPrimary: active.fill,
textColorTextPrimary: normal.fill,
textColorTextHoverPrimary: active.fill,
textColorTextPressedPrimary: pressed.fill,
textColorTextFocusPrimary: active.fill,
}),
}
}

View File

@ -27,6 +27,15 @@
min-width: 0;
}
.r-demo-control-label {
position: absolute;
inline-size: 1px;
block-size: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.r-demo-section-heading {
display: flex;
align-items: center;

View File

@ -0,0 +1,58 @@
import { useI18n } from '@/hooks/template/useI18n'
import {
NCard,
NDescriptions,
NDescriptionsItem,
NFlex,
NList,
NListItem,
NText,
} from 'naive-ui'
import type { PropType } from 'vue'
import type { Project } from './records'
export default defineComponent({
name: 'ProjectDescription',
props: {
project: { type: Object as PropType<Project>, required: true },
},
setup(props) {
const { t } = useI18n('curd')
return () => (
<NFlex vertical size={20}>
<NCard title={t('overview')}>
<NDescriptions column={1} labelPlacement="left">
<NDescriptionsItem label={t('owner')}>
{props.project.owner}
</NDescriptionsItem>
<NDescriptionsItem label={t('status')}>
{t(props.project.status)}
</NDescriptionsItem>
<NDescriptionsItem label={t('summary')}>
{props.project.summary || '—'}
</NDescriptionsItem>
</NDescriptions>
</NCard>
<NCard title={t('milestones')}>
{props.project.milestones.length ? (
<NList>
{props.project.milestones.map((milestone) => (
<NListItem key={milestone.id}>
<NFlex vertical size={4} style={{ overflowWrap: 'anywhere' }}>
<strong>{milestone.name}</strong>
{milestone.outcome && (
<NText depth={2}>{milestone.outcome}</NText>
)}
</NFlex>
</NListItem>
))}
</NList>
) : (
<NText depth={2}>{t('noMilestones')}</NText>
)}
</NCard>
</NFlex>
)
},
})

View File

@ -0,0 +1,256 @@
import { useI18n } from '@/hooks/template/useI18n'
import { useRuntimeGetters } from '@/store/hooks/useRuntimeStore'
import { RForm } from '@ray-template/ui/form'
import { uuid } from '@ray-template/utils/core'
import { cloneDeep } from 'lodash-es'
import {
NButton,
NCard,
NFlex,
NFormItem,
NFormItemGi,
NGrid,
NInput,
NList,
NListItem,
NRadio,
NRadioGroup,
NText,
useMessage,
} from 'naive-ui'
import type { PropType } from 'vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import DemoPage from '../components/DemoPage'
import { useCurdEditor } from './interactions'
import type { WriteResult } from './interactions'
import { projectStatuses } from './records'
import type { ProjectDraft } from './records'
let reloadingDraft:
| {
route: RouteLocationNormalizedLoaded
draft: ProjectDraft
}
| undefined
export default defineComponent({
name: 'ProjectEditor',
props: {
title: { type: String, required: true },
submitLabel: { type: String, required: true },
initial: { type: Object as PropType<ProjectDraft>, required: true },
save: {
type: Function as PropType<(draft: ProjectDraft) => WriteResult>,
required: true,
},
onReturn: { type: Function as PropType<() => void>, required: true },
},
setup(props) {
const { t } = useI18n('curd')
const message = useMessage()
const router = useRouter()
const mountedRoute = router.currentRoute.value
const { globalMainLayoutLoad } = useRuntimeGetters()
const id = useId()
const field = (name: string) => `${id}-${name}`
const editor = useCurdEditor(props.initial, props.save, () => {
message.success(t('saved'))
props.onReturn()
})
const { draft } = editor
if (reloadingDraft?.route === mountedRoute)
draft.value = reloadingDraft.draft
reloadingDraft = void 0
onBeforeRouteLeave(editor.canLeave)
onBeforeRouteUpdate(editor.canLeave)
onBeforeUnmount(() => {
// 工作区刷新会重挂载当前路由;仅同一次路由访问可接回草稿。
if (
!globalMainLayoutLoad.value &&
router.currentRoute.value === mountedRoute &&
editor.dirty.value
)
reloadingDraft = { route: mountedRoute, draft: cloneDeep(draft.value) }
})
const required = (key: string) => ({
required: true,
whitespace: true,
trigger: 'blur',
message: t(key),
})
const focusMilestone = (milestoneId?: string) => {
void nextTick(() => {
const target = milestoneId ? field(milestoneId) : field('add-milestone')
document.getElementById(target)?.focus()
})
}
const addMilestone = () => {
const id = uuid()
draft.value.milestones.push({ id, name: '', outcome: '' })
focusMilestone(id)
}
const removeMilestone = (index: number) => {
draft.value.milestones.splice(index, 1)
focusMilestone(
draft.value.milestones[index]?.id ?? draft.value.milestones.at(-1)?.id,
)
}
return () => (
<DemoPage title={props.title} description={t('editorIntro')}>
<RForm {...editor.formProps} model={draft.value} labelPlacement="top">
<NFlex vertical size={20}>
{editor.errorNotice()}
<NCard title={t('overview')}>
<NGrid cols="1 560:2" responsive="self" xGap={16}>
<NFormItemGi
label={t('projectName')}
labelProps={{ for: field('name') }}
path="name"
rule={required('nameRequired')}
>
<NInput
v-model:value={draft.value.name}
inputProps={{ id: field('name'), required: true }}
maxlength={80}
/>
</NFormItemGi>
<NFormItemGi
label={t('owner')}
labelProps={{ for: field('owner') }}
path="owner"
rule={required('ownerRequired')}
>
<NInput
v-model:value={draft.value.owner}
inputProps={{ id: field('owner'), required: true }}
maxlength={60}
/>
</NFormItemGi>
</NGrid>
<NFormItem
label={t('status')}
labelProps={{ id: field('status') }}
>
<NRadioGroup
v-model:value={draft.value.status}
{...{
role: 'radiogroup',
'aria-labelledby': field('status'),
}}
>
<NFlex>
{projectStatuses.map((status) => (
<NRadio key={status} value={status}>
{t(status)}
</NRadio>
))}
</NFlex>
</NRadioGroup>
</NFormItem>
<NFormItem
label={t('summary')}
labelProps={{ for: field('summary') }}
>
<NInput
v-model:value={draft.value.summary}
inputProps={{ id: field('summary') }}
type="textarea"
maxlength={500}
autosize={{ minRows: 2, maxRows: 6 }}
/>
</NFormItem>
</NCard>
<NCard title={t('milestones')}>
{{
'header-extra': () => (
<NButton
{...{ id: field('add-milestone') }}
size="small"
onClick={addMilestone}
>
{t('addMilestone')}
</NButton>
),
default: () =>
draft.value.milestones.length ? (
<NList>
{draft.value.milestones.map((milestone, index) => (
<NListItem key={milestone.id}>
<NFlex justify="space-between" align="center">
<strong>
{t('milestoneNumber', { number: index + 1 })}
</strong>
<NButton
text
aria-label={t('removeMilestoneNumber', {
number: index + 1,
})}
onClick={() => removeMilestone(index)}
>
{t('removeMilestone')}
</NButton>
</NFlex>
<NGrid cols="1 560:2" responsive="self" xGap={16}>
<NFormItemGi
label={t('milestoneName')}
labelProps={{ for: field(milestone.id) }}
path={`milestones.${index}.name`}
rule={required('milestoneRequired')}
>
<NInput
v-model:value={milestone.name}
inputProps={{
id: field(milestone.id),
required: true,
}}
maxlength={80}
/>
</NFormItemGi>
<NFormItemGi
label={t('milestoneOutcome')}
labelProps={{
for: field(`${milestone.id}-outcome`),
}}
>
<NInput
v-model:value={milestone.outcome}
inputProps={{
id: field(`${milestone.id}-outcome`),
}}
maxlength={120}
/>
</NFormItemGi>
</NGrid>
</NListItem>
))}
</NList>
) : (
<NText depth={2}>{t('noMilestones')}</NText>
),
}}
</NCard>
<NFlex justify="end">
<NButton disabled={editor.saving.value} onClick={props.onReturn}>
{t('cancel')}
</NButton>
<NButton
type="primary"
attrType="submit"
loading={editor.saving.value}
>
{props.submitLabel}
</NButton>
</NFlex>
</NFlex>
</RForm>
</DemoPage>
)
},
})

View File

@ -0,0 +1,27 @@
import { useI18n } from '@/hooks/template/useI18n'
import { NResult } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import { ProjectLink, projectList } from './project-navigation'
export default defineComponent({
name: 'ProjectMissing',
setup() {
const { t } = useI18n('curd')
return () => (
<DemoPage title={t('projectDetail')}>
<NResult
status="warning"
title={t('missingRecord')}
description={t('missingHelp')}
>
{{
footer: () => (
<ProjectLink to={projectList}>{t('backToProjects')}</ProjectLink>
),
}}
</NResult>
</DemoPage>
)
},
})

View File

@ -0,0 +1,108 @@
import { useI18n } from '@/hooks/template/useI18n'
import { RForm } from '@ray-template/ui/form'
import { NButton, NFlex, NFormItem, NInput, NModal, useMessage } from 'naive-ui'
import type { InputInst } from 'naive-ui'
import type { PropType } from 'vue'
import { useCurdEditor } from './interactions'
import type { WriteResult } from './interactions'
import type { TagDraft } from './records'
export type TagAction = {
initial: TagDraft
title: 'createTag' | 'editTag'
submit: 'create' | 'saveChanges'
save: (draft: TagDraft) => WriteResult
}
export default defineComponent({
name: 'TagEditorModal',
props: {
action: { type: Object as PropType<TagAction>, required: true },
onClosed: { type: Function as PropType<() => void>, required: true },
},
setup(props) {
const { t } = useI18n('curd')
const message = useMessage()
const show = ref(true)
const firstInput = shallowRef<InputInst>()
const nameId = useId()
const noteId = useId()
const editor = useCurdEditor(
props.action.initial,
props.action.save,
() => {
show.value = false
message.success(t('saved'))
},
)
const close = async () => {
if (await editor.canLeave()) show.value = false
}
onBeforeRouteLeave(editor.canLeave)
onBeforeRouteUpdate(editor.canLeave)
return () => (
<NModal
show={show.value}
preset="card"
title={t(props.action.title)}
aria-label={t(props.action.title)}
style={{ width: 'min(460px, calc(100vw - 32px))' }}
maskClosable={false}
onUpdateShow={(open) => {
if (!open) void close()
}}
onAfterEnter={() => firstInput.value?.focus()}
onAfterLeave={props.onClosed}
>
<RForm
{...editor.formProps}
model={editor.draft.value}
labelPlacement="top"
>
{editor.errorNotice()}
<NFormItem
label={t('name')}
labelProps={{ for: nameId }}
path="name"
rule={{
required: true,
whitespace: true,
trigger: 'blur',
message: t('nameRequired'),
}}
>
<NInput
ref={firstInput}
v-model:value={editor.draft.value.name}
inputProps={{ id: nameId, required: true }}
maxlength={60}
/>
</NFormItem>
<NFormItem label={t('tagNote')} labelProps={{ for: noteId }}>
<NInput
v-model:value={editor.draft.value.note}
inputProps={{ id: noteId }}
type="textarea"
maxlength={200}
autosize={{ minRows: 2, maxRows: 4 }}
/>
</NFormItem>
<NFlex justify="end">
<NButton disabled={editor.saving.value} onClick={close}>
{t('cancel')}
</NButton>
<NButton
type="primary"
attrType="submit"
loading={editor.saving.value}
>
{t(props.action.submit)}
</NButton>
</NFlex>
</RForm>
</NModal>
)
},
})

View File

@ -0,0 +1,156 @@
import { useI18n } from '@/hooks/template/useI18n'
import { useForm } from '@ray-template/ui/form'
import { cloneDeep, isEqual } from 'lodash-es'
import { NAlert, useDialog } from 'naive-ui'
export type WriteResult = 'duplicate' | 'missingRecord' | 'saveFailed' | void
export const useCurdConfirmation = () => {
const dialog = useDialog()
let pending: Promise<boolean> | undefined
let close: (() => void) | undefined
let active = true
onScopeDispose(() => {
active = false
close?.()
})
return (title: string, content: string, accept: string, cancel: string) => {
if (pending) return pending
pending = new Promise<boolean>((resolve) => {
let accepted = false
const confirmation = dialog.warning({
title,
content,
positiveText: accept,
negativeText: cancel,
positiveButtonProps: { type: 'error' },
closable: false,
maskClosable: false,
onPositiveClick: () => {
accepted = true
},
onAfterLeave: () => {
close = void 0
pending = void 0
resolve(active && accepted)
},
})
close = confirmation.destroy
})
return pending
}
}
export const useCurdEditor = <Draft extends Record<string, unknown>>(
initial: Draft,
save: (draft: Draft) => WriteResult,
onSaved: () => void,
) => {
const { t } = useI18n('curd')
const confirm = useCurdConfirmation()
const [register, { validate, formConditionRef: draft }] = useForm(initial)
const baseline = shallowRef(initial)
const dirty = computed(() => !isEqual(draft.value, baseline.value))
const saving = ref(false)
const error = ref<Exclude<WriteResult, void> | 'checkFields'>()
const errorSummary = shallowRef<HTMLElement>()
let active = true
onScopeDispose(() => {
active = false
})
const canLeave = () =>
!saving.value &&
(!dirty.value ||
confirm(
t('discardTitle'),
t('discardMessage'),
t('discard'),
t('keepEditing'),
))
const beforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
}
watch(
() => dirty.value || saving.value,
(hasDraft, _, onCleanup) => {
if (!hasDraft) return
window.addEventListener('beforeunload', beforeUnload)
onCleanup(() => window.removeEventListener('beforeunload', beforeUnload))
},
{ flush: 'sync' },
)
const submit = async (event: Event) => {
event.preventDefault()
if (saving.value) return
saving.value = true
error.value = void 0
try {
try {
await validate()
} catch {
error.value = 'checkFields'
return
}
if (!active) return
const snapshot = cloneDeep(draft.value)
error.value = save(snapshot) ?? void 0
if (error.value) return
baseline.value = snapshot
} catch {
error.value = 'saveFailed'
return
} finally {
saving.value = false
if (error.value && active) {
await nextTick()
errorSummary.value?.focus()
}
}
onSaved()
}
return {
draft,
dirty,
saving,
canLeave,
formProps: {
onRegister: register,
onSubmit: submit,
onKeydownCapture: (event: KeyboardEvent) => {
if (event.isComposing && event.key === 'Enter') event.preventDefault()
},
novalidate: true,
},
errorNotice: () =>
error.value && (
<div ref={errorSummary} tabindex={-1}>
<NAlert type="error">{t(error.value)}</NAlert>
</div>
),
}
}

View File

@ -0,0 +1,24 @@
import { useI18n } from '@/hooks/template/useI18n'
import { projectList, useProjectReturn } from './project-navigation'
import ProjectEditor from './ProjectEditor'
import { createProjectDraft, useProjects } from './records'
export default defineComponent({
name: 'CurdProjectCreate',
setup() {
const { t } = useI18n('curd')
const { create } = useProjects()
const { returnTo } = useProjectReturn()
const initial = createProjectDraft()
return () => (
<ProjectEditor
title={t('createProject')}
submitLabel={t('create')}
initial={initial}
save={create}
onReturn={() => returnTo(projectList)}
/>
)
},
})

View File

@ -0,0 +1,74 @@
import { useI18n } from '@/hooks/template/useI18n'
import { NButton, useMessage } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import { useCurdConfirmation } from './interactions'
import {
projectEdit,
ProjectLink,
projectList,
useProjectReturn,
} from './project-navigation'
import ProjectDescription from './ProjectDescription'
import ProjectMissing from './ProjectMissing'
import { useProjects } from './records'
import type { Project } from './records'
export default defineComponent({
name: 'CurdProjectDetail',
props: { id: { type: String, required: true } },
setup(props) {
const { t } = useI18n('curd')
const message = useMessage()
const projects = useProjects()
const { returnTo } = useProjectReturn()
const confirm = useCurdConfirmation()
const remove = async (project: Project) => {
const accepted = await confirm(
t('deleteTitle'),
t('deleteProject', { name: project.name }),
t('delete'),
t('cancel'),
)
if (!accepted) return
const error = projects.remove(project.id)
if (error) {
message.error(t(error))
return
}
message.success(t('deleted'))
returnTo(projectList)
}
return () => {
const project = projects.find(props.id)
if (!project) return <ProjectMissing />
return (
<DemoPage title={project.name} description={t('projectDetail')}>
{{
actions: () => (
<>
<NButton onClick={() => returnTo(projectList)}>
{t('backToProjects')}
</NButton>
<ProjectLink primary to={projectEdit(project.id)}>
{t('edit')}
</ProjectLink>
<NButton type="error" secondary onClick={() => remove(project)}>
{t('delete')}
</NButton>
</>
),
default: () => <ProjectDescription project={project} />,
}}
</DemoPage>
)
}
},
})

View File

@ -0,0 +1,39 @@
import { useI18n } from '@/hooks/template/useI18n'
import {
projectDetail,
projectList,
useProjectReturn,
} from './project-navigation'
import ProjectEditor from './ProjectEditor'
import ProjectMissing from './ProjectMissing'
import { useProjects } from './records'
export default defineComponent({
name: 'CurdProjectEdit',
props: { id: { type: String, required: true } },
setup(props) {
const { t } = useI18n('curd')
const projects = useProjects()
const { cameFrom, returnTo } = useProjectReturn()
return () => {
const project = projects.find(props.id)
if (!project) return <ProjectMissing />
const { id, ...initial } = project
const origin = cameFrom(projectList) ? projectList : projectDetail(id)
return (
<ProjectEditor
key={id}
title={t('editProject', { name: project.name })}
submitLabel={t('saveChanges')}
initial={initial}
save={(draft) => projects.update(id, draft)}
onReturn={() => returnTo(origin)}
/>
)
}
},
})

View File

@ -0,0 +1,60 @@
import { NButton } from 'naive-ui'
import type { PropType } from 'vue'
import { useLink } from 'vue-router'
import type { RouteLocationRaw } from 'vue-router'
export const projectList = { name: 'CurdProjects' }
export const projectCreate = { name: 'CurdProjectCreate' }
export const projectDetail = (id: string) => ({
name: 'CurdProjectDetail',
params: { id },
})
export const projectEdit = (id: string) => ({
name: 'CurdProjectEdit',
params: { id },
})
export const useProjectReturn = () => {
const router = useRouter()
const cameFrom = (target: RouteLocationRaw) =>
router.options.history.state.back === router.resolve(target).fullPath
const returnTo = (target: RouteLocationRaw) => {
if (cameFrom(target)) router.back()
else void router.replace(target)
}
return { cameFrom, returnTo }
}
export const ProjectLink = defineComponent({
name: 'ProjectLink',
props: {
to: { type: Object as PropType<RouteLocationRaw>, required: true },
id: { type: String, default: void 0 },
text: Boolean,
primary: Boolean,
onFollow: {
type: Function as PropType<(event: MouseEvent) => void>,
default: void 0,
},
},
setup(props, { slots }) {
const { href, navigate } = useLink(props)
return () => (
<NButton
tag="a"
{...{ id: props.id, href: href.value }}
text={props.text}
type={props.primary ? 'primary' : 'default'}
onClick={(event: MouseEvent) => {
props.onFollow?.(event)
void navigate(event)
}}
>
{slots.default?.()}
</NButton>
)
},
})

View File

@ -0,0 +1,242 @@
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro } from '@ray-template/ui/table-pro'
import type {
TableProInst,
TableProRequest,
TableProSearchOptions,
TableProSearchValues,
} from '@ray-template/ui/table-pro'
import { NButton, NFlex, NTag } from 'naive-ui'
import type { DataTableColumns, DataTableSortState } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import {
projectCreate,
projectDetail,
projectEdit,
ProjectLink,
} from './project-navigation'
import { projectStatuses, useProjects } from './records'
import type { Project } from './records'
const listContext = {
filters: {} as TableProSearchValues,
order: false as DataTableSortState['order'],
page: 1,
opener: '',
}
const createButtonId = 'curd-project-create'
const detailButtonId = (id: string) => `curd-project-detail-${id}`
const editButtonId = (id: string) => `curd-project-edit-${id}`
export default defineComponent({
name: 'CurdProjects',
setup() {
const { t } = useI18n('curd')
const projects = useProjects()
const table = shallowRef<TableProInst>()
const order = ref(listContext.order)
const params = computed(() => ({ order: order.value }))
const initialFilters = listContext.filters
const firstPage = listContext.page
const hasFilters = ref(Object.values(initialFilters).some(Boolean))
const request: TableProRequest = (query, signal) => {
signal.throwIfAborted()
const name =
typeof query.name === 'string' ? query.name.toLowerCase() : ''
const rows = projects.rows.value.filter(
(row) =>
row.name.toLowerCase().includes(name) &&
(!query.status || row.status === query.status),
)
if (query.order) {
const direction = query.order === 'ascend' ? 1 : -1
rows.sort(
(left, right) => direction * left.name.localeCompare(right.name),
)
}
const page = Number(query.page)
const pageSize = Number(query.pageSize)
const start = (page - 1) * pageSize
return Promise.resolve({
data: rows.slice(start, start + pageSize),
total: rows.length,
})
}
const setOrder = (
sorter: DataTableSortState | DataTableSortState[] | null,
) => {
const sort = Array.isArray(sorter) ? sorter[0] : sorter
listContext.order = sort?.order ?? false
order.value = listContext.order
}
const clearFilters = () => {
table.value?.setSearchValues({ name: '', status: null })
void table.value?.submitSearch()
}
const search = computed<TableProSearchOptions>(() => ({
initialValues: initialFilters,
fields: [
{ type: 'text', key: 'name', label: t('projectName') },
{
type: 'select',
key: 'status',
label: t('status'),
options: projectStatuses.map((status) => ({
value: status,
label: t(status),
})),
},
],
renderActions: () => (
<NFlex>
<NButton attrType="submit" type="primary">
{t('search')}
</NButton>
<NButton onClick={clearFilters}>{t('clearFilters')}</NButton>
</NFlex>
),
}))
const rememberOpener = (event: MouseEvent, id: string) => {
if (
event.button === 0 &&
!event.metaKey &&
!event.ctrlKey &&
!event.shiftKey &&
!event.altKey
)
listContext.opener = id
}
let restoreFrame = 0
onMounted(() => {
const id = listContext.opener
listContext.opener = ''
if (!id) return
restoreFrame = requestAnimationFrame(() => {
const target =
document.getElementById(id) ?? document.getElementById(createButtonId)
target?.focus()
})
})
onScopeDispose(() => cancelAnimationFrame(restoreFrame))
const columns = computed<DataTableColumns<Project>>(() => [
{
title: t('projectName'),
key: 'name',
minWidth: 180,
sorter: true,
sortOrder: order.value,
render: ({ id, name }) => (
<ProjectLink
id={detailButtonId(id)}
to={projectDetail(id)}
text
primary
onFollow={(event) => rememberOpener(event, detailButtonId(id))}
>
{name}
</ProjectLink>
),
},
{ title: t('owner'), key: 'owner', minWidth: 134 },
{
title: t('status'),
key: 'status',
width: 110,
render: ({ status }) => (
<NTag
size="small"
bordered={false}
type={status === 'active' ? 'info' : 'default'}
>
{t(status)}
</NTag>
),
},
{
title: t('milestones'),
key: 'milestones',
width: 110,
render: ({ milestones }) => milestones.length,
},
{
title: t('actions'),
key: 'actions',
width: 90,
render: ({ id }) => (
<ProjectLink
id={editButtonId(id)}
to={projectEdit(id)}
text
onFollow={(event) => rememberOpener(event, editButtonId(id))}
>
{t('edit')}
</ProjectLink>
),
},
])
return () => (
<DemoPage title={t('projectsTitle')} description={t('projectsIntro')}>
<RTablePro
ref={table}
request={request}
params={params.value}
columns={columns.value}
search={search.value}
pagination={{
defaultPage: firstPage,
pageSize: 5,
showSizePicker: false,
}}
onUpdateSorter={setOrder}
onUpdatePage={(page) => {
listContext.page = page
}}
onSearch={({ values }) => {
listContext.filters = values
hasFilters.value = Object.values(values).some(Boolean)
}}
tool={false}
scrollX={640}
>
{{
toolbar: () => (
<ProjectLink
id={createButtonId}
to={projectCreate}
primary
onFollow={(event) => rememberOpener(event, createButtonId)}
>
{t('createProject')}
</ProjectLink>
),
empty: () => (
<NFlex vertical align="center" size={8}>
{t(hasFilters.value ? 'noMatches' : 'noProjects')}
{hasFilters.value && (
<NButton text onClick={clearFilters}>
{t('clearFilters')}
</NButton>
)}
</NFlex>
),
}}
</RTablePro>
</DemoPage>
)
},
})

View File

@ -0,0 +1,214 @@
import { getStorageInstance } from '@/utils/cache-backend'
import { uuid } from '@ray-template/utils/core'
import * as v from 'valibot'
import type { WriteResult } from './interactions'
const useRecords = <Row extends { id: string; name: string }>(
resource: string,
initial: Row[],
schema: v.GenericSchema<unknown, Row[]>,
) => {
const key = `ray-curd-demo:v1:${resource}`
const load = () => {
try {
const saved: unknown = JSON.parse(
getStorageInstance().getItem(key) ?? 'null',
)
const result = v.safeParse(schema, saved)
return result.success ? result.output : initial
} catch {
return initial
}
}
const rows = shallowRef(load())
const write = (next: Row[]): WriteResult => {
try {
getStorageInstance().setItem(key, JSON.stringify(next))
rows.value = next
} catch {
return 'saveFailed'
}
}
const save = (row: Row): WriteResult => {
const name = row.name.toLowerCase()
if (
rows.value.some(
(item) => item.id !== row.id && item.name.toLowerCase() === name,
)
)
return 'duplicate'
return write([row, ...rows.value.filter((item) => item.id !== row.id)])
}
const remove = (id: string) =>
write(rows.value.filter((item) => item.id !== id))
return { rows, save, remove }
}
const tagSchema = v.object({
id: v.string(),
name: v.string(),
note: v.string(),
})
export type Tag = v.InferOutput<typeof tagSchema>
export type TagDraft = Omit<Tag, 'id'>
const tagFixtures: Tag[] = [
{ id: 'design', name: 'Design', note: 'Design reviews' },
{ id: 'review', name: 'Review', note: 'Items awaiting review' },
{ id: 'docs', name: 'Docs', note: 'Documentation work' },
]
export const useTags = () => {
const { rows, save, remove } = useRecords(
'tags',
tagFixtures,
v.array(tagSchema),
)
const writeTag = (id: string, { name, note }: TagDraft) =>
save({ id, name: name.trim(), note: note.trim() })
return {
rows,
remove,
create: (draft: TagDraft) => writeTag(uuid(), draft),
update: writeTag,
}
}
export const projectStatuses = ['planned', 'active', 'completed'] as const
const projectSchema = v.object({
id: v.string(),
name: v.string(),
owner: v.string(),
status: v.picklist(projectStatuses),
summary: v.string(),
milestones: v.array(
v.object({
id: v.string(),
name: v.string(),
outcome: v.string(),
}),
),
})
export type Project = v.InferOutput<typeof projectSchema>
export type ProjectDraft = Omit<Project, 'id'>
export type ProjectStatus = Project['status']
export const createProjectDraft = (): ProjectDraft => ({
name: '',
owner: '',
status: 'planned',
summary: '',
milestones: [],
})
const projectFixtures: Project[] = [
{
id: 'atlas',
name: 'Atlas portal',
owner: 'Morgan Lee',
status: 'active',
summary: 'Bring internal support requests into one workspace.',
milestones: [
{
id: 'identity',
name: 'Set up account access',
outcome: 'Staff can sign in',
},
{
id: 'pilot',
name: 'Run the pilot',
outcome: 'Review feedback from two teams',
},
],
},
{
id: 'ridge',
name: 'Ridge rollout',
owner: 'Jamie Chen',
status: 'planned',
summary: 'Prepare the rollout for partner teams.',
milestones: [],
},
{
id: 'canvas',
name: 'Canvas refresh',
owner: 'Taylor Lin',
status: 'active',
summary: '',
milestones: [],
},
{
id: 'orbit',
name: 'Orbit reports',
owner: 'Alex Kim',
status: 'planned',
summary: '',
milestones: [],
},
{
id: 'lantern',
name: 'Lantern handbook',
owner: 'Robin Li',
status: 'completed',
summary: '',
milestones: [],
},
{
id: 'waypoint',
name: 'Waypoint inventory',
owner: 'Casey Wu',
status: 'active',
summary: '',
milestones: [],
},
{
id: 'harbor',
name: 'Harbor onboarding',
owner: 'Morgan Lee',
status: 'active',
summary: '',
milestones: [],
},
]
export const useProjects = () => {
const { rows, save, remove } = useRecords(
'projects',
projectFixtures,
v.array(projectSchema),
)
const find = (id: string) => rows.value.find((row) => row.id === id)
const writeProject = (id: string, draft: ProjectDraft) =>
save({
id,
name: draft.name.trim(),
owner: draft.owner.trim(),
status: draft.status,
summary: draft.summary.trim(),
milestones: draft.milestones.map((milestone) => ({
...milestone,
name: milestone.name.trim(),
outcome: milestone.outcome.trim(),
})),
})
return {
rows,
find,
remove,
create: (draft: ProjectDraft) => writeProject(uuid(), draft),
update: (id: string, draft: ProjectDraft) =>
find(id) ? writeProject(id, draft) : 'missingRecord',
}
}

View File

@ -0,0 +1,169 @@
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro } from '@ray-template/ui/table-pro'
import {
NButton,
NDescriptions,
NDescriptionsItem,
NDrawer,
NDrawerContent,
NFlex,
useMessage,
} from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import { useCurdConfirmation } from './interactions'
import { useTags } from './records'
import type { Tag } from './records'
import TagEditorModal from './TagEditorModal'
import type { TagAction } from './TagEditorModal'
export default defineComponent({
name: 'CurdTags',
setup() {
const { t } = useI18n('curd')
const message = useMessage()
const tags = useTags()
const confirm = useCurdConfirmation()
const action = shallowRef<TagAction>()
const detail = shallowRef<Tag>()
const drawerOpen = ref(false)
const createButtonId = useId()
const openCreate = () => {
action.value = {
initial: { name: '', note: '' },
title: 'createTag',
submit: 'create',
save: tags.create,
}
}
const openEdit = ({ id, name, note }: Tag) => {
action.value = {
initial: { name, note },
title: 'editTag',
submit: 'saveChanges',
save: (draft) => tags.update(id, draft),
}
}
const openDetail = (tag: Tag) => {
detail.value = tag
drawerOpen.value = true
}
const remove = async (tag: Tag) => {
const accepted = await confirm(
t('deleteTitle'),
t('deleteTag', { name: tag.name }),
t('delete'),
t('cancel'),
)
if (!accepted) return
const error = tags.remove(tag.id)
if (error) {
message.error(t(error))
return
}
message.success(t('deleted'))
await nextTick()
document.getElementById(createButtonId)?.focus()
}
const columns = computed<DataTableColumns<Tag>>(() => [
{
title: t('name'),
key: 'name',
minWidth: 112,
render: (tag) => (
<NButton text type="primary" onClick={() => openDetail(tag)}>
{tag.name}
</NButton>
),
},
{
title: t('tagNote'),
key: 'note',
minWidth: 140,
ellipsis: { tooltip: true },
render: ({ note }) => note || '—',
},
{
title: t('actions'),
key: 'actions',
width: 164,
render: (tag) => (
<NFlex size={12} wrap={false}>
<NButton text onClick={() => openEdit(tag)}>
{t('edit')}
</NButton>
<NButton text type="error" onClick={() => remove(tag)}>
{t('delete')}
</NButton>
</NFlex>
),
},
])
return () => (
<DemoPage title={t('tagsTitle')} description={t('tagsIntro')}>
<RTablePro
data={tags.rows.value}
columns={columns.value}
pagination={false}
tool={false}
scrollX={440}
>
{{
toolbar: () => (
<NButton
{...{ id: createButtonId }}
type="primary"
onClick={openCreate}
>
{t('createTag')}
</NButton>
),
empty: () => t('noTags'),
}}
</RTablePro>
{action.value && (
<TagEditorModal
action={action.value}
onClosed={() => {
action.value = void 0
}}
/>
)}
<NDrawer
v-model:show={drawerOpen.value}
width="min(420px, 100vw)"
aria-label={t('tagDetail')}
onAfterLeave={() => {
detail.value = void 0
}}
>
{detail.value && (
<NDrawerContent title={detail.value.name}>
{{
default: () => (
<NDescriptions column={1} labelPlacement="top">
<NDescriptionsItem label={t('tagNote')}>
{detail.value?.note || '—'}
</NDescriptionsItem>
</NDescriptions>
),
footer: () => (
<NButton onClick={() => (drawerOpen.value = false)}>
{t('close')}
</NButton>
),
}}
</NDrawerContent>
)}
</NDrawer>
</DemoPage>
)
},
})

View File

@ -1,5 +1,6 @@
import { useI18n } from '@/hooks'
import { RForm, useForm } from '@ray-template/ui/form'
import { RIcon } from '@ray-template/ui/icon'
import {
NButton,
NCard,
@ -124,7 +125,26 @@ export default defineComponent({
inputProps={{ id: ids.age }}
min={0}
max={120}
/>
>
{{
'minus-icon': () => (
<>
<RIcon name="action/minus" aria-hidden="true" />
<span class="r-demo-control-label">
{t('form.decreaseAge')}
</span>
</>
),
'add-icon': () => (
<>
<RIcon name="action/add" aria-hidden="true" />
<span class="r-demo-control-label">
{t('form.increaseAge')}
</span>
</>
),
}}
</NInputNumber>
</NFormItemGi>
<NFormItemGi label={t('form.date')} path="date">
<NDatePicker v-model:value={model.value.date} type="date" />

View File

@ -96,6 +96,7 @@ export default defineComponent({
v-model:show={visible.value}
preset={variant.value === 'dialog' ? 'dialog' : 'card'}
title={t(`modal.${variant.value}`)}
aria-label={t(`modal.${variant.value}`)}
fullscreen={variant.value === 'fullscreen'}
draggable={variant.value !== 'fullscreen'}
cardWidth={`min(${width.value ?? 480}px, calc(100vw - 32px))`}

View File

@ -5,6 +5,7 @@ import { resolveLandingPath } from '@/router/utils/resolve-landing-path'
import { useSigningActions } from '@/store'
import { announceAdminSessionChange } from '@/store/modules/signing'
import { RForm, useForm } from '@ray-template/ui/form'
import { RIcon } from '@ray-template/ui/icon'
import { NButton, NFlex, NFormItem, NInput } from 'naive-ui'
export default defineComponent({
@ -16,6 +17,7 @@ export default defineComponent({
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const passwordVisible = ref(false)
const signingForm = reactive({ name: '', pwd: '' })
const nameId = useId()
const passwordId = useId()
@ -113,10 +115,33 @@ export default defineComponent({
required: true,
enterkeyhint: 'go',
}}
type="password"
showPasswordOn="click"
type={passwordVisible.value ? 'text' : 'password'}
placeholder={t('PasswordPlaceholder')}
/>
>
{{
suffix: () => (
<NButton
attrType="button"
quaternary
size="small"
aria-controls={passwordId}
aria-label={t(
passwordVisible.value ? 'HidePassword' : 'ShowPassword',
)}
onClick={() => {
passwordVisible.value = !passwordVisible.value
}}
>
<RIcon
name={
passwordVisible.value ? 'action/eye-off' : 'action/eye'
}
aria-hidden="true"
/>
</NButton>
),
}}
</NInput>
</NFormItem>
<NFlex vertical>
<NButton

View File

@ -37,6 +37,7 @@
display: grid;
align-self: center;
grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr);
grid-template-areas: 'story panel';
border: 1px solid var(--r-line);
border-radius: 20px;
overflow: clip;
@ -51,6 +52,7 @@
}
&__story {
grid-area: story;
display: flex;
flex-direction: column;
justify-content: space-between;
@ -63,7 +65,7 @@
color: #9ce7ff;
}
h1 {
h2 {
max-width: 14ch;
margin: 18px 0;
font-size: clamp(2rem, 1.2rem + 2.2vw, 3.6rem);
@ -72,7 +74,7 @@
text-wrap: balance;
}
h1 + p {
h2 + p {
max-width: 36ch;
color: #c6d7eb;
line-height: 1.75;
@ -117,20 +119,28 @@
color: var(--r-text-secondary);
}
&__panel {
grid-area: panel;
}
&__panel-heading {
margin-bottom: 20px;
h2 {
h1 {
font-size: clamp(1.5rem, 1.1rem + 1vw, 2rem);
margin-block: 8px;
}
h2 + p {
h1 + p {
color: var(--r-text-secondary);
line-height: 1.6;
}
}
&__method {
margin-block-start: 12px;
}
&__secondary {
margin-top: 20px;
padding-top: 16px;
@ -148,9 +158,10 @@
.login {
&__grid {
grid-template-columns: minmax(0, 1fr);
grid-template-areas: 'panel' 'story';
}
&__story h1 {
&__story h2 {
max-width: 24ch;
}
@ -163,7 +174,7 @@
@media (forced-colors: active) {
.login__story,
.login__story .login__eyebrow,
.login__story h1 + p {
.login__story h2 + p {
color: CanvasText;
}
}

View File

@ -5,25 +5,38 @@ 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 { navigateHorizontalChoice } from '@ray-template/composables/element'
import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDropdown, NFlex, NTabPane, NTabs } from 'naive-ui'
import { NButton, NDropdown, NFlex, NTab, NTabs } from 'naive-ui'
import QRCodeSigning from './components/QRCodeSigning'
import Register from './components/Register'
import Signing from './components/Signing'
import SSOSigning from './components/SSOSigning'
const signInMethods = [
{ name: 'signing', label: 'Signing', Panel: Signing },
{ name: 'register', label: 'Register', Panel: Register },
{ name: 'qrcodeSigning', label: 'QRCodeSigning', Panel: QRCodeSigning },
]
export default defineComponent({
name: 'RLogin',
setup() {
const { updateLocale } = useSettingActions()
const { t } = useI18n('views.login.index')
const tabsValue = ref('signing')
const tabsId = useId()
watchEffect(() => {
document.title = t('PageTitle')
})
return { updateLocale, tabsValue, copyright: __APP_CFG__.layout.copyright }
return {
updateLocale,
tabsValue,
tabsId,
copyright: __APP_CFG__.layout.copyright,
}
},
render() {
const { $t } = this
@ -51,10 +64,69 @@ export default defineComponent({
</header>
<div class="login__grid">
<section class="login__panel" aria-labelledby="login-panel-heading">
<div class="login__panel-heading">
<p class="login__eyebrow">{copy('Access')}</p>
<h1 id="login-panel-heading">{copy('Welcome')}</h1>
<p>
{copy(
apiMockEnabled ? 'AccessDescription' : 'AccountDescription',
)}
</p>
</div>
{apiMockEnabled ? (
<>
<NTabs
v-model:value={this.tabsValue}
type="line"
size="medium"
{...{ role: 'tablist' }}
aria-label={copy('SignInMethods')}
>
{signInMethods.map(({ name, label }) => (
<NTab
key={name}
name={name}
{...{
id: `${this.tabsId}-tab-${name}`,
role: 'tab',
tabindex: this.tabsValue === name ? 0 : -1,
onKeydown: (event: KeyboardEvent) =>
navigateHorizontalChoice(event),
}}
aria-selected={this.tabsValue === name}
aria-controls={`${this.tabsId}-panel-${name}`}
tab={() => copy(label)}
/>
))}
</NTabs>
{signInMethods.map(({ name, Panel }) => (
<div
key={name}
id={`${this.tabsId}-panel-${name}`}
class="login__method"
role="tabpanel"
aria-labelledby={`${this.tabsId}-tab-${name}`}
hidden={this.tabsValue !== name}
tabindex={name === 'signing' ? void 0 : 0}
>
{this.tabsValue === name && <Panel />}
</div>
))}
<div class="login__secondary">
<span>{copy('OtherSignInOptions')}</span>
<SSOSigning />
</div>
</>
) : (
<Signing />
)}
</section>
<section class="login__story" aria-labelledby="login-intro">
<div class="login__story-copy">
<p class="login__eyebrow">RAY TEMPLATE / WORKSPACE</p>
<h1 id="login-intro">{copy('RayTemplate')}</h1>
<h2 id="login-intro">{copy('RayTemplate')}</h2>
<p>{copy('TemplateDescription')}</p>
<ul class="login__stack" aria-label={copy('Stack')}>
<li>Vue 3</li>
@ -66,39 +138,6 @@ export default defineComponent({
<RIcon name="logo/ray" size={128} />
</div>
</section>
<section class="login__panel" aria-labelledby="login-panel-heading">
<div class="login__panel-heading">
<p class="login__eyebrow">{copy('Access')}</p>
<h2 id="login-panel-heading">{copy('Welcome')}</h2>
<p>
{copy(
apiMockEnabled ? 'AccessDescription' : 'AccountDescription',
)}
</p>
</div>
{apiMockEnabled ? (
<>
<NTabs v-model:value={this.tabsValue} type="line" size="medium">
<NTabPane tab={copy('Signing')} name="signing">
<Signing />
</NTabPane>
<NTabPane tab={copy('Register')} name="register">
<Register />
</NTabPane>
<NTabPane tab={copy('QRCodeSigning')} name="qrcodeSigning">
<QRCodeSigning />
</NTabPane>
</NTabs>
<div class="login__secondary">
<span>{copy('OtherSignInOptions')}</span>
<SSOSigning />
</div>
</>
) : (
<Signing />
)}
</section>
</div>
<footer class="login__footer">

View File

@ -2,9 +2,15 @@
max-width: 1360px;
margin-inline: auto;
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 20px;
container-type: inline-size;
&__source-options {
max-inline-size: 100%;
min-inline-size: 0;
}
&__workspace {
display: grid;
grid-template-columns: minmax(0, 1fr);
@ -51,6 +57,7 @@
}
&__editor {
min-inline-size: 0;
font-family: var(--r-font-mono);
font-size: 13px;
}

View File

@ -25,12 +25,13 @@ import {
NFlex,
NFormItem,
NInput,
NRadioButton,
NRadio,
NRadioGroup,
NSelect,
NTag,
} from 'naive-ui'
import { downloadJson } from './download-json'
import { useRouteDraftGuard } from './use-draft-guard'
export default defineComponent({
name: 'RouteManagement',
@ -40,9 +41,11 @@ export default defineComponent({
const remoteReady = ref(false)
const source = ref<RouteSource>(routeSourceStatus.requested)
const draft = ref('')
const baseline = ref('')
const checked = shallowRef<RouteConfig>()
const error = ref('')
const busy = ref(false)
const saving = ref(false)
const file = useTemplateRef<HTMLInputElement>('file')
const editorId = useId()
const resultId = useId()
@ -50,6 +53,10 @@ export default defineComponent({
const titleId = useId()
const viewId = useId()
const newPage = reactive({ path: '', title: '', component: 'dashboard' })
const confirmDiscard = useRouteDraftGuard(
() => draft.value !== baseline.value || !!newPage.path || !!newPage.title,
() => saving.value,
)
const viewOptions = routeViewCatalog.map(({ id }) => ({
label: id,
value: id,
@ -57,6 +64,19 @@ export default defineComponent({
const report = (reason: unknown) => {
checked.value = void 0
if (reason instanceof SyntaxError) {
const location = /\bline (\d+)\s*,?\s*column (\d+)\b/iu.exec(
reason.message,
)
error.value = location
? t('jsonSyntaxAt', { line: location[1], column: location[2] })
: t('jsonSyntax')
return
}
error.value =
reason instanceof AdminApiError && reason.key === 'editConflict'
? t('editConflict')
@ -69,13 +89,23 @@ export default defineComponent({
checked.value = config
error.value = ''
}
const replaceDraft = (config: RouteConfig) => {
setDraft(config)
baseline.value = draft.value
Object.assign(newPage, { path: '', title: '', component: 'dashboard' })
}
const loadStatic = () => {
try {
setDraft(exportRouteConfig(getStaticAppRoutes()))
replaceDraft(exportRouteConfig(getStaticAppRoutes()))
} catch (reason) {
report(reason)
}
}
const replaceAfterConfirmation = async (
load: () => void | Promise<void>,
) => {
if (!busy.value && (await confirmDiscard()) && !busy.value) await load()
}
const validate = () => {
try {
@ -96,6 +126,9 @@ export default defineComponent({
}
const addPage = (event: Event) => {
event.preventDefault()
if (busy.value) return
const config = validate()
if (!config) return
@ -125,12 +158,21 @@ export default defineComponent({
const input = event.currentTarget as HTMLInputElement
const selected = input.files?.[0]
if (!selected) return
input.value = ''
if (!selected || busy.value) return
busy.value = true
try {
if (selected.size > 256 * 1024) throw new Error(t('fileLimit'))
draft.value = await selected.text()
const imported = await selected.text()
if (!(await confirmDiscard())) return
draft.value = imported
Object.assign(newPage, { path: '', title: '', component: 'dashboard' })
selectDraftSource()
@ -138,7 +180,7 @@ export default defineComponent({
} catch (reason) {
report(reason)
} finally {
input.value = ''
busy.value = false
}
}
const loadRemote = async (useDraft = true) => {
@ -151,7 +193,7 @@ export default defineComponent({
revision = snapshot.revision
remoteReady.value = true
if (useDraft) setDraft(snapshot.config)
if (useDraft) replaceDraft(snapshot.config)
} catch (reason) {
report(reason)
} finally {
@ -161,7 +203,7 @@ export default defineComponent({
if (routeSourceStatus.active === 'remote') void loadRemote()
else {
if (routeSourceStatus.config) setDraft(routeSourceStatus.config)
if (routeSourceStatus.config) replaceDraft(routeSourceStatus.config)
else loadStatic()
if (!remoteRoutesReadOnly) void loadRemote(false)
@ -170,33 +212,31 @@ export default defineComponent({
const apply = async () => {
if (busy.value) return
if (source.value === 'remote' && remoteRoutesReadOnly) {
try {
busy.value = true
await activateRemoteRouteSource()
} catch (reason) {
report(reason)
} finally {
busy.value = false
}
const selectedSource = source.value
const readOnly = selectedSource === 'remote' && remoteRoutesReadOnly
const usesDraft = selectedSource !== 'static' && !readOnly
return
}
if (!usesDraft && !(await confirmDiscard())) return
const config = source.value !== 'static' ? validate() : void 0
if (busy.value || source.value !== selectedSource) return
if (source.value !== 'static' && !config) return
const config = usesDraft ? validate() : void 0
if (usesDraft && !config) return
try {
busy.value = true
saving.value = true
if (source.value === 'remote' && config)
if (readOnly) await activateRemoteRouteSource()
else if (selectedSource === 'remote' && config)
await saveRemoteRouteConfig(config, revision)
else saveRouteSource(source.value, config)
else saveRouteSource(selectedSource, config)
} catch (reason) {
report(reason)
} finally {
busy.value = false
saving.value = false
}
}
@ -238,6 +278,10 @@ export default defineComponent({
<NTag
type={routeSourceStatus.error ? 'warning' : 'info'}
bordered={false}
themeOverrides={{
textColorInfo: 'var(--r-text)',
textColorWarning: 'var(--r-text)',
}}
>
{t('active', { source: t(routeSourceStatus.active) })}
</NTag>
@ -251,16 +295,23 @@ export default defineComponent({
<NCard title={t('source')}>
<NFlex align="center" justify="space-between">
<NRadioGroup v-model:value={source.value} aria-label={t('source')}>
{!serverRoutesRequired && (
<>
<NRadioButton value="static">{t('static')}</NRadioButton>
<NRadioButton value="local">{t('local')}</NRadioButton>
</>
)}
<NRadioButton value="remote" disabled={!remoteRouteUrl}>
{t('remote')}
</NRadioButton>
<NRadioGroup
class="route-management__source-options"
v-model:value={source.value}
disabled={busy.value}
aria-label={t('source')}
>
<NFlex size={[12, 8]}>
{!serverRoutesRequired && (
<>
<NRadio value="static">{t('static')}</NRadio>
<NRadio value="local">{t('local')}</NRadio>
</>
)}
<NRadio value="remote" disabled={!remoteRouteUrl}>
{t('remote')}
</NRadio>
</NFlex>
</NRadioGroup>
<NButton
type="primary"
@ -294,19 +345,27 @@ export default defineComponent({
<div class="route-management__workspace">
<NCard title={t('manifest')}>
<NFlex class="route-management__tools">
<NButton size="small" onClick={loadStatic}>
<NButton
size="small"
disabled={busy.value}
onClick={() => void replaceAfterConfirmation(loadStatic)}
>
{t('loadStatic')}
</NButton>
{remoteRouteUrl && (
<NButton
size="small"
loading={busy.value}
onClick={() => void loadRemote()}
disabled={busy.value}
onClick={() => void replaceAfterConfirmation(loadRemote)}
>
{t('loadRemote')}
</NButton>
)}
<NButton size="small" onClick={() => file.value?.click()}>
<NButton
size="small"
disabled={busy.value}
onClick={() => file.value?.click()}
>
{t('import')}
</NButton>
<input
@ -337,6 +396,7 @@ export default defineComponent({
>
<NInput
v-model:value={newPage.path}
disabled={busy.value}
placeholder="/reports"
inputProps={{ id: pathId, required: true }}
/>
@ -348,6 +408,7 @@ export default defineComponent({
>
<NInput
v-model:value={newPage.title}
disabled={busy.value}
inputProps={{ id: titleId, required: true }}
/>
</NFormItem>
@ -358,12 +419,18 @@ export default defineComponent({
>
<NSelect
v-model:value={newPage.component}
disabled={busy.value}
options={viewOptions}
filterable
aria-labelledby={viewId}
/>
</NFormItem>
<NButton attrType="submit" secondary type="primary">
<NButton
attrType="submit"
secondary
type="primary"
disabled={busy.value}
>
{t('addPage')}
</NButton>
</form>
@ -377,6 +444,7 @@ export default defineComponent({
class="route-management__editor"
type="textarea"
value={draft.value}
disabled={busy.value}
rows={19}
inputProps={{
id: editorId,
@ -402,7 +470,7 @@ export default defineComponent({
</span>
</NFlex>
{error.value && (
<NAlert type="error" title={t('invalid')}>
<NAlert type="error" title={t('invalid')} {...{ role: 'alert' }}>
<pre class="route-management__error">{error.value}</pre>
</NAlert>
)}

View File

@ -0,0 +1,49 @@
import { useI18n } from '@/hooks'
import { useSigningGetters } from '@/store'
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
export function useRouteDraftGuard(
dirty: () => boolean,
saving: () => boolean,
) {
const { t } = useI18n('routeManagement')
const { getSigningCallback } = useSigningGetters()
let pending: Promise<boolean> | undefined
let dialog: ReturnType<typeof window.$dialog.warning> | undefined
const confirmDiscard = () => {
if (!dirty()) return Promise.resolve(true)
pending ??= new Promise<boolean>((resolve) => {
let discarded = false
dialog = window.$dialog.warning({
title: t('discardTitle'),
content: t('discardPrompt'),
positiveText: t('discardChanges'),
negativeText: t('keepEditing'),
closable: false,
maskClosable: false,
onPositiveClick: () => {
discarded = true
},
onAfterLeave: () => {
pending = void 0
dialog = void 0
resolve(discarded)
},
})
})
return pending
}
const canLeave = () =>
!getSigningCallback.value.id || (!saving() && confirmDiscard())
onBeforeRouteLeave(canLeave)
onBeforeRouteUpdate(canLeave)
onScopeDispose(() => dialog?.destroy())
return confirmDiscard
}

View File

@ -30,6 +30,7 @@ import {
} from 'naive-ui'
import type { TreeOption } from 'naive-ui'
import { downloadJson } from './download-json'
import { useRouteDraftGuard } from './use-draft-guard'
type Kind = 'page' | 'group' | 'redirect' | 'external'
@ -57,6 +58,11 @@ export default defineComponent({
const text = (key: string) => t<string>(key)
const { t: translate } = useI18n()
const records = ref<RouteConfigRecord[]>([])
const baseline = ref('[]')
const confirmDiscard = useRouteDraftGuard(
() => JSON.stringify(records.value) !== baseline.value,
() => saving.value,
)
const selected = ref<number>()
const expanded = ref<(string | number)[]>([])
const error = ref('')
@ -115,6 +121,8 @@ export default defineComponent({
valid.value = false
}
const load = async () => {
if (loading.value || saving.value) return
loading.value = true
try {
@ -127,6 +135,7 @@ export default defineComponent({
exportRouteConfig(getStaticAppRoutes())
records.value = orderRoutes(structuredClone(config.routes))
baseline.value = JSON.stringify(records.value)
selected.value = tree.value.options[0]?.key as number | undefined
expanded.value = []
clearResult()
@ -366,7 +375,11 @@ export default defineComponent({
title={text('visualTitle')}
description={text('visualDescription')}
>
<NTag type="info" bordered={false}>
<NTag
type="info"
bordered={false}
themeOverrides={{ textColorInfo: 'var(--r-text)' }}
>
{t('active', { source: text(routeSourceStatus.active) })}
</NTag>
</AppPageHeader>
@ -405,12 +418,14 @@ export default defineComponent({
>
{text('export')}
</NButton>
<NPopconfirm onPositiveClick={load}>
{{
trigger: () => <NButton>{text('resetDraft')}</NButton>,
default: () => text('resetConfirm'),
<NButton
disabled={loading.value || saving.value}
onClick={async () => {
if (await confirmDiscard()) await load()
}}
</NPopconfirm>
>
{text('resetDraft')}
</NButton>
<span role="status">{valid.value ? text('draftValid') : ''}</span>
</NFlex>
{error.value && (
@ -423,7 +438,11 @@ export default defineComponent({
</NAlert>
)}
</NCard>
<div class="route-management__workspace route-management__workspace--visual">
<div
class="route-management__workspace route-management__workspace--visual"
inert={loading.value || saving.value}
aria-busy={loading.value || saving.value}
>
<NCard title={text('preview')}>
{addMenu('addRoot')}
<NTree

View File

@ -36,6 +36,19 @@
&__organization .n-card__content-scrollbar {
overscroll-behavior: contain;
}
&__organization-picker {
> summary {
padding-block: 6px;
cursor: pointer;
font-weight: 600;
}
> summary span {
margin-inline-start: 8px;
color: var(--r-text-secondary);
font-weight: 400;
}
}
&__list-viewport {
block-size: 100%;
}
@ -101,10 +114,18 @@
line-height: 1.5;
padding-block: 4px;
}
&__identity strong {
&--compact &__identity {
justify-items: start;
overflow-wrap: anywhere;
}
&--compact &__row-actions .n-button {
min-inline-size: 24px;
min-block-size: 28px;
}
&__identity > strong {
font-weight: 500;
}
&__identity span {
&__identity > span:not(.n-tag) {
font-size: 12px;
color: var(--r-text-secondary);
}

View File

@ -31,6 +31,7 @@ import {
NCard,
NDescriptions,
NDescriptionsItem,
NDropdown,
NFlex,
NModal,
NResult,
@ -39,7 +40,7 @@ import {
NTag,
NTree,
} from 'naive-ui'
import type { DataTableColumns, TreeOption } from 'naive-ui'
import type { DataTableColumn, DataTableColumns, TreeOption } from 'naive-ui'
import { useUserErrorMessage } from './error-message'
import UserEditor from './UserEditor'
@ -56,6 +57,7 @@ export default defineComponent({
const pageElement = shallowRef<HTMLElement>()
const { width } = useElementSize(pageElement)
const stacked = computed(() => width.value > 0 && width.value <= 850)
const compact = computed(() => width.value > 0 && width.value < 600)
const options = shallowRef<UserOptions>()
const optionError = ref(false)
const optionLoading = ref(false)
@ -63,8 +65,13 @@ export default defineComponent({
const queryParams = computed(() => ({ departmentId: departmentId.value }))
const pagination = { pageSizes: [10, 20, 50] }
const searchFields = computed<TableProSearchFieldConfig[]>(() => [
{ key: 'name', label: t('name'), placeholder: t('nameHint') },
{ key: 'username', label: t('username') },
{
type: 'text',
key: 'name',
label: t('name'),
placeholder: t('nameHint'),
},
{ type: 'text', key: 'username', label: t('username') },
{
type: 'select',
key: 'status',
@ -75,6 +82,10 @@ export default defineComponent({
],
},
])
const search = computed(() => ({
fields: searchFields.value,
defaultCollapsed: stacked.value,
}))
const checked = ref<(string | number)[]>([])
const editorOpen = ref(false)
const editing = shallowRef<AdminUser>()
@ -128,6 +139,28 @@ export default defineComponent({
return [{ key: '', label: t('allUsers'), children: visit(null) }]
})
const renderOrganizationTree = () => (
<NTree
data={tree.value}
blockLine
indent={12}
defaultExpandedKeys={[
'',
...(options.value?.departments ?? [])
.filter((item) =>
options.value?.departments.some(
(child) => child.parentId === item.id,
),
)
.map((item) => item.id),
]}
selectedKeys={[departmentId.value]}
onUpdateSelectedKeys={(keys) => {
departmentId.value = String(keys[0] ?? '')
checked.value = []
}}
/>
)
const roleEditable = (user: AdminUser) =>
!!options.value?.roles.some(
(role) => role.value === user.role && !role.disabled,
@ -214,7 +247,130 @@ export default defineComponent({
loadingUser.value = ''
}
}
const renderStatus = (row: AdminUser) => (
<NTag
size="small"
bordered={false}
type={row.status === 'enabled' ? 'success' : 'default'}
>
{t(row.status)}
</NTag>
)
const renderActions = (row: AdminUser) => {
const enabled = row.status === 'enabled'
const actions = [
{
key: 'edit',
visible: editable(row),
label: t('edit'),
name: t('editNamed', { name: row.name }),
disabled: !!loadingUser.value || busy.value,
run: () => void openUser(row.id, true),
},
{
key: 'status',
visible:
hasPermission('users:status') &&
row.id !== getSigningCallback.value.id &&
roleEditable(row),
label: t(enabled ? 'disable' : 'enable'),
name: t(enabled ? 'disableNamed' : 'enableNamed', { name: row.name }),
disabled: busy.value,
run: () => changeStatus([row.id], enabled ? 'disabled' : 'enabled'),
},
{
key: 'credential',
visible: canSetCredential(row),
label: translate('account.setPassword'),
name: translate('account.setPasswordFor', { name: row.name }),
run: () => {
credentialTarget.value = row
},
},
{
key: 'delete',
visible: removable(row),
label: t('delete'),
name: t('deleteNamed', { name: row.name }),
disabled: busy.value,
run: () => confirmDelete([row.id], row.name),
},
].filter((action) => action.visible)
return (
<NFlex
class="user-management__row-actions"
size={compact.value ? 5 : 'small'}
wrap={false}
align="center"
>
<NButton
text
size="small"
aria-label={t('viewNamed', { name: row.name })}
loading={loadingUser.value === row.id}
onClick={() => void openUser(row.id)}
>
{t('view')}
</NButton>
{compact.value
? actions.length > 0 && (
<NDropdown
trigger="click"
options={actions.map(({ key, label, disabled }) => ({
key,
label,
disabled,
}))}
onSelect={(key) =>
actions.find((action) => action.key === key)?.run()
}
>
<NButton
text
size="small"
aria-label={t('moreNamed', { name: row.name })}
aria-haspopup="menu"
>
<RIcon name="action/more" size={16} aria-hidden="true" />
</NButton>
</NDropdown>
)
: actions.map((action) => (
<NButton
key={action.key}
text
type={
action.key === 'delete'
? 'error'
: action.key === 'edit'
? 'primary'
: 'default'
}
size="small"
aria-label={action.name}
disabled={action.disabled}
onClick={action.run}
>
{action.label}
</NButton>
))}
</NFlex>
)
}
const columns = computed<DataTableColumns<AdminUser>>(() => {
const actionColumn: DataTableColumn<AdminUser> = {
title: t('actions'),
key: 'actions',
fixed: stacked.value ? void 0 : 'right',
width: compact.value
? 100
: hasPermission('users:credentials')
? 300
: 240,
allowExport: false,
render: renderActions,
}
const result: DataTableColumns<AdminUser> = [
{
type: 'selection',
@ -225,14 +381,17 @@ export default defineComponent({
{
title: t('name'),
key: 'name',
minWidth: 155,
width: compact.value ? 116 : void 0,
minWidth: compact.value ? 116 : 155,
render: (row) => (
<div class="user-management__identity">
<strong>{row.name}</strong>
<span>{row.username}</span>
{compact.value && renderStatus(row)}
</div>
),
},
...(compact.value ? [actionColumn] : []),
{
title: t('email'),
key: 'email',
@ -255,93 +414,9 @@ export default defineComponent({
title: t('status'),
key: 'status',
width: 90,
render: (row) => (
<NTag
size="small"
bordered={false}
type={row.status === 'enabled' ? 'success' : 'default'}
>
{t(row.status)}
</NTag>
),
},
{
title: t('actions'),
key: 'actions',
fixed: stacked.value ? void 0 : 'right',
width: hasPermission('users:credentials') ? 300 : 240,
allowExport: false,
render: (row) => (
<NFlex size="small" wrap={false}>
<NButton
text
size="small"
aria-label={t('viewNamed', { name: row.name })}
loading={loadingUser.value === row.id}
onClick={() => void openUser(row.id)}
>
{t('view')}
</NButton>
{editable(row) && (
<NButton
text
type="primary"
size="small"
aria-label={t('editNamed', { name: row.name })}
disabled={!!loadingUser.value || busy.value}
onClick={() => void openUser(row.id, true)}
>
{t('edit')}
</NButton>
)}
{hasPermission('users:status') &&
row.id !== getSigningCallback.value.id &&
roleEditable(row) && (
<NButton
text
size="small"
disabled={busy.value}
aria-label={t(
row.status === 'enabled' ? 'disableNamed' : 'enableNamed',
{ name: row.name },
)}
onClick={() =>
changeStatus(
[row.id],
row.status === 'enabled' ? 'disabled' : 'enabled',
)
}
>
{t(row.status === 'enabled' ? 'disable' : 'enable')}
</NButton>
)}
{canSetCredential(row) && (
<NButton
text
size="small"
aria-label={translate('account.setPasswordFor', {
name: row.name,
})}
onClick={() => (credentialTarget.value = row)}
>
{translate('account.setPassword')}
</NButton>
)}
{removable(row) && (
<NButton
text
type="error"
size="small"
aria-label={t('deleteNamed', { name: row.name })}
disabled={busy.value}
onClick={() => confirmDelete([row.id], row.name)}
>
{t('delete')}
</NButton>
)}
</NFlex>
),
render: renderStatus,
},
...(compact.value ? [] : [actionColumn]),
]
return hasPermission(['users:delete', 'users:status'], 'any')
@ -383,7 +458,10 @@ export default defineComponent({
ref={pageElement}
class={[
'user-management',
{ 'user-management--stacked': stacked.value },
{
'user-management--stacked': stacked.value,
'user-management--compact': compact.value,
},
]}
>
<AppPageHeader
@ -430,32 +508,23 @@ export default defineComponent({
options.value && (
<div class="user-management__layout">
<NCard
title={t('organization')}
title={stacked.value ? void 0 : t('organization')}
class="user-management__organization"
size={stacked.value ? 'small' : 'medium'}
contentScrollable
contentStyle={{ paddingInline: '12px', paddingBlock: '8px' }}
>
<NTree
data={tree.value}
blockLine
indent={12}
defaultExpandedKeys={[
'',
...options.value.departments
.filter((item) =>
options.value!.departments.some(
(child) => child.parentId === item.id,
),
)
.map((item) => item.id),
]}
selectedKeys={[departmentId.value]}
onUpdateSelectedKeys={(keys) => {
departmentId.value = String(keys[0] ?? '')
checked.value = []
}}
/>
{stacked.value ? (
<details class="user-management__organization-picker">
<summary>
{t('organization')}
<span>{departmentLabel(departmentId.value)}</span>
</summary>
{renderOrganizationTree()}
</details>
) : (
renderOrganizationTree()
)}
</NCard>
<NScrollbar
class="user-management__list-viewport"
@ -526,7 +595,7 @@ export default defineComponent({
scrollX={1060}
pageSize={10}
pagination={pagination}
search={searchFields.value}
search={search.value}
onSearch={() => {
checked.value = []
}}

View File

@ -117,6 +117,7 @@ export default defineConfig({
socialLinks: [{ icon: 'github', link: repository }],
},
markdown: {
theme: { light: 'github-light-high-contrast', dark: 'github-dark' },
config(md) {
const renderLink = md.renderer.rules.link_open

View File

@ -38,6 +38,11 @@ export function createSidebar(english: boolean): DefaultTheme.Sidebar {
{
text: label('开发指南', 'Development'),
items: [
entry(
'CURD 交互示例',
'CURD interaction examples',
'/guide/curd-examples',
),
entry(
'路由、菜单与权限',
'Routes, menus, and permissions',

View File

@ -30,4 +30,6 @@ When application changes affect public APIs, update the corresponding documentat
Lightweight examples run directly in the documentation. Examples that need the admin application context embed `example.html` from the same version, register only demo routes, and keep ordinary cache and store state within the example instance. TablePro column visibility uses a separate session namespace so it can be checked across reloads in the same tab. Markdown includes source from the file actually running. During development, run both `pnpm dev` and `pnpm docs:dev`. If the admin server uses a port other than 9527, set `VITE_RAY_EXAMPLE_ORIGIN` for the documentation server, for example `http://127.0.0.1:9528`.
Switching the documentation theme updates open examples in place and preserves their current input and selection.
To verify embedded admin examples or the combined deployment, run `pnpm pages:build`, then `pnpm preview --outDir ../../dist/pages`. Open `/ray-template/docs/` at that shared address and exercise only affected examples. Expand to all examples for a release or an explicit request. `pnpm docs:preview` alone previews the documentation and its directly hosted lightweight examples.

View File

@ -11,7 +11,7 @@ Switch styles under **Preferences → Appearance → Interface style**. Style is
| 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. Solid buttons with a custom primary color choose black or white text for the actual fill of each interaction state. 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.
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.
### Where styles live {#样式放在哪里}

View File

@ -0,0 +1,48 @@
# CURD interaction examples
The CURD examples menu in Ray Admin contains two business workflows. Each example below runs with its own demo data. Edits in the admin app are saved for the current browser session. Reload an embedded example to restore its initial data.
Both menu items are in the initial route configuration. To use them with a saved route snapshot, copy the CURD examples group from the initial configuration into that snapshot.
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
## Simple example: tags {#tags}
Create a tag from the toolbar or edit a tag from its row. The actions pass their own initial values and save function to the same short form. Select a tag name to read the notes in a drawer while keeping your place in the list.
Try using an existing name such as `Design`. The editor keeps your input if the save fails. Change a field and press Esc to choose whether to keep editing or discard your changes. The deletion confirmation names the tag it will remove.
<AdminExample path="/curd/tags" title="Simple CURD: Tags" :height="520" />
::: details View the tag example source
<<< ../../../admin/src/views/demo/curd/tags.tsx
<<< ../../../admin/src/views/demo/curd/TagEditorModal.tsx
:::
## Complex example: projects and milestones {#projects}
The project list has name and status filters, sorting, and pagination. Create, Detail, and Edit have independent routes. Create and Edit share an editor, and Detail presents project information and milestones as readable text.
1. Filter by In progress, open a project, and choose Edit.
2. Change the owner or add a milestone. Cancel to choose whether to keep editing or discard the draft and return to Detail.
3. Save to see the updated Detail. Back to projects restores the applied filters, sort, and page.
4. Open Edit from the list to return to the list after saving or cancelling. When you delete a project, the confirmation identifies its milestones as part of the deletion.
<AdminExample path="/curd/projects" title="Complex CURD: Projects and milestones" :height="780" />
::: details View the project list and action container source
<<< ../../../admin/src/views/demo/curd/projects.tsx
<<< ../../../admin/src/views/demo/curd/project-create.tsx
<<< ../../../admin/src/views/demo/curd/project-edit.tsx
<<< ../../../admin/src/views/demo/curd/project-detail.tsx
<<< ../../../admin/src/views/demo/curd/ProjectEditor.tsx
:::
[Your first business page](./first-page) · [Routes, menus, and permissions](./routing)

View File

@ -55,6 +55,8 @@ Add the `Orders` translation to both `menu.json` language files. If the current
User Management under System Management already demonstrates department filtering, remote queries, create and edit flows, details, bulk actions, and API permissions. Use it as a complete example when integrating a feature. [Standard API contract](./backend)
Use the [CURD interaction examples](./curd-examples) to compare modals and drawers on one list with separate routes for Create, Detail, and Edit.
## Connect the API {#接入-api}
Write the order query in `apps/admin/src/api`. Map TablePro pagination and filters to backend fields and replace `data` with `request={loadOrders}`. Return the current page of rows and the filtered total. Follow the [remote TablePro example](../reference/table-pro-examples#远端查询与失败恢复) for sorting, cancellation, and retry.

View File

@ -20,6 +20,8 @@ Change the path, name, or view ID to see the shared validator's result. This exa
With `routes:write`, the visual and JSON editors load the complete draft from the editor endpoint and save it with `PUT /admin/route-config`. The runtime routes then reload. Mock writes persist in the current browser, and you can switch to a local or built-in configuration. In standard backend mode, the remote configuration is authoritative and load failures surface as errors. If you configured the read-only `VITE_ROUTE_CONFIG_URL`, select the remote source in the JSON editor and enable the remote configuration to resume reading that URL. Save edits to a read-only source locally or export the draft.
If you have unsaved changes, the editor asks for confirmation before you leave the page, reload the saved configuration, or import a replacement. Choose **Keep editing** to retain the draft. You can also export it from the current editor.
The request body is `{ version: 1, routes: [...] }`. Both read and write results are in `data` in the shared `{ code, msg, data }` envelope. `component` must be a registered ID in `router/config/views.ts`. Register the ID for a new frontend page before returning its route from the API. [Standard backend contract](./backend)
## Common metadata {#常用元数据}

View File

@ -31,7 +31,7 @@ Click **Age** to cycle through ascending, descending, and default order. The tab
1. Copy part of a row's name or email into the filter area and submit. The query returns to page 1 and pagination uses the filtered total.
2. Clear the filters, sort by **Age**, and change pages. `onUpdateSorter` maps the sort to `params.sortAge`, which applies to the full result set before pagination.
3. Select rows on two pages. The toolbar shows the total across pages. **More actions → Export CSV** exports visible data columns on the current page.
4. Click **Simulate request failure** to see the old rows clear and an error appear. Click **Refresh** to recover. Forward `request`'s `signal` to the HTTP client for cancellation.
4. Click **Simulate request failure** to see the old rows clear and an error appear in the table. Click **Retry** to recover. Forward `request`'s `signal` to the HTTP client for cancellation.
<AdminExample path="/tables/remote" title="Remote queries, server-side sort, and retry" :height="695" deferred />
@ -59,7 +59,7 @@ Switch between local matching and a mock remote query. After each action, compar
2. **Dependencies and cancellation.** Switch quickly between North and South. The owner draft clears and the previous options request is canceled. Search South's options for **Wang**.
3. **Zero and boolean values.** Apply the delivery and amount scenario and expand an order. Follow the product cascader, warehouse tree, delivery control, and datetime field. Confirm `minAmount: 0` and `invoiced: false` are preserved.
4. **Validation and automatic apply.** Submit a one-character keyword and check that existing rows remain. Correct it, enable automatic submission on input, and edit repeatedly to see the debounce.
5. **Recover independent failures.** Fail the owner options or list request once. Retry options at the field, or resubmit the list query.
5. **Recover independent failures.** Fail the owner options or list request once. Retry options at the field and list requests in the table.
<AdminExample path="/tables/search" title="Combined filters, remote options, and advanced search" :height="960" deferred />

View File

@ -50,7 +50,7 @@ const renderRemote = () => (
)
```
- Remote `request(params, signal)` returns `Promise<{ data, total }>`. The component accepts only the latest result. Changing the source or filter scope clears old rows and the total. Changing the page or page size hides old rows. Until the current page resolves, the instance returns no rows and CSV and printing are unavailable. A failure clears rows and total, shows the empty state, and uses the host toast. Retry with `reload()`. Forward the signal to the HTTP client to cancel the transport.
- Remote `request(params, signal)` returns `Promise<{ data, total }>`. The component accepts only the latest result. Changing the source or filter scope clears old rows and the total. Changing the page or page size hides old rows. Until the current page resolves, the instance returns no rows and CSV and printing are unavailable. A failure clears rows and total and displays an error with a retry button in the table. Call `reload()` to retry from code. Forward the signal to the HTTP client to cancel the transport.
- 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.
@ -64,7 +64,7 @@ Start with any of the following scenarios. Compare the draft, applied filters, a
- **Delivery and amount.** Use the product cascader, warehouse tree, minimum amount, invoice state, custom delivery method, and delivery time. Apply the filters and expand a matching order to check delivery details. The request retains `minAmount: 0` and `invoiced: false`.
- **Validation.** Submit a one-character keyword and check the error while the previous rows remain visible. Correct it, switch to automatic apply on input, and edit rapidly to observe the list requests.
Use the recent request controls to fail either the owner lookup or the list once. Retry owner options under the field. For a list failure, submit the query again from the empty state.
Use the recent request controls to fail either the owner lookup or the list once. Retry owner options under the field. For a list failure, use the retry button in the table.
<AdminExample path="/tables/search" title="Combined filters, dependent fields, and retry" :height="960" />
@ -227,9 +227,10 @@ Pagination objects use `TableProPagination`. Replace the old `pagination.onChang
| `filters` | Above the table. Receives `{ submit(values) }` for string- or number-keyed filters. Submit returns to page 1. Takes precedence over built-in `search`. |
| `title` / `toolbar` | Left title area and right action area. Both are hidden in `bare` mode. |
| `notice` | Custom notice in normal conditions. |
| `error` | Replaces `notice` after failure if supplied. Receives `{ reload }` and replaces the default toast. |
| `error` | Replaces `notice` and the default feedback on request failure. Receives `{ reload }`. |
| `tableFooter` / `tableAction` | Extra regions after DataTable. |
| Other slots | Forwarded to Naive UI DataTable, including loading and empty state. |
| `empty` | Custom empty view after a successful query. The default distinguishes zero rows from zero filter matches and offers a reset for built-in filters. |
| Other slots | Forwarded to Naive UI DataTable, including loading. |
`TableProInst.reload(resetPage?)`, `setPage(page)`, and `setPageSize(size)` return `Promise<void>`. Request errors use events, so promise completion alone does not establish business success. `getTableInstance()` may be `null`. `print(options?)` returns `Promise<boolean>` indicating whether a preview was requested. `downloadCsv(options?)` initiates a browser download. `copyImage(options?)` reports whether a PNG was written to the clipboard.

View File

@ -9,11 +9,14 @@
</summary>
<div v-if="!deferred || started" class="ray-admin-example-frame">
<iframe
ref="exampleFrame"
class="ray-admin-example"
:src="src"
:src="frameSrc"
:title="title"
:height="height ?? 490"
loading="lazy"
referrerpolicy="strict-origin"
@load="syncTheme"
/>
</div>
<p>
@ -24,7 +27,7 @@
<script setup lang="ts">
import { useData, withBase } from 'vitepress'
import { computed, ref } from 'vue'
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue'
const props = defineProps<{
path: string
@ -35,19 +38,24 @@ const props = defineProps<{
deferred?: boolean
}>()
const { isDark, lang } = useData()
const frame = useTemplateRef<HTMLIFrameElement>('exampleFrame')
const started = ref(false)
const frameDark = ref(isDark.value)
const newTabText = computed(() =>
lang.value.startsWith('en')
? 'Run this example in a new tab'
: '在新标签页运行此示例',
)
const openExample = (event: Event) => {
if ((event.currentTarget as HTMLDetailsElement).open) started.value = true
if ((event.currentTarget as HTMLDetailsElement).open && !started.value) {
frameDark.value = isDark.value
started.value = true
}
}
const adminBase = withBase('/').replace(/[^/]+\/$/, '')
const src = computed(() => {
const exampleUrl = (dark: boolean) => {
const query = new URLSearchParams({
theme: isDark.value ? 'dark' : 'light',
theme: dark ? 'dark' : 'light',
lang: lang.value.startsWith('en') ? 'en' : 'zh-CN',
})
@ -60,5 +68,22 @@ const src = computed(() => {
: ''
return `${server}${adminBase}example.html?${query}#${props.path}`
})
}
const frameSrc = computed(() => exampleUrl(frameDark.value))
const src = computed(() => exampleUrl(isDark.value))
const syncTheme = () => {
const iframe = frame.value
iframe?.contentWindow?.postMessage(
{
type: 'ray-template:example-theme',
theme: isDark.value ? 'dark' : 'light',
},
new URL(iframe.src).origin,
)
}
onMounted(syncTheme)
watch(isDark, syncTheme)
</script>

View File

@ -11,7 +11,7 @@
| Material | 紫色调、较大的圆角、胶囊按钮和分层表面 |
| 朴素 | 中性灰、小圆角和无阴影表面 |
手动选择的主题色优先于预设,并随风格保留;点击「使用风格默认色」可恢复当前风格的配色。自定义主色的实心按钮会按各交互状态的实际填充色选择黑字或白字,半透明主色按当前主题卡片底色合成。新用户、恢复默认设置,以及缺少风格的历史配置都使用现代化。已有的显式风格选择会在刷新和导入时保留。
手动选择的主题色优先于预设,并随风格保留。点击「使用风格默认色」可恢复当前风格的配色。浅色模式下,自定义主色的实心按钮使用白字,主题会适度加深过浅的按钮色以保持可读性。深色模式按实际填充色选择黑字或白字。半透明主色按当前主题卡片底色合成。新用户、恢复默认设置和缺少风格的历史配置都使用现代化。已有的显式风格选择会在刷新和导入时保留。
### 样式放在哪里

View File

@ -0,0 +1,48 @@
# CURD 交互示例
Ray Admin 的「CURD 示例」菜单包含两套业务。下方可直接运行,每个示例使用独立的演示数据。后台菜单中的修改保存在当前浏览器会话,内嵌示例刷新后会恢复初始数据。
初始路由配置包含这两个菜单项。已有路由快照可以从初始配置取出「CURD 示例」分组并合并到当前配置。
<script setup>
import AdminExample from '../examples/AdminExample.vue'
</script>
## 简单示例:标签管理 {#tags}
在工具栏新增标签,或从行操作编辑现有标签。两个动作分别提供默认值或现有记录,并把各自的保存函数交给同一个短表单。点击标签名称可在抽屉里快速查看备注,原列表保留在原处。
试着输入已有的标签名,例如 `Design`。保存失败后,表单会保留输入。修改一个字段后按 Esc,可以选择继续编辑或放弃更改。删除确认会显示目标标签。
<AdminExample path="/curd/tags" title="简单 CURD:标签管理" :height="520" />
::: details 查看标签示例源码
<<< ../../admin/src/views/demo/curd/tags.tsx
<<< ../../admin/src/views/demo/curd/TagEditorModal.tsx
:::
## 复杂示例:项目与里程碑 {#projects}
项目列表有名称和状态筛选、排序及分页。新增、详情和编辑各有独立路由。新增和编辑复用同一个编辑器,详情页用只读内容展示基本信息和里程碑。
1. 筛选「进行中」,打开一个项目详情,再进入编辑。
2. 修改负责人或添加里程碑。取消时可保留草稿继续编辑,或放弃更改并返回详情。
3. 保存后,详情会展示新值。返回列表时,会恢复应用过的筛选、排序和页码。
4. 从列表直接编辑,则保存或取消后回到列表。删除项目时,确认弹窗会说明里程碑也将删除。
<AdminExample path="/curd/projects" title="复杂 CURD:项目与里程碑" :height="780" />
::: details 查看项目列表与动作容器源码
<<< ../../admin/src/views/demo/curd/projects.tsx
<<< ../../admin/src/views/demo/curd/project-create.tsx
<<< ../../admin/src/views/demo/curd/project-edit.tsx
<<< ../../admin/src/views/demo/curd/project-detail.tsx
<<< ../../admin/src/views/demo/curd/ProjectEditor.tsx
:::
[第一个业务页面](./first-page) · [路由、菜单与权限](./routing)

View File

@ -55,6 +55,8 @@ orders: { load: () => import('@/views/orders'), name: 'Orders' },
现成的「系统管理 → 用户管理」已演示组织筛选、远端查询、新增编辑、详情、批量操作和接口权限。可先对照这条完整流程,再接入自己的业务。其 API 与数据结构见[标准契约](./backend)。
在 [CURD 交互示例](./curd-examples) 中,可以对比同一列表中的弹窗和抽屉,以及用独立路由组合新增、详情和编辑的做法。
## 接入 API
在 `apps/admin/src/api` 写订单请求函数,将 TablePro 的分页、筛选条件映射成后端的字段,并把 `data` 替换成 `request={loadOrders}`。接口需返回当前页数据和筛选后的总数。参照[远端 TablePro 在线示例](../reference/table-pro-examples#远端查询与失败恢复)接入排序、取消和错误重试。

View File

@ -20,6 +20,8 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue'
有 `routes:write` 权限时,可视化和 JSON 页面从编辑接口加载完整草稿,通过 `PUT /admin/route-config` 保存,随后刷新运行路由。Mock 写入会保存在当前浏览器,也可以切换本机或内置配置。标准后端模式以远端为准,读取失败时显示错误。 若配置了只读的 `VITE_ROUTE_CONFIG_URL`,在 JSON 页面选择远程来源并点击“启用远程配置”即可恢复读取该地址。修改只读来源的草稿可以保存在本地或导出。
编辑器中有未保存的修改时,切换页面、重新读取配置或导入替换草稿都会先请求确认。选择「继续编辑」会保留草稿,也可以从当前编辑器导出草稿。
接口请求体为 `{ version: 1, routes: [...] }`,读取和写入响应都放在统一 `{ code, msg, data }` 包络的 `data` 中。`component` 必须是 `router/config/views.ts` 的注册 ID;新增前端页面先注册 ID,再由接口返回其路由记录。详见[服务端标准契约](./backend)。
## 常用元数据

View File

@ -31,7 +31,7 @@ import AdminExample from '../examples/AdminExample.vue'
1. 复制某行姓名或邮箱的一部分,填入上方筛选区并提交。查询回到第 1 页,分页使用筛选后的总数。
2. 清除条件后排序「年龄」并翻页。年龄排序通过 `onUpdateSorter` 转成 `params.sortAge`,在分页前作用于整个结果集。
3. 分别在两页勾选行;工具栏显示跨页选中总数。「更多操作 → 导出 CSV」导出当前页可见数据列。
4. 点击「模拟请求失败」,观察旧行清空和错误提示;点击「刷新」恢复。传给 `request` 的 `signal` 可转交给 HTTP 客户端。
4. 点击「模拟请求失败」,观察旧行清空和表内错误提示。点击「重试」恢复。传给 `request` 的 `signal` 可转交给 HTTP 客户端。
<AdminExample path="/tables/remote" title="远端查询、服务端排序与重试" :height="695" deferred />
@ -59,7 +59,7 @@ import AdminExample from '../examples/AdminExample.vue'
2. **联动和取消**:快速切换北区和南区。负责人草稿会清空,旧的候选请求会取消。在南区候选项中搜索「王雨」。
3. **零值与布尔值**:点击「交付与金额」,应用条件后展开订单。查看商品级联、仓库树、配送控件和日期时间字段如何配合,确认参数保留 `minAmount: 0` 与 `invoiced: false`。
4. **校验与自动查询**:提交单字符关键词,确认旧结果仍在;修正输入后切换为输入后自动应用,连续编辑观察防抖。
5. **分别恢复失败**:让负责人候选或列表失败一次。候选可在字段处重试,列表可再次提交。
5. **分别恢复失败**:让负责人候选或列表失败一次。候选可在字段处重试,列表可在表格内重试。
<AdminExample path="/tables/search" title="组合条件、远程选项和高级搜索" :height="960" deferred />

View File

@ -50,7 +50,7 @@ const renderRemote = () => (
)
```
- 远端 `request(params, signal)` 返回 `Promise<{ data, total }>`。组件只采用最新请求结果;切换请求源或筛选范围时清空旧行和总数,切页或修改每页条数时隐藏旧行。没有当前页结果时,实例取数为空、CSV 和打印不可用。请求失败时清空行与总数,沿用空态,并通过宿主 Toast 提醒;调用方可用实例 `reload()` 重试。要中止底层 HTTP,请把 signal 交给请求客户端。
- 远端 `request(params, signal)` 返回 `Promise<{ data, total }>`。组件只采用最新请求结果;切换请求源或筛选范围时清空旧行和总数,切页或修改每页条数时隐藏旧行。没有当前页结果时,实例取数为空、CSV 和打印不可用。请求失败时清空行与总数,表格会显示错误和重试按钮。调用方也可以用实例 `reload()` 重试。要中止底层 HTTP,请把 signal 交给请求客户端。
- 搜索提交回到第 1 页。外部筛选用 `params`,复杂表单可从 `filters` 插槽调用 `submit(values)`。服务端排序和过滤由调用方将事件值映射进 `params`。
- 默认每页 10 条;用 `pageSize`、`pagination.pageSizes` 调整,或传 `pagination={false}` 关闭。关闭时不添加分页字段;`bare pagination` 可单独开启分页。
- 初始页用 `pagination.defaultPage`。远端模式下组件管理当前页、每页条数和总数;调用方已有自己的远端控制时可传 `remote + data + pagination`,并自行处理范围切换。受控分页由调用方在回调中更新页码和每页条数;搜索重置和实例操作都触发对应回调。
@ -64,7 +64,7 @@ const renderRemote = () => (
- **交付与金额**填入商品级联、仓库树、最低金额、开票状态、自定义配送方式和交付时间。应用后展开匹配订单核对交付信息,留意请求中保留了 `minAmount: 0` 与 `invoiced: false`。
- **试试校验**提交一个字符的关键词,查看校验提示及保留的列表。修正输入后,可以切换「输入后自动应用」,快速连续编辑并观察列表请求。
在「最近请求」里还能让负责人或列表请求失败一次。负责人选项使用字段下方的重试;列表失败显示空态,通过再次查询恢复。
在「最近请求」里还能让负责人或列表请求失败一次。负责人选项使用字段下方的重试。列表请求失败时,使用表格内的重试按钮。
<AdminExample path="/tables/search" title="组合筛选、组织联动与失败重试" :height="960" />
@ -227,9 +227,10 @@ Naive UI DataTable 的列定义、选择、展开、加载、空态和虚拟滚
| `filters` | 表格上方;接收 `{ submit(values) }`,传入字符串或数字键值,提交后回第一页。优先于内置 `search`。 |
| `title` / `toolbar` | 标题区左侧 / 操作区右侧;`bare` 下两者隐藏。 |
| `notice` | 正常情况下显示自定义提示。 |
| `error` | 显式提供时在请求失败后替换 `notice`,接收 `{ reload }` 并接管默认 Toast。 |
| `error` | 请求失败时接管默认反馈并替换 `notice`,接收 `{ reload }`。 |
| `tableFooter` / `tableAction` | DataTable 之后的额外区域。 |
| 其余插槽 | 转给 Naive UI DataTable,例如空态和加载。 |
| `empty` | 自定义查询成功后的空态。默认区分无数据和无匹配结果,后者为内置筛选提供重置操作。 |
| 其余插槽 | 转给 Naive UI DataTable,例如加载状态。 |
`TableProInst` 的 `reload(resetPage?)`、`setPage(page)`、`setPageSize(size)` 返回 `Promise<void>`。请求错误由事件报告;该 Promise 的完成不能用作业务成功判据。`getTableInstance()` 可能为 `null`;`print(options?)` 返回 `Promise<boolean>` 表示是否发起预览;`downloadCsv(options?)` 发起浏览器下载;`copyImage(options?)` 返回是否成功写入 PNG 剪贴板。

83
docs/curd-conventions.md Normal file
View File

@ -0,0 +1,83 @@
# CURD interaction conventions
Use these conventions when adding or changing business lists and record workflows in Ray Template. Keep short actions close to the list, give work that needs independent access or more space a dedicated page, and return users to a predictable place when the task ends. Create, Edit, and Detail each have an action container and can share the same layout.
Try the [runnable examples](../apps/docs/en/guide/curd-examples.md) for a short tag form and a routed project workflow with milestones.
## Choose the surface
| Surface | Choose it when | Examples |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| Dedicated page | The task needs its own URL for direct access, refresh, sharing, or browser history. Also use it for multistep flows, long or wide content, and editing related records or working across sections. | Configure a project, manage an order with line items, open a linked record from a notification. |
| Drawer | A row-level task benefits from keeping its place in the list and fits in a single side-panel flow. Use it by default for list-bound detail previews and for short edits where the surrounding list provides context. | Preview a member's details or update a record's basic settings. |
| Modal | A brief, focused task needs the user's attention and fits comfortably in one view at the intended sizes. Use it for confirmations and short forms that need little source context. | Create a tag, rename a record, confirm deletion. |
| Inline or split view | Use inline for a small, local change that is easy to reverse. Use a split view when the user needs to interact with the list and record at the same time. | Toggle a reversible preference, inspect several rows in a master–detail view. |
Check for a dedicated-page requirement first. A modal drawer preserves visual context and blocks interaction with the background. Use the same surface for Create and Edit when their workflows are comparable. A drawer preview can offer a link to the full Detail page. [Carbon form variants](https://www.carbondesignsystem.com/building-blocks/core/patterns/forms#variants)
## Start and finish in context
- Put Create in the list toolbar. Give each record a clear Detail entry, such as a linked name for a route or a View button for a drawer. Place Edit and less frequent actions in the row action area. Put destructive actions in its overflow menu when space or prominence calls for it.
- Use distinct verbs for different outcomes. **Create** makes a new record, **Add** attaches an existing one, **Save changes** applies an edit, **Cancel** exits a form, and **Close** dismisses a read-only overlay. Use an object name in the title or confirmation when it helps identify the target. [Carbon common actions](https://www.carbondesignsystem.com/building-blocks/core/patterns/common-actions)
- When Edit starts from Detail, return to Detail on cancel or after a successful save. If both fit in a drawer, replace its Detail content with the Edit container and reuse the same drawer. When editing needs a page, navigate to its route. After a save, show the updated record.
- For Create or Edit launched from the list, return to the same list context on cancel or save. Preserve the applied filters, sort, page, and scroll position as far as the updated results allow. Open the saved record's Detail when the user has a clear next step there. Keep a successful save visible through feedback even when the current filter excludes the saved record.
- Return focus to an overlay's opener. If the opener is gone, focus a logical surviving row or the list toolbar. After deleting a record from its Detail page, return to the list. [WAI-ARIA modal dialog pattern](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/)
## Compose the action containers
The surface renders the title, content, and actions, manages scrolling, and forwards close requests. The action container owns record identity, access checks, data loading and mapping, the write command, and the destination after saving or cancelling. A shared editor owns the working draft, field validation, and the submit interaction. Expose its dirty and pending state to the action container for exit checks.
| Container | Data and behavior | Visible actions |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| Create | Initialize a fresh draft from defaults and explicit context, such as the current department. Bind the create command. | **Create**, **Cancel** |
| Edit | Load the record by ID, capture its revision when supported, and map the response into a fresh draft. Bind the update command to that ID and revision. | **Save changes**, **Cancel** |
| Detail | Load by ID and render readable values, labels, and sections with a description component. Offer Edit only when permitted and applicable. | **Back** on a page or **Close** in an overlay, plus **Edit** when available |
Each project action container can render the same workspace, whether users enter from a route or a list action.
```text
ProjectCreate → ProjectWorkspace → ProjectEditor (defaults, create command)
ProjectEdit → ProjectWorkspace → ProjectEditor (mapped record, bound update command)
ProjectDetail → ProjectWorkspace → ProjectDescription (record)
```
Select the action container at the route or overlay entry point. A single page can select it from local action state such as `{ kind: 'edit', id }`. Let the container supply the title, button copy, permissions, and action-specific fields. The shared editor receives initial values, validation rules, and a save function. Compose separate field groups when Create and Edit diverge. Share labels, section layout, and value formatters between editor and Detail. Keep the containers feature-local and extract shared pieces once their contracts match across consumers.
Reuse `AppPageHeader` for route pages, `RModal` or Naive UI's `NModal` for modal content, `NDrawer` with `NDrawerContent` for drawers, `RForm` with `useForm` for editors, and `NDescriptions` for labelled values. Import shared components from their feature entry points. Add interface copy in Simplified Chinese and English. [UI entry points](../harness/context/ui.md) · [Locale resources](../apps/admin/src/locales/README.md)
## Routes and state ownership
- Use distinct named routes for independent entries, such as `/projects`, `/projects/new`, `/projects/:id`, and `/projects/:id/edit`. Reserve action segments such as `new` from the ID namespace. Open routes inside the current browser tab by default. Register the views and use `hidden` or `sameLevel` as appropriate for parameterized pages. Choose the menu, workspace tab, breadcrumbs, and cache behavior together. [Routing contract](../apps/admin/src/router/README.md)
- Load routed Detail and Edit from their URL identity so direct entry and reload work. Local overlays open from the list or detail page and use local state. Use an ID and the necessary shareable view state in the URL. Fetch record content through the feature API. Reset or reload when the active ID changes, including in reused route views. [Vue Router route parameters](https://router.vuejs.org/guide/essentials/dynamic-matching#reacting-to-params-changes)
- For a page, return to the known in-app origin or use the feature's named fallback on direct entry. The fallback is the list for Create and Detail, and Detail for Edit when accessible. Use the list if Detail is unavailable. After saving, return through known history or replace the completed editing location so browser Back reaches a meaningful page.
- Keep editor routes uncached by default. Make draft retention across workspace tabs an explicit workflow decision. Let the list own its query and selection. Encode the shareable part in route query parameters when needed and account for the shell's full-URL view keys. Clear selection when the page or applied query changes unless the feature explicitly supports cross-page selection with a visible scope and count. [Shell view keys](../packages/admin-shell/src/RouteTransition.vue)
## List and detail states
- Distinguish initial loading, an empty dataset, zero search matches, and load failure. Offer Create on an empty dataset when permitted, clear filters for zero matches, and a retry for failed reads. Detail and Edit also need states for a missing record and denied access. Show content and enable writes for the current, loaded record. Use list rows for summaries and IDs, and load the complete record for an editor.
- Hide actions the user lacks permission to perform. If an otherwise available action is blocked by the record's state, give an accessible reason. Enforce authorization on the server for each read and write, including direct links and batch targets.
## Editing and saving
1. **Start each session or record change with its own draft and baseline.** Determine whether the draft is dirty by comparing editable values with that baseline. Keep draft mutations local to the editor. Cancel superseded reads where supported and let only the current session's results update the editor.
2. **Use one submit path for keyboard and button actions.** Mark required fields, use visible labels, and validate on submit or after interacting with a field. Show actionable errors near their fields and focus the first invalid control or error summary on failed submission. Map the draft to a typed API input and validate it on the server as well.
3. **Allow one submission at a time.** Show progress on the primary action and guard repeated triggers while the write is pending. Display field errors by the affected inputs and other save failures within the editor. Preserve the draft on failure. For a revision conflict, offer a way to review the latest data before resubmitting. If a timeout leaves the outcome unknown, reconcile the result or use the API's supported idempotent retry.
4. **Show success after the write is confirmed.** Use the saved response or re-fetch the changed record. On a remote list, call the `RTablePro` instance's `reload()` to preserve the current page. It handles a page that goes out of range after deletion. Use `reload(true)` for an intentional return to page one. If refreshing fails after a successful write, report the refresh failure and offer a refresh retry. [TablePro contract](../packages/ui/src/RTablePro/README.md)
5. **Use the same exit check for Cancel, close, Escape, navigation, and record changes.** Allow clean exits directly. For dirty drafts, offer **Keep editing** and **Discard changes**. Keep the editor in place while saving and make the pending state visible. Use route leave and update guards as applicable for page editors, and include any workspace controls that refresh or close the current editor. [Vue Router navigation guards](https://router.vuejs.org/guide/advanced/navigation-guards)
## Delete and batch actions
- Use a confirmation modal for irreversible or consequential deletion and for batch deletion. Identify the record or count, state the effect on related data when relevant, and label the destructive action **Delete**. Focus the least destructive action first and disable accidental backdrop dismissal for the confirmation. Direct deletion is reserved for low-impact actions with a reliable undo. [Carbon common actions](https://www.carbondesignsystem.com/building-blocks/core/patterns/common-actions#delete) · [WAI-ARIA initial focus guidance](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/)
- Confirm and submit a snapshot of the selected IDs. Show pending feedback, refresh after confirmed changes, and remove successful targets from the selection. When the API reports partial success, report the succeeded and failed counts, keep failed eligible targets identifiable for retry, and retry only those targets. Start with current-page selection and support cross-page or all-matching selection only when its scope is explicit in both the UI and API.
## Overlay and responsive behavior
- Give modal surfaces an accessible name and a visible exit. On open, focus the first field for a short editor or a heading for long read-only content. Keep keyboard focus inside modal surfaces. Use one record overlay at a time. Its own confirmation may temporarily take focus and return it to the overlay when dismissed. [WAI-ARIA modal dialog pattern](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/)
- Disable backdrop dismissal on editing overlays. Give the body one scroll area when content overflows and keep the actions reachable. Let drawers use the viewport width on narrow screens while preserving the same draft and exit behavior. Use semantic theme tokens and shell dimensions for any custom styling. [UI styling contract](ui-design.md#custom-css-contract)
## Verify a CURD flow
- Exercise the intended list entry, permissions, loading and empty states, Create, Detail, Edit, and Delete as applicable. Check success, failure, dirty cancellation, rapid record changes, and duplicate submit protection on the affected flows.
- For a page, check direct entry, reload, Back, and return to the previous list query. For an overlay, check keyboard focus, Escape, narrow-screen scrolling, and access to actions. For bulk operations, check selection scope and the reported result.
Select the affected paths and dimensions using [Harness verification](../harness/README.md#choosing-the-verification-scope).

View File

@ -70,6 +70,8 @@ Use `minmax(0, 1fr)`, `min-inline-size: 0`, logical sizing/spacing, and content-
## Page composition
Use the [CURD interaction conventions](curd-conventions.md) for business lists, record details, and editing workflows.
- Limit dashboard and explanatory demo content to 1360px and center it. Business tables continue to honor fluid/fixed-width layout preferences; do not narrow them globally.
- Use `DemoPage` and `HookExample`, grouped by function. Separate interactive content from expandable code. Use native details elements for code, retain keyboard operation, and provide copying.
- Hook examples use two columns when the content container reaches 900px. The layout lab uses settings/preview columns at 760px. Default to a single stacked column below those thresholds. Base decisions on available content width, not only browser-window width.

View File

@ -12,6 +12,8 @@ Use this topic when adding or changing pages, shared UI, themes, bilingual copy,
The application's `@/components` and some hook/directive paths retain compatibility exports. Follow exports into the owning shared package before fixing common behavior. Inject host-specific services instead of referencing application aliases from shared packages. Add both Chinese and English for new interface copy.
For business screens, follow the [CURD interaction conventions](../../docs/curd-conventions.md) for surface selection, action containers, and list and editor behavior.
For custom CSS, follow the [semantic-token and scope contract](../../docs/ui-design.md#custom-css), then use the [reader recipe](../../apps/docs/guide/appearance.md#custom-css) or [independent-host example](../../apps/docs/examples/ThemeScopeExample.vue). The authoritative token definitions remain in [theme.css](../../packages/ui/src/theme.css) and its [mapping](../../packages/ui/src/theme-presets.ts); do not copy preset palettes into page styles.
Before adding a component, check existing capabilities using the [Harness reuse conventions](../README.md#engineering-conventions). For full-height content and independent scrolling, start with [TablePro height styles](../../packages/ui/src/RTablePro/src/index.scss), [layout height variables](../../packages/admin-shell/src/layout-css-vars.ts), and the [user management page](../../apps/admin/src/views/user-management/index.tsx). `RTablePro autoHeight` uses `--r-table-height` to fill its host. Naive UI's `NCard contentScrollable` and `NScrollbar` handle scrolling; the parent uses Flex/Grid and `min-block-size: 0` to provide a definite height that can shrink.

View File

@ -15,12 +15,10 @@
.r-layout-presets {
box-sizing: border-box;
display: grid;
grid-auto-flow: column;
grid-auto-columns: minmax(72px, 1fr);
grid-template-columns: repeat(auto-fit, minmax(min(100%, 72px), 1fr));
gap: 6px;
max-inline-size: min(100%, 410px);
padding: 5px;
overflow-x: auto;
}
.r-layout-preset {

View File

@ -24,6 +24,26 @@
"id": "demo/context-menu",
"name": "ContextMenuDemo"
},
{
"id": "demo/curd/tags",
"name": "CurdTags"
},
{
"id": "demo/curd/projects",
"name": "CurdProjects"
},
{
"id": "demo/curd/project-create",
"name": "CurdProjectCreate"
},
{
"id": "demo/curd/project-detail",
"name": "CurdProjectDetail"
},
{
"id": "demo/curd/project-edit",
"name": "CurdProjectEdit"
},
{
"id": "demo/directive",
"name": "RDirective"
@ -183,6 +203,10 @@
"icons": [
"action/add",
"action/adjustment",
"action/archive",
"action/bookmark",
"action/check",
"action/clipboard",
"action/close",
"action/close_all",
"action/close_left",
@ -190,35 +214,149 @@
"action/close_right",
"action/copy",
"action/copy-image",
"action/crop",
"action/cut",
"action/delete",
"action/download",
"action/draggable",
"action/edit",
"action/erase",
"action/external-link",
"action/eye",
"action/eye-off",
"action/filter",
"action/fullscreen",
"action/fullscreen_fold",
"action/heart",
"action/link",
"action/link-off",
"action/lock",
"action/minus",
"action/more",
"action/mouse",
"action/out",
"action/pause",
"action/pin",
"action/play",
"action/print",
"action/redo",
"action/reload",
"action/save",
"action/scan",
"action/search",
"action/setting",
"action/shared",
"action/sort-ascending",
"action/sort-descending",
"action/star",
"action/star-filled",
"action/stop",
"action/table-bordered",
"action/table-striped",
"action/undo",
"action/unlock",
"action/upload",
"action/zoom-in",
"action/zoom-out",
"analytics/area-chart",
"analytics/bar-chart",
"analytics/bar-chart-horizontal",
"analytics/candlestick-chart",
"analytics/dashboard-gauge",
"analytics/data-sheet",
"analytics/donut-chart",
"analytics/line-chart",
"analytics/pie-chart",
"analytics/pulse",
"analytics/report",
"analytics/scatter-chart",
"analytics/target",
"analytics/trend-down",
"analytics/trend-up",
"commerce/bag",
"commerce/bank",
"commerce/credit-card",
"commerce/currency-exchange",
"commerce/discount",
"commerce/gift",
"commerce/invoice",
"commerce/order",
"commerce/package",
"commerce/shop",
"commerce/shopping-cart",
"commerce/tag",
"commerce/truck",
"commerce/wallet",
"communication/announcement",
"communication/at-sign",
"communication/bell",
"communication/bell-off",
"communication/chat",
"communication/chat-unread",
"communication/headset",
"communication/inbox",
"communication/mail",
"communication/mail-open",
"communication/messages",
"communication/microphone",
"communication/microphone-off",
"communication/phone",
"communication/phone-off",
"communication/reply",
"communication/send",
"communication/video-call",
"communication/voicemail",
"directional/arrow-down",
"directional/arrow-down-left",
"directional/arrow-down-right",
"directional/arrow-up",
"directional/arrow-up-left",
"directional/arrow-up-right",
"directional/chevron-left",
"directional/chevron-right",
"directional/chevron-up",
"directional/chevrons-left",
"directional/chevrons-right",
"directional/circle-down",
"directional/circle-up",
"directional/enter",
"directional/expanded",
"directional/left_arrow",
"directional/move",
"directional/resize_h",
"directional/right_arrow",
"directional/row_end",
"directional/row_head",
"directional/swap-horizontal",
"directional/vertical-sort",
"files/book",
"files/book-open",
"files/books",
"files/camera",
"files/cloud-download",
"files/cloud-upload",
"files/file-add",
"files/file-archive",
"files/file-audio",
"files/file-check",
"files/file-code",
"files/file-gif",
"files/file-jpg",
"files/file-lock",
"files/file-pdf",
"files/file-presentation",
"files/file-search",
"files/file-spreadsheet",
"files/file-text",
"files/file-video",
"files/file-word",
"files/folder",
"files/folder-add",
"files/folder-open",
"files/folder-search",
"files/image",
"files/paperclip",
"files/video",
"logo/axios",
"logo/github",
"logo/google",
@ -226,31 +364,89 @@
"logo/twitter",
"navigation/appearance",
"navigation/barcode",
"navigation/building",
"navigation/calendar",
"navigation/calendar-check",
"navigation/calendar-date",
"navigation/cards",
"navigation/compass",
"navigation/components",
"navigation/dashboard",
"navigation/database",
"navigation/document",
"navigation/echart",
"navigation/flag",
"navigation/flow",
"navigation/form",
"navigation/globe",
"navigation/grid",
"navigation/home",
"navigation/icons",
"navigation/layers",
"navigation/layout",
"navigation/list",
"navigation/map",
"navigation/map-pin",
"navigation/menu",
"navigation/other",
"navigation/panel-grid",
"navigation/qr_code",
"navigation/rely",
"navigation/routing",
"navigation/table",
"navigation/timeline",
"navigation/tree",
"navigation/window",
"navigation/workbench",
"status/blocked",
"status/error",
"status/info",
"status/loading",
"status/pending",
"status/question",
"status/success",
"status/warning",
"system/battery",
"system/bluetooth",
"system/bug",
"system/cloud-storage",
"system/code",
"system/code-brackets",
"system/command",
"system/cpu",
"system/dark",
"system/desktop",
"system/fingerprint",
"system/hard-drive",
"system/key",
"system/language",
"system/light",
"system/mobile",
"system/network",
"system/plug",
"system/power",
"system/puzzle",
"system/server",
"system/shield",
"system/shield-check",
"system/system_os",
"system/watermark"
"system/tablet",
"system/terminal",
"system/watermark",
"system/wifi",
"users/contact",
"users/handshake",
"users/id-card",
"users/organization",
"users/team",
"users/user",
"users/user-add",
"users/user-circle",
"users/user-location",
"users/user-remove",
"users/user-search",
"users/user-shield",
"users/users"
],
"iconAliases": {
"action/export_excel": "action/download",

View File

@ -154,6 +154,48 @@
}
]
},
{
"path": "/curd",
"meta": {
"i18nKey": "menu.CurdExamples",
"icon": "navigation/form",
"order": 18
},
"children": [
{
"path": "tags",
"name": "CurdTags",
"component": "demo/curd/tags",
"meta": { "i18nKey": "menu.CurdTags" }
},
{
"path": "projects",
"name": "CurdProjects",
"component": "demo/curd/projects",
"meta": { "i18nKey": "menu.CurdProjects" }
},
{
"path": "projects/new",
"name": "CurdProjectCreate",
"component": "demo/curd/project-create",
"meta": { "i18nKey": "menu.CurdProjectCreate", "sameLevel": true }
},
{
"path": "projects/:id",
"name": "CurdProjectDetail",
"component": "demo/curd/project-detail",
"props": true,
"meta": { "i18nKey": "menu.CurdProjectDetail", "sameLevel": true }
},
{
"path": "projects/:id/edit",
"name": "CurdProjectEdit",
"component": "demo/curd/project-edit",
"props": true,
"meta": { "i18nKey": "menu.CurdProjectEdit", "sameLevel": true }
}
]
},
{
"path": "/examples/components",
"meta": {

View File

@ -25,7 +25,7 @@ import { RTablePro } from '@/components'
- 普通模式按 Naive UI 卡片组织搜索、表头工具、数据与页脚。搜索区在结果上方;`bare` 保留纯表格外观。表格左上方可用 `title` 传文字,或用同名插槽放筛选开关、快捷操作等;都不传时不占位。`toolbar` 插槽和默认工具集中在表格右上方。
- 行标识默认取 `row.id` 或 `row.key`,其他字段使用 `rowKey`。宽表可设置 `scrollX` 和列宽,横向滚动留在表格内部。根列拖动或固定时保留分组的子列。
- `autoHeight` 默认使用当前布局的可用高度,宿主外部使用视口高度;嵌入特定区域时可以用 CSS 变量 `--r-table-height` 覆盖。较短的屏幕保留表格的最小操作高度。
- 只接收最新的请求结果。切换请求源或有效筛选条件会立即清空旧行和总数;切页或修改每页条数会隐藏旧行并保留同一范围的总数。当前页未加载时,实例取数返回空、底层实例返回 `null`,CSV 和打印不会启动。请求失败后显示空态并清空总数,通过宿主 Toast 提醒。可用 `onRequestError` 接收详情、用实例 `reload()` 重试,或显式提供 `error` 插槽接管提示。
- 只接收最新的请求结果。切换请求源或有效筛选条件会立即清空旧行和总数;切页或修改每页条数会隐藏旧行并保留同一范围的总数。当前页未加载时,实例取数返回空、底层实例返回 `null`,CSV 和打印不会启动。请求失败后清空行与总数,在表格中显示错误和重试按钮。可用 `onRequestError` 接收详情、用实例 `reload()` 重试,或提供 `error` 插槽自定义反馈。应用筛选后无结果时,默认显示无匹配提示,并为内置筛选提供重置操作。
- 需要实例时使用 `shallowRef<TableProInst>()`。实例提供 `reload(resetPage?)`、`setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print`、`copyImage` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。
- 工具栏将业务 `toolbar` 插槽与内置工具分组。`request` 模式提供刷新,列设置、复制图片和全屏保持直接入口;「更多操作」统一收纳密度、斑马纹、边框与 CSV。斑马纹和边框的功能图标始终显示,选中状态在文字右侧单独标记;密度子菜单只保留文字和选中标记。TablePro 的 `size` 默认是 `medium`(标准),菜单与表格共用该值;传入 `small` 或 `large` 时分别选中紧凑或宽松。打印默认隐藏,设置 `showPrint` 后出现在该菜单。`tool={false}` 隐藏全部内置工具,仍保留业务插槽。

View File

@ -1,5 +1,6 @@
import { call } from '@ray-template/composables/vue/call'
import { isEqual } from 'lodash-es'
import { NButton, NEmpty } from 'naive-ui'
import type { PaginationProps } from 'naive-ui'
import {
computed,
@ -12,7 +13,6 @@ import {
watch,
} from 'vue'
import type { ExtractPublicPropTypes, PropType } from 'vue'
import { useUiServices } from '../../services'
import Search from './components/Search'
import type { TableSearchFormInst } from './components/Search'
import { useTableLocale } from './locale'
@ -123,7 +123,6 @@ export default defineComponent({
},
setup(props, { attrs, slots, expose, emit }) {
const { t } = useTableLocale()
const { reportError } = useUiServices()
const table = shallowRef<TablePanelInst>()
const searchForm = useTemplateRef<TableSearchFormInst>('searchForm')
const customFilters = ref(!!slots.filters)
@ -261,11 +260,7 @@ export default defineComponent({
? { page: page.value, pageSize: pageSize.value }
: void 0,
updatePage,
reportError: (error) => {
emit('request-error', error)
if (!slots.error) reportError?.(t('requestError'))
},
reportError: (error) => emit('request-error', error),
})
const reload = (resetPage = false) => {
if (resetPage) updatePage(1)
@ -481,7 +476,40 @@ export default defineComponent({
return () => {
const { request, search, loading: externalLoading, remote } = props
const { filters, error, notice, ...panelSlots } = slots
const { filters, error, notice, empty, ...panelSlots } = slots
const failed = !!request && requestPhase.value === 'failed'
const loading = requestPhase.value === 'loading' || externalLoading
const searched = Object.keys(applied.value.values).length > 0
let renderEmpty = empty
if (failed && error) renderEmpty = () => []
else if (failed || (!loading && !empty && searched)) {
renderEmpty = () => [
<NEmpty>
{{
default: () => (
<span role={failed ? 'alert' : 'status'}>
{t(failed ? 'requestError' : 'noMatches')}
</span>
),
extra: () =>
failed ? (
<NButton size="small" onClick={() => void reload()}>
{t('retry')}
</NButton>
) : searchFields.value.length ? (
<NButton
size="small"
onClick={() => void instance.resetSearch()}
>
{t('resetFilters')}
</NButton>
) : null,
}}
</NEmpty>,
]
}
const paginationProps: false | PaginationProps =
pagination.value === false
? false
@ -510,7 +538,7 @@ export default defineComponent({
}
rowActionsDisabled={!!request && !activeResult.value}
reload={request ? reload : void 0}
loading={requestPhase.value === 'loading' || externalLoading}
loading={loading}
pagination={paginationProps}
onUpdatePage={setPage}
onUpdatePageSize={setPageSize}
@ -536,10 +564,8 @@ export default defineComponent({
/>
)
: void 0,
notice:
requestPhase.value === 'failed' && error
? () => error({ reload })
: notice,
empty: renderEmpty,
notice: failed && error ? () => error({ reload }) : notice,
}}
</TablePanel>
)

View File

@ -67,7 +67,14 @@ export default defineComponent({
const wrapper = useTemplateRef<HTMLElement>('wrapper')
const form = useTemplateRef<FormInst>('form')
const { width } = useElementSize(wrapper)
const collapsed = ref(props.options?.defaultCollapsed ?? false)
const chosenCollapsed = ref<boolean>()
const collapsed = computed({
get: () =>
chosenCollapsed.value ?? props.options?.defaultCollapsed ?? false,
set: (value) => {
chosenCollapsed.value = value
},
})
const measuredColumns = computed(() =>
Math.min(
gridSize(props.options?.maxColumns, 4),

View File

@ -33,6 +33,8 @@
"total": "{count} records",
"clearSelection": "Clear selection ({count})",
"requestError": "Couldn't load the data",
"noMatches": "No results match the filters",
"resetFilters": "Reset filters",
"retry": "Retry",
"density": "Table density",
"compact": "Compact",

View File

@ -33,6 +33,8 @@
"total": "共 {count} 条",
"clearSelection": "清除已选({count})",
"requestError": "数据加载失败",
"noMatches": "没有符合筛选条件的数据",
"resetFilters": "重置筛选",
"retry": "重试",
"density": "表格密度",
"compact": "紧凑",