Compare commits

...

9 Commits
v6.0.2 ... main

Author SHA1 Message Date
XiaoDaiGua-Ray
d3a2504d37
refactor: migrate deprecated APIs and prefer component hooks 2026-11-27 16:56:57 +08:00
XiaoDaiGua-Ray
d67e64d48c
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.
2026-11-27 14:51:46 +08:00
XiaoDaiGua-Ray
474d75203c
feat(ui): polish global search and expand icon library 2026-11-27 10:37:14 +08:00
XiaoDaiGua-Ray
b5ccd180ef
docs: add English VitePress documentation 2026-11-19 16:05:56 +08:00
XiaoDaiGua-Ray
9a6851b858
docs: expand v6 monorepo architecture guide 2026-11-19 15:17:29 +08:00
XiaoDaiGua-Ray
edf4794078
feat(menu-tag): add pin icon and drag preview 2026-11-19 14:39:19 +08:00
XiaoDaiGua-Ray
2a4a6182b0
feat: refine tab sorting and breadcrumb icons
Use interact.js for tab dragging, drop detection, and automatic scrolling.

Use the window icon as the breadcrumb fallback.
2026-11-19 14:10:42 +08:00
XiaoDaiGua-Ray
c2019b10e6
feat: enhance menu tags, breadcrumbs, and useMenu
Add configurable tab controls, breadcrumb icons, and interactive useMenu examples.
Batch pointer updates per frame and scope writes to the tab cache.
2026-11-19 12:25:05 +08:00
XiaoDaiGua-Ray
94c2e6cdb6
feat: refine menu tags and CSS tooling
Use native tag styling and close controls, add pill settings, and move the sidebar toggle.

Fix TablePro resize feedback, migrate viewport conversion, and add Zed workspace settings.
2026-11-19 11:33:18 +08:00
384 changed files with 11614 additions and 1230 deletions

98
.zed/settings.json Normal file
View File

@ -0,0 +1,98 @@
{
"languages": {
"TypeScript": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["vtsls", "eslint", "!intl-lens", "..."]
},
"TSX": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["vtsls", "eslint", "!intl-lens", "..."]
},
"JavaScript": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["vtsls", "eslint", "!intl-lens", "..."]
},
"JSX": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["vtsls", "eslint", "!intl-lens", "..."]
},
"Vue.js": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["!intl-lens", "..."]
},
"JSON": {
"formatter": "prettier",
"format_on_save": "on"
},
"SCSS": {
"formatter": "prettier",
"format_on_save": "on"
},
"CSS": {
"formatter": "prettier",
"format_on_save": "on"
},
"HTML": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["!intl-lens", "..."]
},
"Markdown": {
"formatter": "prettier",
"format_on_save": "on"
}
},
"lsp": {
"cspell": {
"initialization_options": {
"defaultSettings": {
"words": [
"baomitu",
"bezier",
"Cascader",
"Clickoutside",
"codabar",
"commitmsg",
"crossorigin",
"daterange",
"datetimerange",
"depcheckrc",
"domtoimage",
"echart",
"EDITMSG",
"ianvs",
"iife",
"internalkey",
"jsbarcode",
"linebreak",
"logicflow",
"macarons",
"menutag",
"ndata",
"persistedstate",
"pharmacode",
"Popselect",
"precommit",
"qrcode",
"rgba",
"sider",
"siderbar",
"snapline",
"stylelint",
"unocss",
"VITE",
"vitepress",
"vueuse",
"WUJIE",
"zlevel"
]
}
}
}
}
}

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

@ -4,7 +4,7 @@
Give developers and coding agents the same path through the project: **find the implementation, understand its contracts, reuse existing capabilities, and verify the change.**
[简体中文](README.zh-CN.md) · **[Live demo](https://xiaodaigua-ray.github.io/ray-template/)** · **[Documentation](https://xiaodaigua-ray.github.io/ray-template/docs/)** · [Quick start](#quick-start) · [Develop with AI](#develop-with-ai)
[简体中文](README.zh-CN.md) · **[Live demo](https://xiaodaigua-ray.github.io/ray-template/)** · **[Documentation](https://xiaodaigua-ray.github.io/ray-template/docs/en/)** · [Quick start](#quick-start) · [Develop with AI](#develop-with-ai)
Ray Template uses Vue 3, TypeScript / TSX, and Naive UI for admin dashboards, operations consoles, and internal tools. The repository brings together a working application, shared components, interactive documentation, and engineering context organized by task.
@ -20,19 +20,19 @@ Ray Template uses Vue 3, TypeScript / TSX, and Naive UI for admin dashboards, op
### Applications, documentation, and examples share source
The admin application and documentation consume the same workspace packages. Interactive examples use real components, and the TablePro documentation includes the source of the examples it runs. Changes to public capabilities can be checked in both the application and documentation. [Explore the examples](apps/docs/reference/table-pro-examples.md) · [Documentation workflow](docs/docs-handoff.md)
The admin application and documentation consume the same workspace packages. Interactive examples use real components, and the TablePro documentation includes the source of the examples it runs. Changes to public capabilities can be checked in both the application and documentation. [Explore the examples](apps/docs/en/reference/table-pro-examples.md) · [Documentation workflow](docs/docs-handoff.md)
### Four styles across the business interface
Modern, Naive UI, Material, and Plain cover the shell, controls, tables, and charts, each with light and dark modes. Custom pages inherit colors, corners, and shadows through semantic theme tokens, while runtime layout variables adapt them to the workspace. [Theme integration](apps/docs/guide/appearance.md) · [CSS contract](docs/ui-design.md#custom-css-contract)
Modern, Naive UI, Material, and Plain cover the shell, controls, tables, and charts, each with light and dark modes. Custom pages inherit colors, corners, and shadows through semantic theme tokens, while runtime layout variables adapt them to the workspace. [Theme integration](apps/docs/en/guide/appearance.md) · [CSS contract](docs/ui-design.md#custom-css-contract)
### TablePro handles interaction and data state
One table component supports local data, remote requests, and controlled pagination, with advanced search, column settings, export, printing, and instance hooks. Request races, cancellation signals, failure recovery, and export scope have explicit contracts and regression coverage. [11 runnable examples](https://xiaodaigua-ray.github.io/ray-template/docs/reference/table-pro-examples.html) · [Component contract](packages/ui/src/RTablePro/README.md)
One table component supports local data, remote requests, and controlled pagination, with advanced search, column settings, export, printing, and instance hooks. Request races, cancellation signals, failure recovery, and export scope have explicit contracts and regression coverage. [11 runnable examples](https://xiaodaigua-ray.github.io/ray-template/docs/en/reference/table-pro-examples.html) · [Component contract](packages/ui/src/RTablePro/README.md)
### One contract from the static demo to your business API
Development and the static hosted demo share MSW HTTP mocks, with pages fetching data through the application's API layer. Shared TypeScript types, Valibot schemas, and generated OpenAPI 3.1 definitions guide backend integration; a dedicated command checks that generated contracts stay in sync. [API contracts](packages/api-contracts/README.md) · [Backend integration](apps/docs/guide/backend.md)
Development and the static hosted demo share MSW HTTP mocks, with pages fetching data through the application's API layer. Shared TypeScript types, Valibot schemas, and generated OpenAPI 3.1 definitions guide backend integration; a dedicated command checks that generated contracts stay in sync. [API contracts](packages/api-contracts/README.md) · [Backend integration](apps/docs/en/guide/backend.md)
### Visual route editing with a validated configuration contract
@ -42,7 +42,7 @@ Manage menu order, roles, visibility, and caching through a visual editor or JSO
### Choose frontend or fullstack source from one project
Export an independently runnable frontend, or include the NestJS, PostgreSQL, and Redis implementation. Distribution scripts use the dependency graph to prune workspaces, the lockfile, and edition-specific documentation, then record the version, source commit, and content digest. [Source distributions and startup](apps/docs/guide/distributions.md)
Export an independently runnable frontend, or include the NestJS, PostgreSQL, and Redis implementation. Distribution scripts use the dependency graph to prune workspaces, the lockfile, and edition-specific documentation, then record the version, source commit, and content digest. [Source distributions and startup](apps/docs/en/guide/distributions.md)
<!-- fullstack:end -->
@ -63,21 +63,21 @@ pnpm dev
Open [http://127.0.0.1:9527/ray-template/](http://127.0.0.1:9527/ray-template/) and click **Continue with demo account**. Switch to manager or read-only accounts to explore permission differences. The frontend demo needs no database or business backend.
- **Try the interface.** Open Settings to change styles and layouts, then explore Users and TablePro.
- **Build your first page.** Follow the [business page guide](apps/docs/guide/first-page.md), reuse components, and register the route with English and Chinese menu labels.
- **Connect your service.** Follow the [backend integration guide](apps/docs/guide/backend.md) to configure `VITE_API_BASE_URL` and `VITE_API_MOCK=false`.
- **Build your first page.** Follow the [business page guide](apps/docs/en/guide/first-page.md), reuse components, and register the route with English and Chinese menu labels.
- **Connect your service.** Follow the [backend integration guide](apps/docs/en/guide/backend.md) to configure `VITE_API_BASE_URL` and `VITE_API_MOCK=false`.
## Develop with AI
AI support is part of the everyday development workflow. Coding agents that can read the repository and run commands can use the same Markdown documents, source entry points, and verification commands as maintainers.
| Development question | Evidence in the repository |
| -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Where should I start, and which conventions apply? | [AGENTS.md](AGENTS.md): scope, reuse, documentation updates, and acceptance rules. |
| Which files matter for this task? | [llms.txt](llms.txt) → [task context](harness/context): implementations, callers, contracts, and tests. |
| Which module owns the behavior, and where are its boundaries? | The [architecture map](docs/architecture.md), public `exports`, and [package boundary checks](scripts/check-package-boundaries.mjs). |
| How do existing capabilities work, and what do their parameters and states mean? | [Component references](apps/docs/reference/components.md), [hook references](apps/docs/reference/hooks.md), module READMEs, and [runnable examples](apps/docs/reference/table-pro-examples.md). |
| How do mocks and business requests agree on API shapes? | [Shared schemas and OpenAPI](packages/api-contracts/README.md), with `pnpm api:check` checking generated contract synchronization. |
| What should I run after a change, and where are the results? | [Verification scopes](harness/scopes.json) and `pnpm harness verify <scope>`, with reports saved under `.harness-local/runs/`. |
| Development question | Evidence in the repository |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Where should I start, and which conventions apply? | [AGENTS.md](AGENTS.md): scope, reuse, documentation updates, and acceptance rules. |
| Which files matter for this task? | [llms.txt](llms.txt) → [task context](harness/context): implementations, callers, contracts, and tests. |
| Which module owns the behavior, and where are its boundaries? | The [architecture map](docs/architecture.md), public `exports`, and [package boundary checks](scripts/check-package-boundaries.mjs). |
| How do existing capabilities work, and what do their parameters and states mean? | [Component references](apps/docs/en/reference/components.md), [hook references](apps/docs/en/reference/hooks.md), module READMEs, and [runnable examples](apps/docs/en/reference/table-pro-examples.md). |
| How do mocks and business requests agree on API shapes? | [Shared schemas and OpenAPI](packages/api-contracts/README.md), with `pnpm api:check` checking generated contract synchronization. |
| What should I run after a change, and where are the results? | [Verification scopes](harness/scopes.json) and `pnpm harness verify <scope>`, with reports saved under `.harness-local/runs/`. |
For a TablePro task, read its context first, then select verification for the change:
@ -112,7 +112,7 @@ Here, `llms.txt` is a repository task index that you can explicitly ask an agent
| **Icons and utilities** | Typed SVG names and generated sprites, QR codes, barcodes, precision arithmetic, storage, composables, and directives. |
| **Engineering and integration** | pnpm workspaces, request cancellation, type and package boundary checks, Vitest, ESLint / Prettier, and a [Wujie sub-application entry point](apps/admin/src/main.ts). |
Frontend permissions shape the page experience; your backend validates real sessions and API authorization. See the [backend integration guide](apps/docs/guide/backend.md) for demo data and integration boundaries.
Frontend permissions shape the page experience; your backend validates real sessions and API authorization. See the [backend integration guide](apps/docs/en/guide/backend.md) for demo data and integration boundaries.
## Styles and layouts
@ -123,7 +123,7 @@ Frontend permissions shape the page experience; your backend validates real sess
| **Material** | Tonal surfaces, larger corners, and capsule-shaped buttons. |
| **Plain** | Neutral colors, small corners, and flat surfaces. |
**Side · Top · Mixed · Right · Split.** Choose fluid or fixed-width content, adjust spacing, and pin the header or footer. Narrow screens use a menu drawer. Switch layouts in the [live demo](https://xiaodaigua-ray.github.io/ray-template/) or explore the [layout playground](apps/docs/guide/layout.md).
**Side · Top · Mixed · Right · Split.** Choose fluid or fixed-width content, adjust spacing, and pin the header or footer. Narrow screens use a menu drawer. Switch layouts in the [live demo](https://xiaodaigua-ray.github.io/ray-template/) or explore the [layout playground](apps/docs/en/guide/layout.md).
<details>
<summary>View the workspace and dark theme previews</summary>
@ -162,11 +162,11 @@ pnpm fullstack:setup
pnpm dev:full
```
`setup` creates the private `apps/server/.env.local`, starts PostgreSQL and Redis, applies migrations, and initializes the administrator. The generated administrator password is stored in that file; mock demo passwords do not authenticate against the server. For existing databases and Redis, use `pnpm fullstack:setup --external` and follow the [startup guide](apps/docs/guide/distributions.md) for configuration.
`setup` creates the private `apps/server/.env.local`, starts PostgreSQL and Redis, applies migrations, and initializes the administrator. The generated administrator password is stored in that file; mock demo passwords do not authenticate against the server. For existing databases and Redis, use `pnpm fullstack:setup --external` and follow the [startup guide](apps/docs/en/guide/distributions.md) for configuration.
Alternatively, run `node scripts/fullstack.mjs up` to build and start the entire stack with Docker, without first installing project dependencies on the host. The default entry point is `http://127.0.0.1:8080/ray-template/`. `pnpm fullstack:stop` stops services and retains data volumes.
The [source distributions workflow](.github/workflows/distributions.yaml) provides manual options to verify archives, generate the `frontend` branch, and attach assets to an existing Release. [Container startup and release instructions](apps/docs/guide/distributions.md#容器启动)
The [source distributions workflow](.github/workflows/distributions.yaml) provides manual options to verify archives, generate the `frontend` branch, and attach assets to an existing Release. [Container startup and release instructions](https://xiaodaigua-ray.github.io/ray-template/docs/en/guide/distributions.html#容器启动)
<!-- fullstack:end -->
@ -196,7 +196,7 @@ The **Pages workflow** builds the admin and documentation on every push to `main
**v6 introduces the monorepo architecture and does not provide an in-place upgrade from v5.** Compatibility with v5 internal imports, APIs, deployment settings, and browser data is not guaranteed.
Existing projects can stay on [legacy/v5](https://github.com/XiaoDaiGua-Ray/ray-template/tree/legacy/v5) or the [v5.2.5 tag](https://github.com/XiaoDaiGua-Ray/ray-template/tree/v5.2.5). Read the [migration notes](apps/docs/migration.md) before adopting v6.
Existing projects can stay on [legacy/v5](https://github.com/XiaoDaiGua-Ray/ray-template/tree/legacy/v5) or the [v5.2.5 tag](https://github.com/XiaoDaiGua-Ray/ray-template/tree/v5.2.5). Read the [migration notes](apps/docs/en/migration.md) before adopting v6.
---

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

@ -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

@ -6,7 +6,7 @@ import type {
TableProSearchOptions,
} from '@ray-template/ui/table-pro'
import { flushPromises, mount } from '@vue/test-utils'
import { NDataTable, NDatePicker, NSelect } from 'naive-ui'
import { NDataTable, NDatePicker, NGrid, NSelect } from 'naive-ui'
import { defineComponent, h, nextTick, shallowRef } from 'vue'
const columns = [{ key: 'name', title: 'Name' }]
@ -15,6 +15,91 @@ const statusOptions = [
{ label: 'Closed', value: 'closed' },
]
it('applies the latest measured search column count on the next frame', async () => {
let resizeSearch: ((width: number) => void) | undefined
vi.useFakeTimers({
toFake: ['requestAnimationFrame', 'cancelAnimationFrame'],
})
vi.stubGlobal(
'ResizeObserver',
class {
readonly callback: ResizeObserverCallback
constructor(callback: ResizeObserverCallback) {
this.callback = callback
}
observe(target: Element) {
if (target.matches('.r-table-search-shell'))
resizeSearch = (width) =>
this.callback(
[
{
target,
contentRect: new DOMRect(0, 0, width, 200),
} as ResizeObserverEntry,
],
this,
)
}
disconnect() {}
unobserve() {}
},
)
const wrapper = mount(RTablePro, {
props: { columns, search: { fields: [{ key: 'name', label: 'Name' }] } },
})
try {
await nextTick()
const grid = wrapper.getComponent(NGrid)
expect(resizeSearch).toBeTypeOf('function')
expect(grid.props('cols')).toBe(1)
resizeSearch?.(864)
await nextTick()
expect(grid.props('cols')).toBe(1)
resizeSearch?.(1310)
await nextTick()
expect(grid.props('cols')).toBe(1)
vi.advanceTimersToNextFrame()
await nextTick()
expect(grid.props('cols')).toBe(3)
} finally {
wrapper.unmount()
vi.unstubAllGlobals()
vi.useRealTimers()
}
})
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

@ -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

@ -0,0 +1,102 @@
import { useMenu } from '@ray-template/composables/useMenu'
import type { UseMenuOptions } from '@ray-template/composables/useMenu'
import { mount } from '@vue/test-utils'
import { NMenu } from 'naive-ui'
import { defineComponent, nextTick } from 'vue'
const daily = { key: 2, label: 'Daily' }
const options = [
{ key: 'home', label: 'Home' },
{ key: 1, label: 'Reports', children: [daily] },
]
const mountMenu = (initial: UseMenuOptions) => {
const menu = useMenu(initial)
const wrapper = mount(
defineComponent({
setup: () => () => <NMenu ref={menu.menuRef} {...menu.menuProps} />,
}),
)
const select = (label: string) =>
wrapper
.findAll('.n-menu-item-content')
.find((row) => row.text() === label)!
.trigger('click')
return { ...menu, wrapper, select }
}
it('updates controlled selection and expansion before notifying native callbacks', async () => {
const onValue = vi.fn(() => menu.menuProps.value)
const onExpanded = vi.fn(() => menu.menuProps.expandedKeys)
const onExpandedAlias = vi.fn()
const menu = mountMenu({
options,
value: 'home',
expandedKeys: [],
'onUpdate:value': onValue,
onUpdateExpandedKeys: [onExpanded, onExpandedAlias],
})
try {
menu.showOption(2)
await nextTick()
expect(onExpanded).toHaveBeenCalledExactlyOnceWith([1])
expect(onExpanded).toHaveReturnedWith([1])
expect(onExpandedAlias).toHaveBeenCalledExactlyOnceWith([1])
expect(menu.menuProps.value).toBe('home')
await menu.select('Daily')
expect(onValue).toHaveBeenCalledExactlyOnceWith(2, daily)
expect(onValue).toHaveReturnedWith(2)
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
'Daily',
)
} finally {
menu.wrapper.unmount()
}
})
it('keeps native defaults for independently uncontrolled props', async () => {
const menu = mountMenu({
options: [],
defaultValue: 'home',
defaultExpandAll: true,
watchProps: ['defaultExpandedKeys'],
})
try {
menu.menuProps.options = options
await nextTick()
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
'Home',
)
expect(menu.wrapper.get('[aria-expanded="true"]').text()).toContain('Daily')
await menu.select('Daily')
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
'Daily',
)
expect(menu.menuProps.value).toBeUndefined()
expect(menu.menuProps.expandedKeys).toBeUndefined()
} finally {
menu.wrapper.unmount()
}
})
it('delegates instance methods only while the menu is mounted', () => {
const menu = useMenu()
const instance = { showOption: vi.fn(), deriveResponsiveState: vi.fn() }
menu.showOption()
menu.deriveResponsiveState()
menu.menuRef.value = instance
menu.showOption()
menu.deriveResponsiveState()
menu.menuRef.value = null
menu.showOption('home')
menu.deriveResponsiveState()
expect(instance.showOption).toHaveBeenCalledExactlyOnceWith(void 0)
expect(instance.deriveResponsiveState).toHaveBeenCalledExactlyOnceWith()
})

View File

@ -1,10 +1,10 @@
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'
import { piniaKeepAliveStore } from '@/store/modules/keep-alive'
import { piniaMenuStore } from '@/store/modules/menu'
import { getCatchMenuTagOptions } from '@/store/modules/menu/utils'
import { piniaSettingStore } from '@/store/modules/setting'
import { piniaSigningStore } from '@/store/modules/signing'
import { setStorage } from '@/utils/cache'
@ -119,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)
@ -176,13 +179,99 @@ 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([])
expect(router.currentRoute.value.path).toBe('/welcome')
})
it('keeps topped tabs together and restores tab order and flags with the latest URL', async () => {
for (const path of ['/reports', '/orders', '/private'])
await router.push(path)
const cachedPages = piniaKeepAliveStore().keepAliveInclude
menu.toggleMenuTagTop('/private')
menu.toggleMenuTagFixed('/orders')
expect(menu.moveMenuTag('/orders', '/private', 'before')).toBe(false)
expect(menu.moveMenuTag('/orders', '/reports', 'before')).toBe(true)
expect(piniaKeepAliveStore().keepAliveInclude).toBe(cachedPages)
await router.push('/orders?sort=desc#details')
await flushPromises()
menu.menuTagOptions = getCatchMenuTagOptions()
await menu.setupAppMenu()
expect(
menu.menuTagOptions.map(({ fullPath, topped, fixed }) => [
fullPath,
topped,
fixed,
]),
).toEqual([
['/private', true, false],
['/orders?sort=desc#details', false, true],
['/reports', false, false],
])
expect(
menu.options.find((option) => option.fullPath === '/private'),
).not.toHaveProperty('topped')
expect(menu.currentMenuOption?.fullPath).toBe('/orders?sort=desc#details')
const settings = piniaSettingStore()
settings.updateSettingState('menuTagDrag', false)
expect(
menu.moveMenuTag('/reports', '/orders?sort=desc#details', 'before'),
).toBe(false)
settings.updateSettingState('menuTagDrag', true)
settings.updateSettingState('menuTagTop', false)
expect(menu.moveMenuTag('/reports', '/private', 'before')).toBe(true)
settings.updateSettingState('menuTagTop', true)
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/private',
'/reports',
'/orders?sort=desc#details',
])
})
it('preserves fixed tabs through single and bulk closes until protection is disabled', async () => {
for (const path of ['/reports', '/orders', '/private'])
await router.push(path)
menu.toggleMenuTagFixed('/orders')
await actions.close('/orders')
await actions.closeLeft('/private')
expect(actions.checkCloseLeft('/private')).toBe(false)
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/orders',
'/private',
])
await actions.closeRight('/orders')
expect(actions.checkCloseRight('/orders')).toBe(false)
expect(router.currentRoute.value.path).toBe('/orders')
await router.push('/reports')
await router.push('/private')
await actions.closeOther('/private')
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/orders',
'/private',
])
await actions.closeAll()
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/orders',
])
expect(router.currentRoute.value.path).toBe('/orders')
piniaSettingStore().updateSettingState('menuTagFixed', false)
await actions.close('/orders')
expect(menu.menuTagOptions).toEqual([])
expect(router.currentRoute.value.path).toBe('/welcome')
})
it('keeps status routes out of tabs and clears active business navigation', async () => {
await router.push('/reports')
@ -254,6 +343,7 @@ it('closes a directly opened 403 to the workspace with no business tags', async
it('removes revoked tags and cached views without choosing another active page', async () => {
await router.push('/reports')
await router.push('/private?mode=edit#section')
menu.toggleMenuTagFixed('/private?mode=edit#section')
piniaSigningStore().signingCallback.role = 'member'
await flushPromises()
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([

View File

@ -0,0 +1,73 @@
import Breadcrumb from '@/layout/components/SiderBar/components/Breadcrumb'
import type { AppMenuOption } from '@/types'
import { mount } from '@vue/test-utils'
import { h, nextTick, ref } from 'vue'
import type { Ref } from 'vue'
const state = vi.hoisted(() => ({
compact: null as unknown as Ref<boolean>,
icons: null as unknown as Ref<boolean>,
fallback: null as unknown as Ref<boolean>,
options: null as unknown as Ref<AppMenuOption[]>,
}))
vi.mock('@/hooks', () => ({
useDevice: () => ({ isTabletOrSmaller: state.compact }),
}))
vi.mock('@/store', () => ({
useMenuActions: () => ({ changeMenuModelValue: vi.fn() }),
useMenuGetters: () => ({ getBreadcrumbOptions: state.options }),
useSettingGetters: () => ({
getBreadcrumbIcon: state.icons,
getBreadcrumbIconFallback: state.fallback,
}),
}))
const option = (path: string, label: string): AppMenuOption => ({
name: label,
path,
key: path,
fullPath: path,
label,
breadcrumbLabel: label,
meta: {},
})
it('displays menu images and defaults to a fallback for the missing icon', async () => {
state.compact = ref(false)
state.icons = ref(true)
state.fallback = ref(true)
state.options = ref([
{
...option('/reports', 'Reports'),
icon: () => h('img', { src: '/report.png', alt: '' }),
},
option('/reports/monthly', 'Monthly'),
])
const wrapper = mount(Breadcrumb)
try {
const iconSelector = '.layout-breadcrumb__icon'
expect(wrapper.get(`${iconSelector} img`).attributes('src')).toBe(
'/report.png',
)
expect(wrapper.findAll(iconSelector)).toHaveLength(2)
state.fallback.value = false
await nextTick()
expect(wrapper.findAll(iconSelector)).toHaveLength(1)
state.compact.value = true
state.fallback.value = true
await nextTick()
expect(wrapper.get('[aria-current="page"]').text()).toBe('Monthly')
expect(wrapper.findAll(iconSelector)).toHaveLength(1)
state.icons.value = false
await nextTick()
expect(wrapper.findAll(iconSelector)).toHaveLength(0)
} 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)
@ -107,8 +116,14 @@ it('does not navigate while composing and supports keyboard result focus and Ent
await flushPromises()
const input = wrapper.find('input').element as HTMLInputElement
input.value = 'Visible'
input.dispatchEvent(new Event('input', { bubbles: true }))
expect(document.activeElement).toBe(input)
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

@ -1,8 +1,9 @@
import MenuTag from '@/layout/components/MenuTag'
import type { MenuTagOptions } from '@/types'
import { RIcon } from '@ray-template/ui/icon'
import { flushPromises, mount } from '@vue/test-utils'
import type { VueWrapper } from '@vue/test-utils'
import { NDropdown } from 'naive-ui'
import { NDropdown, NTag } from 'naive-ui'
import { h, nextTick, ref } from 'vue'
import type { Ref } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
@ -11,8 +12,15 @@ import type { Router } from 'vue-router'
const state = vi.hoisted(() => ({
tags: null as unknown as Ref<MenuTagOptions[]>,
active: null as unknown as Ref<MenuTagOptions | null>,
round: null as unknown as Ref<boolean>,
top: null as unknown as Ref<boolean>,
fixed: null as unknown as Ref<boolean>,
drag: null as unknown as Ref<boolean>,
close: vi.fn(),
navigate: vi.fn(),
move: vi.fn(),
toggleTop: vi.fn(),
toggleFixed: vi.fn(),
}))
vi.mock('@/hooks', () => ({
@ -36,8 +44,23 @@ vi.mock('@/store', () => ({
getMenuTagOptions: state.tags,
getCurrentMenuOption: state.active,
}),
useMenuActions: () => ({ changeMenuModelValue: state.navigate }),
useMenuActions: () => ({
changeMenuModelValue: state.navigate,
isMenuTagTopped: (tag?: MenuTagOptions) =>
state.top.value && tag?.topped === true,
isMenuTagFixed: (tag?: MenuTagOptions) =>
state.fixed.value && tag?.fixed === true,
toggleMenuTagTop: state.toggleTop,
toggleMenuTagFixed: state.toggleFixed,
moveMenuTag: state.move,
}),
useRuntimeGetters: () => ({ globalMainLayoutLoad: ref(true) }),
useSettingGetters: () => ({
getMenuTagRound: state.round,
getMenuTagTop: state.top,
getMenuTagFixed: state.fixed,
getMenuTagDrag: state.drag,
}),
}))
let wrapper: VueWrapper
@ -55,6 +78,10 @@ beforeEach(async () => {
})) as MenuTagOptions[],
)
state.active = ref(state.tags.value[0]!)
state.round = ref(false)
state.top = ref(true)
state.fixed = ref(true)
state.drag = ref(true)
router = createRouter({
history: createMemoryHistory(),
routes: [
@ -69,9 +96,15 @@ beforeEach(async () => {
attachTo: host,
global: {
plugins: [router],
mocks: { $t: (key: string) => key },
stubs: { 'transition-group': false },
mocks: {
$t: (key: string, params?: { name: string }) =>
params ? `${key}:${params.name}` : key,
},
},
})
await import('interactjs')
await flushPromises()
})
afterEach(() => {
@ -79,6 +112,7 @@ afterEach(() => {
router.options.history.destroy()
host.remove()
outside.remove()
vi.unstubAllGlobals()
})
const contextDropdown = () =>
@ -98,6 +132,32 @@ const mouse = (element: Element, type: string, button: number) => {
)
}
const point = (
element: Element,
type: string,
clientX: number,
clientY = 16,
) => {
const event = new PointerEvent(type, {
bubbles: true,
isPrimary: true,
pointerId: 2,
pointerType: 'mouse',
buttons: type === 'pointerup' ? 0 : 1,
clientX,
clientY,
})
Object.defineProperties(event, {
pageX: { value: clientX },
pageY: { value: clientY },
})
element.dispatchEvent(event)
}
const dragPreview = () =>
document.body.querySelector<HTMLElement>('.menu-tag__drag-preview')
const openContextMenu = async (index: number) => {
const tab = wrapper.findAll('.menu-tag__tab')[index]!.element
@ -109,6 +169,80 @@ const openContextMenu = async (index: number) => {
await flushPromises()
}
it('closes with the named native tag button without selecting the page', async () => {
const closeButton = wrapper.get(
'button.n-tag__close[aria-label="menuTag.closeNamed:Orders"]',
)
point(closeButton.element, 'pointerdown', 10)
point(closeButton.element, 'pointermove', 40)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(false)
point(closeButton.element, 'pointerup', 40)
await closeButton.trigger('click', { detail: 1 })
expect(state.close).toHaveBeenCalledExactlyOnceWith(1)
expect(state.navigate).not.toHaveBeenCalled()
})
it('updates the native close label when the tag is renamed', async () => {
const closeButton = wrapper.get('.n-tag__close')
expect(closeButton.attributes('aria-label')).toBe(
'menuTag.closeNamed:Reports',
)
state.tags.value[0]!.breadcrumbLabel = 'Summary'
await nextTick()
expect(closeButton.attributes('aria-label')).toBe(
'menuTag.closeNamed:Summary',
)
})
it.each(['button', 'Delete'])(
'restores focus after closing by keyboard (%s)',
async (method) => {
state.close.mockImplementationOnce((index: number) => {
state.tags.value.splice(index, 1)
})
const tab = wrapper.get<HTMLButtonElement>('.menu-tag__tab[title="Orders"]')
const closeButton = wrapper.get<HTMLButtonElement>(
'button.n-tag__close[aria-label="menuTag.closeNamed:Orders"]',
)
if (method === 'Delete') {
tab.element.focus()
await tab.trigger('keydown', { key: 'Delete' })
} else {
closeButton.element.focus()
await closeButton.trigger('click', { detail: 0 })
}
expect(state.close).toHaveBeenCalledExactlyOnceWith(1)
expect(state.navigate).not.toHaveBeenCalled()
expect(document.activeElement?.textContent).toBe('Users')
},
)
it('shares the native border across tabs and highlights the current page', async () => {
const tagTypes = () =>
wrapper.findAllComponents(NTag).map((tag) => tag.props('type'))
expect(tagTypes()).toEqual(['primary', 'default', 'default'])
state.tags.value[0]!.fixed = true
state.active.value = state.tags.value[1]!
await nextTick()
expect(tagTypes()).toEqual(['default', 'primary', 'default'])
expect(wrapper.findAll('.menu-tag__item .n-tag__border')).toHaveLength(3)
})
it('applies the native round style to open tags when the preference changes', async () => {
const tag = wrapper.get('.menu-tag__item')
expect(tag.classes('n-tag--round')).toBe(false)
state.round.value = true
await nextTick()
expect(tag.classes('n-tag--round')).toBe(true)
})
it('keeps the context menu open while repeatedly right-clicking other tags', async () => {
for (const index of [0, 1, 2, 0]) {
await openContextMenu(index)
@ -132,6 +266,275 @@ it('applies a context command to the most recently right-clicked tag', async ()
expect(contextDropdown().props('show')).toBe(false)
})
it('keeps context commands tied to the selected page when the order changes', async () => {
await openContextMenu(0)
state.tags.value.reverse()
await nextTick()
const command = Array.from(
document.querySelectorAll('.n-dropdown-option-body'),
).find((option) => option.textContent === 'fix')
mouse(command!, 'click', 0)
expect(state.toggleFixed).toHaveBeenCalledExactlyOnceWith('/reports')
})
it('updates tab status and actions while preferences change', async () => {
state.tags.value[0].topped = true
state.tags.value[0].fixed = true
await openContextMenu(0)
const tab = wrapper.get('[data-menu-tag-path="/reports"]')
const actions = () =>
contextDropdown()
.props('options')
?.map((option) => option.key)
const pin = tab.get('.n-tag__icon').getComponent(RIcon)
const label = tab.get('.menu-tag__tab')
expect(tab.find('.n-tag__close').exists()).toBe(false)
expect(pin.props('name')).toBe('action/pin')
expect(pin.attributes('aria-hidden')).toBe('true')
expect(label.attributes('aria-label')).toBe(
'Reports · menuTag.topped · menuTag.fixed',
)
expect(actions()).toEqual(
expect.arrayContaining(['toggleTop', 'toggleFixed']),
)
state.top.value = false
state.fixed.value = false
state.drag.value = false
await nextTick()
expect(tab.find('.n-tag__close').exists()).toBe(true)
expect(tab.find('.n-tag__icon').exists()).toBe(false)
expect(label.attributes('aria-label')).toBeUndefined()
expect(label.attributes('aria-keyshortcuts')).toBeUndefined()
expect(actions()).not.toContain('toggleTop')
expect(actions()).not.toContain('toggleFixed')
})
it('reorders a focused protected tab with Shift and an arrow key', async () => {
state.tags.value[0].fixed = true
await nextTick()
const tab = wrapper.get('[data-menu-tag-path="/reports"]')
const button = tab.get('.menu-tag__tab')
expect(tab.find('.n-tag__close').exists()).toBe(false)
expect(button.attributes('aria-keyshortcuts')).toBe(
'Shift+ArrowLeft Shift+ArrowRight',
)
await button.trigger('keydown', { key: 'ArrowRight' })
expect(state.move).not.toHaveBeenCalled()
await button.trigger('keydown', { key: 'ArrowRight', shiftKey: true })
expect(state.move).toHaveBeenCalledExactlyOnceWith(
'/reports',
'/orders',
'after',
)
expect(state.navigate).not.toHaveBeenCalled()
})
const mockTagRects = (viewportWidth = 300) => {
const row = wrapper.get<HTMLElement>('.menu-tag-wrapper').element
const scroller = row.closest('.n-scrollbar-container')!
const mockRect = (element: Element, measure: () => DOMRect) => {
element.getBoundingClientRect = measure
element.getClientRects = () => [measure()] as unknown as DOMRectList
}
mockRect(scroller, () => new DOMRect(0, 0, viewportWidth, 32))
Object.defineProperties(scroller, {
clientWidth: { value: viewportWidth },
scrollWidth: { value: 300 },
})
mockRect(row, () => new DOMRect(-scroller.scrollLeft, 0, 300, 32))
const tags = wrapper.findAll<HTMLElement>('[data-menu-tag-path]')
tags.forEach(({ element }, index) => {
Object.defineProperties(element, {
offsetLeft: { value: index * 100 },
offsetWidth: { value: 94 },
})
mockRect(
element,
() => new DOMRect(index * 100 - scroller.scrollLeft, 0, 94, 30),
)
})
return { row, scroller, tags }
}
it('reorders from the tab body using the release position and ignores the drag click', async () => {
const { row, tags } = mockTagRects()
const source = tags[0].element
point(source, 'pointerdown', 10)
expect(dragPreview()).toBeNull()
point(tags[1].element, 'pointermove', 180, 22)
const preview = dragPreview()!
expect(preview.parentElement).toBe(row.closest('.menu-tag'))
expect(preview.textContent).toBe(source.textContent)
expect(preview.dataset.menuTagPath).toBeUndefined()
expect(preview.getAttribute('aria-hidden')).toBe('true')
expect(preview.hasAttribute('inert')).toBe(true)
expect(preview.style.transform).toBe('translate3d(170px, 6px, 0)')
point(tags[1].element, 'pointermove', 190, 24)
expect(dragPreview()).toBe(preview)
expect(preview.style.transform).toBe('translate3d(180px, 8px, 0)')
expect(tags[1].attributes('data-menu-tag-drop')).toBe('after')
expect(state.move).not.toHaveBeenCalled()
point(tags[2].element, 'pointerup', 285)
expect(state.move).toHaveBeenCalledExactlyOnceWith(
'/reports',
'/users',
'after',
)
expect(
row.querySelector('[data-menu-tag-drop],[data-menu-tag-dragged]'),
).toBeNull()
expect(dragPreview()).toBeNull()
await tags[0].trigger('click', { detail: 1 })
expect(state.navigate).not.toHaveBeenCalled()
point(source, 'pointerdown', 10)
point(source, 'pointermove', 12)
point(source, 'pointerup', 12)
await tags[0].trigger('click', { detail: 1 })
expect(state.navigate).toHaveBeenCalledExactlyOnceWith(
'/reports',
state.tags.value[0],
)
expect(state.move).toHaveBeenCalledTimes(1)
})
it.each([
{ target: 'outside the horizontal viewport', x: -10, firstTopped: false },
{ target: 'over the other tab group', x: 20, firstTopped: true },
])('rejects a drop $target', async ({ x, firstTopped }) => {
state.tags.value[0]!.topped = firstTopped
await nextTick()
const { row, tags } = mockTagRects()
const source = tags[2].element
const target = firstTopped ? tags[0].element : outside
point(source, 'pointerdown', 240)
point(target, 'pointermove', x)
expect(source.hasAttribute('data-menu-tag-dragged')).toBe(true)
expect(row.querySelector('[data-menu-tag-drop]')).toBeNull()
point(target, 'pointerup', x)
expect(state.move).not.toHaveBeenCalled()
})
it('refreshes the drop marker after a scroll with a stationary pointer', () => {
const { scroller, tags } = mockTagRects(220)
const source = tags[0].element
const requestFrame = vi.fn((_callback: FrameRequestCallback) => 1)
vi.stubGlobal('requestAnimationFrame', requestFrame)
point(source, 'pointerdown', 30)
point(tags[1].element, 'pointermove', 180)
const position = dragPreview()?.style.transform
expect(position).toBe('translate3d(150px, 0px, 0)')
expect(tags[1].attributes('data-menu-tag-drop')).toBe('after')
expect(requestFrame).toHaveBeenCalledTimes(1)
requestFrame.mock.calls[0][0](16)
scroller.scrollLeft = 80
scroller.dispatchEvent(new Event('scroll'))
expect(requestFrame).toHaveBeenCalledTimes(2)
requestFrame.mock.calls[1][0](32)
expect(tags[2].attributes('data-menu-tag-drop')).toBe('after')
expect(dragPreview()?.style.transform).toBe(position)
point(tags[2].element, 'pointerup', 180)
})
it('cancels dragging with Escape and preserves keyboard activation', async () => {
const button = wrapper.get<HTMLButtonElement>(
'[data-menu-tag-path="/orders"] .menu-tag__tab',
)
point(button.element, 'pointerdown', 10)
point(button.element, 'pointermove', 60)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(true)
await button.trigger('keydown', { key: 'Escape' })
expect(dragPreview()).toBeNull()
point(button.element, 'pointerup', 60)
await button.trigger('click', { detail: 0 })
expect(state.navigate).toHaveBeenCalledExactlyOnceWith(
'/orders',
state.tags.value[1],
)
await button.trigger('click', { detail: 1 })
expect(state.move).not.toHaveBeenCalled()
expect(state.navigate).toHaveBeenCalledTimes(1)
})
it.each(['pointercancel', 'disabled'])(
'removes the drag preview when the drag is %s',
async (reason) => {
const { row, tags } = mockTagRects()
const source = tags[0].element
point(source, 'pointerdown', 10)
point(tags[1].element, 'pointermove', 180)
expect(dragPreview()).not.toBeNull()
if (reason === 'pointercancel') point(source, 'pointercancel', 180)
else {
state.drag.value = false
await nextTick()
}
expect(dragPreview()).toBeNull()
expect(
row.querySelector('[data-menu-tag-drop],[data-menu-tag-dragged]'),
).toBeNull()
expect(state.move).not.toHaveBeenCalled()
},
)
it.each([
{ hold: 100, claimed: false },
{ hold: 400, claimed: true },
])(
'claims a horizontal touch after $hold ms: $claimed',
({ hold, claimed }) => {
const button = wrapper.get<HTMLButtonElement>('.menu-tag__tab').element
const start = new PointerEvent('pointerdown', {
bubbles: true,
isPrimary: true,
pointerId: 2,
pointerType: 'touch',
buttons: 1,
clientX: 10,
clientY: 16,
})
const move = new TouchEvent('touchmove', {
bubbles: true,
cancelable: true,
touches: [
new Touch({ identifier: 2, target: button, clientX: 30, clientY: 16 }),
],
})
Object.defineProperty(move, 'timeStamp', { value: start.timeStamp + hold })
button.dispatchEvent(start)
button.dispatchEvent(move)
expect(move.defaultPrevented).toBe(claimed)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(claimed)
expect(Boolean(dragPreview())).toBe(claimed)
},
)
it.each([0, 2])(
'dismisses when mouse button %i is clicked outside the tags and menu',
async (button) => {

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')
@ -132,6 +140,14 @@ describe('layout preferences', () => {
})
expect(store.localeLanguage).toBe('en-US')
expect(store.menuTagSwitch).toBe(false)
expect(store.menuTagRound).toBe(false)
expect(store).toMatchObject({
menuTagTop: true,
menuTagFixed: true,
menuTagDrag: true,
breadcrumbIcon: true,
breadcrumbIconFallback: true,
})
expect(store.menuConfig).toMatchObject({
iconSize: 20,
collapsedIconSize: 22,
@ -186,6 +202,12 @@ describe('layout preferences', () => {
store.updateSettingState('layoutConfig', { mode: 'right' })
store.updateSettingState('appTheme', 'dark')
store.updateSettingState('themeStyle', 'material')
store.updateSettingState('menuTagRound', true)
store.updateSettingState('menuTagTop', false)
store.updateSettingState('menuTagFixed', false)
store.updateSettingState('menuTagDrag', false)
store.updateSettingState('breadcrumbIcon', false)
store.updateSettingState('breadcrumbIconFallback', false)
store.updateSettingState('watermarkConfig', { content: 'Portable' })
store.updateSettingState('keepAliveConfig', {
keepAliveExclude: ['Page'],
@ -195,6 +217,9 @@ describe('layout preferences', () => {
store.updateSettingState('layoutConfig', { mode: 'top' })
store.updateSettingState('appTheme', 'light')
store.updateSettingState('menuTagRound', false)
store.updateSettingState('menuTagDrag', true)
store.updateSettingState('breadcrumbIcon', true)
store.updateSettingState('appRootRoute', { path: '/custom-home' })
store.changePrimaryColor('#000000')
store.updateSettingState('themeStyle', 'plain')
@ -202,6 +227,7 @@ describe('layout preferences', () => {
await nextTick()
expect(store.exportPreferences()).toEqual(file)
expect(store.menuTagRound).toBe(true)
expect(store._appTheme).toBe(true)
expect(store.themeOverrides.common?.primaryColor).toBe('#3468db')
expect(store.themeOverrides.Card?.borderRadius).toBe('20px')
@ -216,6 +242,12 @@ describe('layout preferences', () => {
layoutConfig: { mode: 'right' },
appTheme: 'dark',
themeStyle: 'material',
menuTagRound: true,
menuTagTop: false,
menuTagFixed: false,
menuTagDrag: false,
breadcrumbIcon: false,
breadcrumbIconFallback: false,
})
} finally {
app.unmount()
@ -232,12 +264,30 @@ describe('layout preferences', () => {
try {
store.updateSettingState('themeStyle', 'material')
store.updateSettingState('menuTagRound', true)
store.changePrimaryColor('#3468db')
const { preferences, ...file } = store.exportPreferences()
const { themeStyle: _style, ...legacy } = preferences
const {
themeStyle: _style,
menuTagRound: _round,
menuTagTop: _top,
menuTagFixed: _fixed,
menuTagDrag: _drag,
breadcrumbIcon: _icon,
breadcrumbIconFallback: _fallback,
...legacy
} = preferences
store.importPreferences(JSON.stringify({ ...file, preferences: legacy }))
expect(store.themeStyle).toBe('modern')
expect(store.menuTagRound).toBe(false)
expect(store.exportPreferences().preferences).toMatchObject({
menuTagTop: true,
menuTagFixed: true,
menuTagDrag: true,
breadcrumbIcon: true,
breadcrumbIconFallback: true,
})
expect(store.themeOverrides.Card?.borderRadius).toBe('12px')
expect(store.themeOverrides.common?.primaryColor).toBe('#3468db')
@ -252,7 +302,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)
@ -273,10 +323,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)'
@ -300,7 +358,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

@ -133,17 +133,26 @@ describe('workspace preference shortcuts', () => {
.trigger('click')
try {
const pillToggle = wrapper.get(
'[role="switch"][aria-label="preferences.appearance.menuTagRound"]',
)
expect(pillToggle.attributes('aria-checked')).toBe('false')
await pillToggle.trigger('click')
expect(store.menuTagRound).toBe(true)
await click('appearance.minimal')
expect([
store.breadcrumbSwitch,
store.menuTagSwitch,
store.copyrightSwitch,
]).toEqual([false, false, false])
expect(store.menuTagRound).toBe(true)
await click('appearance.reset')
expect(store.contentTransition).toBe(
getDefaultSettingConfig().contentTransition,
)
expect(store.menuTagSwitch).toBe(getDefaultSettingConfig().menuTagSwitch)
expect(store.menuTagRound).toBe(false)
expect(store.themeStyle).toBe(getDefaultSettingConfig().themeStyle)
expect(store.primaryColorOverride).toEqual({})
expect(store.appTheme).toBe('auto')

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

@ -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

@ -11,6 +11,7 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
| template | `useWatermark` | `/template-hooks`: text, show, hide, and toggle | [useWatermark](../../../../__test__/hooks/useWatermark.spec.ts) |
| template | `useAppNavigation` | `/template-hooks`: full paths, indexes, nested menus, and query | [useAppNavigation](../../../../__test__/hooks/useAppNavigation.spec.ts) |
| template | `useSiderBar` | `/template-hooks`: close tabs by path or close left/right/other/all tabs | [useSiderBar](../../../../__test__/hooks/useSiderBar.spec.ts) |
| components | `useMenu` | `/template-hooks`: bind an NMenu, change the selection, and reveal a nested option | [useMenu](../../../../__test__/hooks/useMenu.spec.tsx) |
| template | `useContentScroll` | `/template-hooks`: scroll content to top or coordinates | [useLayoutScroll](../../../../__test__/hooks/useLayoutScroll.spec.ts) |
| template | `useSiderScroll` | `/template-hooks`: scroll sidebar to top or coordinates | [useLayoutScroll](../../../../__test__/hooks/useLayoutScroll.spec.ts) |
| web | `useDevice` | `/web-hooks`: update breakpoint checks with window size | [useDevice](../../../../__test__/hooks/useDevice.spec.ts) |
@ -34,6 +35,7 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
- Both scroll hooks can be created during setup and read the layout instance only when invoked. Missing sidebars or unmounted instances are safely ignored.
- `useMaximize` acts on layout content and shares state across callers. `useElementFullscreen` acts on one arbitrary element and owns per-instance state. Neither calls the browser Fullscreen API.
- `navigationTo` indexes start at 0. Negative, fractional, non-finite, or out-of-range indexes do not navigate. Full URLs support dynamic parameters, query, and hash; additional query parameters override matching URL parameters. Successful calls return the Router navigation Promise.
- Bind `useMenu().menuRef` and `menuProps` to `NMenu`. Provide `value` or `expandedKeys` to keep that state in the hook. Omit an input to use the corresponding Naive UI defaults. Replace option arrays for shallow reactivity. The hook is available from `@/hooks` and `@ray-template/composables/useMenu`.
- `useDomToImage` return types follow the default format or the current `create(format)` call. Failures reject with Error. `finally` also runs when the target is missing, so its argument may be empty. The `created` callback receives results from runtime format overrides as well; its argument is a union of actual output types and must be narrowed first.
- `useI18n('hooks').t('code')` and `.t('hooks.code')` address the same translation key. Switch application locales with `useSettingActions().updateLocale` to keep dates and component-library locales synchronized.
- Development HMR reuses the internationalization instance. Translation methods created before initialization read the current instance at invocation rather than permanently retaining the fallback that returns raw keys.

View File

@ -1,2 +1,3 @@
export * from './useContextmenuCoordinate'
export * from './useMenu'
export * from './usePagination'

View File

@ -0,0 +1 @@
export * from '@ray-template/composables/useMenu'

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

@ -42,8 +42,24 @@ const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
export function useSiderBar() {
const { getMenuTagOptions, getCurrentMenuOption } = useMenuGetters()
const { router } = useVueRouter()
const { changeMenuModelValue, spliceMenTagOptions, setMenuTagOptions } =
useMenuActions()
const {
changeMenuModelValue,
spliceMenTagOptions,
setMenuTagOptions,
isMenuTagFixed,
} = useMenuActions()
const canClose = (tag: MenuTagOptions) => !isMenuTagFixed(tag)
const closeWhere = (matches: (index: number) => boolean) => {
const current = getMenuTagOptions.value
const remaining = current.filter(
(tag, index) => !matches(index) || !canClose(tag),
)
if (remaining.length !== current.length) setMenuTagOptions(remaining, false)
return remaining
}
/**
*
@ -64,14 +80,9 @@ export function useSiderBar() {
const checkCloseRight = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'checkCloseRight')
if (normal) {
const { index } = normal
const length = getMenuTagOptions.value.length - 1
return !(index >= length)
}
return false
return (
!!normal && getMenuTagOptions.value.slice(normal.index + 1).some(canClose)
)
}
/**
@ -83,7 +94,9 @@ export function useSiderBar() {
const checkCloseLeft = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'checkCloseLeft')
return !!normal && normal.index > 0
return (
!!normal && getMenuTagOptions.value.slice(0, normal.index).some(canClose)
)
}
/**
@ -91,14 +104,14 @@ export function useSiderBar() {
* @param target 要关闭的标签对象、索引或路径
*
* @description
* 所有业务标签都可关闭;关闭最后一项进入空工作区,其余激活项切换到相邻标签。
* 固定的标签会保留;关闭最后一项进入空工作区,关闭激活项时切换到相邻标签。
*
* @returns 需要跳转时返回 Router 导航结果。
*/
const close = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'close')
if (normal) {
if (normal && canClose(normal.option)) {
const { index, option } = normal
const active = option.fullPath === getCurrentMenuOption.value?.fullPath
@ -118,14 +131,17 @@ export function useSiderBar() {
/**
*
* @description
* 清空所有业务标签及其缓存,然后进入空工作区;不依赖任何业务首页。
* 关闭未固定的标签;优先保留当前页面,再尝试第一个固定标签或空工作区。
*
* @returns Router 导航结果。
*/
const closeAll = () => {
setMenuTagOptions([], false)
const current = getCurrentMenuOption.value?.fullPath
const remaining = closeWhere(() => true)
return router.replace(WELCOME_ROUTE_PATH)
if (remaining.some((tag) => tag.fullPath === current)) return
return router.replace(remaining[0]?.fullPath ?? WELCOME_ROUTE_PATH)
}
const closeForbiddenPage = () => {
@ -148,19 +164,19 @@ export function useSiderBar() {
* @param target 要保留的边界标签对象、索引或路径
*
* @description
* 关闭右侧标签;激活项被移除时切换到边界标签。
* 关闭右侧未固定的标签;激活项被移除时切换到边界标签。
*/
const closeRight = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'closeRight')
if (normal) {
const { option, index } = normal
const spliceLength = getMenuTagOptions.value.length - index // 待删除长度
const currentIndex = getCurrentTagIndex()
const current = getMenuTagOptions.value[currentIndex]
spliceMenTagOptions(index + 1, spliceLength)
closeWhere((tagIndex) => tagIndex > index)
if (currentIndex > index)
if (currentIndex > index && canClose(current))
return changeMenuModelValue(option.fullPath, option)
}
}
@ -170,7 +186,7 @@ export function useSiderBar() {
* @param target 要保留的边界标签对象、索引或路径
*
* @description
* 关闭左侧标签;激活项被移除时切换到边界标签。
* 关闭左侧未固定的标签;激活项被移除时切换到边界标签。
*/
const closeLeft = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'closeLeft')
@ -178,10 +194,11 @@ export function useSiderBar() {
if (normal) {
const { option, index } = normal
const currentIndex = getCurrentTagIndex()
const current = getMenuTagOptions.value[currentIndex]
spliceMenTagOptions(0, index)
closeWhere((tagIndex) => tagIndex < index)
if (currentIndex >= 0 && currentIndex < index)
if (currentIndex >= 0 && currentIndex < index && canClose(current))
return changeMenuModelValue(option.fullPath, option)
}
}
@ -191,15 +208,15 @@ export function useSiderBar() {
* @param target 要保留的标签对象、索引或路径
*
* @description
* 仅保留并激活目标标签;目标无效时不操作。
* 保留目标与所有固定标签,并激活目标。
*/
const closeOther = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'closeOther')
if (normal) {
const { option } = normal
const { option, index } = normal
setMenuTagOptions(option, false)
closeWhere((tagIndex) => tagIndex !== index)
if (getCurrentMenuOption.value?.fullPath !== option.fullPath)
return changeMenuModelValue(option.fullPath, option)

View File

@ -11,12 +11,14 @@ import {
} from '@/store'
import type { AppMenuOption, NaiveMenuOptions } from '@/types'
import { useMenuKeyboard } from '@ray-template/admin-shell'
import { useMenu } from '@ray-template/composables/useMenu'
import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDrawer, NLayoutContent, NLayoutSider, NMenu } from 'naive-ui'
import type { MenuInst } from 'naive-ui'
import type { PropType } from 'vue'
import SiderBarLogo from './components/SiderBarLogo'
const triggerStyle = { top: 'max(24px, calc(50% - 240px))' }
export default defineComponent({
name: 'AppMenu',
props: {
@ -26,7 +28,7 @@ export default defineComponent({
inert: Boolean,
},
setup(props) {
const menuRef = shallowRef<MenuInst | null>(null)
const { menuRef, showOption } = useMenu()
const { changeMenuModelValue, collapsedMenu } = useMenuActions()
const { t } = useI18n('layout')
const { getAppTheme, getMenuConfig } = useSettingGetters()
@ -54,8 +56,7 @@ export default defineComponent({
async () => {
await nextTick()
if (getMenuKey.value != null)
menuRef.value?.showOption(String(getMenuKey.value))
if (getMenuKey.value != null) showOption(String(getMenuKey.value))
positionSelectedMenuItem()
},
@ -72,6 +73,8 @@ export default defineComponent({
class={['app-menu__sider', { 'app-menu__sider--end': props.end }]}
{...{ inert: props.inert }}
showTrigger={!isTabletOrSmaller.value}
triggerStyle={triggerStyle}
collapsedTriggerStyle={triggerStyle}
collapseMode={getMenuConfig.value.collapsedMode}
collapsedWidth={getMenuConfig.value.collapsedWidth}
onUpdateCollapsed={collapsedMenu}

View File

@ -4,3 +4,83 @@
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
}
.menu-tag-wrapper {
position: relative;
padding-inline: 4px;
}
.menu-tag-wrapper[data-menu-tag-sortable] .menu-tag__item {
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
}
.menu-tag__top-icon {
rotate: 180deg;
}
.menu-tag-wrapper--dragging,
.menu-tag-wrapper--dragging :is(.menu-tag__item:hover, .menu-tag__tab) {
cursor: grabbing;
}
.menu-tag__item[data-menu-tag-dragged] {
opacity: 0.55;
}
.menu-tag__item.menu-tag__drag-preview {
position: fixed;
inset: 0 auto auto 0;
z-index: 4;
background-color: var(--r-surface);
background-image: linear-gradient(var(--n-color), var(--n-color));
box-shadow: var(--r-shadow-soft);
pointer-events: none;
transition: none;
}
.menu-tag__item[data-menu-tag-drop]::after {
position: absolute;
inset-block: 0;
z-index: 5;
inline-size: 2px;
border-radius: var(--r-control-radius);
background: var(--r-theme-primary-color);
pointer-events: none;
content: '';
}
.menu-tag__item[data-menu-tag-drop='before']::after {
inset-inline-start: -4px;
}
.menu-tag__item[data-menu-tag-drop='after']::after {
inset-inline-end: -4px;
}
.menu-tag-move {
transition: transform 150ms var(--r-bezier);
}
.menu-tag__status {
position: absolute;
inline-size: 1px;
block-size: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@media (forced-colors: active) {
.menu-tag__item[data-menu-tag-drop]::after {
background: Highlight;
forced-color-adjust: none;
}
}
@media (prefers-reduced-motion: reduce) {
.menu-tag-move {
transition: none;
}
}

View File

@ -1,15 +1,25 @@
import './index.scss'
import { useI18n, useMaximize, useSiderBar, useSpinning } from '@/hooks'
import { FORBIDDEN_ROUTE_PATH } from '@/router/constant'
import { useMenuActions, useMenuGetters, useRuntimeGetters } from '@/store'
import {
useMenuActions,
useMenuGetters,
useRuntimeGetters,
useSettingGetters,
} from '@/store'
import type { AppMenuOption, MenuTagOptions } from '@/types'
import { ShellTab } from '@ray-template/admin-shell'
import { RIcon } from '@ray-template/ui/icon'
import { RMoreDropdown } from '@ray-template/ui/more-dropdown'
import { usePreferredReducedMotion, useResizeObserver } from '@vueuse/core'
import {
usePreferredReducedMotion,
useResizeObserver,
useTimeoutFn,
} from '@vueuse/core'
import { NDropdown, NFlex, NLayoutHeader, NScrollbar } from 'naive-ui'
import type { ScrollbarInst } from 'naive-ui'
import { useTemplateRef } from 'vue'
import { TransitionGroup, useTemplateRef } from 'vue'
import { useTagReorder } from './use-tag-reorder'
const Chevron = ({ direction }: { direction: 'left' | 'right' }) => (
<RIcon
@ -25,14 +35,25 @@ export default defineComponent({
const scrollRef = useTemplateRef<ScrollbarInst | null>('scrollRef')
const tagsRef = useTemplateRef<HTMLElement>('tags')
const actionsButton = useTemplateRef<HTMLButtonElement>('actionsButton')
const statusRef = useTemplateRef<HTMLSpanElement>('reorderStatus')
const route = useRoute()
const showingForbidden = computed(() => route.path === FORBIDDEN_ROUTE_PATH)
const { t } = useI18n('menuTag')
const { t: translate } = useI18n()
const { getCurrentMenuOption, getMenuTagOptions } = useMenuGetters()
const { getMenuTagRound, getMenuTagTop, getMenuTagFixed, getMenuTagDrag } =
useSettingGetters()
const getMenuKey = computed(
() => getCurrentMenuOption.value?.fullPath ?? null,
)
const { changeMenuModelValue } = useMenuActions()
const {
changeMenuModelValue,
isMenuTagTopped,
isMenuTagFixed,
toggleMenuTagTop,
toggleMenuTagFixed,
moveMenuTag,
} = useMenuActions()
const { maximize } = useMaximize()
const { reload } = useSpinning()
const {
@ -45,8 +66,15 @@ export default defineComponent({
checkCloseLeft,
checkCloseRight,
} = useSiderBar()
// 当前右键标签页索引位置
const currentContextmenuIndex = ref(-1)
const contextPath = ref<string>()
const currentContextmenuIndex = computed(() =>
getMenuTagOptions.value.findIndex(
({ fullPath }) => fullPath === contextPath.value,
),
)
const contextTag = computed(
() => getMenuTagOptions.value[currentContextmenuIndex.value],
)
const closeStatus = async (restoreFocus: boolean) => {
const navigation = closeForbiddenPage()
@ -67,7 +95,7 @@ export default defineComponent({
key: 'closeCurrentPage',
disabled:
!(showingForbidden.value && currentContextmenuIndex.value === -1) &&
!canClose(getMenuTagOptions.value[currentContextmenuIndex.value]),
!canClose(contextTag.value),
icon: () => <RIcon name="action/close" size="1em" />,
},
{
@ -83,9 +111,37 @@ export default defineComponent({
{
label: t('newWindow'),
key: 'windowOpenTab',
disabled: !getMenuTagOptions.value[currentContextmenuIndex.value],
disabled: !contextTag.value,
icon: () => <RIcon name="navigation/window" size="1em" />,
},
...(getMenuTagTop.value
? [
{
label: t(isMenuTagTopped(contextTag.value) ? 'untop' : 'top'),
key: 'toggleTop',
disabled: !contextTag.value,
icon: () => (
<RIcon
name="directional/expanded"
size="1em"
customClassName="menu-tag__top-icon"
/>
),
},
]
: []),
...(getMenuTagFixed.value
? [
{
label: t(isMenuTagFixed(contextTag.value) ? 'unfix' : 'fix'),
key: 'toggleFixed',
disabled: !contextTag.value,
icon: () => (
<RIcon name="action/pin" size="1em" aria-hidden="true" />
),
},
]
: []),
{
type: 'divider',
key: 'd1',
@ -94,16 +150,14 @@ export default defineComponent({
label: t('closeLeft'),
key: 'closeLeft',
disabled:
!getMenuTagOptions.value[currentContextmenuIndex.value] ||
!checkCloseLeft(currentContextmenuIndex.value),
!contextTag.value || !checkCloseLeft(currentContextmenuIndex.value),
icon: () => <RIcon name="action/close_left" size="1em" />,
},
{
label: t('closeRight'),
key: 'closeRight',
disabled:
!getMenuTagOptions.value[currentContextmenuIndex.value] ||
!checkCloseRight(currentContextmenuIndex.value),
!contextTag.value || !checkCloseRight(currentContextmenuIndex.value),
icon: () => <RIcon name="action/close_right" size="1em" />,
},
{
@ -114,15 +168,17 @@ export default defineComponent({
label: t('closeOther'),
key: 'closeOther',
disabled:
getMenuTagOptions.value.length < 2 ||
!getMenuTagOptions.value[currentContextmenuIndex.value],
!contextTag.value ||
!getMenuTagOptions.value.some(
(tag) => tag !== contextTag.value && canClose(tag),
),
icon: () => <RIcon name="action/close_other" size="1em" />,
},
{
label: t('closeAll'),
key: 'closeAll',
icon: () => <RIcon name="action/close_all" size="1em" />,
disabled: getMenuTagOptions.value.length === 0,
disabled: !getMenuTagOptions.value.some(canClose),
},
])
const actionMap = {
@ -133,7 +189,7 @@ export default defineComponent({
closeCurrentMenuTag(currentContextmenuIndex.value)
},
reloadCurrentPage: async () => {
const option = getMenuTagOptions.value[currentContextmenuIndex.value]
const option = contextTag.value
if (option && route.fullPath !== option.fullPath) {
await changeMenuModelValue(option.fullPath, option)
@ -155,8 +211,26 @@ export default defineComponent({
closeOther: () => {
$closeOther(currentContextmenuIndex.value)
},
toggleTop: () => {
const option = contextTag.value
if (!option || !toggleMenuTagTop(option.fullPath)) return
void nextTick(() => {
const tag = Array.from(tagsRef.value?.children ?? []).find(
(element): element is HTMLElement =>
element instanceof HTMLElement &&
element.dataset.menuTagPath === option.fullPath,
)
if (tag) revealTag(tag)
})
},
toggleFixed: () => {
if (contextTag.value) toggleMenuTagFixed(contextTag.value.fullPath)
},
windowOpenTab: () => {
const option = getMenuTagOptions.value[currentContextmenuIndex.value]
const option = contextTag.value
if (!option?.fullPath) {
return
@ -170,7 +244,7 @@ export default defineComponent({
window.open(path, '_blank', 'noopener')
},
maximizeLayoutContent: () => {
const option = getMenuTagOptions.value[currentContextmenuIndex.value]
const option = contextTag.value
maximize(true)
option && menuTagClick(option)
@ -183,7 +257,12 @@ export default defineComponent({
actionDropdownShow: false,
})
const globalMainLayoutLoad = useRuntimeGetters().globalMainLayoutLoad
const canClose = (option?: MenuTagOptions) => !!option
const canClose = (option?: MenuTagOptions) =>
!!option && !isMenuTagFixed(option)
const tagLabel = (tag: MenuTagOptions) =>
tag.meta.i18nKey
? translate(tag.meta.i18nKey)
: tag.breadcrumbLabel || tag.fullPath
const closeCurrentMenuTag = (index: number, restoreFocus = false) => {
const option = getMenuTagOptions.value[index]
@ -217,6 +296,61 @@ export default defineComponent({
)
const scrollState = reactive({ left: false, right: false })
const reducedMotion = usePreferredReducedMotion()
const revealTag = (tag: HTMLElement) => {
const element = scroller.value
if (!element) return
const start = tag.offsetLeft
const end = start + tag.offsetWidth
const left = element.scrollLeft
const right = left + element.clientWidth
if (start < left || tag.offsetWidth >= element.clientWidth)
element.scrollLeft = start
else if (end > right) element.scrollLeft = end - element.clientWidth
}
const { start: scheduleAnnouncement } = useTimeoutFn(
(message: string) => {
if (statusRef.value) statusRef.value.textContent = message
},
500,
{ immediate: false },
)
const announce = (message: string) => {
if (statusRef.value) statusRef.value.textContent = ''
scheduleAnnouncement(message)
}
const moveTagWithKey = useTagReorder(
getMenuTagDrag,
tagsRef,
scroller,
(path, target, button) => {
if (!moveMenuTag(path, target.path, target.placement)) return
const position = getMenuTagOptions.value.findIndex(
(tag) => tag.fullPath === path,
)
const option = getMenuTagOptions.value[position]
const wasFocused = document.activeElement === button
void nextTick(() => {
const tag = button.closest<HTMLElement>('[data-menu-tag-path]')
if (!tag?.isConnected) return
revealTag(tag)
if (wasFocused) button.focus({ preventScroll: true })
announce(
t('moved', { name: tagLabel(option), position: position + 1 }),
)
})
},
() => announce(t('moveCanceled')),
)
const syncScroll = () => {
const element = scroller.value
@ -252,12 +386,10 @@ export default defineComponent({
return fn?.()
}
// 右键点击标签页
// 缓存当前点击标签页索引值(用于关闭左或者右侧标签页操作)
const menuTagContextMenu = (idx: number, e: MouseEvent) => {
const menuTagContextMenu = (path: string, e: MouseEvent) => {
e.preventDefault()
currentContextmenuIndex.value = idx
contextPath.value = path
actionState.x = e.clientX
actionState.y = e.clientY
actionState.actionDropdownShow = true
@ -276,10 +408,8 @@ export default defineComponent({
actionState.actionDropdownShow = false
}
const setCurrentContextmenuIndex = () => {
currentContextmenuIndex.value = getMenuTagOptions.value.findIndex(
({ fullPath }) => fullPath === getMenuKey.value,
)
const selectActiveContext = () => {
contextPath.value = getMenuKey.value ?? void 0
}
const positionMenuTag = () => {
@ -305,7 +435,12 @@ export default defineComponent({
}
watch(
[getMenuKey, () => getMenuTagOptions.value.length, tagsRef],
[
getMenuKey,
() => getMenuTagOptions.value.length,
getMenuTagRound,
tagsRef,
],
positionMenuTag,
{ flush: 'post' },
)
@ -314,7 +449,12 @@ export default defineComponent({
return {
getMenuTagOptions,
canClose,
getMenuTagRound,
getMenuTagDrag,
isMenuTagTopped,
isMenuTagFixed,
moveTagWithKey,
tagLabel,
closeCurrentMenuTag,
getMenuKey,
menuTagClick,
@ -330,7 +470,7 @@ export default defineComponent({
actionState,
menuTagContextMenu,
dismissContextMenu,
setCurrentContextmenuIndex,
selectActiveContext,
maximize,
reload,
globalMainLayoutLoad,
@ -339,7 +479,6 @@ export default defineComponent({
render() {
const { getMenuTagOptions, globalMainLayoutLoad } = this
const {
canClose,
closeCurrentMenuTag,
$t,
menuTagClick,
@ -393,34 +532,68 @@ export default defineComponent({
<div
ref="tags"
class="menu-tag-wrapper"
data-menu-tag-sortable={this.getMenuTagDrag ? '' : void 0}
role="group"
aria-label={$t('menuTag.pages')}
onKeydown={this.moveTagWithKey}
>
{getMenuTagOptions.map((curr, idx) => {
const active = curr.fullPath === this.getMenuKey
const label = curr.meta.i18nKey
? $t(curr.meta.i18nKey)
: curr.breadcrumbLabel || curr.fullPath
<TransitionGroup name="menu-tag" css={false}>
{getMenuTagOptions.map((curr, idx) => {
const active = curr.fullPath === this.getMenuKey
const label = this.tagLabel(curr)
const topped = this.isMenuTagTopped(curr)
const fixed = this.isMenuTagFixed(curr)
const topLabel = topped ? $t('menuTag.topped') : ''
const fixedLabel = fixed ? $t('menuTag.fixed') : ''
return (
<ShellTab
key={curr.fullPath}
label={label}
active={active}
select={() => menuTagClick(curr)}
closeLabel={$t('menuTag.closeNamed', { name: label })}
close={
canClose(curr)
? (restoreFocus) =>
closeCurrentMenuTag(idx, restoreFocus)
: void 0
}
contextMenu={(event) => menuTagContextMenu(idx, event)}
/>
)
})}
return (
<ShellTab
key={curr.fullPath}
label={label}
active={active}
data-menu-tag-path={curr.fullPath}
data-menu-tag-top={topped ? '' : void 0}
statusLabel={
topLabel && fixedLabel
? `${topLabel} · ${fixedLabel}`
: topLabel || fixedLabel
}
round={this.getMenuTagRound}
keyShortcuts={
this.getMenuTagDrag
? 'Shift+ArrowLeft Shift+ArrowRight'
: void 0
}
select={() => menuTagClick(curr)}
closeLabel={$t('menuTag.closeNamed', { name: label })}
close={
!fixed
? (restoreFocus) =>
closeCurrentMenuTag(idx, restoreFocus)
: void 0
}
contextMenu={(event) =>
menuTagContextMenu(curr.fullPath, event)
}
>
{{
prefix: fixed
? () => (
<RIcon
name="action/pin"
size={14}
aria-hidden="true"
/>
)
: void 0,
}}
</ShellTab>
)
})}
</TransitionGroup>
</div>
</NScrollbar>
<span ref="reorderStatus" class="menu-tag__status" role="status" />
<button
type="button"
class="menu-tag__control menu-tag__control--scroll"
@ -481,7 +654,7 @@ export default defineComponent({
class="menu-tag__control"
aria-label={$t('menuTag.actions')}
title={$t('menuTag.actions')}
onClick={this.setCurrentContextmenuIndex}
onClick={this.selectActiveContext}
>
<RIcon name="action/more" size={16} />
</button>

View File

@ -0,0 +1,484 @@
import type { DragEvent } from '@interactjs/actions/drag/plugin'
import type { DropEvent } from '@interactjs/actions/drop/DropEvent'
import type { PointerEvent as InteractPointerEvent } from '@interactjs/pointer-events/PointerEvent'
import { useEventListener } from '@vueuse/core'
import { watch } from 'vue'
import type { Ref } from 'vue'
type Interact = typeof import('interactjs').default
type Placement = 'before' | 'after'
type ClientPosition = Pick<PointerEvent, 'clientX' | 'clientY'>
const TAB_SELECTOR = '[data-menu-tag-path]'
const CLOSE_SELECTOR = '.n-tag__close'
const DRAG_SLOP = 5
const TOUCH_HOLD_DELAY = 280
interface DropTarget {
path: string
placement: Placement
}
interface DropMarker {
tab: HTMLElement
placement: Placement
}
interface Press {
down: PointerEvent
pointer: InteractPointerEvent
row: HTMLElement
tab: HTMLElement
button: HTMLButtonElement
path: string
offsetX: number
offsetY: number
}
interface Drag {
preview: HTMLElement
restoreDropMode: () => void
release?: PointerEvent
}
let activeTagDrags = 0
let previousDynamicDrop = false
const retainDynamicDrop = (interact: Interact) => {
// dynamicDrop 由同一个 interact.js 实例共享,最后一次标签拖动结束时恢复。
if (activeTagDrags === 0) {
previousDynamicDrop = interact.dynamicDrop() === true
interact.dynamicDrop(true)
}
activeTagDrags++
return () => {
activeTagDrags--
if (activeTagDrags === 0) interact.dynamicDrop(previousDynamicDrop)
}
}
export function useTagReorder(
enabled: Ref<boolean>,
list: Ref<HTMLElement | null>,
scroller: Ref<HTMLElement | null | undefined>,
move: (path: string, target: DropTarget, button: HTMLButtonElement) => void,
announceCancellation: () => void,
) {
let press: Press | undefined
let drag: Drag | undefined
let marker: DropMarker | undefined
let frame: number | undefined
let suppressPointerClick = false
const mark = (target?: DropMarker) => {
if (target?.tab === marker?.tab && target?.placement === marker?.placement)
return
marker?.tab.removeAttribute('data-menu-tag-drop')
target?.tab.setAttribute('data-menu-tag-drop', target.placement)
marker = target
}
const finish = () => {
press?.row.classList.remove('menu-tag-wrapper--dragging')
press?.tab.removeAttribute('data-menu-tag-dragged')
mark()
if (frame !== void 0) cancelAnimationFrame(frame)
frame = void 0
drag?.preview.remove()
drag?.restoreDropMode()
drag = void 0
press = void 0
}
const cancel = () => {
if (drag) {
press?.pointer.interaction.stop()
announceCancellation()
}
finish()
}
const refreshDrop = () => {
if (!drag || frame !== void 0) return
frame = requestAnimationFrame(() => {
frame = void 0
// 跳过同坐标的优化,让滚动后的落区重新参与检测。
press?.pointer.interaction.move({ skipModifiers: 1 })
})
}
const movePreview = ({ clientX, clientY }: ClientPosition) => {
if (!press || !drag) return
const x = clientX - press.offsetX
const y = clientY - press.offsetY
drag.preview.style.transform = `translate3d(${x}px, ${y}px, 0)`
}
const start = ({ pointer, tab }: Press, position: ClientPosition) => {
pointer.interaction.start({ name: 'drag' }, pointer.interactable, tab)
movePreview(position)
}
const startWithPointer = (event: PointerEvent) => {
const current = press
if (
!current ||
drag ||
event.pointerId !== current.down.pointerId ||
event.pointerType === 'touch'
)
return
const x = Math.abs(event.clientX - current.down.clientX)
const y = Math.abs(event.clientY - current.down.clientY)
if (Math.max(x, y) >= DRAG_SLOP) start(current, event)
}
const trackTouch = (event: TouchEvent) => {
const current = press
if (current?.down.pointerType !== 'touch') return
if (!event.cancelable || event.touches.length !== 1) {
cancel()
return
}
if (!drag) {
const touch = event.touches[0]
const x = Math.abs(touch.clientX - current.down.clientX)
const y = Math.abs(touch.clientY - current.down.clientY)
if (Math.max(x, y) < DRAG_SLOP) return
if (
event.timeStamp - current.down.timeStamp < TOUCH_HOLD_DELAY ||
y > x
) {
finish()
return
}
start(current, touch)
}
// 普通滑动保持原生滚动,长按启动拖动后才接管触摸。
if (drag) event.preventDefault()
}
const bind = (
interact: Interact,
row: HTMLElement,
viewport: HTMLElement,
) => {
const previewHost = row.closest('.menu-tag')
if (!previewHost) return
const zoneRect = (element: Element) => {
const visible = interact.getElementRect(viewport)
const origin = interact.getElementRect(row)?.left
if (!visible || origin === void 0)
return { left: 0, right: 0, top: 0, bottom: 0 }
const previous = element.previousElementSibling
const next = element.nextElementSibling
// 落区延伸到两侧相邻标签的边缘,使标签间的插入线也可以落下。
return {
left:
previous instanceof HTMLElement
? Math.max(
visible.left,
origin + previous.offsetLeft + previous.offsetWidth,
)
: visible.left,
right:
next instanceof HTMLElement
? Math.min(visible.right, origin + next.offsetLeft)
: visible.right,
top: visible.top,
bottom: visible.bottom,
}
}
const placementAt = (
event: DropEvent,
x: number,
): DropMarker | undefined => {
const { target: tab, relatedTarget: source } = event
if (!(tab instanceof HTMLElement)) return
const middle =
row.getBoundingClientRect().left + tab.offsetLeft + tab.offsetWidth / 2
const placement = x < middle ? 'before' : 'after'
const neighbor =
placement === 'before'
? tab.previousElementSibling
: tab.nextElementSibling
if (neighbor !== source) return { tab, placement }
}
const interactable = interact(TAB_SELECTOR, { context: row })
.styleCursor(false)
.preventDefault('never')
.rectChecker(zoneRect)
.draggable({
manualStart: true,
ignoreFrom: CLOSE_SELECTOR,
autoScroll: { container: viewport, margin: 36, speed: 450 },
listeners: {
start: () => {
if (!press) return
const preview = press.tab.cloneNode(true) as HTMLElement
preview.classList.add('menu-tag__drag-preview')
preview.removeAttribute('data-menu-tag-path')
preview.setAttribute('aria-hidden', 'true')
preview.setAttribute('inert', '')
// 副本浮在滚动区外,原标签继续占位并参与落点判定。
previewHost.append(preview)
drag = { preview, restoreDropMode: retainDynamicDrop(interact) }
suppressPointerClick = true
row.classList.add('menu-tag-wrapper--dragging')
press.tab.setAttribute('data-menu-tag-dragged', '')
refreshDrop()
},
move: movePreview,
end: finish,
},
})
.dropzone({
accept: ({ draggableElement }) =>
draggableElement.parentElement === row,
overlap: 'pointer',
checker: (
event: DragEvent,
_native,
over,
_zone,
target,
_from,
source,
) => {
if (
!drag ||
target.hasAttribute('data-menu-tag-top') !==
source.hasAttribute('data-menu-tag-top')
)
return false
if (event.type !== 'dragend') return over
const released = drag.release
if (!released) return false
if (
released.clientX === event.clientX &&
released.clientY === event.clientY
)
return over
// 1.10.28 的 dragend 坐标取自上一条 dragmove。松手坐标可能已变化。
const rect = zoneRect(target)
return (
released.pageX > rect.left &&
released.pageX < rect.right &&
released.pageY > rect.top &&
released.pageY < rect.bottom
)
},
ondropmove: (event: DropEvent) =>
mark(placementAt(event, event.dragEvent.clientX)),
ondragleave: () => mark(),
ondrop: (event: DropEvent) => {
const released = drag?.release
if (!press || !released) return
const marker = placementAt(event, released.clientX)
const path = marker?.tab.dataset.menuTagPath
if (marker && path)
move(
press.path,
{ path, placement: marker.placement },
press.button,
)
},
})
.pointerEvents({ ignoreFrom: CLOSE_SELECTOR })
.on('down', (pointer: InteractPointerEvent) => {
const event = pointer.originalEvent
const tab = pointer.currentTarget
if (
press ||
!(event instanceof PointerEvent) ||
!event.isPrimary ||
event.button !== 0 ||
!(tab instanceof HTMLElement) ||
tab.parentElement !== row
)
return
const path = tab.dataset.menuTagPath
const button = tab.querySelector<HTMLButtonElement>('.menu-tag__tab')
if (!path || !button) return
const { left, top } = tab.getBoundingClientRect()
press = {
down: event,
pointer,
row,
tab,
button,
path,
offsetX: event.clientX - left,
offsetY: event.clientY - top,
}
})
return () => {
cancel()
interactable.unset()
}
}
watch(
[enabled, list, scroller],
([allowed, row, viewport], _, onCleanup) => {
if (!allowed || !row || !viewport) return
let disposed = false
let unbind: (() => void) | undefined
onCleanup(() => {
disposed = true
unbind?.()
})
void import('interactjs').then(({ default: interact }) => {
if (!disposed) unbind = bind(interact, row, viewport)
})
},
{ immediate: true, flush: 'post' },
)
useEventListener('pointermove', startWithPointer, {
capture: true,
passive: true,
})
useEventListener(
'pointerup',
(event) => {
if (press?.down.pointerId !== event.pointerId) return
if (drag) drag.release = event
else finish()
},
{ capture: true },
)
useEventListener(
'pointercancel',
(event) => {
if (press?.down.pointerId === event.pointerId) cancel()
},
{ capture: true },
)
useEventListener(list, 'touchmove', trackTouch, { passive: false })
useEventListener(scroller, 'scroll', refreshDrop, { passive: true })
useEventListener(list, 'pointerdown', (event) => {
if (!drag && event.isPrimary && event.button === 0)
suppressPointerClick = false
})
useEventListener(
list,
'click',
(event) => {
if (!suppressPointerClick || event.detail === 0) return
suppressPointerClick = false
event.preventDefault()
event.stopPropagation()
},
{ capture: true },
)
useEventListener(
list,
'contextmenu',
(event) => {
if (press?.down.pointerType !== 'touch') return
event.preventDefault()
event.stopPropagation()
},
{ capture: true },
)
useEventListener(
'keydown',
(event) => {
if (event.key !== 'Escape' || !press) return
event.preventDefault()
cancel()
},
{ capture: true },
)
return (event: KeyboardEvent) => {
if (
!enabled.value ||
drag ||
!event.shiftKey ||
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.isComposing ||
(event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')
)
return
const button = event.target
if (
!(button instanceof HTMLButtonElement) ||
!button.classList.contains('menu-tag__tab')
)
return
event.preventDefault()
const item = button.closest<HTMLElement>(TAB_SELECTOR)
const placement = event.key === 'ArrowLeft' ? 'before' : 'after'
const neighbor =
placement === 'before'
? item?.previousElementSibling
: item?.nextElementSibling
const path = item?.dataset.menuTagPath
const target =
neighbor instanceof HTMLElement ? neighbor.dataset.menuTagPath : void 0
if (path && target) move(path, { path: target, placement }, button)
}
}

View File

@ -1,130 +1,243 @@
.global-search.n-card {
inline-size: min(650px, calc(100dvw - 24px));
max-block-size: calc(100dvh - 24px);
margin: 12px auto auto;
border-radius: var(--r-radius);
--search-gutter: 20px;
--search-top: min(56px, 8dvh);
--search-scrollbar-gutter: 8px;
--search-focus: color-mix(
in srgb,
var(--r-theme-primary-color) 50%,
var(--r-text)
);
.n-card__content {
min-block-size: 0;
overflow: auto;
inline-size: min(620px, calc(100dvw - 24px));
max-block-size: calc(100dvh - var(--search-top) - 12px);
margin: var(--search-top) auto auto;
border-radius: var(--r-radius);
box-shadow: var(--r-shadow-soft);
> .n-card-header {
gap: 16px;
padding: 10px var(--search-gutter);
}
.n-card__action {
padding: 12px 20px;
> .n-card__content {
display: flex;
flex-direction: column;
min-block-size: 0;
padding: 0 var(--search-gutter);
}
> .n-card__action {
flex-shrink: 0;
padding: 8px var(--search-gutter);
border-block-start: 1px solid var(--r-line);
border-end-start-radius: inherit;
border-end-end-radius: inherit;
background: var(--r-surface-muted);
}
}
.global-search__header,
.global-search__group-heading,
.global-search__item,
.global-search__help {
display: flex;
align-items: center;
}
.global-search__header,
.global-search__group-heading {
justify-content: space-between;
.global-search__title {
color: var(--r-text);
font-size: 16px;
font-weight: 600;
}
.global-search__header {
gap: 16px;
}
.global-search__group {
margin-top: 20px;
}
.global-search__group-heading {
min-height: 28px;
margin-bottom: 8px;
h2 {
font-size: 13px;
font-weight: 500;
color: var(--r-text-secondary);
}
.global-search__input {
flex-shrink: 0;
}
.global-search__results.n-scrollbar {
flex: 0 1 auto;
inline-size: auto;
block-size: auto;
min-block-size: 0;
max-block-size: 400px;
margin-block: 14px 12px;
margin-inline-end: calc(-1 * var(--search-scrollbar-gutter));
}
.global-search__results-content {
padding-inline-end: var(--search-scrollbar-gutter);
}
.global-search__group + .global-search__group {
margin-block-start: 16px;
}
.global-search__group-heading {
margin: 0 0 5px;
padding-inline: 8px;
color: var(--r-text-secondary);
font-size: 12px;
font-weight: 600;
}
.global-search__list {
display: grid;
gap: 4px;
margin: 0;
padding: 0;
list-style: none;
}
.global-search__item {
gap: 4px;
border: 1px solid var(--r-line);
min-inline-size: 0;
padding-inline-end: 4px;
border-radius: var(--r-control-radius);
margin-block: 6px;
padding-inline-end: 8px;
&:hover,
&:focus-within {
background: var(--r-surface-hover);
@media (hover: hover) {
&:hover {
background: var(--r-surface-hover);
}
}
&:has(> .global-search__destination:focus-visible) {
background: color-mix(
in srgb,
var(--r-theme-primary-color) 9%,
var(--r-surface)
);
outline: 2px solid var(--search-focus);
outline-offset: -2px;
> .global-search__destination {
outline: none;
}
.global-search__page-icon {
color: var(--search-focus);
background: color-mix(
in srgb,
var(--r-theme-primary-color) 15%,
var(--r-surface)
);
}
}
&:has(> .global-search__destination:active) {
background: color-mix(in srgb, var(--r-text) 12%, var(--r-surface));
}
}
.global-search__destination {
display: flex;
flex: 1;
align-items: center;
gap: 12px;
min-width: 0;
min-height: 46px;
padding: 10px 12px;
gap: 10px;
min-inline-size: 0;
min-block-size: 44px;
padding: 6px 8px;
border: 0;
border-radius: var(--r-control-radius);
background: transparent;
color: var(--r-text);
text-align: start;
cursor: pointer;
line-height: 1.5;
font-weight: 500;
line-height: 1.4;
}
> span {
overflow-wrap: anywhere;
}
.r-icon {
flex-shrink: 0;
color: var(--r-theme-primary-color);
.global-search__destination,
.global-search__close.n-button,
.global-search__favorite.n-button,
.global-search__clear.n-button {
&:focus-visible {
outline: 2px solid var(--search-focus);
outline-offset: -2px;
}
}
.global-search__favorite {
.global-search__close,
.global-search__favorite,
.global-search__clear {
flex-shrink: 0;
font-size: 20px;
}
.global-search__page-icon {
display: grid;
flex-shrink: 0;
place-items: center;
inline-size: 32px;
block-size: 32px;
border-radius: var(--r-control-radius);
background: var(--r-surface-muted);
color: var(--r-text-secondary);
}
.global-search__page-label {
overflow-wrap: anywhere;
}
.global-search__external {
color: var(--r-text-muted);
}
.global-search__empty {
padding: 36px 12px;
display: grid;
justify-items: center;
gap: 10px;
margin: 0;
padding: 28px 12px;
text-align: center;
color: var(--r-text-secondary);
}
.global-search__hint {
margin-top: 12px;
margin: 10px 0 0;
color: var(--r-text-secondary);
}
.global-search__help {
flex-wrap: wrap;
gap: 16px;
gap: 6px 14px;
min-block-size: 30px;
font-size: 12px;
color: var(--r-text-secondary);
}
.global-search__shortcut {
display: inline-flex;
align-items: center;
gap: 4px;
white-space: nowrap;
kbd {
padding: 2px 5px;
display: inline-grid;
place-items: center;
min-inline-size: 20px;
min-block-size: 20px;
padding-inline: 4px;
border: 1px solid var(--r-line);
border-radius: 4px;
border-radius: var(--r-control-radius);
background: var(--r-surface);
font-family: var(--r-font-mono);
}
}
.global-search__results {
max-block-size: min(440px, calc(100dvh - 230px));
.global-search__clear {
margin-inline-start: auto;
}
@media (max-width: 768px) {
.global-search.n-card {
.n-card-header {
padding: 12px 16px;
}
--search-gutter: 14px;
--search-top: 12px;
.n-card__content {
padding-inline: 16px;
}
.n-card__action {
padding: 12px 16px;
> .n-card__action:not(:has(.global-search__clear)) {
display: none;
}
}
.global-search__header > .n-button,
.global-search__favorite {
.global-search__close.n-button,
.global-search__favorite.n-button,
.global-search__clear.n-button {
min-inline-size: 44px;
min-block-size: 44px;
}
@ -132,14 +245,10 @@
.global-search__shortcut {
display: none;
}
.global-search__help:has(> :not(.global-search__shortcut)) {
justify-content: flex-end;
}
}
@media (min-width: 769px) {
@media (forced-colors: active) {
.global-search.n-card {
margin-block-start: min(60px, 8dvh);
--search-focus: Highlight;
}
}

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),
},
]
@ -104,6 +122,13 @@ export default defineComponent({
if (show) resetSearch()
},
)
watch(
[() => props.show, input],
([show, field]) => {
if (show) field?.focus()
},
{ flush: 'post' },
)
const openPage = async (option: AppMenuOption) => {
// 从当前菜单重新解析,缓存里的旧路径不能绕过权限或路由来源变化。
@ -167,7 +192,7 @@ export default defineComponent({
onUpdateShow={(value) => {
modelShow.value = value
}}
onAfterEnter={() => input.value?.focus()}
autoFocus={false}
transformOrigin="center"
displayDirective="if"
>
@ -179,25 +204,34 @@ export default defineComponent({
>
{{
header: () => (
<div class="global-search__header">
<label for={inputId}>{t('title')}</label>
<NButton
quaternary
size="small"
aria-label={t('close')}
onClick={() => {
modelShow.value = false
}}
>
<RIcon name="action/close" />
</NButton>
</div>
<label class="global-search__title" for={inputId}>
{t('title')}
</label>
),
'header-extra': () => (
<NButton
quaternary
circle
size="small"
class="global-search__close"
aria-label={t('close')}
onClick={() => {
modelShow.value = false
}}
>
<RIcon name="action/close" size={16} />
</NButton>
),
default: () => (
<>
<NInput
ref={input}
class="global-search__input"
size="large"
themeOverrides={{
color: 'var(--r-surface-muted)',
colorFocus: 'var(--r-surface)',
}}
value={searchValue.value}
onUpdateValue={(value) => {
searchValue.value = value
@ -212,21 +246,24 @@ export default defineComponent({
onKeydown={(event) => moveResult(event, true)}
clearable
>
{{ prefix: () => <RIcon name="action/search" /> }}
{{ prefix: () => <RIcon name="action/search" size={18} /> }}
</NInput>
{storageUnavailable.value && (
<p class="global-search__hint" role="status">
{t('storageUnavailable')}
</p>
)}
<NScrollbar class="global-search__results">
<NScrollbar
class="global-search__results"
contentClass="global-search__results-content"
>
{options.value.length ? (
groups.value.map((group) => (
<section class="global-search__group" key={group.key}>
<div class="global-search__group-heading">
<h2>{t(group.key)}</h2>
</div>
<ul role="list">
<h2 class="global-search__group-heading">
{t(group.key)}
</h2>
<ul class="global-search__list" role="list">
{group.options.map((option) => {
const favorite = favoritePaths.value.includes(
option.fullPath,
@ -252,15 +289,23 @@ export default defineComponent({
onKeydown={(event) => moveResult(event)}
onClick={() => void openPage(option)}
>
{typeof option.meta.icon === 'string' &&
option.meta.icon ? (
<RIcon name={option.meta.icon} size={20} />
) : (
<RIcon name="navigation/menu" size={20} />
)}
<span>{option.breadcrumbLabel}</span>
<span class="global-search__page-icon">
<RIcon
name={
typeof option.meta.icon === 'string' &&
option.meta.icon
? option.meta.icon
: 'navigation/menu'
}
size={18}
/>
</span>
<span class="global-search__page-label">
{option.breadcrumbLabel}
</span>
{option.meta.windowOpen && (
<RIcon
class="global-search__external"
name="action/external-link"
size={14}
/>
@ -268,6 +313,7 @@ export default defineComponent({
</button>
<NButton
quaternary
circle
size="small"
class="global-search__favorite"
type={favorite ? 'primary' : 'default'}
@ -278,9 +324,14 @@ export default defineComponent({
)}
onClick={() => toggle(option.fullPath)}
>
<span aria-hidden="true">
{favorite ? '★' : '☆'}
</span>
<RIcon
name={
favorite
? 'action/star-filled'
: 'action/star'
}
size={18}
/>
</NButton>
</li>
)
@ -289,8 +340,11 @@ export default defineComponent({
</section>
))
) : (
<p class="global-search__empty">
{t(searchValue.value.trim() ? 'noResults' : 'empty')}
<p class="global-search__empty" role="status">
<RIcon name="action/search" size={24} />
<span>
{t(searchValue.value.trim() ? 'noResults' : 'empty')}
</span>
</p>
)}
</NScrollbar>
@ -308,7 +362,15 @@ export default defineComponent({
<kbd>Esc</kbd> {t('close')}
</span>
{recentPaths.value.length > 0 && (
<NButton text size="tiny" onClick={clearRecent}>
<NButton
class="global-search__clear"
quaternary
size="small"
onClick={() => {
clearRecent()
input.value?.focus()
}}
>
{t('clearRecent')}
</NButton>
)}

View File

@ -20,15 +20,40 @@
}
.layout-breadcrumb,
.layout-breadcrumb__current {
.layout-breadcrumb__item {
min-inline-size: 0;
}
.layout-breadcrumb__item {
display: inline-flex;
align-items: center;
gap: 5px;
max-inline-size: 100%;
}
.layout-breadcrumb__icon {
display: inline-flex;
flex: none;
place-items: center;
inline-size: 1em;
block-size: 1em;
img {
inline-size: 100%;
block-size: 100%;
object-fit: contain;
}
}
.layout-breadcrumb__current {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 15px;
font-weight: 600;
color: var(--r-text);
}
.layout-breadcrumb__current .layout-breadcrumb__label {
min-inline-size: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

View File

@ -1,7 +1,8 @@
import './index.scss'
import { useDevice } from '@/hooks'
import { useMenuActions, useMenuGetters } from '@/store'
import { useMenuActions, useMenuGetters, useSettingGetters } from '@/store'
import type { AppMenuOption } from '@/types'
import { RIcon } from '@ray-template/ui/icon'
import { NBreadcrumb, NBreadcrumbItem, NDropdown } from 'naive-ui'
import type { DropdownOption } from 'naive-ui'
import { TransitionGroup } from 'vue'
@ -11,6 +12,7 @@ export default defineComponent({
setup() {
const { changeMenuModelValue } = useMenuActions()
const { getBreadcrumbOptions } = useMenuGetters()
const { getBreadcrumbIcon, getBreadcrumbIconFallback } = useSettingGetters()
const { isTabletOrSmaller } = useDevice()
const dropdownSelect = (key: string | number, option: DropdownOption) => {
@ -33,53 +35,78 @@ export default defineComponent({
}
}
return {
getBreadcrumbOptions,
dropdownSelect,
breadcrumbItemClick,
isTabletOrSmaller,
const renderIcon = (option: Pick<AppMenuOption, 'icon'>) => {
if (!getBreadcrumbIcon.value) return null
const icon =
option.icon?.() ??
(getBreadcrumbIconFallback.value ? (
<RIcon name="navigation/window" size="1em" />
) : null)
return (
icon && (
<span class="layout-breadcrumb__icon" aria-hidden="true">
{icon}
</span>
)
)
}
const renderLabel = (
option: AppMenuOption,
current: boolean,
compact = false,
) => (
<span
class={[
'layout-breadcrumb__item',
{ 'layout-breadcrumb__current': compact },
]}
aria-current={current ? 'page' : void 0}
>
{renderIcon(option)}
<span class="layout-breadcrumb__label">
{!compact && typeof option.label === 'function'
? option.label()
: option.breadcrumbLabel}
</span>
</span>
)
return () => {
const trail = getBreadcrumbOptions.value
const current = trail.at(-1)
if (isTabletOrSmaller.value)
return current && renderLabel(current, true, true)
return (
<NBreadcrumb class="layout-breadcrumb">
<TransitionGroup name="breadcrumb" appear>
{trail.map((option) => (
<NBreadcrumbItem
key={option.fullPath}
onClick={() => breadcrumbItemClick(option)}
>
{option.children && option.children.length > 1 ? (
<NDropdown
labelField="breadcrumbLabel"
keyField="fullPath"
options={option.children}
renderIcon={renderIcon}
onSelect={dropdownSelect}
>
{renderLabel(option, option === current)}
</NDropdown>
) : (
renderLabel(option, option === current)
)}
</NBreadcrumbItem>
))}
</TransitionGroup>
</NBreadcrumb>
)
}
},
render() {
const { isTabletOrSmaller, getBreadcrumbOptions } = this
const { dropdownSelect, breadcrumbItemClick } = this
return isTabletOrSmaller ? (
<span class="layout-breadcrumb__current" aria-current="page">
{getBreadcrumbOptions.at(-1)?.breadcrumbLabel}
</span>
) : (
<NBreadcrumb class="layout-breadcrumb">
<TransitionGroup tag="li" name="breadcrumb" appear>
{getBreadcrumbOptions.map((curr) => (
<NBreadcrumbItem
key={curr.fullPath}
onClick={breadcrumbItemClick.bind(this, curr)}
>
<NDropdown
labelField="breadcrumbLabel"
keyField="fullPath"
options={
curr.children && curr.children?.length > 1
? curr.children
: []
}
onSelect={dropdownSelect.bind(this)}
>
{{
default: () => (
<span>
{curr.label && typeof curr.label === 'function'
? curr.label()
: curr.breadcrumbLabel}
</span>
),
}}
</NDropdown>
</NBreadcrumbItem>
))}
</TransitionGroup>
</NBreadcrumb>
)
},
})

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

@ -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

@ -38,7 +38,13 @@ export default defineComponent({
getDrawerPlacement,
getContentTransition,
getMenuTagSwitch,
getMenuTagRound,
getMenuTagTop,
getMenuTagFixed,
getMenuTagDrag,
getBreadcrumbSwitch,
getBreadcrumbIcon,
getBreadcrumbIconFallback,
getCopyrightSwitch,
getColorWeakness,
} = useSettingGetters()
@ -78,7 +84,13 @@ export default defineComponent({
})
const switches = [
['breadcrumbSwitch', getBreadcrumbSwitch],
['breadcrumbIcon', getBreadcrumbIcon],
['breadcrumbIconFallback', getBreadcrumbIconFallback],
['menuTagSwitch', getMenuTagSwitch],
['menuTagRound', getMenuTagRound],
['menuTagTop', getMenuTagTop],
['menuTagFixed', getMenuTagFixed],
['menuTagDrag', getMenuTagDrag],
['copyrightSwitch', getCopyrightSwitch],
['colorWeakness', getColorWeakness],
] as const

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

@ -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

@ -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

@ -22,7 +22,15 @@
"closeLeft": "Close tabs on the left",
"closeRight": "Close tabs on the right",
"closeCurrent": "Close current tab",
"closeAll": "Close all and open workspace",
"closeAll": "Close all tabs",
"menuExample": "Menu hook example",
"menuOverview": "Overview",
"menuReports": "Reports",
"menuDaily": "Daily report",
"menuMonthly": "Monthly report",
"menuReveal": "Reveal monthly report",
"menuClear": "Clear selection",
"menuState": "Selected {selected} · Expanded {expanded}",
"contentTop": "Scroll content to top",
"content300": "Scroll content to 300 px",
"siderTop": "Scroll sidebar to top",
@ -55,6 +63,7 @@
"useWatermark": "Update the global watermark and control visibility. An empty string keeps the previous text.",
"useAppNavigation": "Navigate by menu object, full path or zero-based top-level index. Returns an awaitable navigation result.",
"useSiderBar": "Close tabs and their neighbors by path, index or tab object.",
"useMenu": "Manage NMenu selection and expanded groups. Reveal a menu item through the component instance.",
"useContentScroll": "Obtain a scroll function in setup. Each call resolves the current layout instance.",
"useSiderScroll": "Scroll the current sidebar. Safely does nothing when top navigation has no sidebar.",
"useDevice": "Observe viewport size and apply a custom tablet breakpoint. Resize the window to see changes.",

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

@ -9,6 +9,14 @@
"maximize": "Maximize page",
"reload": "Reload page",
"newWindow": "Open in new window",
"top": "Move to front",
"untop": "Remove from front group",
"topped": "At the front",
"fix": "Protect tab",
"unfix": "Unprotect tab",
"fixed": "Protected",
"moved": "{name} moved to position {position}",
"moveCanceled": "Tab reordering canceled",
"scrollLeft": "Scroll tabs left",
"scrollRight": "Scroll tabs right",
"actions": "Tab actions"

View File

@ -42,7 +42,13 @@
"placement": "Drawer position",
"display": "Interface display",
"breadcrumbSwitch": "Breadcrumbs",
"breadcrumbIcon": "Show breadcrumb icons",
"breadcrumbIconFallback": "Use a fallback for missing icons",
"menuTagSwitch": "Page tabs",
"menuTagRound": "Pill-shaped page tabs",
"menuTagTop": "Allow moving tabs to the front",
"menuTagFixed": "Allow protecting tabs",
"menuTagDrag": "Allow dragging to reorder tabs",
"copyrightSwitch": "Footer",
"colorWeakness": "Color vision mode",
"displayHint": "Show or hide breadcrumbs, page tabs, and the footer together, or adjust each below.",

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

@ -22,7 +22,15 @@
"closeLeft": "关闭左侧标签",
"closeRight": "关闭右侧标签",
"closeCurrent": "关闭当前标签",
"closeAll": "关闭全部并进入工作区",
"closeAll": "关闭全部",
"menuExample": "菜单 Hook 示例",
"menuOverview": "概览",
"menuReports": "报表",
"menuDaily": "日报",
"menuMonthly": "月报",
"menuReveal": "展开月报所在菜单",
"menuClear": "清除选中项",
"menuState": "选中 {selected} · 展开 {expanded}",
"contentTop": "内容滚动到顶部",
"content300": "内容滚动到 300px",
"siderTop": "侧栏滚动到顶部",
@ -55,6 +63,7 @@
"useWatermark": "更新全局水印文本并控制显示。空字符串沿用上一次内容。",
"useAppNavigation": "支持菜单对象、完整路径和从 0 开始的一级菜单索引,返回可等待的导航结果。",
"useSiderBar": "按路径、索引或标签对象关闭指定标签及其相邻标签。",
"useMenu": "管理 NMenu 的选中项和展开项,并通过实例方法展开指定菜单。",
"useContentScroll": "在 setup 中获取滚动方法,执行时使用当前布局实例。",
"useSiderScroll": "滚动当前侧栏;顶部导航没有侧栏,调用时会安全忽略。",
"useDevice": "观察窗口尺寸并按自定义断点判断是否为平板或更小设备。缩放窗口查看结果。",

View File

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

View File

@ -9,6 +9,14 @@
"maximize": "最大化当前页面",
"reload": "刷新当前页面",
"newWindow": "新窗口打开",
"top": "置顶标签页",
"untop": "取消置顶",
"topped": "已置顶",
"fix": "固定标签页",
"unfix": "取消固定",
"fixed": "已固定",
"moved": "{name} 已移至第 {position} 位",
"moveCanceled": "已取消标签页排序",
"scrollLeft": "向左滚动标签页",
"scrollRight": "向右滚动标签页",
"actions": "标签页操作"

View File

@ -42,7 +42,13 @@
"placement": "设置抽屉位置",
"display": "界面显示",
"breadcrumbSwitch": "面包屑导航",
"breadcrumbIcon": "显示面包屑图标",
"breadcrumbIconFallback": "缺少图标时显示占位图标",
"menuTagSwitch": "页面标签",
"menuTagRound": "胶囊形页面标签",
"menuTagTop": "允许置顶标签",
"menuTagFixed": "允许固定标签",
"menuTagDrag": "允许拖拽排序标签",
"copyrightSwitch": "页脚信息",
"colorWeakness": "色弱模式",
"displayHint": "批量调整面包屑、页面标签和页脚,也可继续逐项设置。",

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

@ -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

@ -93,8 +93,9 @@ See the [layout guide](../layout/README.md) for usage and slots.
## Menu synchronization
- Build menu trees and path indexes when roles change or during explicit refresh. Do not mutate original module routes. After navigation, synchronize tabs and breadcrumbs from Vue Router's matched records.
- No business root is mandatory or protected. System states (`/welcome`, `/403`, `/404`, `/500`) have no active business menu, breadcrumb, or tab. Never fabricate an active tab from cached selection or the first visible menu.
- System states (`/welcome`, `/403`, `/404`, `/500`) have no active business menu, breadcrumb, or tab. Derive the active tab from the actual route.
- Preserve existing cache keys and tab-list structure. Restore historical tabs using registered routes and roles, ignoring deleted or inaccessible routes. Write the session cache only when the tab list changes.
- Store tab order and optional `topped` and `fixed` flags in the ordered tab list. Topped tabs form the leading group while the preference is enabled. The close actions in `useSiderBar` preserve fixed tabs while their preference is enabled. Role or account reconciliation still prunes unavailable tabs.
- Keep one tag per concrete pathname and preserve its latest query/hash in `fullPath`; keep the sidebar's `menuKey` canonical. Derive menu selection from Router rather than a persisted key.
- Update KeepAlive in recent-access order, deduplicate, trim to its limit, and prune closed or revoked tab names. Merge themes only when the effective theme changes; observe color-weakness mode and document titles independently.

View File

@ -63,6 +63,11 @@ export const useMenuActions = () => {
collapsedMenu,
spliceMenTagOptions,
setMenuTagOptions,
isMenuTagTopped,
isMenuTagFixed,
toggleMenuTagTop,
toggleMenuTagFixed,
moveMenuTag,
resolveOption,
updateMenuState,
setupAppMenu,
@ -73,6 +78,11 @@ export const useMenuActions = () => {
collapsedMenu,
spliceMenTagOptions,
setMenuTagOptions,
isMenuTagTopped,
isMenuTagFixed,
toggleMenuTagTop,
toggleMenuTagFixed,
moveMenuTag,
resolveOption,
updateMenuState,
setupAppMenu,

View File

@ -38,12 +38,20 @@ export const useSettingGetters = () => {
* 获取菜单标签开关。
*/
const getMenuTagSwitch = computed(() => variable.menuTagSwitch)
const getMenuTagRound = computed(() => variable.menuTagRound)
const getMenuTagTop = computed(() => variable.menuTagTop)
const getMenuTagFixed = computed(() => variable.menuTagFixed)
const getMenuTagDrag = computed(() => variable.menuTagDrag)
/**
*
* @description
* 获取面包屑开关。
*/
const getBreadcrumbSwitch = computed(() => variable.breadcrumbSwitch)
const getBreadcrumbIcon = computed(() => variable.breadcrumbIcon)
const getBreadcrumbIconFallback = computed(
() => variable.breadcrumbIconFallback,
)
/**
*
* @description
@ -132,7 +140,13 @@ export const useSettingGetters = () => {
getThemeStyle,
getAppTheme,
getMenuTagSwitch,
getMenuTagRound,
getMenuTagTop,
getMenuTagFixed,
getMenuTagDrag,
getBreadcrumbSwitch,
getBreadcrumbIcon,
getBreadcrumbIconFallback,
getLocaleLanguage,
getLockScreenSwitch,
getCopyrightSwitch,

View File

@ -19,6 +19,7 @@ import { pick } from 'lodash-es'
import { NEllipsis } from 'naive-ui'
import type { LocationQuery } from 'vue-router'
import { piniaNavigationHistoryStore } from '../navigation-history'
import { piniaSettingStore } from '../setting'
import { piniaSigningStore } from '../signing'
import { pickRouteRecordNormalizedConstant } from './constant'
import {
@ -67,16 +68,14 @@ export const piniaMenuStore = defineStore(
breadcrumbOptions: [], // 面包屑菜单
currentMenuOption: null, // 当前激活菜单项
})
const settings = piniaSettingStore()
const signing = piniaSigningStore()
const navigationHistory = piniaNavigationHistoryStore()
const menuIndex = new Map<
string,
{ option: AppMenuOption; parentPath: string }
>()
const cacheTags = () => {
retainKeepAliveInclude(
new Set(menuState.menuTagOptions.map(({ name }) => name)),
)
const persistTags = () => {
setStorage(
APP_CATCH_KEY.appMenuTagOptions,
menuState.menuTagOptions.map(
@ -89,20 +88,119 @@ export const piniaMenuStore = defineStore(
breadcrumbLabel,
fullPath,
closeable,
topped,
fixed,
}) => ({
name,
key,
path,
show,
meta,
meta: {
...meta,
icon: typeof meta.icon === 'string' ? meta.icon : void 0,
extra: meta.extra && {
...meta.extra,
icon:
typeof meta.extra.icon === 'string'
? meta.extra.icon
: void 0,
},
},
breadcrumbLabel,
fullPath,
closeable,
topped,
fixed,
}),
),
)
}
const syncOpenTags = () => {
retainKeepAliveInclude(
new Set(menuState.menuTagOptions.map(({ name }) => name)),
)
persistTags()
}
const isMenuTagTopped = (tag?: MenuTagOptions) =>
settings.menuTagTop && tag?.topped === true
const isMenuTagFixed = (tag?: MenuTagOptions) =>
settings.menuTagFixed && tag?.fixed === true
const orderMenuTags = (tags: MenuTagOptions[]) =>
settings.menuTagTop
? [
...tags.filter(isMenuTagTopped),
...tags.filter((tag) => !isMenuTagTopped(tag)),
]
: tags
const toggleMenuTagTop = (fullPath: string) => {
if (!settings.menuTagTop) return false
const tags = [...menuState.menuTagOptions]
const index = tags.findIndex((tag) => tag.fullPath === fullPath)
if (index < 0) return false
const [tag] = tags.splice(index, 1)
const topped = !tag.topped
const firstRegular = tags.findIndex((tag) => !isMenuTagTopped(tag))
const insert = topped ? 0 : firstRegular < 0 ? tags.length : firstRegular
tags.splice(insert, 0, { ...tag, topped })
menuState.menuTagOptions = tags
persistTags()
return true
}
const toggleMenuTagFixed = (fullPath: string) => {
if (!settings.menuTagFixed) return
const tags = menuState.menuTagOptions
const index = tags.findIndex((tag) => tag.fullPath === fullPath)
if (index < 0) return
tags[index] = { ...tags[index], fixed: !tags[index].fixed }
persistTags()
}
const moveMenuTag = (
fullPath: string,
targetPath: string,
placement: 'before' | 'after',
) => {
if (!settings.menuTagDrag) return false
const tags = [...menuState.menuTagOptions]
const from = tags.findIndex((tag) => tag.fullPath === fullPath)
const to = tags.findIndex((tag) => tag.fullPath === targetPath)
if (
from < 0 ||
to < 0 ||
from === to ||
isMenuTagTopped(tags[from]) !== isMenuTagTopped(tags[to])
)
return false
const insert = to + Number(placement === 'after') - Number(from < to)
if (from === insert) return false
const [tag] = tags.splice(from, 1)
tags.splice(insert, 0, tag)
menuState.menuTagOptions = tags
persistTags()
return true
}
const clearActiveMenu = () => {
menuState.menuKey = null
menuState.currentMenuOption = null
@ -206,11 +304,11 @@ export const piniaMenuStore = defineStore(
!option.meta.windowOpen,
)
isAppend
? menuState.menuTagOptions.push(...arr)
: (menuState.menuTagOptions = arr)
menuState.menuTagOptions = orderMenuTags(
isAppend ? [...menuState.menuTagOptions, ...arr] : arr,
)
cacheTags()
syncOpenTags()
if (!menuState.menuTagOptions.length) clearActiveMenu()
}
@ -237,12 +335,14 @@ export const piniaMenuStore = defineStore(
if (tagIndex < 0) {
menuState.menuTagOptions.push(option)
cacheTags()
syncOpenTags()
} else if (
menuState.menuTagOptions[tagIndex].fullPath !== option.fullPath
) {
menuState.menuTagOptions[tagIndex] = option
cacheTags()
const { topped, fixed } = menuState.menuTagOptions[tagIndex]
menuState.menuTagOptions[tagIndex] = { ...option, topped, fixed }
syncOpenTags()
}
setBreadcrumbOptions(option.key)
@ -372,22 +472,25 @@ export const piniaMenuStore = defineStore(
menuState.currentMenuOption = null
menuState.breadcrumbOptions = []
const restoredTags = menuState.menuTagOptions.flatMap(({ fullPath }) => {
if (typeof fullPath !== 'string' || !fullPath.startsWith('/')) return []
const restoredTags = menuState.menuTagOptions.flatMap(
({ fullPath, topped, fixed }) => {
if (typeof fullPath !== 'string' || !fullPath.startsWith('/'))
return []
const option = optionForRoute(resolve(fullPath))
const option = optionForRoute(resolve(fullPath))
return option && !option.meta.sameLevel && !option.meta.windowOpen
? [option]
: []
})
return option && !option.meta.sameLevel && !option.meta.windowOpen
? [{ ...option, topped: topped === true, fixed: fixed === true }]
: []
},
)
menuState.menuTagOptions = [
menuState.menuTagOptions = orderMenuTags([
...new Map(
restoredTags.map((option) => [resolve(option.fullPath).path, option]),
).values(),
]
cacheTags()
])
syncOpenTags()
const active = optionForRoute(route)
@ -426,13 +529,29 @@ export const piniaMenuStore = defineStore(
const spliceMenTagOptions = (idx: number, length = 1) => {
const r = menuState.menuTagOptions.splice(idx, length)
cacheTags()
syncOpenTags()
if (!menuState.menuTagOptions.length) clearActiveMenu()
return r
}
watch(
() => settings.menuTagTop,
(enabled) => {
if (!enabled) return
const current = menuState.menuTagOptions
const ordered = orderMenuTags(current)
if (ordered.every((tag, index) => tag === current[index])) return
menuState.menuTagOptions = ordered
persistTags()
},
{ flush: 'sync' },
)
watch(
[
() => signing.signingCallback.role,
@ -446,7 +565,7 @@ export const piniaMenuStore = defineStore(
if (!current[1]) {
menuState.options = []
menuIndex.clear()
cacheTags()
syncOpenTags()
clearActiveMenu()
return
@ -488,6 +607,11 @@ export const piniaMenuStore = defineStore(
collapsedMenu,
spliceMenTagOptions,
setMenuTagOptions,
isMenuTagTopped,
isMenuTagFixed,
toggleMenuTagTop,
toggleMenuTagFixed,
moveMenuTag,
resolveOption,
updateMenuState,
setupAppMenu,

View File

@ -1,12 +1,17 @@
import { APP_CATCH_KEY } from '@/app-config'
import { useI18n } from '@/hooks'
import { resolveIconName } from '@/icons'
import type { AppMenuKey, AppMenuOption } from '@/types/modules/app'
import type {
AppMenuKey,
AppMenuOption,
MenuTagOptions,
} from '@/types/modules/app'
import { getStorage } from '@/utils/cache'
import { isValueType } from '@/utils/core'
import { RIcon } from '@ray-template/ui/icon'
import { NTag } from 'naive-ui'
import type { TagProps } from 'naive-ui'
import { cloneVNode } from 'vue'
import { piniaSettingStore } from '../setting'
/**
@ -148,7 +153,7 @@ export const createMenuIcon = (option: AppMenuOption) => {
}
if (isValueType<object>(icon, 'Object')) {
return () => icon
return () => cloneVNode(icon)
}
const name = resolveIconName(icon)
@ -228,7 +233,7 @@ export const getCatchMenuKey = () => {
* @returns 获取缓存的菜单标签页
*/
export const getCatchMenuTagOptions = () => {
const cached = getStorage<AppMenuOption[]>(
const cached = getStorage<MenuTagOptions[]>(
APP_CATCH_KEY.appMenuTagOptions,
'sessionStorage',
)

View File

@ -10,7 +10,13 @@ type OmitKeys =
| 'keepAliveConfig'
| 'menuConfig'
| 'menuTagSwitch'
| 'menuTagRound'
| 'menuTagTop'
| 'menuTagFixed'
| 'menuTagDrag'
| 'breadcrumbSwitch'
| 'breadcrumbIcon'
| 'breadcrumbIconFallback'
| 'copyrightSwitch'
| 'drawerPlacement'
| 'colorWeakness'
@ -57,8 +63,14 @@ const defaultSettingConfig: Readonly<Config> = {
},
// 多标签页开关
menuTagSwitch: true,
menuTagRound: false,
menuTagTop: true,
menuTagFixed: true,
menuTagDrag: true,
// 面包屑开关
breadcrumbSwitch: true,
breadcrumbIcon: true,
breadcrumbIconFallback: true,
// 底部区域开关
copyrightSwitch: true,
// 默认设置出现位置

View File

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

View File

@ -61,7 +61,13 @@ const preferences = v.strictObject({
),
drawerPlacement: v.picklist(['left', 'right']),
breadcrumbSwitch: flag,
breadcrumbIcon: v.optional(flag, true),
breadcrumbIconFallback: v.optional(flag, true),
menuTagSwitch: flag,
menuTagRound: v.optional(flag, false),
menuTagTop: v.optional(flag, true),
menuTagFixed: v.optional(flag, true),
menuTagDrag: v.optional(flag, true),
copyrightSwitch: flag,
colorWeakness: flag,
menuConfig: v.strictObject({

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

@ -37,7 +37,13 @@ export interface SettingState {
appTheme: 'dark' | 'light' | 'auto'
_appTheme: boolean
menuTagSwitch: boolean
menuTagRound: boolean
menuTagTop: boolean
menuTagFixed: boolean
menuTagDrag: boolean
breadcrumbSwitch: boolean
breadcrumbIcon: boolean
breadcrumbIconFallback: boolean
localeLanguage: string
lockScreenSwitch: boolean
watermarkSwitch: boolean

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,106 @@
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 { 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 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={() => document.getElementById(nameId)?.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
autofocus
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,155 @@
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()
}
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,244 @@
import { useI18n } from '@/hooks/template/useI18n'
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import type {
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 [registerTable, { isReady, setSearchValues, submitSearch }] =
useTablePro()
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 = () => {
if (!isReady.value) return
setSearchValues({ name: '', status: null })
void 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
onRegister={registerTable}
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

@ -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')}
@ -96,6 +101,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

@ -12,9 +12,11 @@ import {
useWatermark,
} from '@/hooks'
import { useMenuGetters, useRuntimeGetters, useSettingGetters } from '@/store'
import { useMenuKeyboard } from '@ray-template/admin-shell'
import { useMenu } from '@ray-template/composables/useMenu'
import { RIcon } from '@ray-template/ui/icon'
import { useTimeoutFn } from '@vueuse/core'
import { NButton, NFlex, NInput, NTag } from 'naive-ui'
import { NButton, NFlex, NInput, NMenu, NTag } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import HookExample from '../hooks/HookExample'
@ -32,6 +34,22 @@ export default defineComponent({
const spinning = useSpinning()
const maximize = useMaximize()
const tags = useSiderBar()
const menuKeyboard = useMenuKeyboard(false)
const { menuRef, menuProps, showOption } = useMenu({
options: [
{ key: 'overview', label: () => text('menuOverview') },
{
key: 'reports',
label: () => text('menuReports'),
children: [
{ key: 'daily', label: () => text('menuDaily') },
{ key: 'monthly', label: () => text('menuMonthly') },
],
},
],
value: 'monthly',
expandedKeys: [],
})
const { navigationTo } = useAppNavigation()
const contentScrollTo = useContentScroll()
const siderScrollTo = useSiderScroll()
@ -70,7 +88,7 @@ export default defineComponent({
title={label('templateTitle')}
description={text('templateIntro')}
eyebrow={label('templateEyebrow')}
meta="9 Hooks"
meta="10 Hooks"
>
<h2 class="r-demo-section-heading">{label('appearanceAndPage')}</h2>
<div class="r-hook-grid">
@ -256,6 +274,59 @@ export default defineComponent({
</NFlex>
),
)}
{example(
'useMenu',
`const { menuRef, menuProps, showOption } = useMenu({
options: [
{ key: 'overview', label: 'Overview' },
{
key: 'reports',
label: 'Reports',
children: [
{ key: 'daily', label: 'Daily report' },
{ key: 'monthly', label: 'Monthly report' },
],
},
],
value: 'monthly',
expandedKeys: [],
})
// TSX
<NMenu ref={menuRef} {...menuProps} />
<NButton onClick={() => showOption('monthly')}>Reveal monthly report</NButton>`,
() => (
<NFlex vertical>
<nav
aria-label={text('menuExample')}
onKeydown={menuKeyboard.onKeydown}
>
<NMenu
ref={menuRef}
{...menuProps}
nodeProps={menuKeyboard.nodeProps}
/>
</nav>
<NFlex>
<NButton onClick={() => showOption('monthly')}>
{text('menuReveal')}
</NButton>
<NButton
disabled={menuProps.value === null}
onClick={() => (menuProps.value = null)}
>
{text('menuClear')}
</NButton>
</NFlex>
<code>
{t('menuState', {
selected: menuProps.value ?? '—',
expanded: menuProps.expandedKeys?.join(', ') || '—',
})}
</code>
</NFlex>
),
)}
</div>
<h2 class="r-demo-section-heading">{label('scrollControls')}</h2>
<div class="r-hook-grid">

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);
}

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