refactor: migrate deprecated APIs and prefer component hooks

This commit is contained in:
XiaoDaiGua-Ray 2026-11-27 16:56:57 +08:00
parent d67e64d48c
commit d3a2504d37
No known key found for this signature in database
35 changed files with 223 additions and 184 deletions

View File

@ -5,6 +5,8 @@ A Vue 3 + TSX admin template with an admin application, a documentation site, an
- To locate an implementation, choose a topic from the [task index](llms.txt) or `pnpm harness context <scope>`. Consult the [architecture map](docs/architecture.md) for changes that cross module boundaries.
- Check `git status` first and preserve existing changes. Trace callers and existing data contracts before changing routing, persistence, requests, or shared components.
- Prefer feature entry points for runtime imports. Follow the [runtime import boundaries](harness/README.md#runtime-import-boundaries) when adding exports or changing what loads at startup or on demand.
- Prefer supported component hooks for imperative actions. Bind the hook's registration callback when required and call its returned actions. Follow the [component action conventions](docs/curd-conventions.md#component-actions) for tables, forms, and modals.
- Use `void 0` for an undefined runtime value and `undefined` in type annotations. Use the recommended replacements for APIs marked `@deprecated`.
- For complex tasks, the lead agent may choose to use subagents under the [delegation guidelines](harness/README.md#using-subagents-when-useful), when the host supports them and current permissions allow it. Delegation needs no separate approval. The lead agent owns integration and final verification.
- Write agent guidance and internal engineering documentation in English. Preserve the intended languages of product copy and reader-facing documentation.
- Follow the [comment style](docs/comment-style.md) when adding or editing comments. Maintain both Chinese and English product copy. For visible behavior changes, use [browser verification](harness/README.md#browser-verification) only for affected pages, actions, and dimensions.

View File

@ -28,15 +28,25 @@ vi.mock('@/hooks', () => ({
it('honors avatar shape, native size, and keyboard focus', () => {
const wrapper = mount(AppAvatar, {
props: { round: false, size: 42, objectFit: 'contain' },
props: {
round: false,
size: 42,
objectFit: 'contain',
color: 'rgb(18, 52, 86)',
},
})
try {
expect(wrapper.findComponent(NAvatar).props()).toMatchObject({
const avatar = wrapper.findComponent(NAvatar)
expect(avatar.props()).toMatchObject({
round: false,
size: 42,
objectFit: 'contain',
})
expect((avatar.element as HTMLElement).style.backgroundColor).toBe(
'rgb(18, 52, 86)',
)
expect(wrapper.findComponent(NButton).props('focusable')).toBe(true)
} finally {
wrapper.unmount()

View File

@ -1,51 +0,0 @@
import { useAppRoot } from '../../apps/admin/src/hooks/template/useAppRoot'
import setupMiniApp from '../utils/setupMiniApp'
describe('useAppRoot', async () => {
await setupMiniApp()
const { setRootRoute } = useAppRoot()
it(`should return '/test' and 'test'`, () => {
setRootRoute({
path: '/test',
name: 'test',
})
const { getRootPath, getRootName } = useAppRoot()
expect(getRootPath.value).toBe('/test')
expect(getRootName.value).toBe('test')
})
it(`should be returned a object like: {path: /test2, name: test2}`, () => {
const baseRootRoute = {
path: '/test2',
name: 'test2',
}
setRootRoute(baseRootRoute)
const { getRootRoute } = useAppRoot()
expect(getRootRoute.value).toEqual(baseRootRoute)
})
it('should update root route when setRootRoute is called', () => {
const baseRootRoute = {
path: '/test3',
name: 'test3',
}
setRootRoute({
path: '/test3',
name: 'test3',
})
const { getRootPath, getRootName, getRootRoute } = useAppRoot()
expect(getRootPath.value).toBe('/test3')
expect(getRootName.value).toBe('test3')
expect(getRootRoute.value).toEqual(baseRootRoute)
})
})

View File

@ -2,18 +2,7 @@ import { useDevice } from '../../apps/admin/src/hooks/web/useDevice'
describe('useDevice', () => {
const addEventListenerSpy = vi.spyOn(window, 'addEventListener')
const matchMediaSpy = vi
.spyOn(window, 'matchMedia')
.mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
const matchMediaSpy = vi.spyOn(window, 'matchMedia')
beforeEach(() => {
addEventListenerSpy.mockClear()

View File

@ -6,7 +6,6 @@ const { state } = vi.hoisted(() => ({
state: {
instance: void 0 as
| {
mode: string
global: {
t: (key: string, ...args: unknown[]) => string
locale: Ref<string>
@ -24,7 +23,6 @@ vi.mock('../../apps/admin/src/locales', () => ({
beforeEach(() => {
state.instance = {
mode: 'composition',
global: { t: (key) => key, locale: ref('zh-CN') },
}
})
@ -46,12 +44,12 @@ describe('useI18n namespaces', () => {
expect(hook.t('code')).toBe('hooks.code')
expectTypeOf(hook.t('code')).toEqualTypeOf<string>()
state.instance = {
mode: 'composition',
global: { t: (key) => `translated:${key}`, locale: ref('zh-CN') },
}
expect(hook.t('code')).toBe('translated:hooks.code')
hook.locale('en-US')
expect(state.instance.global.locale.value).toBe('en-US')
expect(document.documentElement.lang).toBe('en-US')
state.instance.global.t = (key) => `updated:${key}`
expect(hook.t('code')).toBe('updated:hooks.code')
})

View File

@ -1,5 +1,4 @@
import { APP_CATCH_KEY } from '@/app-config'
import { useAppRoot } from '@/hooks/template/useAppRoot'
import { useSiderBar } from '@/hooks/template/useSiderBar'
import { setupI18n } from '@/locales'
import { permissionRouter } from '@/router/utils/permission'
@ -120,7 +119,10 @@ it('starts with no active business page and never injects a missing cached dashb
})
it('closes the final business tab, even when it is the legacy root preference', async () => {
useAppRoot().setRootRoute({ path: '/reports', name: 'Reports' })
piniaSettingStore().updateSettingState('appRootRoute', {
path: '/reports',
name: 'Reports',
})
await router.push('/reports?sort=asc#summary')
await flushPromises()
expect(actions.getCurrentTagIndex()).toBe(0)
@ -177,7 +179,9 @@ it('closes left, right and other tabs without protecting any business path', asy
it('closes all tags independently of missing or unauthorized root preferences', async () => {
await router.push('/reports')
await router.push('/orders')
useAppRoot().setRootRoute({ path: '/deleted-home' })
piniaSettingStore().updateSettingState('appRootRoute', {
path: '/deleted-home',
})
await actions.closeAll()
await flushPromises()
expect(menu.menuTagOptions).toEqual([])

View File

@ -62,8 +62,12 @@ describe('layout preferences', () => {
const store = piniaSettingStore()
expect(store.sideBarLogo?.url).toBe(migrated)
expect(store.appRootRoute.path).toBe('/old-unregistered-home')
expect(store.appRootRoute).toEqual({
name: 'Old',
path: '/old-unregistered-home',
})
store.updateSettingState('sideBarLogo', { url: '/dashboard' })
store.updateSettingState('appRootRoute', { path: '/saved-home' })
store.$persist()
first.app.unmount()
disposePinia(first.pinia)
@ -71,6 +75,10 @@ describe('layout preferences', () => {
try {
expect(piniaSettingStore().sideBarLogo?.url).toBe('/dashboard')
expect(piniaSettingStore().appRootRoute).toEqual({
name: 'Old',
path: '/saved-home',
})
expect(
piniaSettingStore().exportPreferences().preferences,
).not.toHaveProperty('workspaceLandingMigrated')

View File

@ -6,9 +6,10 @@ import {
setupRouter,
} from '../../apps/admin/src/router'
const { load, register } = vi.hoisted(() => ({
const { load, register, resetScroll } = vi.hoisted(() => ({
load: vi.fn(),
register: vi.fn(),
resetScroll: vi.fn(),
}))
vi.mock('../../apps/admin/src/router/config/source', () => ({
@ -31,7 +32,7 @@ vi.mock('../../apps/admin/src/router/app-route-modules', () => ({
getStaticAppRoutes: () => [],
}))
vi.mock('../../apps/admin/src/router/utils', () => ({
scrollViewToTop: vi.fn(),
scrollViewToTop: resetScroll,
vueRouterRegister: register,
}))
@ -53,6 +54,39 @@ it('loads no business routes before login, then shares a retry and registers gua
expect(register).toHaveBeenCalledOnce()
} finally {
clearAccountRoutes()
router.options.history.destroy()
}
})
afterAll(() => {
router.options.history.destroy()
})
it('resets workspace scroll after successful and repeated navigation', async () => {
const removeRoute = router.addRoute({
path: '/scroll-target',
component: { render: () => null },
})
const removeBlockedRoute = router.addRoute({
path: '/scroll-blocked',
component: { render: () => null },
beforeEnter: () => false,
})
try {
resetScroll.mockClear()
await router.push('/scroll-target')
expect(resetScroll).toHaveBeenCalledExactlyOnceWith(
router.currentRoute.value,
)
resetScroll.mockClear()
await router.push('/scroll-blocked')
expect(resetScroll).not.toHaveBeenCalled()
await router.push('/scroll-target')
expect(resetScroll).toHaveBeenCalledExactlyOnceWith(
router.currentRoute.value,
)
} finally {
removeBlockedRoute()
removeRoute()
}
})

View File

@ -5,12 +5,7 @@
*
* 如果可以操作 DOM,则返回 true,否则返回 false。
*/
const canUseDom = () => {
return !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
)
}
const canUseDom = () =>
typeof window !== 'undefined' && !!window.document?.documentElement
export default canUseDom

View File

@ -6,10 +6,6 @@
* 如果是浏览器环境,则返回 true,否则返回 false。
*/
const isBrowser = () =>
!!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
)
typeof window !== 'undefined' && !!window.document?.documentElement
export default isBrowser

View File

@ -4,6 +4,11 @@ import { avatarProps, NAvatar } from 'naive-ui'
const center = 20
const fontSize = 26
export const accountAvatarProps = {
...avatarProps,
color: String,
}
export const accountAvatarFont = {
fontWeight: 600,
fontFamily: 'system-ui, sans-serif',
@ -41,7 +46,7 @@ export function measureAccountText(text: string, size: number) {
export default defineComponent({
name: 'AccountAvatar',
props: {
...avatarProps,
...accountAvatarProps,
name: { type: String, default: '' },
},
setup(props) {
@ -83,13 +88,13 @@ export default defineComponent({
}
return () => {
const { name: _name, ...avatar } = props
const { name: _name, color, ...avatar } = props
return (
<NAvatar
{...avatar}
class="r-account-avatar"
style={avatar.color ? { backgroundColor: avatar.color } : void 0}
style={color ? { backgroundColor: color } : void 0}
renderFallback={
avatar.renderFallback ??
(avatar.fallbackSrc ? void 0 : renderInitial)

View File

@ -1,9 +1,10 @@
import { useSigningGetters } from '@/store'
import { avatarProps, NButton, NFlex } from 'naive-ui'
import { NButton, NFlex } from 'naive-ui'
import type { AvatarProps, FlexProps } from 'naive-ui'
import type { PropType } from 'vue'
import AccountAvatar, {
accountAvatarFont,
accountAvatarProps,
accountInitial,
measureAccountText,
} from './AccountAvatar'
@ -13,7 +14,7 @@ const captionSize = 14
const AppAvatar = defineComponent({
name: 'AppAvatar',
props: {
...avatarProps,
...accountAvatarProps,
round: { type: Boolean, default: true },
objectFit: {
type: String as PropType<AvatarProps['objectFit']>,

View File

@ -1,5 +1,13 @@
import { useSettingActions, useSettingGetters } from '@/store'
import type { AppRootRoute } from '@/store/modules/setting/types'
import type { ComputedRef } from 'vue'
export type UseAppRootReturnType = {
getRootRoute: ComputedRef<AppRootRoute>
getRootPath: ComputedRef<string>
getRootName: ComputedRef<string>
setRootRoute: (route: Partial<AppRootRoute>) => void
}
/**
*
@ -9,7 +17,7 @@ import type { AppRootRoute } from '@/store/modules/setting/types'
* @returns 历史首页偏好的响应式引用和合并更新方法。
* @deprecated 仅兼容旧设置;使用 Router 显式导航,空工作区统一为 /welcome。
*/
export function useAppRoot() {
export function useAppRoot(): UseAppRootReturnType {
const { getAppRootRoute } = useSettingGetters()
const { updateSettingState } = useSettingActions()
@ -38,5 +46,3 @@ export function useAppRoot() {
setRootRoute,
}
}
export type UseAppRootReturnType = ReturnType<typeof useAppRoot>

View File

@ -1,8 +1,7 @@
import { i18n } from '@/locales'
import type { I18n } from 'vue-i18n'
export interface OverrideUseI18nReturnType extends Partial<
Omit<I18n['global'], 't' | 'locale'>
Omit<NonNullable<typeof i18n>['global'], 't' | 'locale'>
> {
t: <T extends string = string>(key: string, ...args: unknown[]) => T
locale: (lang: string) => void
@ -70,14 +69,7 @@ export const useI18n = (namespace?: string): OverrideUseI18nReturnType => {
if (!instance) return
if (instance.mode === 'legacy') {
instance.global.locale = lang
} else if (isRef(instance.global.locale)) {
instance.global.locale.value = lang
} else {
instance.global.locale = lang
}
instance.global.locale.value = lang
document.documentElement.lang = lang
}

View File

@ -7,7 +7,6 @@ import type { SettingState } from '@/store/modules/setting/types'
import { downloadAnyFile } from '@/utils/files'
import { navigateHorizontalChoice } from '@ray-template/composables/element'
import { RIcon } from '@ray-template/ui/icon'
import { useModal } from '@ray-template/ui/modal'
import { cloneDeep, forIn } from 'lodash-es'
import {
drawerProps,
@ -16,6 +15,7 @@ import {
NDrawerContent,
NTab,
NTabs,
useModal,
} from 'naive-ui'
import Appearance from './segment-views/Appearance'
import Common from './segment-views/Common'
@ -113,7 +113,7 @@ export default defineComponent({
content: t('resetDescription'),
positiveText: t('reset'),
negativeText: t('cancel'),
dialogWidth: 'min(420px, calc(100vw - 32px))',
style: { width: 'min(420px, calc(100vw - 32px))' },
onPositiveClick: () => {
forIn(cloneDeep(getDefaultSettingConfig()), (value, key) => {
updateSettingState(key as keyof SettingState, value)

View File

@ -2,11 +2,12 @@ import { LOCAL_OPTIONS, SYSTEM_FALLBACK_LOCALE } from '@/app-config'
import { getAppDefaultLanguage, getAppLocalMessages } from '@/locales/utils'
import type { App } from 'vue'
import { createI18n } from 'vue-i18n'
import type { I18n, I18nOptions } from 'vue-i18n'
import type { I18nOptions } from 'vue-i18n'
type AppI18n = ReturnType<typeof createI18nOptions>
/** 已安装的国际化实例;热更新期间保留同一个实例。 */
export let i18n: I18n | undefined = import.meta.hot?.data.i18n as
I18n | undefined
export let i18n = import.meta.hot?.data.i18n as AppI18n | undefined
if (import.meta.hot) {
import.meta.hot.dispose((data) => {
@ -30,8 +31,6 @@ const createI18nOptions = () => {
legacy: false,
locale,
messages: messages as unknown as I18nOptions['messages'],
sync: true,
silentFallbackWarn: true,
fallbackLocale: SYSTEM_FALLBACK_LOCALE,
})

View File

@ -1,5 +1,11 @@
import { nextTick } from 'vue'
import type { App, Component } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import {
createRouter,
createWebHashHistory,
isNavigationFailure,
NavigationFailureType,
} from 'vue-router'
import { getStaticAppRoutes, setAppRouteModules } from './app-route-modules'
import { loadRouteConfig, resetRouteSource } from './config/source'
import {
@ -13,9 +19,20 @@ import { scrollViewToTop, vueRouterRegister } from './utils'
export const router = createRouter({
history: createWebHashHistory(),
routes: [],
scrollBehavior: (to) => {
scrollViewToTop(to)
},
})
// 工作区使用独立的内容滚动容器,关闭浏览器对文档的自动滚动恢复。
if ('scrollRestoration' in window.history)
window.history.scrollRestoration = 'manual'
router.afterEach((to, from, failure) => {
if (
failure &&
!isNavigationFailure(failure, NavigationFailureType.duplicated)
)
return
void nextTick(() => scrollViewToTop(failure ? from : to))
})
let pending: Promise<void> | undefined

View File

@ -1,7 +1,6 @@
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'
@ -24,7 +23,6 @@ export default defineComponent({
const { t } = useI18n('curd')
const message = useMessage()
const show = ref(true)
const firstInput = shallowRef<InputInst>()
const nameId = useId()
const noteId = useId()
const editor = useCurdEditor(
@ -53,7 +51,7 @@ export default defineComponent({
onUpdateShow={(open) => {
if (!open) void close()
}}
onAfterEnter={() => firstInput.value?.focus()}
onAfterEnter={() => document.getElementById(nameId)?.focus()}
onAfterLeave={props.onClosed}
>
<RForm
@ -74,7 +72,7 @@ export default defineComponent({
}}
>
<NInput
ref={firstInput}
autofocus
v-model:value={editor.draft.value.name}
inputProps={{ id: nameId, required: true }}
maxlength={60}

View File

@ -77,7 +77,6 @@ export const useCurdEditor = <Draft extends Record<string, unknown>>(
const beforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
}
watch(

View File

@ -1,7 +1,6 @@
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro } from '@ray-template/ui/table-pro'
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import type {
TableProInst,
TableProRequest,
TableProSearchOptions,
TableProSearchValues,
@ -33,7 +32,8 @@ export default defineComponent({
setup() {
const { t } = useI18n('curd')
const projects = useProjects()
const table = shallowRef<TableProInst>()
const [registerTable, { isReady, setSearchValues, submitSearch }] =
useTablePro()
const order = ref(listContext.order)
const params = computed(() => ({ order: order.value }))
const initialFilters = listContext.filters
@ -76,8 +76,10 @@ export default defineComponent({
order.value = listContext.order
}
const clearFilters = () => {
table.value?.setSearchValues({ name: '', status: null })
void table.value?.submitSearch()
if (!isReady.value) return
setSearchValues({ name: '', status: null })
void submitSearch()
}
const search = computed<TableProSearchOptions>(() => ({
initialValues: initialFilters,
@ -192,7 +194,7 @@ export default defineComponent({
return () => (
<DemoPage title={t('projectsTitle')} description={t('projectsIntro')}>
<RTablePro
ref={table}
onRegister={registerTable}
request={request}
params={params.value}
columns={columns.value}

View File

@ -1,6 +1,6 @@
import { useI18n } from '@/hooks'
import { RModal, useModal } from '@ray-template/ui/modal'
import { NButton, NCard, NFlex, NInputNumber, NTag } from 'naive-ui'
import { RModal } from '@ray-template/ui/modal'
import { NButton, NCard, NFlex, NInputNumber, NTag, useModal } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
@ -68,7 +68,12 @@ export default defineComponent({
<NFlex align="center">
<NButton
onClick={() =>
create({ preset: 'card', title: t('modal.card'), content })
create({
preset: 'card',
title: t('modal.card'),
content,
style: { width: '600px' },
})
}
>
{t('modal.createCard')}

View File

@ -12,6 +12,8 @@ import AdminExample from '../../examples/AdminExample.vue'
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.
The editor validates with `useForm` and controls its modal through `show`. Draft-discard and deletion confirmations use Naive UI's `useDialog`.
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" />
@ -24,7 +26,7 @@ Try using an existing name such as `Design`. The editor keeps your input if the
## 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.
The project list has name and status filters, sorting, and pagination. It uses `useTablePro` to clear filters and run the query again. 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.

View File

@ -1,6 +1,6 @@
# Hooks
Import public template hooks from `@/hooks`. The hooks tied to components, `useForm`, `useModal`, `useChart`, and `useFlow`, come from `@/components` and are documented with each component. Import `useRequest` from `@/axios`.
Import public template hooks from `@/hooks`. The hooks tied to components, `useForm`, `useChart`, and `useFlow`, come from `@/components` and are documented with each component. For imperative modals, import [`useModal`](./components/modal) from `naive-ui`. Import `useRequest` from `@/axios`.
| Task | Reference |
| ------------------------------------------------------------ | --------------------------------------------- |

View File

@ -108,25 +108,13 @@ Use `defaultCollapsed`, `collapsedRows`, `maxColumns`, and field `span` for layo
`autoHeight` fills the available workspace height. For a custom region, set `--r-table-height`. Set column widths and `scrollX` so wide tables scroll inside the table.
```tsx
import { RTablePro, type TableProInst } from '@/components'
import { shallowRef } from 'vue'
const table = shallowRef<TableProInst>()
const reloadFromFirstPage = () => table.value?.reload(true)
const renderTable = () => (
<RTablePro ref={table} columns={[{ title: 'Name', key: 'name' }]} data={[]} />
)
```
The instance also exposes `setPage`, `setPageSize`, `getCurrentPageData`, `downloadCsv`, `print`, `copyImage`, and `getTableInstance`. Extend the table with `title`, `toolbar`, `tableFooter`, or `tableAction`. Use `error` for custom error content.
Extend the table with `title`, `toolbar`, `tableFooter`, or `tableAction`. Use `error` for custom error content.
The toolbar separates application actions from built-in tools. In `request` mode it offers Refresh. Column settings, Copy table image, and fullscreen are direct actions. **More actions** contains density, striped rows, border, and CSV. Stripe and border icons remain visible, with a separate selection mark on the right. Density items use text and a selection mark. The default `size` is `medium` (Standard), shared by the menu and table. `small` selects Compact and `large` selects Comfortable. Use `showPrint` to add Print table. `tool={false}` hides built-in tools and retains the custom `toolbar` slot.
### `useTablePro`
The same package entry exports `useTablePro`. Register the instance with `[register, actions]`.
Use `useTablePro` from the same package entry to reload, paginate, export, or print from the page. Call it in `setup` and bind the callback from `[register, actions]` to the table.
```tsx
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
@ -146,9 +134,9 @@ const renderTable = () => (
)
```
In an SFC, use `<RTablePro @register="register" />`. Call the hook once per table. Registration occurs on mount and clears on unmount. `actions` includes the instance methods, `getTableProInstance()`, and read-only `isReady`. `isReady` indicates instance binding, independent of request status. Calling an instance method before binding throws.
In an SFC, use `<RTablePro @register="register" />`. Call the hook once per table. Registration occurs on mount and clears on unmount. `actions` includes `reload`, `setPage`, `setPageSize`, `getCurrentPageData`, `downloadCsv`, `print`, `copyImage`, `getTableInstance`, and `getTableProInstance()`. The read-only `isReady` signals that the table is bound. Calling an action before binding throws.
Destructure `queryState` from `actions` and read `queryState.value` reactively for TablePro-managed remote requests. With a component ref, read `table.value?.queryState`.
Destructure `queryState` from `actions` and read `queryState.value` reactively for TablePro-managed remote requests.
| Field | Meaning |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |

View File

@ -12,6 +12,8 @@ import AdminExample from '../examples/AdminExample.vue'
在工具栏新增标签,或从行操作编辑现有标签。两个动作分别提供默认值或现有记录,并把各自的保存函数交给同一个短表单。点击标签名称可在抽屉里快速查看备注,原列表保留在原处。
编辑器用 `useForm` 校验表单,通过 `show` 控制弹窗显隐。离开草稿与删除确认使用 Naive UI 的 `useDialog`。
试着输入已有的标签名,例如 `Design`。保存失败后,表单会保留输入。修改一个字段后按 Esc,可以选择继续编辑或放弃更改。删除确认会显示目标标签。
<AdminExample path="/curd/tags" title="简单 CURD:标签管理" :height="520" />
@ -24,7 +26,7 @@ import AdminExample from '../examples/AdminExample.vue'
## 复杂示例:项目与里程碑 {#projects}
项目列表有名称和状态筛选、排序及分页。新增、详情和编辑各有独立路由。新增和编辑复用同一个编辑器,详情页用只读内容展示基本信息和里程碑。
项目列表有名称和状态筛选、排序及分页,使用 `useTablePro` 清除筛选并重新查询。新增、详情和编辑各有独立路由。新增和编辑复用同一个编辑器,详情页用只读内容展示基本信息和里程碑。
1. 筛选「进行中」,打开一个项目详情,再进入编辑。
2. 修改负责人或添加里程碑。取消时可保留草稿继续编辑,或放弃更改并返回详情。

View File

@ -1,6 +1,6 @@
# Hooks
模板的公开 Hooks 从 `@/hooks` 导入。与具体组件一起使用的 `useForm`、`useModal`、`useChart`、`useFlow` 从 `@/components` 导入,请看对应组件页。`useRequest` 从 `@/axios` 导入。
模板的公开 Hooks 从 `@/hooks` 导入。与具体组件一起使用的 `useForm`、`useChart`、`useFlow` 从 `@/components` 导入,请看对应组件页。命令式弹窗使用 `naive-ui` 的 [`useModal`](./components/modal)。`useRequest` 从 `@/axios` 导入。
| 需求 | API |
| -------------------------------------- | ---------------------------------- |

View File

@ -108,25 +108,13 @@ const renderRemote = () => (
`autoHeight` 让表格填充当前工作区;嵌入自定义区域时可用 `--r-table-height` 设定可用高度。宽表设置列宽与 `scrollX`,使横向滚动留在表格内。
```tsx
import { RTablePro, type TableProInst } from '@/components'
import { shallowRef } from 'vue'
const table = shallowRef<TableProInst>()
const reloadFromFirstPage = () => table.value?.reload(true)
const renderTable = () => (
<RTablePro ref={table} columns={[{ title: '姓名', key: 'name' }]} data={[]} />
)
```
实例还提供 `setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print`、`copyImage` 和 `getTableInstance`。扩展表格区域可用 `title`、`toolbar`、`tableFooter`、`tableAction`;错误区域用 `error` 插槽。
扩展表格区域可用 `title`、`toolbar`、`tableFooter`、`tableAction`;错误区域用 `error` 插槽。
工具栏分为业务操作与内置工具两组。`request` 模式提供刷新,列设置、复制图片和全屏为直接入口;密度、斑马纹、边框和 CSV 收入「更多操作」。斑马纹和边框的功能图标始终显示,选中状态在文字右侧单独标记;密度子菜单只保留文字和选中标记。TablePro 的 `size` 默认是 `medium`(标准),菜单与表格共用该值;传入 `small` 或 `large` 时分别选中紧凑或宽松。打印默认不显示,设置 `showPrint` 后才加入菜单。`tool={false}` 隐藏内置工具,保留自定义 `toolbar` 插槽。
### `useTablePro`
也可以用同一入口导出的 `useTablePro` 注册实例,保留 `[register, actions]` 的写法:
页面主动刷新、切页、导出或打印时,优先从同一入口导入 `useTablePro`。在 `setup` 中获取 `[register, actions]`,再将注册回调绑定到表格。
```tsx
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
@ -146,9 +134,9 @@ const renderTable = () => (
)
```
SFC 使用 `<RTablePro @register="register" />`。每张表单独调用一次 Hook;表格挂载后注册,卸载时清除。`actions` 提供上述实例方法、`getTableProInstance()` 和只读 `isReady`;它表示实例已绑定,和请求是否完成无关。未绑定时调用实例方法会抛错。
SFC 使用 `<RTablePro @register="register" />`。每张表单独调用一次 Hook;表格挂载后注册,卸载时清除。`actions` 提供 `reload`、`setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print`、`copyImage`、`getTableInstance` 和 `getTableProInstance()`。只读 `isReady` 表示表格已绑定。未绑定时调用操作方法会抛错。
从 `actions` 解构 `queryState`,用 `queryState.value` 响应式读取 TablePro 管理的远端请求。通过组件 ref 使用时,读取 `table.value?.queryState`。
从 `actions` 解构 `queryState`,用 `queryState.value` 响应式读取 TablePro 管理的远端请求。
| 字段 | 含义 |
| ------------------- | ------------------------------------------------------------------------------- |

View File

@ -45,6 +45,12 @@ Select the action container at the route or overlay entry point. A single page c
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)
## Component actions
Call component hooks in `setup` and use their returned actions, such as `useTablePro` for table queries and `useForm` for form validation. For a hook that returns `[register, actions]`, bind `onRegister={register}` in TSX or `@register="register"` in a Vue template. Call actions after registration. Use `isReady` when a TablePro action can run before the table mounts. [TablePro reference](../apps/docs/en/reference/table-pro.md#usetablepro)
Use Naive UI's `useDialog` for confirmations and `useModal` for programmatically created content. For form modals with draft and close handling, use reactive `show` and the component's update event. Use a template ref for an action that is only available through the component instance. [Modal reference](../apps/docs/en/reference/components/modal.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)

View File

@ -299,3 +299,9 @@ Local Chrome comparison used three cold HTTP cache loads per build, a 390 × 844
`pnpm harness verify all` passed with loopback access for the server tests. The run covered 576 frontend tests, 12 server tests, both site builds, and both source distributions. The optional Redis integration test was skipped. The admin build stayed below the chunk warning limit. VitePress still reports a large chunk for the TablePro examples page.
The assembled Pages preview verified demo sign-in, session restoration, chart, flow, barcode, grouped table views, the 404 route, and the first opening of the lock dialog. The documentation iframe fetched rows, cleared them on a simulated failure, and restored them on retry. The example entry also rendered the workspace shell when requested. Browser evidence is in `.harness-local/browser/admin-startup-2026-11-10/report.json`.
## 2026-11-27 Type-aware ESLint checks
ESLint resolves `@deprecated` declarations in TypeScript, TSX, JavaScript scripts, and Vue script blocks through the workspace TypeScript projects. The [script lint project](../tsconfig.eslint-scripts.json) includes the JavaScript tooling. It lists the hidden Prettier config and the JavaScript entry points with paired declaration files explicitly. `no-undefined` still enforces `void 0` for runtime values. [ESLint configuration](../eslint.config.mjs) · [Deprecation rule](https://typescript-eslint.io/rules/no-deprecated/)
Local lint passed. Rule probes rejected deprecated calls, property reads, option keys, and TSX props. They accepted `void 0` and TypeScript's `undefined` type. The 624 frontend tests, type checks, documentation build, and both source distribution checks passed. The full Harness stopped at the existing InteractJS package boundary errors. [Tag reordering imports](../apps/admin/src/layout/components/MenuTag/use-tag-reorder.ts)

View File

@ -32,6 +32,19 @@ export default defineConfig([
],
languageOptions: {
ecmaVersion: 'latest',
parserOptions: {
tsconfigRootDir: import.meta.dirname,
project: [
'./tsconfig.app.json',
'./tsconfig.node.json',
'./tsconfig.test.json',
'./tsconfig.packages.json',
'./tsconfig.eslint-scripts.json',
'./apps/*/tsconfig.json',
],
extraFileExtensions: ['.vue'],
jsDocParsingMode: 'all',
},
globals: {
...globals.browser,
...globals.node,
@ -41,6 +54,7 @@ export default defineConfig([
},
rules: {
'no-undefined': ['error'],
'@typescript-eslint/no-deprecated': 'error',
'@typescript-eslint/no-explicit-any': [
'error',
{
@ -193,13 +207,6 @@ export default defineConfig([
message: 'Disallow using key as a custom attribute',
},
],
'no-restricted-syntax': [
'error',
{
selector: "CallExpression[callee.property.name='deprecated']",
message: 'Using deprecated API is not allowed.',
},
],
'padding-line-between-statements': [
'error',
{ blankLine: 'always', prev: 'import', next: '*' },

View File

@ -11,4 +11,6 @@ Use this topic for dependencies, public exports, aliases, auto-imports, producti
Each workspace's `package.json#exports` defines its public exports. Compare Vite, TypeScript, and Vitest resolution when changing aliases. Update generated declarations through configuration. When publishing the combined site, check both the admin and documentation bases.
`pnpm lint` checks resolved `@deprecated` usages in TypeScript, TSX, JavaScript scripts, and Vue script blocks. ESLint uses the existing workspace TypeScript projects and the [script lint project](../../tsconfig.eslint-scripts.json). Use `void 0` for runtime values and `undefined` in type annotations.
Targeted verification: `pnpm harness verify toolchain` runs package-boundary and type checks. For changes to dependencies, public exports, or build configuration, run `pnpm harness verify all` once at completion using the [verification scope](../README.md#choosing-the-verification-scope). Preview affected entry points when build artifacts or deployment paths change. Toolchain prose alone does not trigger these runtime checks. Passing targeted checks does not prove CI, Docker, or production publication succeeded.

View File

@ -1,5 +1,4 @@
import type { ExtractPublicPropTypes } from 'vue'
import useModal from './src/hooks/useModal'
import type { UseModalReturn } from './src/hooks/useModal'
import RModal from './src/Modal'
import modalProps from './src/props'
@ -8,4 +7,11 @@ import type * as RModalType from './src/types'
export type ModalProps = ExtractPublicPropTypes<typeof modalProps>
export type { RModalType, UseModalReturn }
export { RModal, modalProps, useModal }
export { RModal, modalProps }
export {
/**
*
* @deprecated 改用 Naive UI 的 useModal 或声明式 RModal。
*/
default as useModal,
} from './src/hooks/useModal'

View File

@ -5,10 +5,16 @@ import {
setStyle,
} from '@ray-template/composables/element'
import { NScrollbar, useModal as useNaiveModal } from 'naive-ui'
import type { ModalReactive } from 'naive-ui'
import { h, nextTick } from 'vue'
import { CSS_VARS_KEYS, R_MODAL_CLASS } from '../constant'
import type { RModalProps } from '../types'
export type UseModalReturn = {
create: (options: RModalProps) => ModalReactive
destroyAll: () => void
}
/**
*
* @description
@ -16,11 +22,11 @@ import type { RModalProps } from '../types'
*
* @returns 创建弹窗与关闭全部弹窗的方法
*
* @deprecated
* @deprecated 改用 Naive UI 的 useModal 或声明式 RModal。
*
* @see https://www.naiveui.com/zh-CN/dark/components/modal#useModal-API
*/
const useModal = () => {
export default function useModal(): UseModalReturn {
const { create: naiveCreate, destroyAll: naiveDestroyAll } = useNaiveModal()
/**
@ -99,7 +105,3 @@ const useModal = () => {
destroyAll: naiveDestroyAll,
}
}
export type UseModalReturn = ReturnType<typeof useModal>
export default useModal

View File

@ -26,12 +26,12 @@ import { RTablePro } from '@/components'
- 行标识默认取 `row.id` 或 `row.key`,其他字段使用 `rowKey`。宽表可设置 `scrollX` 和列宽,横向滚动留在表格内部。根列拖动或固定时保留分组的子列。
- `autoHeight` 默认使用当前布局的可用高度,宿主外部使用视口高度;嵌入特定区域时可以用 CSS 变量 `--r-table-height` 覆盖。较短的屏幕保留表格的最小操作高度。
- 只接收最新的请求结果。切换请求源或有效筛选条件会立即清空旧行和总数;切页或修改每页条数会隐藏旧行并保留同一范围的总数。当前页未加载时,实例取数返回空、底层实例返回 `null`,CSV 和打印不会启动。请求失败后清空行与总数,在表格中显示错误和重试按钮。可用 `onRequestError` 接收详情、用实例 `reload()` 重试,或提供 `error` 插槽自定义反馈。应用筛选后无结果时,默认显示无匹配提示,并为内置筛选提供重置操作。
- 需要实例时使用 `shallowRef<TableProInst>()`。实例提供 `reload(resetPage?)`、`setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print`、`copyImage` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。
- 主动操作表格时优先使用 `useTablePro()`,可调用 `reload(resetPage?)`、`setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print`、`copyImage` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。
- 工具栏将业务 `toolbar` 插槽与内置工具分组。`request` 模式提供刷新,列设置、复制图片和全屏保持直接入口;「更多操作」统一收纳密度、斑马纹、边框与 CSV。斑马纹和边框的功能图标始终显示,选中状态在文字右侧单独标记;密度子菜单只保留文字和选中标记。TablePro 的 `size` 默认是 `medium`(标准),菜单与表格共用该值;传入 `small` 或 `large` 时分别选中紧凑或宽松。打印默认隐藏,设置 `showPrint` 后出现在该菜单。`tool={false}` 隐藏全部内置工具,仍保留业务插槽。
## 注册 Hook
也可以从 `@ray-template/ui/table-pro` 或 Ray Admin 的 `@/components` 导入 `useTablePro`。每张表调用一次,保持 `[register, actions]` 和 `onRegister` 的用法:
从 `@ray-template/ui/table-pro` 导入 `useTablePro`。每张表调用一次,将 `[register, actions]` 中的注册回调绑定到 `onRegister`。
```tsx
const [register, { reload }] = useTablePro()
@ -106,7 +106,7 @@ RIcon 外部精灵图和本地 `#symbol` 会在快照中展开为独立静态 SV
/>
```
内置按钮使用 `printTableOptions`。单次打印可以用 `table.value?.print({ target: reportRef, title: '报表', style: '@page { size: landscape; }' })` 覆盖配置;目标支持元素、ref 或 getter。自定义区域以独立打印文档呈现。默认复制页面样式表、根节点主题和普通表单的当前值;设置 `includePageStyles: false` 可只用打印样式。用 `style` 添加覆盖,或用 `data-print-ignore` 排除控件。依赖区域外祖先、运行时脚本或嵌入内容的样式需自行在打印 CSS 中补齐;密码和文件值不会复制。图片和字体等待有上限,未就绪时可能使用替代样式。旧版 `printOptions.documentTitle` 改用 `title`,截图配置不再适用。
内置按钮使用 `printTableOptions`。单次打印可以用 `useTablePro()` 返回的 `print({ target: reportRef, title: '报表', style: '@page { size: landscape; }' })` 覆盖配置;目标支持元素、ref 或 getter。自定义区域以独立打印文档呈现。默认复制页面样式表、根节点主题和普通表单的当前值;设置 `includePageStyles: false` 可只用打印样式。用 `style` 添加覆盖,或用 `data-print-ignore` 排除控件。依赖区域外祖先、运行时脚本或嵌入内容的样式需自行在打印 CSS 中补齐;密码和文件值不会复制。图片和字体等待有上限,未就绪时可能使用替代样式。旧版 `printOptions.documentTitle` 改用 `title`,截图配置不再适用。
CSV 默认导出当前页可见数据列;`keepOriginalData` 使用传入的整批数据(远端模式不会为导出额外请求)。`allowExport: false` 排除对应列,`getCsvCell` / `getCsvHeader` 返回原始文本,由组件处理 CSV 转义。

View File

@ -0,0 +1,21 @@
{
"extends": "./tsconfig.node.json",
"compilerOptions": {
"allowJs": true
},
"files": [
".prettierrc.cjs",
"scripts/distributions.mjs",
"scripts/icons.mjs"
],
"include": [
"*.js",
"*.mjs",
"*.cjs",
"apps/*/scripts",
"packages/*/scripts",
"deploy",
"harness",
"scripts"
]
}