mirror of
https://github.com/XiaoDaiGua-Ray/ray-template.git
synced 2026-11-20 18:34:13 +08:00
fix: address system-wide UI and data review findings
Restore keyboard navigation and fix page refresh, icons, and table interactions. Guard concurrent edits and align Mock persistence with the API contracts.
This commit is contained in:
parent
eba29fcfcf
commit
15b1da763f
@ -1,7 +1,9 @@
|
||||
import * as adminApi from '@/api/admin'
|
||||
import { AdminApiError } from '@/api/admin/client'
|
||||
import { router } from '@/router'
|
||||
import { piniaSigningStore } from '@/store/modules/signing'
|
||||
import UserManagement from '@/views/user-management'
|
||||
import { useUserErrorMessage } from '@/views/user-management/error-message'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import setupMiniApp from '../utils/setupMiniApp'
|
||||
|
||||
@ -56,3 +58,21 @@ it('keeps the current list and selection context when opening and closing an edi
|
||||
vi.restoreAllMocks()
|
||||
}
|
||||
})
|
||||
|
||||
it('shows localized limit and outage messages and falls back for unknown server errors', async () => {
|
||||
const { app } = await setupMiniApp()
|
||||
|
||||
try {
|
||||
const message = useUserErrorMessage()
|
||||
const label = (code: number, key: string) =>
|
||||
message(new AdminApiError(code, key, key))
|
||||
|
||||
expect(label(429, 'tooManyRequests')).toBe('请求过于频繁,请稍后再试。')
|
||||
expect(label(503, 'serviceUnavailable')).toBe(
|
||||
'服务暂时不可用,请稍后重试。',
|
||||
)
|
||||
expect(label(500, 'unexpectedCode')).toBe('请求失败,请稍后重试。')
|
||||
} finally {
|
||||
app.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
import { resolve } from 'node:path'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import barcode from 'jsbarcode'
|
||||
import { compile } from 'sass'
|
||||
import { reactive } from 'vue'
|
||||
import { RBarcode } from '../../packages/ui/src/RBarcode'
|
||||
|
||||
@ -7,6 +9,30 @@ vi.mock('jsbarcode', () => ({ default: vi.fn() }))
|
||||
|
||||
beforeEach(() => vi.mocked(barcode).mockClear())
|
||||
|
||||
it('keeps the fixed dimension on either responsive axis', async () => {
|
||||
const style = document.createElement('style')
|
||||
|
||||
style.textContent = compile(
|
||||
resolve('packages/ui/src/RBarcode/src/index.scss'),
|
||||
).css
|
||||
document.head.append(style)
|
||||
const wrapper = mount(RBarcode, {
|
||||
attachTo: document.body,
|
||||
props: { text: '123', responsive: true, width: 'responsive', height: 48 },
|
||||
})
|
||||
|
||||
try {
|
||||
const canvas = wrapper.get('canvas').element
|
||||
|
||||
expect(getComputedStyle(canvas).height).toBe('48px')
|
||||
await wrapper.setProps({ width: 96, height: 'responsive' })
|
||||
expect(getComputedStyle(canvas).width).toBe('96px')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
style.remove()
|
||||
}
|
||||
})
|
||||
|
||||
it('redraws changed format, options and renderer without changing text', async () => {
|
||||
const options = reactive({ lineColor: '#123456' })
|
||||
const wrapper = mount(RBarcode, { props: { text: '123456', options } })
|
||||
|
||||
37
__test__/components/disabled-directive.spec.ts
Normal file
37
__test__/components/disabled-directive.spec.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { defineComponent, h, ref, withDirectives } from 'vue'
|
||||
import disabled from '../../packages/directives/src/modules/disabled'
|
||||
|
||||
it('restores a native button and toggles the whole form without changing its children', async () => {
|
||||
const value = ref(false)
|
||||
const directive = disabled()
|
||||
const wrapper = mount(
|
||||
defineComponent(
|
||||
() => () =>
|
||||
h('div', [
|
||||
withDirectives(h('button'), [[directive, value.value]]),
|
||||
withDirectives(h('form', [h('input', { disabled: true })]), [
|
||||
[directive, value.value],
|
||||
]),
|
||||
]),
|
||||
),
|
||||
)
|
||||
|
||||
try {
|
||||
const button = wrapper.get('button').element
|
||||
const form = wrapper.get('form').element
|
||||
|
||||
expect(button.disabled).toBe(false)
|
||||
value.value = true
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(button.disabled).toBe(true)
|
||||
expect(form.hasAttribute('inert')).toBe(true)
|
||||
value.value = false
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(button.disabled).toBe(false)
|
||||
expect(form.hasAttribute('inert')).toBe(false)
|
||||
expect(wrapper.get('input').element.disabled).toBe(true)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
@ -32,6 +32,22 @@ beforeEach(() => {
|
||||
vi.mocked(interact).mockClear()
|
||||
})
|
||||
|
||||
it('uses the rendered body as the drag handle when the card has no title', async () => {
|
||||
const wrapper = mount(RDraggableCard, { slots: { default: 'Body' } })
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
const { allowFrom } = mocks.instances[0].draggable.mock.calls[0][0]
|
||||
|
||||
expect(
|
||||
document.querySelector('.r-draggable-card')?.querySelector(allowFrom)
|
||||
?.textContent,
|
||||
).toContain('Body')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('releases drag listeners on disable/unmount and removes only the final shared container', async () => {
|
||||
const first = mount(RDraggableCard, { props: { title: 'First' } })
|
||||
const second = mount(RDraggableCard, { props: { title: 'Second' } })
|
||||
|
||||
@ -15,6 +15,38 @@ const statusOptions = [
|
||||
{ label: 'Closed', value: 'closed' },
|
||||
]
|
||||
|
||||
it('labels compound picker triggers and both endpoints of a date range', async () => {
|
||||
const fields: TableProSearchOptions['fields'] = [
|
||||
{ key: 'created', type: 'dateRange', label: 'Created' },
|
||||
{ key: 'at', type: 'time', label: 'Time' },
|
||||
{ key: 'group', type: 'cascader', label: 'Group' },
|
||||
{ key: 'team', type: 'treeSelect', label: 'Team' },
|
||||
]
|
||||
const wrapper = mount(RTablePro, { props: { columns, search: { fields } } })
|
||||
|
||||
try {
|
||||
await nextTick()
|
||||
const [range, time, ...selections] = wrapper.findAll('.n-form-item')
|
||||
const endpoints = range.findAll('input')
|
||||
|
||||
expect(endpoints.map((input) => input.attributes('aria-label'))).toEqual([
|
||||
'Created start',
|
||||
'Created end',
|
||||
])
|
||||
expect(range.get('label').attributes('for')).toBe(endpoints[0].element.id)
|
||||
expect(time.get('input').attributes('aria-labelledby')).toBe(
|
||||
time.get('label').element.id,
|
||||
)
|
||||
|
||||
for (const field of selections)
|
||||
expect(field.get('[tabindex="0"]').attributes('aria-labelledby')).toBe(
|
||||
field.get('label').element.id,
|
||||
)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('matches text, multiple values, dates, zero and false before local pagination', async () => {
|
||||
const [register, actions] = useTablePro()
|
||||
const data = [
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { DOMWrapper, flushPromises, mount } from '@vue/test-utils'
|
||||
import { NDataTable, NDropdown } from 'naive-ui'
|
||||
import type { DropdownOption } from 'naive-ui'
|
||||
import { RTablePro } from '../../packages/ui/src/RTablePro'
|
||||
import { RTablePro, useTablePro } from '../../packages/ui/src/RTablePro'
|
||||
import type { TableProRequest } from '../../packages/ui/src/RTablePro'
|
||||
import * as csv from '../../packages/ui/src/RTablePro/src/csv'
|
||||
import * as printing from '../../packages/ui/src/RTablePro/src/printing'
|
||||
@ -206,20 +206,22 @@ it('keeps appearance icons visible when checked or unchecked', async () => {
|
||||
})
|
||||
|
||||
it('refreshes the current remote query and preserves the caller toolbar when tools are disabled', async () => {
|
||||
const request = vi.fn<TableProRequest>(async () => ({ data, total: 1 }))
|
||||
const [register, actions] = useTablePro()
|
||||
const request = vi.fn<TableProRequest>(async () => ({ data, total: 30 }))
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: { columns, request },
|
||||
props: { columns, request, onRegister: register },
|
||||
slots: { toolbar: 'Business action' },
|
||||
})
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
expect(request).toHaveBeenCalledOnce()
|
||||
await actions.setPage(2)
|
||||
await flushPromises()
|
||||
await wrapper.get('[aria-label="Refresh"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(request).toHaveBeenCalledTimes(2)
|
||||
expect(request.mock.lastCall?.[0]).toEqual(request.mock.calls[0][0])
|
||||
expect(request.mock.lastCall?.[1]).not.toBe(request.mock.calls[0][1])
|
||||
expect(request.mock.calls.map(([params]) => params.page)).toEqual([1, 2, 2])
|
||||
expect(request.mock.lastCall?.[1]).not.toBe(request.mock.calls[1][1])
|
||||
expect(wrapper.get('.r-table__business-actions').text()).toBe(
|
||||
'Business action',
|
||||
)
|
||||
|
||||
@ -3,6 +3,7 @@ import { NDropdown, NForm, NFormItem, NGrid, NSpin } from 'naive-ui'
|
||||
import { defineComponent, h, nextTick, ref } from 'vue'
|
||||
import { RCollapseGrid } from '../../packages/ui/src/RCollapseGrid'
|
||||
import { RForm, useForm } from '../../packages/ui/src/RForm'
|
||||
import { RIcon } from '../../packages/ui/src/RIcon'
|
||||
import { RIframe } from '../../packages/ui/src/RIframe'
|
||||
import type { RIframeInst } from '../../packages/ui/src/RIframe/src/types'
|
||||
import { RMoreDropdown } from '../../packages/ui/src/RMoreDropdown'
|
||||
@ -60,6 +61,51 @@ it('forwards dropdown placement and renders segment label functions', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves SVG root paint when no sprite service is installed', async () => {
|
||||
const wrapper = mount(RIcon, { props: { name: 'action/close_all' } })
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => expect(wrapper.find('svg rect').exists()).toBe(true))
|
||||
expect(wrapper.get('svg').attributes()).toMatchObject({
|
||||
fill: 'none',
|
||||
stroke: 'currentColor',
|
||||
'stroke-width': '1.8',
|
||||
})
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('moves segment focus past disabled choices and emits each change once', async () => {
|
||||
const change = vi.fn()
|
||||
const wrapper = mount(RSegment, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
options: [
|
||||
{ key: 'a', label: 'A' },
|
||||
{ key: 'b', label: 'B', disabled: true },
|
||||
{ key: 'c', label: 'C' },
|
||||
],
|
||||
onUpdateValue: change,
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
const [a, b, c] = wrapper.findAll('[role="radio"]')
|
||||
|
||||
expect(a.attributes('tabindex')).toBe('0')
|
||||
expect(b.attributes('aria-disabled')).toBe('true')
|
||||
await a.trigger('keydown', { key: 'ArrowRight' })
|
||||
expect(change.mock.calls).toEqual([['c']])
|
||||
expect(document.activeElement).toBe(c.element)
|
||||
expect(c.attributes('aria-checked')).toBe('true')
|
||||
await c.trigger('keydown', { key: 'Home' })
|
||||
expect(a.attributes('aria-checked')).toBe('true')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('starts iframe loading for every source and exposes the same native element', async () => {
|
||||
const wrapper = mount(RIframe, { props: { src: '/one.html' } })
|
||||
|
||||
|
||||
@ -36,8 +36,15 @@ describe('useAppNavigation', () => {
|
||||
expect(pending).toBeInstanceOf(Promise)
|
||||
await pending
|
||||
expect(state.router?.currentRoute.value.path).toBe('/target')
|
||||
await navigationTo({ fullPath: '/items/4' } as AppMenuOption)
|
||||
expect(state.router?.currentRoute.value.path).toBe('/items/4')
|
||||
await navigationTo(
|
||||
{ fullPath: '/items/4?q=one#details' } as AppMenuOption,
|
||||
{
|
||||
query: { page: '2' },
|
||||
},
|
||||
)
|
||||
expect(state.router?.currentRoute.value.fullPath).toBe(
|
||||
'/items/4?q=one&page=2#details',
|
||||
)
|
||||
})
|
||||
|
||||
it('resolves a dynamic path and preserves URL query and hash when replacing', async () => {
|
||||
|
||||
93
__test__/layout/menu-keyboard.spec.ts
Normal file
93
__test__/layout/menu-keyboard.spec.ts
Normal file
@ -0,0 +1,93 @@
|
||||
import { useMenuKeyboard } from '@ray-template/admin-shell'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { NMenu } from 'naive-ui'
|
||||
import { defineComponent, h } from 'vue'
|
||||
|
||||
const options = [
|
||||
{
|
||||
key: 'group',
|
||||
label: 'Group',
|
||||
children: [
|
||||
{ key: 'a', label: 'Alpha' },
|
||||
{ key: 'b', label: 'Beta' },
|
||||
],
|
||||
},
|
||||
{ key: 'c', label: 'Gamma' },
|
||||
]
|
||||
|
||||
const mountMenu = (horizontal = false, collapsed = false) => {
|
||||
const selected = vi.fn()
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
const keyboard = useMenuKeyboard(horizontal, () => collapsed)
|
||||
|
||||
return () =>
|
||||
h('nav', { onKeydown: keyboard.onKeydown }, [
|
||||
h(NMenu, {
|
||||
options,
|
||||
collapsed,
|
||||
mode: horizontal ? 'horizontal' : 'vertical',
|
||||
nodeProps: keyboard.nodeProps,
|
||||
dropdownProps: keyboard.dropdownProps,
|
||||
onUpdateValue: selected,
|
||||
}),
|
||||
])
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
)
|
||||
|
||||
return { wrapper, selected }
|
||||
}
|
||||
|
||||
it('opens an inline group, moves focus to its child, and selects it from the keyboard', async () => {
|
||||
const { wrapper, selected } = mountMenu()
|
||||
|
||||
try {
|
||||
const group = wrapper.get('[role="menuitem"]')
|
||||
|
||||
expect(group.attributes('tabindex')).toBe('0')
|
||||
await group.trigger('keydown', { key: 'Enter' })
|
||||
const items = wrapper.findAll('[role="menuitem"]')
|
||||
|
||||
expect(items.map((item) => item.text())).toEqual([
|
||||
'Group',
|
||||
'Alpha',
|
||||
'Beta',
|
||||
'Gamma',
|
||||
])
|
||||
await group.trigger('keydown', { key: 'ArrowDown' })
|
||||
expect(document.activeElement).toBe(items[1]!.element)
|
||||
await items[1]!.trigger('keydown', { key: ' ' })
|
||||
expect(selected.mock.calls[0]?.[0]).toBe('a')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
[true, false],
|
||||
[false, true],
|
||||
])(
|
||||
'selects from a keyboard-opened popup (horizontal=%s, collapsed=%s)',
|
||||
async (horizontal, collapsed) => {
|
||||
const { wrapper, selected } = mountMenu(horizontal, collapsed)
|
||||
|
||||
try {
|
||||
const group = wrapper.get('[role="menuitem"]')
|
||||
|
||||
await group.trigger('keydown', { key: 'Enter' })
|
||||
await flushPromises()
|
||||
expect(document.querySelector('.n-dropdown-menu')).not.toBeNull()
|
||||
|
||||
for (const key of ['ArrowDown', 'Enter']) {
|
||||
await group.trigger('keydown', { key })
|
||||
}
|
||||
|
||||
expect(selected.mock.calls[0]?.[0]).toBe('a')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
},
|
||||
)
|
||||
@ -252,6 +252,64 @@ describe('layout preferences', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('uses the contrast of each resolved button fill after importing an accent and switching modes', () => {
|
||||
const pinia = createPinia()
|
||||
|
||||
setActivePinia(pinia)
|
||||
const store = piniaSettingStore()
|
||||
const file = store.exportPreferences()
|
||||
const paints: string[] = []
|
||||
let pixels = [45, 140, 240, 255, 76, 157, 242, 255]
|
||||
const context = {
|
||||
fillStyle: '',
|
||||
fillRect() {
|
||||
paints.push(this.fillStyle)
|
||||
},
|
||||
getImageData: () => ({ data: new Uint8ClampedArray(pixels) }),
|
||||
}
|
||||
const canvas = vi
|
||||
.spyOn(HTMLCanvasElement.prototype, 'getContext')
|
||||
.mockReturnValue(context as unknown as CanvasRenderingContext2D)
|
||||
|
||||
try {
|
||||
store.changePrimaryColor('#2d8cf0')
|
||||
expect(store.themeOverrides.Button).toMatchObject({
|
||||
colorPrimary: 'rgb(45, 140, 240)',
|
||||
textColorPrimary: '#000',
|
||||
textColorHoverPrimary: '#000',
|
||||
})
|
||||
const primaryColor = 'hsla(0, 0%, 90%, 0.1)'
|
||||
|
||||
store.importPreferences(
|
||||
JSON.stringify({
|
||||
...file,
|
||||
preferences: { ...file.preferences, primaryColor, appTheme: 'dark' },
|
||||
}),
|
||||
)
|
||||
pixels = [44, 53, 67, 255, 199, 200, 202, 255]
|
||||
expect(store.themeOverrides.Button).toMatchObject({
|
||||
textColorPrimary: '#fff',
|
||||
textColorPressedPrimary: '#fff',
|
||||
textColorHoverPrimary: '#000',
|
||||
textColorFocusPrimary: '#000',
|
||||
})
|
||||
expect(paints.slice(-3)).toEqual([
|
||||
'#172131',
|
||||
primaryColor,
|
||||
'hsla(0, 0%, 90%, 0.85)',
|
||||
])
|
||||
store.updateSettingState('appTheme', 'light')
|
||||
pixels = [252, 252, 252, 255, 234, 234, 234, 255]
|
||||
expect(store.themeOverrides.Button?.textColorPrimary).toBe('#000')
|
||||
expect(paints.at(-3)).toBe('#ffffff')
|
||||
store.changePrimaryColor()
|
||||
expect(store.themeOverrides.Button?.textColorPrimary).toBeUndefined()
|
||||
} finally {
|
||||
canvas.mockRestore()
|
||||
disposePinia(pinia)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not change any preference when the file contains invalid settings', () => {
|
||||
const pinia = createPinia()
|
||||
|
||||
|
||||
@ -129,3 +129,26 @@ it('keeps distinct fullPath cache entries while reusing the same page component'
|
||||
expect(host.querySelector('[data-page="one"]')?.textContent).toBe('one-1')
|
||||
expect(mounts.one).toBe(2)
|
||||
})
|
||||
|
||||
it.each([true, false])(
|
||||
'remounts the refreshed URL and retains other cached URLs (cache=%s)',
|
||||
async (cache) => {
|
||||
await mountRoutes(cache)
|
||||
await navigate('/one?view=other')
|
||||
await vi.advanceTimersByTimeAsync(714)
|
||||
expect(host.querySelector('[data-page="one"]')?.textContent).toBe('one-2')
|
||||
|
||||
await wrapper!.setProps({ refreshingPath: '/one?view=other' })
|
||||
await vi.advanceTimersByTimeAsync(714)
|
||||
expect(host.querySelector('[data-page="one"]')).toBeNull()
|
||||
await wrapper!.setProps({ refreshingPath: null })
|
||||
await vi.advanceTimersByTimeAsync(714)
|
||||
expect(host.querySelector('[data-page="one"]')?.textContent).toBe('one-3')
|
||||
|
||||
await navigate('/one')
|
||||
await vi.advanceTimersByTimeAsync(714)
|
||||
expect(host.querySelector('[data-page="one"]')?.textContent).toBe(
|
||||
cache ? 'one-1' : 'one-4',
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { locks } from 'node:worker_threads'
|
||||
import {
|
||||
changeAccountPassword,
|
||||
createUser,
|
||||
@ -180,37 +181,113 @@ it('invalidates the server-side Mock session on logout', async () => {
|
||||
await expect(getUsers({})).rejects.toMatchObject({ code: 401 })
|
||||
})
|
||||
|
||||
it('restores Mock writes and active sessions after recreating the database', async () => {
|
||||
it('preserves simultaneous edits and sessions across independent browser clients', async () => {
|
||||
localStorage.clear()
|
||||
const first = createAdminDatabase(localStorage)
|
||||
const session = await first.login({ username: 'admin', password: '123456' })
|
||||
const user = first.saveUser(input, session.accessToken)
|
||||
const second = createAdminDatabase(localStorage)
|
||||
const first = createAdminDatabase(localStorage, locks)
|
||||
const second = createAdminDatabase(localStorage, locks)
|
||||
const { accessToken } = await first((db) =>
|
||||
db.login({ username: 'admin', password: '123456' }),
|
||||
)
|
||||
const [one, two] = await Promise.all([
|
||||
first((db) => db.saveUser(input, accessToken)),
|
||||
second((db) =>
|
||||
db.saveUser(
|
||||
{ ...input, username: 'second', email: 'second@example.com' },
|
||||
accessToken,
|
||||
),
|
||||
),
|
||||
])
|
||||
|
||||
expect(second.getUser(user.id, session.accessToken)).toMatchObject(input)
|
||||
expect(second.authorize(session.accessToken).user.id).toBe(session.user.id)
|
||||
await Promise.all([
|
||||
first((db) =>
|
||||
db.saveUser({ ...one, name: 'First changed' }, accessToken, one.id),
|
||||
),
|
||||
second((db) =>
|
||||
db.saveUser({ ...two, name: 'Second changed' }, accessToken, two.id),
|
||||
),
|
||||
])
|
||||
const reopened = createAdminDatabase(localStorage, locks)
|
||||
|
||||
await expect(
|
||||
reopened((db) => [
|
||||
db.getUser(one.id, accessToken).name,
|
||||
db.getUser(two.id, accessToken).name,
|
||||
]),
|
||||
).resolves.toEqual(['First changed', 'Second changed'])
|
||||
})
|
||||
|
||||
it('keeps writes atomic when persistence fails', async () => {
|
||||
const storage: Storage = {
|
||||
length: 0,
|
||||
key: () => null,
|
||||
clear() {},
|
||||
removeItem() {},
|
||||
getItem: () => null,
|
||||
setItem: vi.fn(),
|
||||
const db = createAdminDatabase(localStorage, locks)
|
||||
const { accessToken } = await db((snapshot) =>
|
||||
snapshot.login({ username: 'admin', password: '123456' }),
|
||||
)
|
||||
const persist = vi
|
||||
.spyOn(localStorage, 'setItem')
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error('Quota exceeded')
|
||||
})
|
||||
|
||||
try {
|
||||
await expect(
|
||||
db((snapshot) => snapshot.saveUser(input, accessToken)),
|
||||
).rejects.toThrow('storage')
|
||||
expect(
|
||||
await db((snapshot) => snapshot.listUsers({}, accessToken).total),
|
||||
).toBe(24)
|
||||
} finally {
|
||||
persist.mockRestore()
|
||||
}
|
||||
const database = createAdminDatabase(storage)
|
||||
const session = await database.login({
|
||||
username: 'admin',
|
||||
password: '123456',
|
||||
})
|
||||
|
||||
it('signs in an explicitly provisioned account whose username matches a demo alias', async () => {
|
||||
const candidate = await createUser({ ...input, username: 'member' })
|
||||
|
||||
await setUserCredential(candidate.id, 'new-demo-credential')
|
||||
const session = await loginAdmin('member', 'new-demo-credential')
|
||||
|
||||
expect(session.user.id).toBe(candidate.id)
|
||||
expect((await loginAdmin('user002', '123456')).user.role).toBe('member')
|
||||
})
|
||||
|
||||
it('rejects stale account and route replacements without losing the committed changes', async () => {
|
||||
const user = await createUser(input)
|
||||
let userRevision: string | undefined
|
||||
const original = await getUser(user.id, void 0, (value) => {
|
||||
userRevision = value
|
||||
})
|
||||
|
||||
vi.mocked(storage.setItem).mockImplementation(() => {
|
||||
throw new Error('Quota exceeded')
|
||||
expect(userRevision).toBeTruthy()
|
||||
await updateUserStatus([user.id], 'disabled')
|
||||
await expect(
|
||||
updateUser(user.id, { ...original, name: 'New name' }, userRevision),
|
||||
).rejects.toMatchObject({ code: 412, key: 'editConflict' })
|
||||
expect((await getUser(user.id)).status).toBe('disabled')
|
||||
|
||||
let routeRevision: string | undefined
|
||||
const config = await getAdminRoutes('editor', void 0, (value) => {
|
||||
routeRevision = value
|
||||
})
|
||||
expect(() => database.saveUser(input, session.accessToken)).toThrow('storage')
|
||||
expect(database.listUsers({}, session.accessToken).total).toBe(24)
|
||||
|
||||
expect(routeRevision).toBeTruthy()
|
||||
const next = {
|
||||
...config,
|
||||
routes: [
|
||||
...config.routes,
|
||||
{ path: '/revision', component: 'dashboard', meta: {} },
|
||||
],
|
||||
}
|
||||
|
||||
try {
|
||||
await updateAdminRoutes(next, routeRevision)
|
||||
await expect(
|
||||
updateAdminRoutes(config, routeRevision),
|
||||
).rejects.toMatchObject({ code: 412, key: 'editConflict' })
|
||||
expect((await getAdminRoutes('editor')).routes.at(-1)?.path).toBe(
|
||||
'/revision',
|
||||
)
|
||||
} finally {
|
||||
await updateAdminRoutes(config)
|
||||
}
|
||||
})
|
||||
|
||||
it('provisions a Mock login and updates only the signed-in profile', async () => {
|
||||
|
||||
@ -13,8 +13,33 @@ import { getRouteJsonSchema } from '@/router/config/json-schema'
|
||||
import { expandRoutes } from '@/router/utils/expand-routes'
|
||||
import { orderRoutes } from '@/router/utils/order-routes'
|
||||
import { validRole } from '@/router/utils/valid-role'
|
||||
import { piniaMenuStore } from '@/store/modules/menu'
|
||||
import { piniaSigningStore } from '@/store/modules/signing'
|
||||
import { createRouteParser } from '@ray-template/api-contracts/route-validation'
|
||||
import { nextTick } from 'vue'
|
||||
import setupMiniApp from '../utils/setupMiniApp'
|
||||
|
||||
const page = { component: 'dashboard', meta: {} }
|
||||
|
||||
it('accepts nested icon names for both menu and badge after catalog validation', () => {
|
||||
const icon = 'business/orders/approved'
|
||||
const isIconName = vi.fn((name: string) => name === icon)
|
||||
const parser = createRouteParser({
|
||||
managementPath: '/route-management',
|
||||
findRouteView: () => ({ name: 'Dashboard' }),
|
||||
normalizeIcon: (name) => name,
|
||||
isIconName,
|
||||
})
|
||||
const config = {
|
||||
version: 1,
|
||||
routes: [{ ...page, path: '/reports', meta: { icon, extra: { icon } } }],
|
||||
}
|
||||
|
||||
expect(parser(JSON.stringify(config)).routes[0].meta).toEqual(
|
||||
config.routes[0].meta,
|
||||
)
|
||||
expect(isIconName).toHaveBeenCalledWith(icon)
|
||||
})
|
||||
const parse = (routes: unknown[]) =>
|
||||
parseRouteConfig(JSON.stringify({ version: 1, routes }))
|
||||
|
||||
@ -218,3 +243,46 @@ describe('route configuration', () => {
|
||||
expect(input).toEqual([second, first])
|
||||
})
|
||||
})
|
||||
|
||||
it('rebuilds the menu when the next account finishes loading its routes', async () => {
|
||||
const { app } = await setupMiniApp()
|
||||
const signing = app.runWithContext(() => piniaSigningStore())
|
||||
const menu = app.runWithContext(() => piniaMenuStore())
|
||||
|
||||
try {
|
||||
signing.signingCallback = { id: 'first', name: 'First', role: 'admin' }
|
||||
setAppRouteModules(getStaticAppRoutes())
|
||||
await nextTick()
|
||||
expect(menu.options.length).toBeGreaterThan(1)
|
||||
|
||||
signing.clearSigningCallback()
|
||||
await nextTick()
|
||||
signing.signingCallback = { id: 'second', name: 'Second', role: 'member' }
|
||||
await nextTick()
|
||||
expect(menu.options).toHaveLength(0)
|
||||
setAppRouteModules(toRuntimeRoutes(parse([{ ...page, path: '/returned' }])))
|
||||
await nextTick()
|
||||
expect(menu.options.map(({ fullPath }) => fullPath)).toEqual(['/returned'])
|
||||
} finally {
|
||||
app.unmount()
|
||||
setAppRouteModules(getStaticAppRoutes())
|
||||
}
|
||||
})
|
||||
|
||||
it('localizes saved built-in literal menu titles and preserves edited titles', () => {
|
||||
for (const [title, key] of [
|
||||
['信息详情', 'menu.RouterPersonDetail'],
|
||||
['已有定制标题', void 0],
|
||||
]) {
|
||||
const config = parse([
|
||||
{
|
||||
...page,
|
||||
path: '/router-demo/router-demo-detail',
|
||||
meta: { noLocalTitle: title },
|
||||
},
|
||||
])
|
||||
|
||||
expect(toRuntimeRoutes(config)[0].meta.i18nKey).toBe(key)
|
||||
expect(config.routes[0].meta.i18nKey).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
@ -45,3 +45,32 @@ it('ignores previously saved static routes when the backend owns runtime routes'
|
||||
await expect(loadRouteConfig()).rejects.toThrow('Route backend unavailable')
|
||||
expect(getRoutes).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('activates the read-only legacy source from a local preference without publishing a draft', async () => {
|
||||
vi.stubEnv('VITE_ROUTE_CONFIG_URL', 'https://example.com/routes.json')
|
||||
localStorage.setItem(
|
||||
'rayRouteConfig.v1',
|
||||
JSON.stringify({ source: 'local', local: { version: 1, routes: [] } }),
|
||||
)
|
||||
const request = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValue(new Response(JSON.stringify({ version: 1, routes: [] })))
|
||||
const reload = vi.spyOn(location, 'reload').mockImplementation(() => {})
|
||||
|
||||
try {
|
||||
const { activateRemoteRouteSource, remoteRoutesReadOnly } =
|
||||
await import('@/router/config/source')
|
||||
|
||||
expect(remoteRoutesReadOnly).toBe(true)
|
||||
await activateRemoteRouteSource()
|
||||
expect(request).toHaveBeenCalledTimes(1)
|
||||
expect(request.mock.calls[0]?.[1]?.method ?? 'GET').toBe('GET')
|
||||
expect(
|
||||
JSON.parse(localStorage.getItem('rayRouteConfig.v1')!),
|
||||
).toMatchObject({ source: 'remote' })
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
request.mockRestore()
|
||||
reload.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
@ -1,7 +1,49 @@
|
||||
import { createHttpClient } from '@ray-template/http'
|
||||
import RequestCanceler from '@ray-template/http/RequestCanceler'
|
||||
import type { AppRawRequestConfig } from '@ray-template/http/types'
|
||||
import { AxiosError } from 'axios'
|
||||
import type { AxiosAdapter, AxiosResponse } from 'axios'
|
||||
|
||||
it('compares repeated form fields, URL parameters and uploaded file identity when cancelling duplicates', () => {
|
||||
const canceler = new RequestCanceler()
|
||||
const submit = (data: FormData | URLSearchParams) => {
|
||||
const config: AppRawRequestConfig = { url: '/upload', method: 'post', data }
|
||||
|
||||
canceler.removePendingRequest(config)
|
||||
canceler.addPendingRequest(config)
|
||||
|
||||
return config.signal!
|
||||
}
|
||||
const first = submit(new URLSearchParams('x=1&x=2'))
|
||||
const second = submit(new URLSearchParams('x=2&x=1'))
|
||||
|
||||
expect(first.aborted).toBe(false)
|
||||
submit(new URLSearchParams('x=1&x=2'))
|
||||
expect(first.aborted).toBe(true)
|
||||
expect(second.aborted).toBe(false)
|
||||
|
||||
const form = (text: string, file: File) => {
|
||||
const body = new FormData()
|
||||
|
||||
body.append('tag', text)
|
||||
body.append('file', file)
|
||||
|
||||
return body
|
||||
}
|
||||
const file = new File(['a'], 'same.txt')
|
||||
const uploaded = submit(form('first', file))
|
||||
const anotherText = submit(form('second', file))
|
||||
const anotherFile = submit(form('first', new File(['b'], 'same.txt')))
|
||||
|
||||
expect(uploaded.aborted).toBe(false)
|
||||
submit(form('first', file))
|
||||
expect(uploaded.aborted).toBe(true)
|
||||
expect(anotherText.aborted).toBe(false)
|
||||
expect(anotherFile.aborted).toBe(false)
|
||||
canceler.cancelAllRequest()
|
||||
expect(anotherFile.aborted).toBe(true)
|
||||
})
|
||||
|
||||
it('isolates pending requests by client and leaves caller-owned signals intact', async () => {
|
||||
const pending: Array<{ signal: unknown; finish: () => void }> = []
|
||||
const adapter: AxiosAdapter = (config) =>
|
||||
|
||||
@ -789,7 +789,7 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[\\w-]+\\/[\\w-]+$",
|
||||
"pattern": "^[a-z][a-z0-9_-]*(\\/[a-z][a-z0-9_-]*)+$",
|
||||
"description": "IconName from src/icons/manifest.ts."
|
||||
},
|
||||
"role": {
|
||||
@ -878,7 +878,7 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[\\w-]+\\/[\\w-]+$"
|
||||
"pattern": "^[a-z][a-z0-9_-]*(\\/[a-z][a-z0-9_-]*)+$"
|
||||
},
|
||||
"show": {
|
||||
"type": "boolean"
|
||||
@ -1024,7 +1024,7 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[\\w-]+\\/[\\w-]+$",
|
||||
"pattern": "^[a-z][a-z0-9_-]*(\\/[a-z][a-z0-9_-]*)+$",
|
||||
"description": "IconName from src/icons/manifest.ts."
|
||||
},
|
||||
"role": {
|
||||
@ -1113,7 +1113,7 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[\\w-]+\\/[\\w-]+$"
|
||||
"pattern": "^[a-z][a-z0-9_-]*(\\/[a-z][a-z0-9_-]*)+$"
|
||||
},
|
||||
"show": {
|
||||
"type": "boolean"
|
||||
@ -1961,6 +1961,9 @@
|
||||
"data": {
|
||||
"type": "null"
|
||||
},
|
||||
"revision": {
|
||||
"type": "string"
|
||||
},
|
||||
"error": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@ -3879,6 +3882,10 @@
|
||||
"msg": {
|
||||
"type": "string"
|
||||
},
|
||||
"revision": {
|
||||
"type": "string",
|
||||
"description": "Opaque edit revision. Route configuration includes it only for view=editor."
|
||||
},
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/RouteConfig"
|
||||
}
|
||||
@ -4001,6 +4008,17 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "If-Match",
|
||||
"in": "header",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Quoted revision from the editor read. A changed resource returns 412 editConflict."
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Success",
|
||||
@ -4078,6 +4096,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "See error.key for a stable machine-readable reason.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"413": {
|
||||
"description": "See error.key for a stable machine-readable reason.",
|
||||
"content": {
|
||||
@ -4751,6 +4779,10 @@
|
||||
"msg": {
|
||||
"type": "string"
|
||||
},
|
||||
"revision": {
|
||||
"type": "string",
|
||||
"description": "Opaque edit revision. Route configuration includes it only for view=editor."
|
||||
},
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/User"
|
||||
}
|
||||
@ -4863,6 +4895,17 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "If-Match",
|
||||
"in": "header",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Quoted revision from the editor read. A changed resource returns 412 editConflict."
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Success",
|
||||
@ -4940,6 +4983,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "See error.key for a stable machine-readable reason.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"413": {
|
||||
"description": "See error.key for a stable machine-readable reason.",
|
||||
"content": {
|
||||
|
||||
@ -53,6 +53,7 @@ export async function adminRequest<Schema extends v.GenericSchema>(
|
||||
path: string,
|
||||
schema: Schema,
|
||||
options: AppRawRequestConfig<unknown> = {},
|
||||
onRevision?: (revision: string | undefined) => void,
|
||||
): Promise<v.InferOutput<Schema>> {
|
||||
let body: unknown
|
||||
const version = sessionVersion
|
||||
@ -121,5 +122,9 @@ export async function adminRequest<Schema extends v.GenericSchema>(
|
||||
),
|
||||
)
|
||||
|
||||
return v.parse(schema, envelope.data)
|
||||
const result = v.parse(schema, envelope.data)
|
||||
|
||||
onRevision?.(envelope.revision)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@ -45,16 +45,30 @@ export const setUserCredential = (id: string, newPassword: string) =>
|
||||
method: 'put',
|
||||
data: { newPassword },
|
||||
})
|
||||
export const getAdminRoutes = (view?: 'editor', signal?: AbortSignal) =>
|
||||
adminRequest('route-config', routeConfigSchema, {
|
||||
method: 'get',
|
||||
params: view ? { view } : void 0,
|
||||
signal,
|
||||
})
|
||||
export const updateAdminRoutes = (config: RouteConfig) =>
|
||||
export const getAdminRoutes = (
|
||||
view?: 'editor',
|
||||
signal?: AbortSignal,
|
||||
onRevision?: (revision: string | undefined) => void,
|
||||
) =>
|
||||
adminRequest(
|
||||
'route-config',
|
||||
routeConfigSchema,
|
||||
{
|
||||
method: 'get',
|
||||
params: view ? { view } : void 0,
|
||||
signal,
|
||||
},
|
||||
onRevision,
|
||||
)
|
||||
|
||||
const revisionHeaders = (revision?: string) =>
|
||||
revision ? { 'If-Match': `"${revision}"` } : {}
|
||||
|
||||
export const updateAdminRoutes = (config: RouteConfig, revision?: string) =>
|
||||
adminRequest('route-config', routeConfigSchema, {
|
||||
method: 'put',
|
||||
data: config,
|
||||
headers: revisionHeaders(revision),
|
||||
})
|
||||
export const getUserOptions = (signal?: AbortSignal) =>
|
||||
adminRequest('users/options', userOptionsSchema, { method: 'get', signal })
|
||||
@ -70,16 +84,26 @@ export const getUsers = async (
|
||||
|
||||
return { data: items, total }
|
||||
}
|
||||
export const getUser = (id: string, signal?: AbortSignal) =>
|
||||
adminRequest(`users/${encodeURIComponent(id)}`, userSchema, {
|
||||
method: 'get',
|
||||
signal,
|
||||
})
|
||||
export const getUser = (
|
||||
id: string,
|
||||
signal?: AbortSignal,
|
||||
onRevision?: (revision: string | undefined) => void,
|
||||
) =>
|
||||
adminRequest(
|
||||
`users/${encodeURIComponent(id)}`,
|
||||
userSchema,
|
||||
{
|
||||
method: 'get',
|
||||
signal,
|
||||
},
|
||||
onRevision,
|
||||
)
|
||||
export const createUser = (data: UserInput) =>
|
||||
adminRequest('users', userSchema, { method: 'post', data })
|
||||
export const updateUser = (id: string, data: UserInput) =>
|
||||
export const updateUser = (id: string, data: UserInput, revision?: string) =>
|
||||
adminRequest(`users/${encodeURIComponent(id)}`, userSchema, {
|
||||
method: 'put',
|
||||
headers: revisionHeaders(revision),
|
||||
data,
|
||||
})
|
||||
export const deleteUsers = (ids: string[]) =>
|
||||
|
||||
@ -20,4 +20,4 @@ const loadOrders = (signal: AbortSignal) =>
|
||||
})
|
||||
```
|
||||
|
||||
When supplying a signal, set `cancelConfig.cancel` to `false` to avoid default-canceller replacement, and own the abort lifecycle. The person list demonstrates [forwarding TablePro's signal](../api/demo/mock/person.ts). `useRequest` wraps the same instance and must run within an active Vue effect scope.
|
||||
The canceller compares encoded URLSearchParams and ordered FormData entries, including file identity. Passing a signal or setting `cancelConfig.cancel` to `false` opts out of default cancellation. The person list demonstrates [forwarding TablePro's signal](../api/demo/mock/person.ts). `useRequest` wraps the same instance and must run within an active Vue effect scope.
|
||||
|
||||
@ -143,7 +143,7 @@ const Demo = defineComponent({
|
||||
|
||||
#### Tip
|
||||
|
||||
> 该指令基于 css 层面进行禁用操作,如果元素含有 `disabled` 属性方法,会尝试使用原生 `disabled` 属性。对于组件库而言,本身就提供了丰富的 `disabled props`,所以应该是优先使用组件自带属性。
|
||||
> 原生表单控件使用 `disabled` 属性。表单和其他容器使用 `inert` 暂停整棵子树的键盘和指针交互。组件提供 `disabled` prop 时优先使用组件自身的接口。
|
||||
|
||||
#### 示例
|
||||
|
||||
|
||||
@ -71,16 +71,14 @@ export function useAppNavigation() {
|
||||
return deepNavigation(menu)
|
||||
}
|
||||
|
||||
if (typeof target !== 'string')
|
||||
return navigate({ path: target.fullPath, query })
|
||||
|
||||
const resolved = router.resolve(target)
|
||||
const path = typeof target === 'string' ? target : target.fullPath
|
||||
const resolved = router.resolve(path)
|
||||
|
||||
if (
|
||||
!resolved.matched.length ||
|
||||
resolved.matched.at(-1)?.path === NOT_FOUND_ROUTE_PATH
|
||||
) {
|
||||
console.warn(`[navigationTo]: The path "${target}" is not found.`)
|
||||
console.warn(`[navigationTo]: The path "${path}" is not found.`)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { useRuntimeActions } from '@/store'
|
||||
import { useVueRouter } from './useVueRouter'
|
||||
|
||||
/**
|
||||
*
|
||||
@ -9,7 +10,10 @@ import { useRuntimeActions } from '@/store'
|
||||
* @returns 页面刷新以及手动开启、关闭加载状态的方法。
|
||||
*/
|
||||
export const useSpinning = () => {
|
||||
const { reloadContent: reload, setRuntimeState } = useRuntimeActions()
|
||||
const { reloadContent, setRuntimeState } = useRuntimeActions()
|
||||
const reload = (wait?: number) =>
|
||||
reloadContent(wait, useVueRouter().router.currentRoute.value.fullPath)
|
||||
const reloadWorkspace = (wait?: number) => reloadContent(wait)
|
||||
|
||||
/**
|
||||
*
|
||||
@ -25,7 +29,7 @@ export const useSpinning = () => {
|
||||
*/
|
||||
const closeSpin = () => setRuntimeState('layoutContentSpinning', false)
|
||||
|
||||
return { reload, openSpin, closeSpin }
|
||||
return { reload, reloadWorkspace, openSpin, closeSpin }
|
||||
}
|
||||
|
||||
export type UseSpinningReturnType = ReturnType<typeof useSpinning>
|
||||
|
||||
@ -10,6 +10,7 @@ import {
|
||||
useSettingGetters,
|
||||
} from '@/store'
|
||||
import type { AppMenuOption, NaiveMenuOptions } from '@/types'
|
||||
import { useMenuKeyboard } from '@ray-template/admin-shell'
|
||||
import { RIcon } from '@ray-template/ui/icon'
|
||||
import { NButton, NDrawer, NLayoutContent, NLayoutSider, NMenu } from 'naive-ui'
|
||||
import type { MenuInst } from 'naive-ui'
|
||||
@ -46,6 +47,8 @@ export default defineComponent({
|
||||
() => !isTabletOrSmaller.value && getCollapsed.value,
|
||||
)
|
||||
|
||||
const keyboard = useMenuKeyboard(false, () => collapsed.value)
|
||||
|
||||
watch(
|
||||
[getMenuKey, () => props.options, menuRef],
|
||||
async () => {
|
||||
@ -117,32 +120,40 @@ export default defineComponent({
|
||||
}
|
||||
ref={LAYOUT_SIDER_REF}
|
||||
>
|
||||
<NMenu
|
||||
ref={menuRef}
|
||||
class="r-menu--app"
|
||||
keyField="fullPath"
|
||||
value={getMenuKey.value}
|
||||
options={
|
||||
(props.options ??
|
||||
getMenuOptions.value) as unknown as NaiveMenuOptions[]
|
||||
}
|
||||
indent={getMenuConfig.value.collapsedIndent}
|
||||
collapsed={collapsed.value}
|
||||
collapsedIconSize={getMenuConfig.value.collapsedIconSize}
|
||||
collapsedWidth={getMenuConfig.value.collapsedWidth}
|
||||
onUpdateValue={(key, option) => {
|
||||
changeMenuModelValue(key, option as unknown as AppMenuOption)
|
||||
<nav
|
||||
class="r-shell-menu"
|
||||
aria-label={t('navigation')}
|
||||
onKeydown={keyboard.onKeydown}
|
||||
>
|
||||
<NMenu
|
||||
ref={menuRef}
|
||||
nodeProps={keyboard.nodeProps}
|
||||
dropdownProps={keyboard.dropdownProps}
|
||||
class="r-menu--app"
|
||||
keyField="fullPath"
|
||||
value={getMenuKey.value}
|
||||
options={
|
||||
(props.options ??
|
||||
getMenuOptions.value) as unknown as NaiveMenuOptions[]
|
||||
}
|
||||
indent={getMenuConfig.value.collapsedIndent}
|
||||
collapsed={collapsed.value}
|
||||
collapsedIconSize={getMenuConfig.value.collapsedIconSize}
|
||||
collapsedWidth={getMenuConfig.value.collapsedWidth}
|
||||
onUpdateValue={(key, option) => {
|
||||
changeMenuModelValue(key, option as unknown as AppMenuOption)
|
||||
|
||||
if (isTabletOrSmaller.value)
|
||||
setRuntimeState('globalDrawerValue', false)
|
||||
}}
|
||||
accordion={getMenuConfig.value.accordion}
|
||||
iconSize={getMenuConfig.value.iconSize}
|
||||
themeOverrides={
|
||||
isTabletOrSmaller.value ? { itemHeight: '44px' } : void 0
|
||||
}
|
||||
inverted={getMenuConfig.value.inverted}
|
||||
/>
|
||||
if (isTabletOrSmaller.value)
|
||||
setRuntimeState('globalDrawerValue', false)
|
||||
}}
|
||||
accordion={getMenuConfig.value.accordion}
|
||||
iconSize={getMenuConfig.value.iconSize}
|
||||
themeOverrides={
|
||||
isTabletOrSmaller.value ? { itemHeight: '44px' } : void 0
|
||||
}
|
||||
inverted={getMenuConfig.value.inverted}
|
||||
/>
|
||||
</nav>
|
||||
</NLayoutContent>
|
||||
</NLayoutSider>
|
||||
)
|
||||
|
||||
@ -132,7 +132,15 @@ export default defineComponent({
|
||||
|
||||
closeCurrentMenuTag(currentContextmenuIndex.value)
|
||||
},
|
||||
reloadCurrentPage: () => {
|
||||
reloadCurrentPage: async () => {
|
||||
const option = getMenuTagOptions.value[currentContextmenuIndex.value]
|
||||
|
||||
if (option && route.fullPath !== option.fullPath) {
|
||||
await changeMenuModelValue(option.fullPath, option)
|
||||
|
||||
if (route.fullPath !== option.fullPath) return
|
||||
}
|
||||
|
||||
reload()
|
||||
},
|
||||
closeAll: () => {
|
||||
|
||||
@ -36,6 +36,7 @@ export default defineComponent({
|
||||
})
|
||||
|
||||
return {
|
||||
t,
|
||||
options,
|
||||
modelAppTheme,
|
||||
}
|
||||
@ -45,6 +46,7 @@ export default defineComponent({
|
||||
|
||||
return (
|
||||
<RSegment
|
||||
aria-label={this.t('appearance.theme')}
|
||||
options={options}
|
||||
size="small"
|
||||
width="block"
|
||||
|
||||
@ -1,65 +1,35 @@
|
||||
import { useTheme } from '@/hooks'
|
||||
import { useI18n, useTheme } from '@/hooks'
|
||||
import { useSettingGetters } from '@/store'
|
||||
import { RIcon } from '@ray-template/ui/icon'
|
||||
import { NFlex, NSwitch, NTooltip } from 'naive-ui'
|
||||
import { NSwitch, NTooltip } from 'naive-ui'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'ThemeSwitch',
|
||||
setup() {
|
||||
const { darkTheme, lightTheme } = useTheme()
|
||||
const { t } = useI18n('preferences')
|
||||
const { getAppTheme } = useSettingGetters()
|
||||
const modelAppThemeRef = ref(getAppTheme.value)
|
||||
const { lightTheme, darkTheme } = useTheme()
|
||||
|
||||
const railStyle = ({ checked }: { checked: boolean }) => {
|
||||
return checked
|
||||
? {
|
||||
backgroundColor: '#000000',
|
||||
}
|
||||
: {
|
||||
color: '#000000',
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
darkTheme,
|
||||
lightTheme,
|
||||
getAppTheme,
|
||||
railStyle,
|
||||
modelAppThemeRef,
|
||||
}
|
||||
},
|
||||
render() {
|
||||
const { $t, darkTheme, lightTheme, railStyle } = this
|
||||
|
||||
return (
|
||||
<NFlex justify="center">
|
||||
<NTooltip>
|
||||
{{
|
||||
trigger: () => (
|
||||
<NSwitch
|
||||
v-model:value={this.modelAppThemeRef}
|
||||
railStyle={railStyle.bind(this)}
|
||||
onUpdateValue={(bool: boolean) =>
|
||||
bool ? darkTheme() : lightTheme()
|
||||
}
|
||||
>
|
||||
{{
|
||||
'checked-icon': () => <RIcon name="system/dark" size={14} />,
|
||||
'unchecked-icon': () => (
|
||||
<RIcon name="system/light" size={14} />
|
||||
),
|
||||
checked: () => '亮',
|
||||
unchecked: () => '暗',
|
||||
}}
|
||||
</NSwitch>
|
||||
),
|
||||
default: () =>
|
||||
this.getAppTheme
|
||||
? $t('headerSettingOptions.ThemeOptions.Dark')
|
||||
: $t('headerSettingOptions.ThemeOptions.Light'),
|
||||
}}
|
||||
</NTooltip>
|
||||
</NFlex>
|
||||
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>
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
@ -82,6 +82,11 @@
|
||||
|
||||
&__tab {
|
||||
min-block-size: 44px;
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--r-primary-text);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
}
|
||||
|
||||
> .n-tabs-nav {
|
||||
@ -89,10 +94,10 @@
|
||||
border-radius: var(--r-radius);
|
||||
background: var(--r-surface);
|
||||
}
|
||||
}
|
||||
|
||||
> .n-tab-pane {
|
||||
padding-block-start: 14px;
|
||||
}
|
||||
.r-settings-panel {
|
||||
padding-block-start: 14px;
|
||||
}
|
||||
|
||||
.r-settings-stack,
|
||||
|
||||
@ -5,6 +5,7 @@ import { getDefaultSettingConfig } from '@/store/modules/setting/constant'
|
||||
import { PREFERENCE_FILE_LIMIT } from '@/store/modules/setting/preference-file'
|
||||
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'
|
||||
@ -13,7 +14,7 @@ import {
|
||||
NButton,
|
||||
NDrawer,
|
||||
NDrawerContent,
|
||||
NTabPane,
|
||||
NTab,
|
||||
NTabs,
|
||||
} from 'naive-ui'
|
||||
import Appearance from './segment-views/Appearance'
|
||||
@ -33,6 +34,15 @@ export default defineComponent({
|
||||
{ key: 'watermark', icon: 'system/watermark', view: Watermark },
|
||||
{ key: 'general', icon: 'action/setting', view: Common },
|
||||
] as const
|
||||
const selectedCategory = ref<string | number>('appearance')
|
||||
const tabsId = useId()
|
||||
|
||||
watch(
|
||||
() => props.show,
|
||||
(show) => {
|
||||
if (show) selectedCategory.value = 'appearance'
|
||||
},
|
||||
)
|
||||
const { t } = useI18n('preferences')
|
||||
const { create } = useModal()
|
||||
const {
|
||||
@ -144,42 +154,65 @@ export default defineComponent({
|
||||
</div>
|
||||
),
|
||||
default: () => (
|
||||
<NTabs
|
||||
type="line"
|
||||
defaultValue="appearance"
|
||||
class="r-settings-tabs"
|
||||
tabClass="r-settings-tabs__tab"
|
||||
tabsPadding={14}
|
||||
themeOverrides={{
|
||||
tabGapMediumLine: '16px',
|
||||
tabPaddingMediumLine: '10px 4px',
|
||||
tabTextColorActiveLine: 'var(--r-primary-text)',
|
||||
tabTextColorHoverLine: 'var(--r-primary-text)',
|
||||
barColor: 'var(--r-primary-text)',
|
||||
}}
|
||||
>
|
||||
{categories.map(({ key, icon, view: View }) => (
|
||||
<NTabPane
|
||||
key={key}
|
||||
name={key}
|
||||
tab={() => (
|
||||
<span class="r-settings-tabs__label">
|
||||
<RIcon
|
||||
class="r-settings-tabs__icon"
|
||||
name={icon}
|
||||
size={16}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="r-settings-tabs__text">
|
||||
{t(`section.${key}`)}
|
||||
<>
|
||||
<NTabs
|
||||
type="line"
|
||||
v-model:value={selectedCategory.value}
|
||||
{...{ role: 'tablist' }}
|
||||
aria-label={t('title')}
|
||||
class="r-settings-tabs"
|
||||
tabClass="r-settings-tabs__tab"
|
||||
tabsPadding={14}
|
||||
themeOverrides={{
|
||||
tabGapMediumLine: '16px',
|
||||
tabPaddingMediumLine: '10px 4px',
|
||||
tabTextColorActiveLine: 'var(--r-primary-text)',
|
||||
tabTextColorHoverLine: 'var(--r-primary-text)',
|
||||
barColor: 'var(--r-primary-text)',
|
||||
}}
|
||||
>
|
||||
{categories.map(({ key, icon }) => (
|
||||
<NTab
|
||||
key={key}
|
||||
name={key}
|
||||
{...{
|
||||
role: 'tab',
|
||||
onKeydown: (event: KeyboardEvent) =>
|
||||
navigateHorizontalChoice(event),
|
||||
tabindex: selectedCategory.value === key ? 0 : -1,
|
||||
id: `${tabsId}-tab-${key}`,
|
||||
}}
|
||||
aria-controls={`${tabsId}-panel-${key}`}
|
||||
aria-selected={selectedCategory.value === key}
|
||||
tab={() => (
|
||||
<span class="r-settings-tabs__label">
|
||||
<RIcon
|
||||
class="r-settings-tabs__icon"
|
||||
name={icon}
|
||||
size={16}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="r-settings-tabs__text">
|
||||
{t(`section.${key}`)}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</NTabs>
|
||||
{categories.map(({ key, view: View }) => (
|
||||
<div
|
||||
key={key}
|
||||
id={`${tabsId}-panel-${key}`}
|
||||
class="r-settings-panel"
|
||||
role="tabpanel"
|
||||
aria-labelledby={`${tabsId}-tab-${key}`}
|
||||
hidden={selectedCategory.value !== key}
|
||||
>
|
||||
<View />
|
||||
</NTabPane>
|
||||
{selectedCategory.value === key && <View />}
|
||||
</div>
|
||||
))}
|
||||
</NTabs>
|
||||
</>
|
||||
),
|
||||
footer: () => (
|
||||
<div class="r-settings-drawer__actions">
|
||||
|
||||
@ -35,7 +35,7 @@ export default defineComponent({
|
||||
const { recentPaths, storageUnavailable } = useNavigationHistoryGetters()
|
||||
const { clearRecent } = useNavigationHistoryActions()
|
||||
const { globalMainLayoutLoad } = useRuntimeGetters()
|
||||
const { reload } = useSpinning()
|
||||
const { reloadWorkspace } = useSpinning()
|
||||
const scrollTo = useContentScroll()
|
||||
const cacheHintId = useId()
|
||||
const status = ref('')
|
||||
@ -104,7 +104,7 @@ export default defineComponent({
|
||||
<div class="r-settings-actions">
|
||||
<NButton
|
||||
loading={!globalMainLayoutLoad.value}
|
||||
onClick={() => reload()}
|
||||
onClick={() => reloadWorkspace()}
|
||||
>
|
||||
{t('general.refresh')}
|
||||
</NButton>
|
||||
|
||||
@ -5,17 +5,18 @@ import { useRuntimeGetters, useSettingGetters } from '@/store'
|
||||
export default defineComponent({
|
||||
name: 'LayoutContentWrapper',
|
||||
setup() {
|
||||
const { globalMainLayoutLoad } = useRuntimeGetters()
|
||||
const { globalMainLayoutLoad, refreshingPath } = useRuntimeGetters()
|
||||
const { getContentTransition } = useSettingGetters()
|
||||
|
||||
return () => (
|
||||
<>
|
||||
<AppRequestCancelerProvider />
|
||||
{globalMainLayoutLoad.value ? (
|
||||
{globalMainLayoutLoad.value || refreshingPath.value !== null ? (
|
||||
<RTransitionComponent
|
||||
class="content-wrapper"
|
||||
transitionPropName={`${getContentTransition.value}-transform`}
|
||||
transitionAppear={false}
|
||||
refreshingPath={refreshingPath.value}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
|
||||
@ -59,5 +59,12 @@
|
||||
"RouteManagementVisual": "Visual editor",
|
||||
"RouteManagementJson": "JSON configuration",
|
||||
"SystemManagement": "System management",
|
||||
"UserManagement": "Users"
|
||||
"UserManagement": "Users",
|
||||
"RouterPeople": "People (same-level routes)",
|
||||
"RouterPersonDetail": "Person details",
|
||||
"NestedOne": "Nested menu 1",
|
||||
"NestedTwo": "Nested menu 2",
|
||||
"NestedTwoOne": "Nested menu 2-1",
|
||||
"NestedTwoTwo": "Nested menu 2-2",
|
||||
"NestedTwoTwoOne": "Nested menu 2-2-1"
|
||||
}
|
||||
|
||||
@ -20,6 +20,7 @@
|
||||
"general": "General"
|
||||
},
|
||||
"theme": {
|
||||
"darkMode": "Dark mode",
|
||||
"light": "Light",
|
||||
"dark": "Dark",
|
||||
"auto": "System"
|
||||
@ -131,7 +132,7 @@
|
||||
"language": "Interface language",
|
||||
"workspaceActions": "Workspace actions",
|
||||
"refresh": "Refresh workspace",
|
||||
"refreshHint": "Reload the current page and release workspace page instances. Unsaved form changes will be lost.",
|
||||
"refreshHint": "Reload the workspace and clear all cached pages. Unsaved changes in any tab will be lost.",
|
||||
"scrollTop": "Scroll content to top",
|
||||
"cacheLimitHint": "Pages are queued by recent access. Set to 0 to stop adding pages; turn caching off to disable it immediately.",
|
||||
"clearCache": "Clear page cache",
|
||||
|
||||
@ -66,5 +66,8 @@
|
||||
"group": "Menu group",
|
||||
"redirect": "Redirect",
|
||||
"external": "External link"
|
||||
}
|
||||
},
|
||||
"editConflict": "Another administrator saved a new configuration. Export any draft you want to keep, then reload the configuration and merge your changes.",
|
||||
"readOnlyHint": "The remote source is read-only. Activating it reloads the workspace. You can export your edits or save them as a local configuration.",
|
||||
"activateRemote": "Activate remote configuration"
|
||||
}
|
||||
|
||||
@ -78,7 +78,11 @@
|
||||
"invalidCredentials": "Incorrect username or password.",
|
||||
"forbidden": "Your account does not have permission for this action.",
|
||||
"invalidRoutes": "The route configuration failed validation.",
|
||||
"requestFailed": "The request failed. Please retry."
|
||||
"requestFailed": "The request failed. Please retry.",
|
||||
"editConflict": "Someone else changed this account. Reopen the editor and review the latest values before saving.",
|
||||
"serverStorage": "The server cannot access its database. Try again later.",
|
||||
"serviceUnavailable": "The service is temporarily unavailable. Try again later.",
|
||||
"tooManyRequests": "Too many requests. Wait before trying again."
|
||||
},
|
||||
"allUsers": "All users",
|
||||
"apiContract": "API contract"
|
||||
|
||||
@ -59,5 +59,12 @@
|
||||
"RouteManagementVisual": "可视化配置",
|
||||
"RouteManagementJson": "JSON 配置",
|
||||
"SystemManagement": "系统管理",
|
||||
"UserManagement": "用户管理"
|
||||
"UserManagement": "用户管理",
|
||||
"RouterPeople": "人员信息(平级模式)",
|
||||
"RouterPersonDetail": "信息详情",
|
||||
"NestedOne": "多级菜单-1",
|
||||
"NestedTwo": "多级菜单-2",
|
||||
"NestedTwoOne": "多级菜单-2-1",
|
||||
"NestedTwoTwo": "多级菜单-2-2",
|
||||
"NestedTwoTwoOne": "多级菜单-2-2-1"
|
||||
}
|
||||
|
||||
@ -20,6 +20,7 @@
|
||||
"general": "通用"
|
||||
},
|
||||
"theme": {
|
||||
"darkMode": "深色模式",
|
||||
"light": "浅色",
|
||||
"dark": "深色",
|
||||
"auto": "跟随系统"
|
||||
@ -131,7 +132,7 @@
|
||||
"language": "界面语言",
|
||||
"workspaceActions": "工作区操作",
|
||||
"refresh": "刷新工作区",
|
||||
"refreshHint": "重新加载当前页面并释放工作区中的页面实例;未保存的表单内容会丢失。",
|
||||
"refreshHint": "重新加载工作区并清空所有页面缓存。各标签页未保存的表单内容都会丢失。",
|
||||
"scrollTop": "回到内容顶部",
|
||||
"cacheLimitHint": "按最近访问顺序管理缓存。设为 0 将停止加入新页面;如需立即停用,请关闭页面缓存。",
|
||||
"clearCache": "清理页面缓存",
|
||||
|
||||
@ -66,5 +66,8 @@
|
||||
"group": "菜单分组",
|
||||
"redirect": "重定向",
|
||||
"external": "外部链接"
|
||||
}
|
||||
},
|
||||
"editConflict": "其他管理员已保存新配置。请先导出需要保留的草稿,再重新读取配置并合并修改。",
|
||||
"readOnlyHint": "远程地址只支持读取。启用后将重新加载工作区,编辑器的改动仅供导出或另存为本地配置。",
|
||||
"activateRemote": "启用远程配置"
|
||||
}
|
||||
|
||||
@ -78,7 +78,11 @@
|
||||
"invalidCredentials": "账号或密码错误。",
|
||||
"forbidden": "当前账号没有执行此操作的权限。",
|
||||
"invalidRoutes": "路由配置未通过校验。",
|
||||
"requestFailed": "请求失败,请稍后重试。"
|
||||
"requestFailed": "请求失败,请稍后重试。",
|
||||
"editConflict": "此账号已被其他人修改。请重新打开编辑框,核对最新内容后再保存。",
|
||||
"serverStorage": "服务器暂时无法访问数据库,请稍后重试。",
|
||||
"serviceUnavailable": "服务暂时不可用,请稍后重试。",
|
||||
"tooManyRequests": "请求过于频繁,请稍后再试。"
|
||||
},
|
||||
"allUsers": "全部用户",
|
||||
"apiContract": "API 接入契约"
|
||||
|
||||
@ -71,15 +71,24 @@ async function demoDigest(password: string, salt: string) {
|
||||
).join('')
|
||||
}
|
||||
|
||||
export function createAdminDatabase(storage?: Storage) {
|
||||
const key = 'rayMockAdmin.v1'
|
||||
const snapshotKey = 'rayMockAdmin.v1'
|
||||
const aliases = new Map(
|
||||
Object.entries({
|
||||
'ray admin': 'user001',
|
||||
admin: 'user001',
|
||||
manager: 'user011',
|
||||
member: 'user002',
|
||||
}),
|
||||
)
|
||||
|
||||
function openSnapshot(storage?: Storage) {
|
||||
let users = createInitialUsers()
|
||||
let routes = parseRouteConfig(JSON.stringify(initialRoutes))
|
||||
let sessions: v.InferOutput<typeof loginResultSchema>[] = []
|
||||
let credentials: v.InferOutput<typeof snapshotSchema>['credentials'] = []
|
||||
|
||||
try {
|
||||
const raw = storage?.getItem(key)
|
||||
const raw = storage?.getItem(snapshotKey)
|
||||
|
||||
if (raw) {
|
||||
const value = v.parse(snapshotSchema, JSON.parse(raw))
|
||||
@ -107,7 +116,7 @@ export function createAdminDatabase(storage?: Storage) {
|
||||
}) => {
|
||||
try {
|
||||
storage?.setItem(
|
||||
key,
|
||||
snapshotKey,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
users,
|
||||
@ -261,25 +270,16 @@ export function createAdminDatabase(storage?: Storage) {
|
||||
authorize,
|
||||
async login(input: unknown) {
|
||||
const { username, password } = parseInput(loginInputSchema, input)
|
||||
const aliases = new Map(
|
||||
Object.entries({
|
||||
'ray admin': 'user001',
|
||||
admin: 'user001',
|
||||
manager: 'user011',
|
||||
member: 'user002',
|
||||
}),
|
||||
)
|
||||
const key = username.toLowerCase()
|
||||
const user = users.find(
|
||||
(item) =>
|
||||
item.username.toLowerCase() === (aliases.get(key) ?? key) &&
|
||||
item.status === 'enabled',
|
||||
)
|
||||
const user =
|
||||
users.find((item) => item.username.toLowerCase() === key) ??
|
||||
users.find((item) => item.username.toLowerCase() === aliases.get(key))
|
||||
|
||||
const snapshot = credentials
|
||||
|
||||
if (
|
||||
!user ||
|
||||
user.status !== 'enabled' ||
|
||||
!(await matchesPassword(user, password)) ||
|
||||
snapshot !== credentials ||
|
||||
!users.includes(user)
|
||||
@ -540,4 +540,38 @@ export function createAdminDatabase(storage?: Storage) {
|
||||
}
|
||||
}
|
||||
|
||||
export type AdminDatabase = ReturnType<typeof createAdminDatabase>
|
||||
type Snapshot = ReturnType<typeof openSnapshot>
|
||||
|
||||
export type AdminDatabase = <T>(
|
||||
action: (snapshot: Snapshot) => T | Promise<T>,
|
||||
) => Promise<T>
|
||||
|
||||
export function createAdminDatabase(
|
||||
storage?: Storage,
|
||||
locks = globalThis.navigator?.locks,
|
||||
): AdminDatabase {
|
||||
if (storage) {
|
||||
return async (action) => {
|
||||
if (!locks) throw new MockApiError(503, 'storage')
|
||||
|
||||
// 在同源标签共享的锁内重新读取快照,异步校验和提交也属于同一操作。
|
||||
return locks.request(snapshotKey, async () =>
|
||||
action(openSnapshot(storage)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const database = openSnapshot()
|
||||
let pending = Promise.resolve()
|
||||
|
||||
return (action) => {
|
||||
const result = pending.then(() => action(database))
|
||||
|
||||
pending = result.then(
|
||||
() => {},
|
||||
() => {},
|
||||
)
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { userListQuerySchema } from '@/api/admin/contracts'
|
||||
import { editRevision, userListQuerySchema } from '@/api/admin/contracts'
|
||||
import {
|
||||
chartsQuerySchema,
|
||||
orderSearchInputSchema,
|
||||
@ -23,7 +23,7 @@ import { routeDemoPeople } from './data/route-people'
|
||||
import { MockApiError } from './database'
|
||||
import type { AdminDatabase } from './database'
|
||||
|
||||
export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
|
||||
export function createAdminHandlers(transact: AdminDatabase, apiBase: string) {
|
||||
const url = (path: string) => `${apiBase}${path}`
|
||||
const token = (request: Request) =>
|
||||
request.headers.get('Authorization')?.replace(/^Bearer /u, '') ?? null
|
||||
@ -46,11 +46,20 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
|
||||
|
||||
return v.parse(schema, query)
|
||||
}
|
||||
const respond = async (action: () => unknown | Promise<unknown>) => {
|
||||
const respond = async (
|
||||
action: () => unknown | Promise<unknown>,
|
||||
revisioned = false,
|
||||
) => {
|
||||
await delay(120)
|
||||
|
||||
try {
|
||||
return HttpResponse.json({ code: 200, msg: 'OK', data: await action() })
|
||||
const data = await action()
|
||||
const revision = revisioned ? await editRevision(data) : void 0
|
||||
|
||||
return HttpResponse.json(
|
||||
{ code: 200, msg: 'OK', data, ...(revision ? { revision } : {}) },
|
||||
revision ? { headers: { ETag: `"${revision}"` } } : void 0,
|
||||
)
|
||||
} catch (error) {
|
||||
const failure =
|
||||
error instanceof MockApiError ? error : new MockApiError(400, 'invalid')
|
||||
@ -67,6 +76,17 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
|
||||
}
|
||||
}
|
||||
|
||||
const respondAdmin = (
|
||||
action: Parameters<AdminDatabase>[0],
|
||||
revisioned = false,
|
||||
) => respond(() => transact(action), revisioned)
|
||||
const checkRevision = async (request: Request, current: unknown) => {
|
||||
const match = request.headers.get('If-Match')
|
||||
|
||||
if (match !== null && match !== `"${await editRevision(current)}"`)
|
||||
throw new MockApiError(412, 'editConflict')
|
||||
}
|
||||
|
||||
return [
|
||||
http.get(url('admin/mock-health'), () =>
|
||||
HttpResponse.json(
|
||||
@ -123,60 +143,66 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
|
||||
}),
|
||||
),
|
||||
http.post(url('admin/auth/login'), ({ request }) =>
|
||||
respond(async () => database.login(await request.json())),
|
||||
respondAdmin(async (database) => database.login(await request.json())),
|
||||
),
|
||||
http.get(url('admin/auth/session'), ({ request }) =>
|
||||
respond(() => database.authorize(token(request))),
|
||||
respondAdmin((database) => database.authorize(token(request))),
|
||||
),
|
||||
http.post(url('admin/auth/logout'), ({ request }) =>
|
||||
respond(() => database.logout(token(request))),
|
||||
respondAdmin((database) => database.logout(token(request))),
|
||||
),
|
||||
http.get(url('admin/auth/profile'), ({ request }) =>
|
||||
respond(() => database.getProfile(token(request))),
|
||||
respondAdmin((database) => database.getProfile(token(request))),
|
||||
),
|
||||
http.patch(url('admin/auth/profile'), ({ request }) =>
|
||||
respond(async () =>
|
||||
respondAdmin(async (database) =>
|
||||
database.updateProfile(await request.json(), token(request)),
|
||||
),
|
||||
),
|
||||
http.patch(url('admin/auth/password'), ({ request }) =>
|
||||
respond(async () =>
|
||||
respondAdmin(async (database) =>
|
||||
database.changePassword(await request.json(), token(request)),
|
||||
),
|
||||
),
|
||||
http.get(url('admin/route-config'), ({ request }) =>
|
||||
respond(() => {
|
||||
const view = new URL(request.url).searchParams.getAll('view')
|
||||
respondAdmin(
|
||||
(database) => {
|
||||
const view = new URL(request.url).searchParams.getAll('view')
|
||||
|
||||
if (view.length && (view.length !== 1 || view[0] !== 'editor'))
|
||||
throw new MockApiError(400, 'invalid')
|
||||
if (view.length && (view.length !== 1 || view[0] !== 'editor'))
|
||||
throw new MockApiError(400, 'invalid')
|
||||
|
||||
return database.getRoutes(token(request), view[0] === 'editor')
|
||||
}),
|
||||
),
|
||||
http.put(url('admin/route-config'), ({ request }) =>
|
||||
respond(async () =>
|
||||
database.saveRoutes(await request.json(), token(request)),
|
||||
return database.getRoutes(token(request), view[0] === 'editor')
|
||||
},
|
||||
new URL(request.url).searchParams.get('view') === 'editor',
|
||||
),
|
||||
),
|
||||
http.put(url('admin/route-config'), ({ request }) =>
|
||||
respondAdmin(async (database) => {
|
||||
if (request.headers.has('If-Match'))
|
||||
await checkRevision(request, database.getRoutes(token(request), true))
|
||||
|
||||
return database.saveRoutes(await request.json(), token(request))
|
||||
}),
|
||||
),
|
||||
http.get(url('admin/users/options'), ({ request }) =>
|
||||
respond(() => database.getOptions(token(request))),
|
||||
respondAdmin((database) => database.getOptions(token(request))),
|
||||
),
|
||||
http.post(url('admin/users/batch-delete'), ({ request }) =>
|
||||
respond(async () =>
|
||||
respondAdmin(async (database) =>
|
||||
database.deleteUsers(await request.json(), token(request)),
|
||||
),
|
||||
),
|
||||
http.patch(url('admin/users/status'), ({ request }) =>
|
||||
respond(async () =>
|
||||
respondAdmin(async (database) =>
|
||||
database.changeStatus(await request.json(), token(request)),
|
||||
),
|
||||
),
|
||||
http.post(url('admin/users/reset'), ({ request }) =>
|
||||
respond(() => database.resetUsers(token(request))),
|
||||
respondAdmin((database) => database.resetUsers(token(request))),
|
||||
),
|
||||
http.get(url('admin/users'), ({ request }) =>
|
||||
respond(() =>
|
||||
respondAdmin((database) =>
|
||||
database.listUsers(
|
||||
readQuery(request, userListQuerySchema),
|
||||
token(request),
|
||||
@ -184,24 +210,35 @@ export function createAdminHandlers(database: AdminDatabase, apiBase: string) {
|
||||
),
|
||||
),
|
||||
http.post(url('admin/users'), ({ request }) =>
|
||||
respond(async () =>
|
||||
respondAdmin(async (database) =>
|
||||
database.saveUser(await request.json(), token(request)),
|
||||
),
|
||||
),
|
||||
http.get(url('admin/users/:id'), ({ request, params }) =>
|
||||
respond(() => database.getUser(String(params.id), token(request))),
|
||||
respondAdmin(
|
||||
(database) => database.getUser(String(params.id), token(request)),
|
||||
true,
|
||||
),
|
||||
),
|
||||
http.put(url('admin/users/:id'), ({ request, params }) =>
|
||||
respond(async () =>
|
||||
database.saveUser(
|
||||
respondAdmin(async (database) => {
|
||||
if (request.headers.has('If-Match')) {
|
||||
database.authorize(token(request), 'users:update')
|
||||
await checkRevision(
|
||||
request,
|
||||
database.getUser(String(params.id), token(request)),
|
||||
)
|
||||
}
|
||||
|
||||
return database.saveUser(
|
||||
await request.json(),
|
||||
token(request),
|
||||
String(params.id),
|
||||
),
|
||||
),
|
||||
)
|
||||
}),
|
||||
),
|
||||
http.put(url('admin/users/:id/credential'), ({ request, params }) =>
|
||||
respond(async () =>
|
||||
respondAdmin(async (database) =>
|
||||
database.setCredential(
|
||||
String(params.id),
|
||||
await request.json(),
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { initialRoutes } from '@ray-template/demo-data'
|
||||
import { computed, shallowRef } from 'vue'
|
||||
import { parseRouteConfig, toRuntimeRoutes } from './config/contract'
|
||||
import { ROUTE_MANAGEMENT_PATH } from './constant'
|
||||
import type { AppRouteRecordRaw } from './types'
|
||||
@ -38,16 +39,18 @@ const managementRoute: AppRouteRecordRaw = {
|
||||
export const getStaticAppRoutes = () =>
|
||||
orderRoutes(toRuntimeRoutes(parseRouteConfig(JSON.stringify(initialRoutes))))
|
||||
|
||||
let activeRoutes: AppRouteRecordRaw[] | undefined
|
||||
const activeRoutes = shallowRef<AppRouteRecordRaw[]>()
|
||||
|
||||
export function setAppRouteModules(routes: AppRouteRecordRaw[]) {
|
||||
activeRoutes = orderRoutes(routes)
|
||||
activeRoutes.value = orderRoutes(routes)
|
||||
}
|
||||
|
||||
export const getAppRawRoutes = () => [
|
||||
...(activeRoutes ?? getStaticAppRoutes()),
|
||||
const rawRoutes = computed(() => [
|
||||
...(activeRoutes.value ?? getStaticAppRoutes()),
|
||||
managementRoute,
|
||||
]
|
||||
])
|
||||
|
||||
export const getAppRawRoutes = () => rawRoutes.value
|
||||
|
||||
export const appExpandRoutes = () =>
|
||||
expandRoutes(getAppRawRoutes()).filter(({ meta }) => !meta.windowOpen)
|
||||
|
||||
@ -8,25 +8,72 @@ import {
|
||||
} from '@/router/constant'
|
||||
import { routeViewPermission } from '@ray-template/api-contracts/routes'
|
||||
import { createRouteContract } from '@ray-template/routing/contract'
|
||||
import type { AppRouteRecordRaw } from '../types'
|
||||
import { joinRoutePath } from '../utils/join-route-path'
|
||||
import type { RouteConfig } from './schema'
|
||||
import { findRouteView, findRouteViewId } from './views'
|
||||
|
||||
export const { parseRouteConfig, toRuntimeRoutes, exportRouteConfig } =
|
||||
createRouteContract({
|
||||
layout: LAYOUT,
|
||||
findRouteView,
|
||||
findRouteViewId,
|
||||
viewPermission: routeViewPermission,
|
||||
managementPath: ROUTE_MANAGEMENT_PATH,
|
||||
reservedPaths: [...SYSTEM_ROUTE_PATHS, ACCOUNT_PROFILE_PATH],
|
||||
reservedNames: [
|
||||
...SYSTEM_ROUTE_NAMES,
|
||||
ACCOUNT_PROFILE_NAME,
|
||||
'RLogin',
|
||||
'RLayout',
|
||||
'RNotFound',
|
||||
'RouteManagement',
|
||||
'RouteManagementVisual',
|
||||
'ErrorPage',
|
||||
'RayTemplateDoc',
|
||||
],
|
||||
})
|
||||
const contract = createRouteContract({
|
||||
layout: LAYOUT,
|
||||
findRouteView,
|
||||
findRouteViewId,
|
||||
viewPermission: routeViewPermission,
|
||||
managementPath: ROUTE_MANAGEMENT_PATH,
|
||||
reservedPaths: [...SYSTEM_ROUTE_PATHS, ACCOUNT_PROFILE_PATH],
|
||||
reservedNames: [
|
||||
...SYSTEM_ROUTE_NAMES,
|
||||
ACCOUNT_PROFILE_NAME,
|
||||
'RLogin',
|
||||
'RLayout',
|
||||
'RNotFound',
|
||||
'RouteManagement',
|
||||
'RouteManagementVisual',
|
||||
'ErrorPage',
|
||||
'RayTemplateDoc',
|
||||
],
|
||||
})
|
||||
|
||||
export const { parseRouteConfig, exportRouteConfig } = contract
|
||||
|
||||
// 旧 Mock、本地配置和已初始化的服务端可能仍保存内置菜单原文。只识别原路径和原文的组合。
|
||||
const formerTitles = new Map<string, [string, string]>([
|
||||
[
|
||||
'/router-demo/router-demo-home',
|
||||
['人员信息(平级模式)', 'menu.RouterPeople'],
|
||||
],
|
||||
['/router-demo/router-demo-detail', ['信息详情', 'menu.RouterPersonDetail']],
|
||||
['/multi/multi-menu-one', ['多级菜单-1', 'menu.NestedOne']],
|
||||
['/multi/multi-menu-two', ['多级菜单-2', 'menu.NestedTwo']],
|
||||
[
|
||||
'/multi/multi-menu-two/sub-menu-other',
|
||||
['多级菜单-2-1', 'menu.NestedTwoOne'],
|
||||
],
|
||||
['/multi/multi-menu-two/sub-menu', ['多级菜单-2-2', 'menu.NestedTwoTwo']],
|
||||
[
|
||||
'/multi/multi-menu-two/sub-menu/sub-menu-one',
|
||||
['多级菜单-2-2-1', 'menu.NestedTwoTwoOne'],
|
||||
],
|
||||
])
|
||||
|
||||
export function toRuntimeRoutes(config: RouteConfig) {
|
||||
const routes = contract.toRuntimeRoutes(config)
|
||||
const localize = (records: AppRouteRecordRaw[], parent: string) => {
|
||||
for (const record of records) {
|
||||
const path = joinRoutePath(parent, record.path)
|
||||
const former = formerTitles.get(path)
|
||||
|
||||
if (
|
||||
former &&
|
||||
!record.meta.i18nKey &&
|
||||
record.meta.noLocalTitle === former[0]
|
||||
)
|
||||
record.meta.i18nKey = former[1]
|
||||
|
||||
if (record.children) localize(record.children, path)
|
||||
}
|
||||
}
|
||||
|
||||
localize(routes, '')
|
||||
|
||||
return routes
|
||||
}
|
||||
|
||||
@ -14,6 +14,8 @@ const storageKey = 'rayRouteConfig.v1'
|
||||
|
||||
export const remoteRouteUrl =
|
||||
import.meta.env.VITE_ROUTE_CONFIG_URL?.trim() || apiUrl('admin/route-config')
|
||||
export const remoteRoutesReadOnly =
|
||||
!!import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()
|
||||
export const serverRoutesRequired =
|
||||
!apiMockEnabled && !import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()
|
||||
|
||||
@ -54,11 +56,14 @@ export const routeSourceStatus: {
|
||||
export async function fetchRemoteRouteConfig(
|
||||
view?: 'editor',
|
||||
signal?: AbortSignal,
|
||||
onRevision?: (revision: string | undefined) => void,
|
||||
): Promise<RouteConfig> {
|
||||
if (!import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()) {
|
||||
const { parseRouteConfig } = await import('./contract')
|
||||
|
||||
return parseRouteConfig(JSON.stringify(await getAdminRoutes(view, signal)))
|
||||
return parseRouteConfig(
|
||||
JSON.stringify(await getAdminRoutes(view, signal, onRevision)),
|
||||
)
|
||||
}
|
||||
|
||||
if (!remoteRouteUrl) throw new Error('VITE_ROUTE_CONFIG_URL is missing.')
|
||||
@ -86,13 +91,30 @@ export async function fetchRemoteRouteConfig(
|
||||
return parseRouteConfig(await response.text())
|
||||
}
|
||||
|
||||
export async function saveRemoteRouteConfig(config: RouteConfig) {
|
||||
export async function readRouteEditorSnapshot() {
|
||||
let revision: string | undefined
|
||||
const config = await fetchRemoteRouteConfig('editor', void 0, (value) => {
|
||||
revision = value
|
||||
})
|
||||
|
||||
return { config, revision }
|
||||
}
|
||||
|
||||
export async function activateRemoteRouteSource() {
|
||||
await fetchRemoteRouteConfig()
|
||||
saveRouteSource('remote')
|
||||
}
|
||||
|
||||
export async function saveRemoteRouteConfig(
|
||||
config: RouteConfig,
|
||||
revision?: string,
|
||||
) {
|
||||
if (import.meta.env.VITE_ROUTE_CONFIG_URL?.trim())
|
||||
throw new Error(
|
||||
'VITE_ROUTE_CONFIG_URL is a read-only legacy endpoint. Configure VITE_API_BASE_URL for route writes.',
|
||||
)
|
||||
|
||||
await updateAdminRoutes(config)
|
||||
await updateAdminRoutes(config, revision)
|
||||
saveRouteSource('remote')
|
||||
}
|
||||
|
||||
|
||||
@ -7,6 +7,7 @@ export const useRuntimeGetters = () => {
|
||||
return {
|
||||
globalSpinning: readonly(state.globalSpinning),
|
||||
globalDrawerValue: readonly(state.globalDrawerValue),
|
||||
refreshingPath: readonly(state.refreshingPath),
|
||||
globalMainLayoutLoad: readonly(state.globalMainLayoutLoad),
|
||||
layoutContentMaximize: readonly(state.layoutContentMaximize),
|
||||
layoutContentMaximizeVersion: readonly(state.layoutContentMaximizeVersion),
|
||||
|
||||
@ -434,9 +434,10 @@ export const piniaMenuStore = defineStore(
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [
|
||||
signing.signingCallback.role,
|
||||
signing.signingCallback.id || signing.signingCallback.name,
|
||||
[
|
||||
() => signing.signingCallback.role,
|
||||
() => signing.signingCallback.id || signing.signingCallback.name,
|
||||
getAppRawRoutes,
|
||||
],
|
||||
(current, previous) => {
|
||||
if (previous?.[1] && current[1] !== previous[1]) {
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
export interface RuntimeState {
|
||||
globalSpinning: boolean
|
||||
globalDrawerValue: boolean
|
||||
refreshingPath: string | null
|
||||
globalMainLayoutLoad: boolean
|
||||
layoutContentMaximize: boolean
|
||||
layoutContentMaximizeVersion: number
|
||||
@ -16,6 +17,7 @@ export const piniaRuntimeStore = defineStore('runtime', () => {
|
||||
const state = reactive<RuntimeState>({
|
||||
globalSpinning: false,
|
||||
globalDrawerValue: false,
|
||||
refreshingPath: null,
|
||||
globalMainLayoutLoad: true,
|
||||
layoutContentMaximize: false,
|
||||
layoutContentMaximizeVersion: 0,
|
||||
@ -36,11 +38,13 @@ export const piniaRuntimeStore = defineStore('runtime', () => {
|
||||
}
|
||||
|
||||
// 刷新会卸载发起调用的页面,计时器必须由 store 持有;重复刷新以最后一次为准。
|
||||
const reloadContent = (wait = 800) => {
|
||||
const reloadContent = (wait = 800, path: string | null = null) => {
|
||||
clearTimeout(reloadTimer)
|
||||
state.refreshingPath = path
|
||||
state.globalMainLayoutLoad = false
|
||||
reloadTimer = setTimeout(() => {
|
||||
state.globalMainLayoutLoad = true
|
||||
state.refreshingPath = null
|
||||
reloadTimer = void 0
|
||||
}, wait)
|
||||
}
|
||||
|
||||
@ -15,8 +15,10 @@ import {
|
||||
} from '@ray-template/ui/theme-presets'
|
||||
import { usePreferredDark } from '@vueuse/core'
|
||||
import { cloneDeep } from 'lodash-es'
|
||||
import { darkTheme, lightTheme } from 'naive-ui'
|
||||
import { getDefaultSettingConfig, normalizeLayoutConfig } from './constant'
|
||||
import { createPreferenceFile, parsePreferenceFile } from './preference-file'
|
||||
import { primaryButtonColors } from './primary-button-colors'
|
||||
|
||||
export const piniaSettingStore = defineStore(
|
||||
'setting',
|
||||
@ -90,12 +92,26 @@ export const piniaSettingStore = defineStore(
|
||||
style === 'modern'
|
||||
? APP_THEME.appNaiveUIThemeOverrides[mode]
|
||||
: themeStyleOverrides[style][mode]
|
||||
const accent = settingState.primaryColorOverride.common
|
||||
const surface =
|
||||
preset.common?.cardColor ??
|
||||
(mode === 'dark' ? darkTheme : lightTheme).common.cardColor
|
||||
|
||||
return {
|
||||
...preset,
|
||||
...(accent?.primaryColor && {
|
||||
Button: {
|
||||
...preset.Button,
|
||||
...primaryButtonColors(
|
||||
accent.primaryColor,
|
||||
accent.primaryColorHover ?? accent.primaryColor,
|
||||
surface,
|
||||
),
|
||||
},
|
||||
}),
|
||||
common: {
|
||||
...preset.common,
|
||||
...settingState.primaryColorOverride.common,
|
||||
...accent,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
@ -0,0 +1,64 @@
|
||||
/**
|
||||
*
|
||||
* @param primary 用户选择的主色
|
||||
* @param hover 悬停与聚焦状态的主色
|
||||
* @param surface 当前风格和明暗模式的卡片底色
|
||||
*
|
||||
* @description
|
||||
* 用浏览器解析 CSS 颜色,并把半透明填充合成在主题底色上。按钮使用同一不透明色,
|
||||
* 使文字对比度不受按钮下方实际页面内容影响。
|
||||
*/
|
||||
export function primaryButtonColors(
|
||||
primary: string,
|
||||
hover: string,
|
||||
surface: string,
|
||||
) {
|
||||
const canvas = document.createElement('canvas')
|
||||
|
||||
canvas.width = 2
|
||||
canvas.height = 1
|
||||
const context = canvas.getContext('2d')
|
||||
|
||||
if (!context) return
|
||||
|
||||
context.fillStyle = surface
|
||||
context.fillRect(0, 0, 2, 1)
|
||||
|
||||
for (const [index, color] of [primary, hover].entries()) {
|
||||
context.fillStyle = color
|
||||
context.fillRect(index, 0, 1, 1)
|
||||
}
|
||||
|
||||
const pixels = context.getImageData(0, 0, 2, 1).data
|
||||
const colors = (index: number) => {
|
||||
const rgb = Array.from(pixels.slice(index, index + 3))
|
||||
const [r, g, b] = rgb.map((byte) => {
|
||||
const channel = byte / 255
|
||||
|
||||
return channel <= 0.04045
|
||||
? channel / 12.92
|
||||
: ((channel + 0.055) / 1.055) ** 2.4
|
||||
})
|
||||
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)
|
||||
|
||||
return {
|
||||
fill: `rgb(${rgb.join(', ')})`,
|
||||
text: blackContrast >= whiteContrast ? '#000' : '#fff',
|
||||
}
|
||||
}
|
||||
const normal = colors(0)
|
||||
const active = colors(4)
|
||||
|
||||
return {
|
||||
colorPrimary: normal.fill,
|
||||
colorPressedPrimary: normal.fill,
|
||||
colorHoverPrimary: active.fill,
|
||||
colorFocusPrimary: active.fill,
|
||||
textColorPrimary: normal.text,
|
||||
textColorPressedPrimary: normal.text,
|
||||
textColorHoverPrimary: active.text,
|
||||
textColorFocusPrimary: active.text,
|
||||
}
|
||||
}
|
||||
@ -135,7 +135,7 @@ export default defineComponent({
|
||||
attrType="button"
|
||||
disabled={loading.value}
|
||||
onClick={() => {
|
||||
signingForm.name = 'Ray Admin'
|
||||
signingForm.name = 'user001'
|
||||
signingForm.pwd = '123456'
|
||||
void handleLogin()
|
||||
}}
|
||||
@ -148,7 +148,8 @@ export default defineComponent({
|
||||
secondary
|
||||
disabled={loading.value}
|
||||
onClick={() => {
|
||||
signingForm.name = role
|
||||
signingForm.name =
|
||||
role === 'manager' ? 'user011' : 'user002'
|
||||
signingForm.pwd = '123456'
|
||||
void handleLogin()
|
||||
}}
|
||||
|
||||
@ -1,11 +1,14 @@
|
||||
import './index.scss'
|
||||
import { AdminApiError } from '@/api/admin/client'
|
||||
import AppPageHeader from '@/app-components/app/AppPageHeader'
|
||||
import { useAccess, useI18n } from '@/hooks'
|
||||
import { useI18n } from '@/hooks'
|
||||
import { getStaticAppRoutes } from '@/router/app-route-modules'
|
||||
import { exportRouteConfig, parseRouteConfig } from '@/router/config/contract'
|
||||
import type { RouteConfig } from '@/router/config/schema'
|
||||
import {
|
||||
fetchRemoteRouteConfig,
|
||||
activateRemoteRouteSource,
|
||||
readRouteEditorSnapshot,
|
||||
remoteRoutesReadOnly,
|
||||
remoteRouteUrl,
|
||||
routeSourceStatus,
|
||||
saveRemoteRouteConfig,
|
||||
@ -33,7 +36,8 @@ export default defineComponent({
|
||||
name: 'RouteManagement',
|
||||
setup() {
|
||||
const { t } = useI18n('routeManagement')
|
||||
const { hasPermission } = useAccess()
|
||||
let revision: string | undefined
|
||||
const remoteReady = ref(false)
|
||||
const source = ref<RouteSource>(routeSourceStatus.requested)
|
||||
const draft = ref('')
|
||||
const checked = shallowRef<RouteConfig>()
|
||||
@ -53,7 +57,12 @@ export default defineComponent({
|
||||
|
||||
const report = (reason: unknown) => {
|
||||
checked.value = void 0
|
||||
error.value = reason instanceof Error ? reason.message : String(reason)
|
||||
error.value =
|
||||
reason instanceof AdminApiError && reason.key === 'editConflict'
|
||||
? t('editConflict')
|
||||
: reason instanceof Error
|
||||
? reason.message
|
||||
: String(reason)
|
||||
}
|
||||
const setDraft = (config: RouteConfig) => {
|
||||
draft.value = JSON.stringify(config, null, 2)
|
||||
@ -80,6 +89,11 @@ export default defineComponent({
|
||||
report(reason)
|
||||
}
|
||||
}
|
||||
const selectDraftSource = () => {
|
||||
if (remoteRoutesReadOnly && source.value !== 'local')
|
||||
source.value = 'local'
|
||||
else if (source.value === 'static') source.value = 'remote'
|
||||
}
|
||||
const addPage = (event: Event) => {
|
||||
event.preventDefault()
|
||||
const config = validate()
|
||||
@ -101,7 +115,7 @@ export default defineComponent({
|
||||
newPage.path = ''
|
||||
newPage.title = ''
|
||||
|
||||
if (source.value === 'static') source.value = 'remote'
|
||||
selectDraftSource()
|
||||
} catch (reason) {
|
||||
report(reason)
|
||||
}
|
||||
@ -118,7 +132,7 @@ export default defineComponent({
|
||||
|
||||
draft.value = await selected.text()
|
||||
|
||||
if (source.value === 'static') source.value = 'remote'
|
||||
selectDraftSource()
|
||||
|
||||
validate()
|
||||
} catch (reason) {
|
||||
@ -127,15 +141,17 @@ export default defineComponent({
|
||||
input.value = ''
|
||||
}
|
||||
}
|
||||
const loadRemote = async () => {
|
||||
const loadRemote = async (useDraft = true) => {
|
||||
remoteReady.value = false
|
||||
busy.value = true
|
||||
|
||||
try {
|
||||
setDraft(
|
||||
await fetchRemoteRouteConfig(
|
||||
hasPermission('routes:write') ? 'editor' : void 0,
|
||||
),
|
||||
)
|
||||
const snapshot = await readRouteEditorSnapshot()
|
||||
|
||||
revision = snapshot.revision
|
||||
remoteReady.value = true
|
||||
|
||||
if (useDraft) setDraft(snapshot.config)
|
||||
} catch (reason) {
|
||||
report(reason)
|
||||
} finally {
|
||||
@ -144,12 +160,29 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
if (routeSourceStatus.active === 'remote') void loadRemote()
|
||||
else if (routeSourceStatus.config) setDraft(routeSourceStatus.config)
|
||||
else loadStatic()
|
||||
else {
|
||||
if (routeSourceStatus.config) setDraft(routeSourceStatus.config)
|
||||
else loadStatic()
|
||||
|
||||
if (!remoteRoutesReadOnly) void loadRemote(false)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const config = source.value !== 'static' ? validate() : void 0
|
||||
|
||||
if (source.value !== 'static' && !config) return
|
||||
@ -158,7 +191,7 @@ export default defineComponent({
|
||||
busy.value = true
|
||||
|
||||
if (source.value === 'remote' && config)
|
||||
await saveRemoteRouteConfig(config)
|
||||
await saveRemoteRouteConfig(config, revision)
|
||||
else saveRouteSource(source.value, config)
|
||||
} catch (reason) {
|
||||
report(reason)
|
||||
@ -233,13 +266,26 @@ export default defineComponent({
|
||||
type="primary"
|
||||
onClick={apply}
|
||||
disabled={
|
||||
busy.value || (source.value === 'remote' && !remoteRouteUrl)
|
||||
busy.value ||
|
||||
(source.value === 'remote' &&
|
||||
(!remoteRouteUrl ||
|
||||
(!remoteRoutesReadOnly && !remoteReady.value)))
|
||||
}
|
||||
>
|
||||
{t('apply')}
|
||||
{t(
|
||||
source.value === 'remote' && remoteRoutesReadOnly
|
||||
? 'activateRemote'
|
||||
: 'apply',
|
||||
)}
|
||||
</NButton>
|
||||
</NFlex>
|
||||
<p class="route-management__hint">{t(`${source.value}Hint`)}</p>
|
||||
<p class="route-management__hint">
|
||||
{t(
|
||||
source.value === 'remote' && remoteRoutesReadOnly
|
||||
? 'readOnlyHint'
|
||||
: `${source.value}Hint`,
|
||||
)}
|
||||
</p>
|
||||
{remoteRouteUrl && (
|
||||
<code class="route-management__endpoint">{remoteRouteUrl}</code>
|
||||
)}
|
||||
@ -252,7 +298,11 @@ export default defineComponent({
|
||||
{t('loadStatic')}
|
||||
</NButton>
|
||||
{remoteRouteUrl && (
|
||||
<NButton size="small" loading={busy.value} onClick={loadRemote}>
|
||||
<NButton
|
||||
size="small"
|
||||
loading={busy.value}
|
||||
onClick={() => void loadRemote()}
|
||||
>
|
||||
{t('loadRemote')}
|
||||
</NButton>
|
||||
)}
|
||||
@ -335,6 +385,7 @@ export default defineComponent({
|
||||
}}
|
||||
onUpdateValue={(value) => {
|
||||
draft.value = value
|
||||
selectDraftSource()
|
||||
checked.value = void 0
|
||||
error.value = ''
|
||||
}}
|
||||
|
||||
@ -1,11 +1,13 @@
|
||||
import './index.scss'
|
||||
import { AdminApiError } from '@/api/admin/client'
|
||||
import AppPageHeader from '@/app-components/app/AppPageHeader'
|
||||
import { useAccess, useI18n } from '@/hooks'
|
||||
import { getStaticAppRoutes } from '@/router/app-route-modules'
|
||||
import { exportRouteConfig, parseRouteConfig } from '@/router/config/contract'
|
||||
import type { RouteConfigRecord } from '@/router/config/schema'
|
||||
import {
|
||||
fetchRemoteRouteConfig,
|
||||
readRouteEditorSnapshot,
|
||||
remoteRoutesReadOnly,
|
||||
routeSourceStatus,
|
||||
saveRemoteRouteConfig,
|
||||
} from '@/router/config/source'
|
||||
@ -49,6 +51,8 @@ export default defineComponent({
|
||||
const { hasPermission } = useAccess()
|
||||
const saving = ref(false)
|
||||
const loading = ref(false)
|
||||
let revision: string | undefined
|
||||
const remoteReady = ref(false)
|
||||
const loaded = ref(false)
|
||||
const text = (key: string) => t<string>(key)
|
||||
const { t: translate } = useI18n()
|
||||
@ -102,26 +106,36 @@ export default defineComponent({
|
||||
valid.value = false
|
||||
}
|
||||
const report = (reason: unknown) => {
|
||||
error.value = reason instanceof Error ? reason.message : String(reason)
|
||||
error.value =
|
||||
reason instanceof AdminApiError && reason.key === 'editConflict'
|
||||
? text('editConflict')
|
||||
: reason instanceof Error
|
||||
? reason.message
|
||||
: String(reason)
|
||||
valid.value = false
|
||||
}
|
||||
const load = async () => {
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
remoteReady.value = false
|
||||
const activeRemote = routeSourceStatus.active === 'remote'
|
||||
const snapshot = activeRemote ? await readRouteEditorSnapshot() : void 0
|
||||
const config =
|
||||
routeSourceStatus.active === 'remote'
|
||||
? await fetchRemoteRouteConfig(
|
||||
hasPermission('routes:write') ? 'editor' : void 0,
|
||||
)
|
||||
: (routeSourceStatus.config ??
|
||||
exportRouteConfig(getStaticAppRoutes()))
|
||||
snapshot?.config ??
|
||||
routeSourceStatus.config ??
|
||||
exportRouteConfig(getStaticAppRoutes())
|
||||
|
||||
records.value = orderRoutes(structuredClone(config.routes))
|
||||
selected.value = tree.value.options[0]?.key as number | undefined
|
||||
expanded.value = []
|
||||
clearResult()
|
||||
loaded.value = true
|
||||
|
||||
if (!remoteRoutesReadOnly) {
|
||||
revision = (snapshot ?? (await readRouteEditorSnapshot())).revision
|
||||
remoteReady.value = true
|
||||
}
|
||||
} catch (reason) {
|
||||
report(reason)
|
||||
} finally {
|
||||
@ -148,6 +162,7 @@ export default defineComponent({
|
||||
}
|
||||
const apply = async () => {
|
||||
if (
|
||||
!remoteReady.value ||
|
||||
!loaded.value ||
|
||||
loading.value ||
|
||||
saving.value ||
|
||||
@ -161,7 +176,7 @@ export default defineComponent({
|
||||
|
||||
try {
|
||||
saving.value = true
|
||||
await saveRemoteRouteConfig(config)
|
||||
await saveRemoteRouteConfig(config, revision)
|
||||
} catch (reason) {
|
||||
report(reason)
|
||||
} finally {
|
||||
@ -361,14 +376,19 @@ export default defineComponent({
|
||||
</NAlert>
|
||||
)}
|
||||
<NCard title={text('visualDraft')}>
|
||||
<p class="route-management__hint">{text('visualHint')}</p>
|
||||
<p class="route-management__hint">
|
||||
{text(remoteRoutesReadOnly ? 'readOnlyHint' : 'visualHint')}
|
||||
</p>
|
||||
<NFlex align="center">
|
||||
<NButton
|
||||
type="primary"
|
||||
onClick={apply}
|
||||
loading={saving.value}
|
||||
disabled={
|
||||
!loaded.value || loading.value || !hasPermission('routes:write')
|
||||
!remoteReady.value ||
|
||||
!loaded.value ||
|
||||
loading.value ||
|
||||
!hasPermission('routes:write')
|
||||
}
|
||||
>
|
||||
{text('apply')}
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import { createUser, updateUser } from '@/api/admin'
|
||||
import { AdminApiError } from '@/api/admin/client'
|
||||
import type { AdminUser, UserInput, UserOptions } from '@/api/admin/contracts'
|
||||
import { useAccess, useI18n } from '@/hooks'
|
||||
import { RForm, useForm } from '@ray-template/ui/form'
|
||||
@ -16,6 +15,7 @@ import {
|
||||
} from 'naive-ui'
|
||||
import type { FormRules, InputInst } from 'naive-ui'
|
||||
import type { PropType } from 'vue'
|
||||
import { useUserErrorMessage } from './error-message'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'UserEditor',
|
||||
@ -23,11 +23,13 @@ export default defineComponent({
|
||||
user: { type: Object as PropType<AdminUser>, default: void 0 },
|
||||
options: { type: Object as PropType<UserOptions>, required: true },
|
||||
departmentId: { type: String, default: void 0 },
|
||||
revision: { type: String, default: void 0 },
|
||||
currentUserId: { type: String, default: void 0 },
|
||||
},
|
||||
emits: { close: () => true, saved: (_user: AdminUser) => true },
|
||||
setup(props, { emit }) {
|
||||
const { t } = useI18n('userManagement')
|
||||
const errorText = useUserErrorMessage()
|
||||
const { t: translate } = useI18n()
|
||||
const { hasPermission } = useAccess()
|
||||
const initial: UserInput = {
|
||||
@ -129,14 +131,12 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
const user = props.user
|
||||
? await updateUser(props.user.id, model.value)
|
||||
? await updateUser(props.user.id, model.value, props.revision)
|
||||
: await createUser(model.value)
|
||||
|
||||
emit('saved', user)
|
||||
} catch (reason) {
|
||||
error.value = t(
|
||||
`errors.${reason instanceof AdminApiError ? reason.key : 'requestFailed'}`,
|
||||
)
|
||||
error.value = errorText(reason)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
|
||||
17
apps/admin/src/views/user-management/error-message.ts
Normal file
17
apps/admin/src/views/user-management/error-message.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { AdminApiError, apiMockEnabled } from '@/api/admin/client'
|
||||
import { useI18n } from '@/hooks'
|
||||
|
||||
export function useUserErrorMessage() {
|
||||
const { t, te } = useI18n('userManagement')
|
||||
|
||||
return (reason: unknown) => {
|
||||
const key = reason instanceof AdminApiError ? reason.key : 'requestFailed'
|
||||
const message = key === 'storage' && !apiMockEnabled ? 'serverStorage' : key
|
||||
|
||||
return t(
|
||||
te?.(`userManagement.errors.${message}`)
|
||||
? `errors.${message}`
|
||||
: 'errors.requestFailed',
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -8,7 +8,7 @@ import {
|
||||
setUserCredential,
|
||||
updateUserStatus,
|
||||
} from '@/api/admin'
|
||||
import { AdminApiError, apiMockEnabled } from '@/api/admin/client'
|
||||
import { apiMockEnabled } from '@/api/admin/client'
|
||||
import type { AdminUser, UserOptions, UserStatus } from '@/api/admin/contracts'
|
||||
import AccountPasswordForm from '@/app-components/app/AccountPasswordForm'
|
||||
import AppPageHeader from '@/app-components/app/AppPageHeader'
|
||||
@ -40,6 +40,7 @@ import {
|
||||
NTree,
|
||||
} from 'naive-ui'
|
||||
import type { DataTableColumns, TreeOption } from 'naive-ui'
|
||||
import { useUserErrorMessage } from './error-message'
|
||||
import UserEditor from './UserEditor'
|
||||
|
||||
export default defineComponent({
|
||||
@ -77,6 +78,7 @@ export default defineComponent({
|
||||
const checked = ref<(string | number)[]>([])
|
||||
const editorOpen = ref(false)
|
||||
const editing = shallowRef<AdminUser>()
|
||||
const editingRevision = ref<string>()
|
||||
const details = shallowRef<AdminUser>()
|
||||
const credentialTarget = shallowRef<AdminUser>()
|
||||
const loadingUser = ref('')
|
||||
@ -84,10 +86,7 @@ export default defineComponent({
|
||||
const abort = new AbortController()
|
||||
|
||||
onScopeDispose(() => abort.abort())
|
||||
const errorText = (error: unknown) =>
|
||||
t(
|
||||
`errors.${error instanceof AdminApiError ? error.key : 'requestFailed'}`,
|
||||
)
|
||||
const errorText = useUserErrorMessage()
|
||||
const loadOptions = async () => {
|
||||
optionLoading.value = true
|
||||
optionError.value = false
|
||||
@ -199,7 +198,9 @@ export default defineComponent({
|
||||
loadingUser.value = id
|
||||
|
||||
try {
|
||||
const user = await getUser(id, abort.signal)
|
||||
const user = await getUser(id, abort.signal, (revision) => {
|
||||
if (edit) editingRevision.value = revision
|
||||
})
|
||||
|
||||
if (abort.signal.aborted) return
|
||||
|
||||
@ -554,6 +555,7 @@ export default defineComponent({
|
||||
{editorOpen.value && options.value && (
|
||||
<UserEditor
|
||||
user={editing.value}
|
||||
revision={editingRevision.value}
|
||||
options={options.value}
|
||||
departmentId={departmentId.value || void 0}
|
||||
currentUserId={getSigningCallback.value.id}
|
||||
|
||||
@ -24,7 +24,19 @@
|
||||
</template>
|
||||
<template #sidebar>
|
||||
<NLayoutSider :width="132" bordered>
|
||||
<NMenu :options="menu" :value="active" @update:value="navigate" />
|
||||
<nav
|
||||
class="r-shell-menu"
|
||||
:aria-label="copy.navigation"
|
||||
@keydown="keyboard.onKeydown"
|
||||
>
|
||||
<NMenu
|
||||
:options="menu"
|
||||
:value="active"
|
||||
:nodeProps="keyboard.nodeProps"
|
||||
:dropdownProps="keyboard.dropdownProps"
|
||||
@update:value="navigate"
|
||||
/>
|
||||
</nav>
|
||||
</NLayoutSider>
|
||||
</template>
|
||||
<template #tabs>
|
||||
@ -59,6 +71,7 @@ import {
|
||||
LayoutSettings,
|
||||
ShellTab,
|
||||
ShellTopNavigation,
|
||||
useMenuKeyboard,
|
||||
} from '@ray-template/admin-shell'
|
||||
import type { LayoutConfig } from '@ray-template/admin-shell'
|
||||
import { NButton, NLayoutSider, NMenu } from 'naive-ui'
|
||||
@ -66,6 +79,7 @@ import { computed, onMounted, ref } from 'vue'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import DemoFrame from './DemoFrame.vue'
|
||||
|
||||
const keyboard = useMenuKeyboard(false)
|
||||
const props = withDefaults(defineProps<{ locale?: 'zh-CN' | 'en' }>(), {
|
||||
locale: 'zh-CN',
|
||||
})
|
||||
|
||||
@ -33,7 +33,12 @@
|
||||
columnStateKey="docs-demo"
|
||||
autoHeight
|
||||
@register="register"
|
||||
/>
|
||||
>
|
||||
<template #error="{ reload: retry }">
|
||||
<p role="alert">{{ copy.failed }}</p>
|
||||
<NButton size="small" @click="retry()">{{ copy.retry }}</NButton>
|
||||
</template>
|
||||
</RTablePro>
|
||||
</div>
|
||||
</DemoFrame>
|
||||
</template>
|
||||
@ -59,6 +64,8 @@ const copy = computed(() =>
|
||||
remote: 'Simulated request',
|
||||
virtual: 'Virtual scroll',
|
||||
fail: 'Simulate a request failure',
|
||||
failed: 'The request failed. Try loading this page again.',
|
||||
retry: 'Retry',
|
||||
cancelled: 'Cancelled requests:',
|
||||
name: 'Name',
|
||||
searchName: 'Enter a name',
|
||||
@ -71,6 +78,8 @@ const copy = computed(() =>
|
||||
remote: '模拟远端查询',
|
||||
virtual: '虚拟滚动',
|
||||
fail: '模拟请求失败',
|
||||
failed: '请求失败,请重新加载当前页。',
|
||||
retry: '重试',
|
||||
cancelled: '已取消请求:',
|
||||
name: '姓名',
|
||||
searchName: '请输入姓名',
|
||||
|
||||
@ -11,7 +11,7 @@
|
||||
| Material | 紫色调、较大的圆角、胶囊按钮和分层表面 |
|
||||
| 朴素 | 中性灰、小圆角和无阴影表面 |
|
||||
|
||||
手动选择的主题色优先于预设,并随风格保留;点击「使用风格默认色」可恢复当前风格的配色。新用户、恢复默认设置,以及缺少风格的历史配置都使用现代化。已有的显式风格选择会在刷新和导入时保留。
|
||||
手动选择的主题色优先于预设,并随风格保留;点击「使用风格默认色」可恢复当前风格的配色。自定义主色的实心按钮会按各交互状态的实际填充色选择黑字或白字,半透明主色按当前主题卡片底色合成。新用户、恢复默认设置,以及缺少风格的历史配置都使用现代化。已有的显式风格选择会在刷新和导入时保留。
|
||||
|
||||
### 样式放在哪里
|
||||
|
||||
|
||||
@ -77,6 +77,8 @@ Redis 为 API、登录和改密提供跨进程限流,并缓存可重建的演
|
||||
}
|
||||
```
|
||||
|
||||
用户详情与完整路由配置(`view=editor`)的成功包络会携带不透明的 `revision`。编辑后保存到同一资源时,发送 `If-Match: "<revision>"`。如果读取后已有其他修改,API 返回 412 和 `editConflict`,编辑器保留草稿。请重新读取并核对差异,再提交。已有客户端仍可省略请求头执行完整替换。自有后端要返回修订值并在写入事务中核对它,才能提供同样的并发保护。
|
||||
|
||||
400 表示输入不合法,401 表示会话失效,403 表示权限不足,404 表示对象不存在,409 表示账号/邮箱冲突或当前账号保护,413 表示请求体过大,429 表示请求受到限流,503 表示存储或依赖暂时不可用(Mock 中包括演示数据库写入失败)。`error.key` 是稳定的业务错误标识;可选的 `error.fields` 为字段到错误键的映射。API 层把错误转换为 `AdminApiError`,用户页将已约定的错误键翻译为中英文提示。读取响应也会经过 Schema 校验。
|
||||
|
||||
## 登录、会话与权限
|
||||
|
||||
@ -16,6 +16,8 @@ import { withBase } from 'vitepress'
|
||||
<<< @/examples/ShellDemo.vue
|
||||
:::
|
||||
|
||||
菜单支持键盘操作。Tab 可聚焦菜单项,Enter 或空格展开分组或打开页面。侧栏用上下方向键移动焦点,顶部菜单用左右方向键。折叠侧栏和顶部菜单的子菜单可用方向键选择、Enter 打开、Esc 关闭。
|
||||
|
||||
## 配置工作区
|
||||
|
||||
```ts
|
||||
|
||||
@ -38,7 +38,7 @@ export function loadOrders(
|
||||
}
|
||||
```
|
||||
|
||||
默认取消器按 URL、方法、参数和请求体识别重复请求,默认布局在路由更新前取消受管理的请求。示例将信号交给 TablePro 管理,所以关闭模板的默认注入;否则默认取消器会替换调用方传入的 signal。后台任务禁用默认取消后,需要自行管理生命周期。
|
||||
默认取消器按 URL、方法、参数和请求体识别重复请求。`URLSearchParams` 比较编码后的参数序列,`FormData` 比较有序字段、文本值和文件实例。默认布局在路由更新前取消受管理的请求。调用方提供 `signal` 或设置 `cancelConfig.cancel: false` 时自行管理取消;示例中的信号由 TablePro 管理。
|
||||
|
||||
## 配置与拦截器
|
||||
|
||||
|
||||
@ -18,7 +18,7 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue'
|
||||
|
||||
## 在线编辑与接口接入
|
||||
|
||||
有 `routes:write` 权限时,可视化和 JSON 页面从编辑接口加载完整草稿,通过 `PUT /admin/route-config` 保存,随后刷新运行路由。Mock 写入会保存在当前浏览器,也可以切换本机或内置配置。标准后端模式以远端为准,读取失败时显示错误。
|
||||
有 `routes:write` 权限时,可视化和 JSON 页面从编辑接口加载完整草稿,通过 `PUT /admin/route-config` 保存,随后刷新运行路由。Mock 写入会保存在当前浏览器,也可以切换本机或内置配置。标准后端模式以远端为准,读取失败时显示错误。 若配置了只读的 `VITE_ROUTE_CONFIG_URL`,在 JSON 页面选择远程来源并点击“启用远程配置”即可恢复读取该地址。修改只读来源的草稿可以保存在本地或导出。
|
||||
|
||||
接口请求体为 `{ version: 1, routes: [...] }`,读取和写入响应都放在统一 `{ code, msg, data }` 包络的 `data` 中。`component` 必须是 `router/config/views.ts` 的注册 ID;新增前端页面先注册 ID,再由接口返回其路由记录。详见[服务端标准契约](./backend)。
|
||||
|
||||
|
||||
@ -789,7 +789,7 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[\\w-]+\\/[\\w-]+$",
|
||||
"pattern": "^[a-z][a-z0-9_-]*(\\/[a-z][a-z0-9_-]*)+$",
|
||||
"description": "IconName from src/icons/manifest.ts."
|
||||
},
|
||||
"role": {
|
||||
@ -878,7 +878,7 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[\\w-]+\\/[\\w-]+$"
|
||||
"pattern": "^[a-z][a-z0-9_-]*(\\/[a-z][a-z0-9_-]*)+$"
|
||||
},
|
||||
"show": {
|
||||
"type": "boolean"
|
||||
@ -1024,7 +1024,7 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[\\w-]+\\/[\\w-]+$",
|
||||
"pattern": "^[a-z][a-z0-9_-]*(\\/[a-z][a-z0-9_-]*)+$",
|
||||
"description": "IconName from src/icons/manifest.ts."
|
||||
},
|
||||
"role": {
|
||||
@ -1113,7 +1113,7 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[\\w-]+\\/[\\w-]+$"
|
||||
"pattern": "^[a-z][a-z0-9_-]*(\\/[a-z][a-z0-9_-]*)+$"
|
||||
},
|
||||
"show": {
|
||||
"type": "boolean"
|
||||
@ -1961,6 +1961,9 @@
|
||||
"data": {
|
||||
"type": "null"
|
||||
},
|
||||
"revision": {
|
||||
"type": "string"
|
||||
},
|
||||
"error": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@ -3879,6 +3882,10 @@
|
||||
"msg": {
|
||||
"type": "string"
|
||||
},
|
||||
"revision": {
|
||||
"type": "string",
|
||||
"description": "Opaque edit revision. Route configuration includes it only for view=editor."
|
||||
},
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/RouteConfig"
|
||||
}
|
||||
@ -4001,6 +4008,17 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "If-Match",
|
||||
"in": "header",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Quoted revision from the editor read. A changed resource returns 412 editConflict."
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Success",
|
||||
@ -4078,6 +4096,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "See error.key for a stable machine-readable reason.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"413": {
|
||||
"description": "See error.key for a stable machine-readable reason.",
|
||||
"content": {
|
||||
@ -4751,6 +4779,10 @@
|
||||
"msg": {
|
||||
"type": "string"
|
||||
},
|
||||
"revision": {
|
||||
"type": "string",
|
||||
"description": "Opaque edit revision. Route configuration includes it only for view=editor."
|
||||
},
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/User"
|
||||
}
|
||||
@ -4863,6 +4895,17 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "If-Match",
|
||||
"in": "header",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Quoted revision from the editor read. A changed resource returns 412 editConflict."
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Success",
|
||||
@ -4940,6 +4983,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "See error.key for a stable machine-readable reason.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"413": {
|
||||
"description": "See error.key for a stable machine-readable reason.",
|
||||
"content": {
|
||||
|
||||
@ -45,6 +45,8 @@ export const renderOrderBarcode = (orderNo: string) => (
|
||||
| `watchText` | `true` | 文本变化时重绘。`format`、`options`(包括响应式嵌套字段)、尺寸和渲染介质变化也会自动重绘,无需更换 `key`。 |
|
||||
| `loading` | `false` | 控制 Spin;调用方负责开关。 |
|
||||
|
||||
例如 `responsive width="responsive" :height="48"` 会让宽度跟随容器,高度保持 48px。高度随容器变化时,请给父容器设置明确的高度。
|
||||
|
||||
`onSuccess(text, format, options)`、`onError(error)`、`onFinally()` 支持函数或回调数组。成功回调收到原始 options;组件响应式调整的条宽和条高不写回该对象。绘制异常通过 `onError` 通知,业务代码可据此提示或清理旧预览。
|
||||
|
||||
支持 `CODE39`、`CODE128` 及 `A/B/C` 变体、`EAN13/EAN8/EAN5/EAN2`、`UPC`、`ITF14/ITF`、`MSI/MSI10/MSI11/MSI1010/MSI1110`、`pharmacode`、`codabar`。使用 EAN 或 UPC 前验证输入长度和校验位。打印后是否可扫取决于设备和成品尺寸。
|
||||
|
||||
@ -6,6 +6,8 @@ import AdminExample from '../../examples/AdminExample.vue'
|
||||
|
||||
`RSegment` 用 Naive UI Tabs 的 `segment` 模式渲染选项。通过 `value` 和 `onUpdateValue`(或 `v-model:value`)切换业务状态,`defaultValue` 可提供非受控初值。页面内容由调用方根据值渲染。
|
||||
|
||||
分段器通过单选组向辅助技术描述选项。可用 `aria-label` 指定组名。Tab 进入当前选项,左右方向键切换并跳过禁用项,Home 和 End 选择首尾可用项。
|
||||
|
||||
| 属性 | 默认 | 说明 |
|
||||
| ---------------- | -------------- | --------------------------------------------------- |
|
||||
| `options` | `[]` | `RSegmentOptions[]`,每个选项的 `key` 需唯一。 |
|
||||
|
||||
@ -70,7 +70,7 @@ const countClick = () => {
|
||||
```
|
||||
|
||||
- `options.leading` / `trailing` 决定在等待周期首尾是否执行;防抖还可设 `maxWait`。挂载时读取绑定值,更新不会重绑。若回调依赖变动数据,让原函数在执行时读取响应式值。
|
||||
- 当前实现将监听器句柄保存在指令工厂闭包,多个绑定实例共用同一清理位置。需要同一指令同时绑多个元素或动态修改间隔时,在组件里单独创建防抖或节流函数并清理。
|
||||
- 同一指令可以绑定多个元素。每个元素独立计时,卸载时只清理自己的监听器和待执行回调。需要动态修改间隔时,可更换元素的 `key` 重新绑定。
|
||||
- 防抖和节流只约束事件触发,异步请求仍需独立处理取消、并发或幂等。
|
||||
|
||||
[防抖源码](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/debounce/index.ts) · [节流源码](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/throttle/index.ts)
|
||||
@ -103,7 +103,7 @@ const countClick = () => {
|
||||
|
||||
## v-disabled
|
||||
|
||||
接收布尔值并修改原生 `disabled` 属性和模板禁用样式。当前实现关闭禁用时仍会写入空的 `disabled` 属性,HTML 原生按钮将继续视为禁用。因此原生控件使用 `:disabled="busy"`,Naive UI 使用对应 `disabled` prop。对自定义控件,要同时处理指针、键盘与可访问状态;样式不能取代业务权限检查。
|
||||
原生表单控件使用布尔 `disabled` 属性。表单、容器和自定义控件的根元素使用 `inert`,禁用期间子树退出键盘焦点顺序,指针也无法操作。绑定值恢复为 `false` 后即可继续交互。组件库提供 `disabled` prop 时优先使用它。
|
||||
|
||||
[源码](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/disabled/index.ts)
|
||||
|
||||
|
||||
@ -32,10 +32,11 @@ export function useReportLayout() {
|
||||
|
||||
## useSpinning
|
||||
|
||||
| 返回方法 | 用途 |
|
||||
| ---------------------------- | ----------------------------------------------- |
|
||||
| `openSpin()` / `closeSpin()` | 开关布局内容区的加载动画,不改变应用全局 Spin。 |
|
||||
| `reload(wait?)` | 卸载当前内容后重新挂载,缺省等待 800ms。 |
|
||||
| 返回方法 | 用途 |
|
||||
| ---------------------------- | ------------------------------------------------------------ |
|
||||
| `openSpin()` / `closeSpin()` | 开关布局内容区的加载动画,不改变应用全局 Spin。 |
|
||||
| `reload(wait?)` | 重新挂载当前地址的页面,保留其他标签的缓存,缺省等待 800ms。 |
|
||||
| `reloadWorkspace(wait?)` | 重新挂载整个内容区,释放所有标签的页面实例。 |
|
||||
|
||||
内容区用细线进度与普通文本提示呈现加载;`openSpin` 持续超过 120ms 才显示,短操作不会闪烁,`reload` 则立即显示。只想表示请求未完成时调用 `openSpin`,并在 `finally` 用 `closeSpin` 关闭。`reload` 会丢失当前页面未持久化的本地状态;多次重载时,Runtime Store 只保留最后一次恢复计时。
|
||||
|
||||
|
||||
@ -37,7 +37,7 @@ export const readQuery = () => useVueRouter().router.currentRoute.value.query
|
||||
| target | 行为 |
|
||||
| --------------- | ----------------------------------------------------------------------------------------- |
|
||||
| 完整路径字符串 | 先用 Router 解析,保留动态路径、query 和 hash。未匹配或只匹配兜底路由时返回 `undefined`。 |
|
||||
| `AppMenuOption` | 按 `fullPath` 导航。 |
|
||||
| `AppMenuOption` | 按 `fullPath` 导航,保留参数与锚点;可用 `query` 覆盖同名参数。 |
|
||||
| 从 0 开始的整数 | 从当前菜单取项,遇到父菜单沿第一个子项查到叶子。菜单需要先初始化。 |
|
||||
|
||||
`NavigationToOptions.isPush` 默认 `true`;设为 `false` 使用 `router.replace`。`query` 可覆盖字符串路径中的同名查询参数。成功发起时返回 Router Promise。负数、小数、非有限数和越界索引不会导航;实际结果仍受路由守卫影响。
|
||||
@ -55,7 +55,9 @@ export function useTableNavigation() {
|
||||
}
|
||||
```
|
||||
|
||||
## useAppRoot(兼容接口)
|
||||
<span id="useapproot-兼容接口"></span>
|
||||
|
||||
## useAppRoot(兼容接口) {#useapproot}
|
||||
|
||||
此接口已废弃,仅为旧调用方保留历史偏好的读写。`getRootRoute`、`getRootPath`、`getRootName` 是计算引用,`setRootRoute({ name?, path? })` 合并更新该字段;它不再控制登录落点、标签保护或关闭全部后的导航,也没有启动时首页校验。空工作区固定使用 `/welcome`。新代码直接通过 Router 显式导航。
|
||||
|
||||
|
||||
@ -2,19 +2,20 @@
|
||||
|
||||
## Runtime Store
|
||||
|
||||
`useRuntimeGetters()` 提供只读 ref;`useRuntimeActions()` 返回 `setRuntimeState(key, value)`、`reloadContent(wait = 800)`。这些 UI 状态不持久化。
|
||||
`useRuntimeGetters()` 提供只读 ref;`useRuntimeActions()` 返回 `setRuntimeState(key, value)`、`reloadContent(wait = 800, path?)`。这些 UI 状态不持久化。
|
||||
|
||||
| 字段 | 默认 | 用途 |
|
||||
| ------------------------------ | ----------------- | ---------------------------------------------------------- |
|
||||
| `globalSpinning` | `false` | 全局 Spin。 |
|
||||
| `globalDrawerValue` | `false` | 窄屏菜单抽屉。 |
|
||||
| `globalMainLayoutLoad` | `true` | 默认布局是否挂载页面内容。 |
|
||||
| `refreshingPath` | `null` | 当前单页刷新的完整地址。 |
|
||||
| `layoutContentMaximize` | `false` | 工作区最大化。 |
|
||||
| `layoutContentMaximizeVersion` | `0` | 最大化状态变动序号,用于过滤过期回调,业务代码不直接更新。 |
|
||||
| `layoutContentSpinning` | `false` | 布局内容区 Spin。 |
|
||||
| `layoutContentMaximizeStyle` | `{ zIndex: 999 }` | 最大化的层级、背景、过渡样式。 |
|
||||
|
||||
`reloadContent` 暂时卸载当前内容并等待恢复;多次调用只保留最后一个计时,Store 卸载时清理计时。`useSpinning().reload()` 是同一动作。控制最大化时用 [useMaximize](../hooks/layout#usemaximize) 来保留回调和退出逻辑。全局 Spin 和内容 Spin 互相独立。
|
||||
`reloadContent` 传入当前完整地址时重新挂载该页面,省略地址时释放整个内容区的缓存实例。多次调用只保留最后一个计时,Store 卸载时清理计时。页面可调用 `useSpinning().reload()` 刷新当前页,或调用 `reloadWorkspace()` 刷新整工作区。控制最大化时用 [useMaximize](../hooks/layout#usemaximize) 来保留回调和退出逻辑。全局 Spin 和内容 Spin 互相独立。
|
||||
|
||||
```ts
|
||||
import { useRuntimeActions } from '@/store'
|
||||
|
||||
@ -2,14 +2,15 @@
|
||||
|
||||
`useSigningGetters().getSigningCallback` 返回会话用户资料,主要字段为 `id`、`username`、`name`、`role`、`avatar?`。`getPermissions` 返回当前会话的权限码;前端菜单与操作分别消费角色和权限,后端独立检查业务请求。
|
||||
|
||||
| 方法 | 行为 |
|
||||
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `signing({ name, pwd })` | 调用标准登录接口,保存返回的 token、资料与权限。为兼容组件调用,动作成功仍返回 `{ code: 0, data, message }`;错误拒绝。HTTP 接口本身使用标准 `{ code: 200, msg, data }` 包络。 |
|
||||
| `restoreSession()` | 启动时重新读取用户资料与权限,401 清除失效会话;网络或协议错误拒绝,不沿用旧权限。 |
|
||||
| `clearSigningCallback(toSigning)` | 清理当前应用登录、菜单与 Session Storage,关闭标签;`true` 时回登录页并刷新。 |
|
||||
| `logout()` | 先请求服务端注销,再清理本地会话。 |
|
||||
| 方法 | 行为 |
|
||||
| ------------------------ | ---------------------------------------------------------------------------------------------------------- |
|
||||
| `signing({ name, pwd })` | 登录成功后将资料和权限写入 Store,返回 `Promise<void>`。调用方通过 getters 读取资料。失败时 Promise 拒绝。 |
|
||||
| `restoreSession()` | 从会话接口恢复资料与权限。收到 401 时清理失效会话,其他请求错误向调用方抛出。 |
|
||||
| `clearSigningCallback()` | 清理当前应用的登录和路由状态、锁屏信息及菜单标签缓存,保留当前地址。 |
|
||||
| `endSession(redirect?)` | 清理本地会话,通知其他标签页,并导航到登录页。可选参数用于下次登录后返回原页。 |
|
||||
| `logout(redirect?)` | 请求服务端注销。成功或收到 401 后执行 `endSession`,其他请求错误向调用方抛出。 |
|
||||
|
||||
Pinia 仅持久化用户资料;权限由会话接口刷新。搜索收藏和最近访问按稳定用户 id 隔离,旧的演示资料没有 id 时才使用名称。接口输入、输出和真实后端接入见[服务端契约](../../guide/backend)。
|
||||
用户资料和权限保存在内存。刷新后由会话接口重新取得。Bearer 模式将访问令牌存入当前应用的本地存储,Cookie 模式由浏览器管理会话凭据。搜索收藏和最近访问按账号隔离。接口定义见[服务端契约](../../guide/backend)。
|
||||
|
||||
```ts
|
||||
import { useSigningActions, useSigningGetters } from '@/store'
|
||||
@ -22,6 +23,6 @@ export function useAccountMenu() {
|
||||
}
|
||||
```
|
||||
|
||||
退出会清理当前来源的 Session Storage。多个业务共用同一来源时,接入方应明确其清理范围。动作还依赖已经挂载的消息 Provider 和 Router;从用户操作或已初始化的应用流程触发。
|
||||
退出只移除本应用使用的会话和缓存键。同一来源中其他业务的 Session Storage 条目会保留。
|
||||
|
||||
[Signing 实现](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/signing/index.ts) · [类型](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/signing/types.ts) · [演示登录](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/views/login/components/Signing/index.tsx) · [权限守卫](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/router/utils/permission.ts)
|
||||
|
||||
@ -92,7 +92,8 @@ const renderRemote = () => (
|
||||
|
||||
- `initialValues` 优先于字段的 `initialValue`。默认条件参与首查,重置恢复默认并重新查询。字段配置 `rules` 后,查询按钮和 `submitSearch()` 会校验,失败保留上次结果。重置会清理校验提示并应用默认值。空值、空白文本和空数组省略,`0` 和 `false` 保留。
|
||||
- `transform(value, values)` 返回请求参数片段。例如日期区间可返回 `{ createdFrom, createdTo }`,原字段不再进入参数。本地匹配仍使用字段值。列表请求按外部 `params`、转换后的搜索参数、表格的 `page` 和 `pageSize` 合并,提交回到第 1 页,分页和重试沿用已提交的条件。
|
||||
- `onSearch` 接收 `{ values, params, reason }`,`reason` 为 `submit` 或 `reset`。使用对象式 `search` 与 `remote + data + pagination` 时,可在事件中自行取数并控制页码和总数。搜索回调抛错会触发 `onSearchError`,并保留上次有效条件;本地默认字段读取支持 `customer.name` 等路径,`getValue` 优先。动态替换字段的匹配、读取、转换或可见规则时,仍兼容的条件会按新规则重新计算。
|
||||
- 处理字段时,`visible`、`transform`、`getValue` 或 `matches` 抛错会触发 `onSearchError`,本次提交保留上次有效条件。本地字段读取支持 `customer.name` 等路径,优先使用 `getValue`。动态替换字段规则时,仍兼容的条件会按新规则重新计算。
|
||||
- 条件应用后,`onSearch` 接收 `{ values, params, reason }`,`reason` 为 `submit` 或 `reset`。在手动远端模式下,可在该事件中取数并管理页码和总数。监听器抛出的异常进入 Vue 的事件错误处理,已应用的条件会保留。调用方负责显示请求错误和提供重试。
|
||||
- 实例和 `useTablePro()` 都提供 `getSearchValues('draft' | 'applied')`、`setSearchValues(patch)`、`submitSearch()`、`resetSearch()`。读取默认是草稿。提交和重置返回 `Promise<boolean>`,表示是否成功应用条件。设 `submitMode: 'change'` 可在编辑时防抖提交,`debounce` 默认 300 ms。
|
||||
|
||||
### 远程选项、联动和布局
|
||||
|
||||
@ -24,7 +24,7 @@ The runtime route configuration requires an active session and filters by `route
|
||||
|
||||
When `DEMO_ENABLED=true`, public `/admin/demo/*` endpoints use the same fixtures as Mock. Redis caches only fixed request and chart fixtures and the two search-option locales for five minutes. Demos default to off in production.
|
||||
|
||||
Usernames and email addresses have normalized unique database keys. Department queries include descendants. Bulk updates and deletion are atomic, deduplicate IDs, and reject changes to missing/protected targets. A user cannot delete or disable their own account or change their own role. Non-admin actors cannot manage roles with permissions they do not hold.
|
||||
Usernames and email addresses have normalized unique database keys. Editor reads for users and the full route configuration return an opaque envelope revision and ETag. Both editors send it in `If-Match`; stale replacements return 412 `editConflict` from the write transaction. Clients that omit the header retain unconditional PUT semantics. Department queries include descendants. Bulk updates and deletion are atomic, deduplicate IDs, and reject changes to missing/protected targets. A user cannot delete or disable their own account or change their own role. Non-admin actors cannot manage roles with permissions they do not hold.
|
||||
|
||||
Authentication verifies the JWT signature, issuer, audience and expiry, then checks the token digest and live account grants in PostgreSQL. Passwords use salted scrypt. Logout revokes the current session; password changes, credential reset, account disabling and role changes revoke all affected sessions. The upgrade requires existing opaque-token clients to sign in again. Audits omit passwords, tokens and request bodies.
|
||||
|
||||
|
||||
@ -70,11 +70,18 @@ export class EnvelopeInterceptor implements NestInterceptor {
|
||||
response.status(200)
|
||||
|
||||
return next.handle().pipe(
|
||||
map((data: unknown): ApiResponse<unknown> => ({
|
||||
code: 200,
|
||||
msg: 'OK',
|
||||
data: data ?? null,
|
||||
})),
|
||||
map((data: unknown): ApiResponse<unknown> => {
|
||||
const revision: string | undefined = response.locals.editRevision
|
||||
|
||||
if (revision) response.setHeader('ETag', `"${revision}"`)
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
msg: 'OK',
|
||||
data: data ?? null,
|
||||
...(revision ? { revision } : {}),
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,17 @@
|
||||
import { Body, Controller, Get, Inject, Put, Query, Req } from '@nestjs/common'
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Inject,
|
||||
Put,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
} from '@nestjs/common'
|
||||
import { editRevision } from '@ray-template/api-contracts/admin'
|
||||
import { filterRuntimeRoutes } from '@ray-template/api-contracts/routes'
|
||||
import { parseApplicationRoutes } from '@ray-template/demo-data'
|
||||
import type { Request } from 'express'
|
||||
import type { Request, Response } from 'express'
|
||||
import { SERVER_CONFIG } from '../../config'
|
||||
import type { Prisma } from '../../generated/prisma/client'
|
||||
import { ApiError, requestIdFrom, tokenFrom } from '../../http'
|
||||
@ -23,6 +33,7 @@ export class RoutesController {
|
||||
async get(
|
||||
@Req() request: AuthenticatedRequest,
|
||||
@Query('view') view: unknown,
|
||||
@Res({ passthrough: true }) response: Response,
|
||||
) {
|
||||
if (view !== void 0 && view !== 'editor') throw new ApiError(400, 'invalid')
|
||||
|
||||
@ -40,13 +51,17 @@ export class RoutesController {
|
||||
try {
|
||||
const routes = parseApplicationRoutes(JSON.stringify(record.config))
|
||||
|
||||
return view === 'editor'
|
||||
? routes
|
||||
: filterRuntimeRoutes(routes, {
|
||||
role: session.user.role,
|
||||
permissions: session.permissions,
|
||||
demoEnabled: this.config.demoEnabled,
|
||||
})
|
||||
if (view === 'editor') {
|
||||
response.locals.editRevision = await editRevision(routes)
|
||||
|
||||
return routes
|
||||
}
|
||||
|
||||
return filterRuntimeRoutes(routes, {
|
||||
role: session.user.role,
|
||||
permissions: session.permissions,
|
||||
demoEnabled: this.config.demoEnabled,
|
||||
})
|
||||
} catch {
|
||||
throw new ApiError(503, 'invalidRoutes')
|
||||
}
|
||||
@ -70,6 +85,21 @@ export class RoutesController {
|
||||
transaction,
|
||||
)
|
||||
|
||||
const ifMatch = request.get('If-Match')
|
||||
|
||||
if (ifMatch !== void 0) {
|
||||
const current = await transaction.routeConfig.findUnique({
|
||||
where: { id: 'admin' },
|
||||
})
|
||||
|
||||
if (
|
||||
!current ||
|
||||
ifMatch !==
|
||||
`"${await editRevision(parseApplicationRoutes(JSON.stringify(current.config)))}"`
|
||||
)
|
||||
throw new ApiError(412, 'editConflict')
|
||||
}
|
||||
|
||||
await transaction.routeConfig.upsert({
|
||||
where: { id: 'admin' },
|
||||
create: { id: 'admin', config: config as Prisma.InputJsonValue },
|
||||
|
||||
@ -9,8 +9,10 @@ import {
|
||||
Put,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
} from '@nestjs/common'
|
||||
import type { Request } from 'express'
|
||||
import { editRevision } from '@ray-template/api-contracts/admin'
|
||||
import type { Request, Response } from 'express'
|
||||
import { queryInput, requestIdFrom, tokenFrom } from '../../http'
|
||||
import { authFrom, RequirePermission } from '../auth/auth.guard'
|
||||
import type { AuthenticatedRequest } from '../auth/auth.guard'
|
||||
@ -34,8 +36,15 @@ export class UsersController {
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('users:read')
|
||||
get(@Param('id') id: string) {
|
||||
return this.users.get(id)
|
||||
async get(
|
||||
@Param('id') id: string,
|
||||
@Res({ passthrough: true }) response: Response,
|
||||
) {
|
||||
const user = await this.users.get(id)
|
||||
|
||||
response.locals.editRevision = await editRevision(user)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ -56,6 +65,7 @@ export class UsersController {
|
||||
tokenFrom(request),
|
||||
requestIdFrom(request),
|
||||
id,
|
||||
request.get('If-Match'),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { Inject, Injectable } from '@nestjs/common'
|
||||
import {
|
||||
credentialInputSchema,
|
||||
editRevision,
|
||||
idsSchema,
|
||||
statusInputSchema,
|
||||
userInputSchema,
|
||||
@ -190,6 +191,7 @@ export class UsersService {
|
||||
token: string | null,
|
||||
requestId: string | null,
|
||||
id?: string,
|
||||
ifMatch?: string,
|
||||
) {
|
||||
const value = parseInput(userInputSchema, input)
|
||||
|
||||
@ -204,6 +206,13 @@ export class UsersService {
|
||||
if (existing)
|
||||
await this.assertManageRole(transaction, session, existing.role)
|
||||
|
||||
if (
|
||||
existing &&
|
||||
ifMatch !== void 0 &&
|
||||
ifMatch !== `"${await editRevision(userView(existing))}"`
|
||||
)
|
||||
throw new ApiError(412, 'editConflict')
|
||||
|
||||
await this.assertManageRole(transaction, session, value.role)
|
||||
|
||||
if (
|
||||
|
||||
@ -142,7 +142,7 @@ export class PlatformRuntime {
|
||||
response.setHeader('Access-Control-Allow-Origin', origin)
|
||||
response.setHeader(
|
||||
'Access-Control-Expose-Headers',
|
||||
'X-Request-Id, Retry-After',
|
||||
'ETag, X-Request-Id, Retry-After',
|
||||
)
|
||||
}
|
||||
|
||||
@ -153,7 +153,7 @@ export class PlatformRuntime {
|
||||
)
|
||||
response.setHeader(
|
||||
'Access-Control-Allow-Headers',
|
||||
'Authorization, Content-Type, X-Request-Id',
|
||||
'Authorization, Content-Type, If-Match, X-Request-Id',
|
||||
)
|
||||
response.setHeader('Access-Control-Max-Age', '600')
|
||||
response.status(204).end()
|
||||
|
||||
@ -1138,3 +1138,75 @@ test('disabling demos hides runtime routes and endpoints without dropping editab
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test('rejects stale user and route editor replacements in their write transactions', async () => {
|
||||
const admin = await create('revision-admin', { role: 'admin' })
|
||||
|
||||
await setPassword(database, admin.username, password)
|
||||
const otherToken = (await login(admin.username)).accessToken
|
||||
const user = await create('revision-target')
|
||||
const row = await request<AdminUser>(`admin/users/${user.id}`, {
|
||||
token: adminToken,
|
||||
})
|
||||
|
||||
assert.ok(row.body.revision)
|
||||
const disabled = await request('admin/users/status', {
|
||||
method: 'PATCH',
|
||||
token: otherToken,
|
||||
body: { ids: [user.id], status: 'disabled' },
|
||||
})
|
||||
|
||||
assert.equal(disabled.status, 200)
|
||||
const stale = await request(`admin/users/${user.id}`, {
|
||||
method: 'PUT',
|
||||
token: adminToken,
|
||||
headers: { 'If-Match': `"${row.body.revision}"` },
|
||||
body: { ...row.body.data, name: 'Updated' },
|
||||
})
|
||||
|
||||
assert.equal(stale.status, 412)
|
||||
assert.equal(
|
||||
(await database.user.findUniqueOrThrow({ where: { id: user.id } })).status,
|
||||
'disabled',
|
||||
)
|
||||
|
||||
const remote = await request<RouteConfig>('admin/route-config?view=editor', {
|
||||
token: adminToken,
|
||||
})
|
||||
|
||||
assert.ok(remote.body.revision)
|
||||
const publish = (config: RouteConfig, token: string) =>
|
||||
request('admin/route-config', {
|
||||
method: 'PUT',
|
||||
token,
|
||||
headers: { 'If-Match': `"${remote.body.revision}"` },
|
||||
body: config,
|
||||
})
|
||||
|
||||
try {
|
||||
const results = await Promise.all([
|
||||
publish(
|
||||
{
|
||||
...remote.body.data,
|
||||
routes: [{ path: '/first', component: 'dashboard', meta: {} }],
|
||||
},
|
||||
adminToken,
|
||||
),
|
||||
publish(
|
||||
{
|
||||
...remote.body.data,
|
||||
routes: [{ path: '/second', component: 'dashboard', meta: {} }],
|
||||
},
|
||||
otherToken,
|
||||
),
|
||||
])
|
||||
|
||||
assert.deepEqual(results.map((result) => result.status).sort(), [200, 412])
|
||||
} finally {
|
||||
await request('admin/route-config', {
|
||||
method: 'PUT',
|
||||
token: adminToken,
|
||||
body: remote.body.data,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@ -15,11 +15,20 @@
|
||||
:exclude="getKeepAliveConfig.keepAliveExclude"
|
||||
>
|
||||
<Suspense>
|
||||
<Component :is="Component" :key="route.fullPath" />
|
||||
<component :is="frameFor(Component)" :key="route.fullPath">
|
||||
<component
|
||||
:is="Component"
|
||||
v-if="refreshingPath !== route.fullPath"
|
||||
/>
|
||||
</component>
|
||||
</Suspense>
|
||||
</KeepAlive>
|
||||
<Suspense v-else>
|
||||
<Component :is="Component" :key="route.fullPath" />
|
||||
<Component
|
||||
:is="Component"
|
||||
v-if="refreshingPath !== route.fullPath"
|
||||
:key="route.fullPath"
|
||||
/>
|
||||
</Suspense>
|
||||
</Transition>
|
||||
</template>
|
||||
@ -27,6 +36,8 @@
|
||||
</div>
|
||||
</template>
|
||||
<script lang="ts" setup>
|
||||
import { defineComponent } from 'vue'
|
||||
import type { ComponentOptions, Component as PageComponent, VNode } from 'vue'
|
||||
import { RouterView } from 'vue-router'
|
||||
import defaults from './transition-defaults'
|
||||
import type { TransitionProps } from './transition-types'
|
||||
@ -34,6 +45,28 @@ import type { TransitionProps } from './transition-types'
|
||||
defineOptions({
|
||||
name: 'RTransitionComponent',
|
||||
})
|
||||
// 缓存页面外层,以便刷新时单独卸载该地址的内容,并保留其它地址的实例。
|
||||
const frames = new WeakMap<PageComponent, PageComponent>()
|
||||
|
||||
function frameFor(page: VNode) {
|
||||
const type = page.type as PageComponent
|
||||
let frame = frames.get(type)
|
||||
|
||||
if (!frame) {
|
||||
frame = defineComponent({
|
||||
name:
|
||||
(type as ComponentOptions).name ?? (type as ComponentOptions).__name,
|
||||
setup:
|
||||
(_, { slots }) =>
|
||||
() =>
|
||||
slots.default?.()[0],
|
||||
})
|
||||
frames.set(type, frame)
|
||||
}
|
||||
|
||||
return frame
|
||||
}
|
||||
|
||||
withDefaults(
|
||||
defineProps<
|
||||
TransitionProps & {
|
||||
|
||||
@ -5,6 +5,7 @@ import { NMenu } from 'naive-ui'
|
||||
import type { MenuOption } from 'naive-ui'
|
||||
import { computed, defineComponent } from 'vue'
|
||||
import type { PropType } from 'vue'
|
||||
import { useMenuKeyboard } from './menu-keyboard'
|
||||
|
||||
export const ShellTopNavigation = defineComponent({
|
||||
name: 'ShellTopNavigation',
|
||||
@ -20,6 +21,7 @@ export const ShellTopNavigation = defineComponent({
|
||||
},
|
||||
},
|
||||
setup(props, { slots }) {
|
||||
const keyboard = useMenuKeyboard(true)
|
||||
const mixed = computed(() => props.grouped)
|
||||
const options = computed(() =>
|
||||
mixed.value
|
||||
@ -43,10 +45,16 @@ export const ShellTopNavigation = defineComponent({
|
||||
}
|
||||
|
||||
return () => (
|
||||
<nav class="r-layout-top-navigation" aria-label={props.label}>
|
||||
<nav
|
||||
class="r-layout-top-navigation r-shell-menu"
|
||||
aria-label={props.label}
|
||||
onKeydown={keyboard.onKeydown}
|
||||
>
|
||||
{slots.logo?.()}
|
||||
<NMenu
|
||||
mode="horizontal"
|
||||
nodeProps={keyboard.nodeProps}
|
||||
dropdownProps={keyboard.dropdownProps}
|
||||
responsive
|
||||
iconSize={props.iconSize}
|
||||
collapsedIconSize={props.iconSize}
|
||||
|
||||
@ -5,3 +5,4 @@ export { default as RouteTransition } from './RouteTransition.vue'
|
||||
export type * from './transition-types'
|
||||
export * from './TopNavigation'
|
||||
export * from './ShellTab'
|
||||
export * from './menu-keyboard'
|
||||
|
||||
113
packages/admin-shell/src/menu-keyboard.ts
Normal file
113
packages/admin-shell/src/menu-keyboard.ts
Normal file
@ -0,0 +1,113 @@
|
||||
import type { MenuProps } from 'naive-ui'
|
||||
|
||||
export function useMenuKeyboard(horizontal: boolean, collapsed = () => false) {
|
||||
let popup: HTMLElement | undefined
|
||||
const dropdownProps: NonNullable<MenuProps['dropdownProps']> = {
|
||||
delay: 0,
|
||||
'onUpdate:show': (show: boolean) => {
|
||||
if (!show) popup = void 0
|
||||
},
|
||||
}
|
||||
const nodeProps: NonNullable<MenuProps['nodeProps']> = (option) => ({
|
||||
tabindex: option.disabled ? -1 : 0,
|
||||
'aria-haspopup':
|
||||
option.children?.length && (horizontal || collapsed()) ? 'menu' : void 0,
|
||||
})
|
||||
const onKeydown = (event: KeyboardEvent) => {
|
||||
const item = event.target
|
||||
const menu = event.currentTarget
|
||||
|
||||
if (
|
||||
event.isComposing ||
|
||||
event.altKey ||
|
||||
event.metaKey ||
|
||||
event.ctrlKey ||
|
||||
!(menu instanceof HTMLElement) ||
|
||||
!(item instanceof HTMLElement) ||
|
||||
item.getAttribute('role') !== 'menuitem'
|
||||
)
|
||||
return
|
||||
|
||||
const control = item.firstElementChild
|
||||
|
||||
if (!(control instanceof HTMLElement)) return
|
||||
|
||||
if (popup === item) {
|
||||
// 下拉层已打开,方向键、Enter、Escape 均由 Naive UI 处理。
|
||||
if (event.key === 'Tab')
|
||||
item.parentElement?.dispatchEvent(new MouseEvent('mouseleave'))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const hasPopup = item.getAttribute('aria-haspopup') === 'menu'
|
||||
|
||||
if (
|
||||
event.key === 'Enter' ||
|
||||
event.key === ' ' ||
|
||||
(hasPopup && event.key === 'ArrowDown')
|
||||
) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
if (event.repeat) return
|
||||
|
||||
if (hasPopup) {
|
||||
// NMenu 的折叠和横向子菜单共用 hover 浮层,沿用同一触发节点和键盘选项。
|
||||
popup = item
|
||||
item.parentElement?.dispatchEvent(new MouseEvent('mouseenter'))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
control.click()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const group = item.parentElement
|
||||
|
||||
if (
|
||||
!horizontal &&
|
||||
group?.hasAttribute('aria-expanded') &&
|
||||
(event.key === 'ArrowRight' || event.key === 'ArrowLeft')
|
||||
) {
|
||||
if (
|
||||
(event.key === 'ArrowRight') !==
|
||||
(group.getAttribute('aria-expanded') === 'true')
|
||||
)
|
||||
control.click()
|
||||
|
||||
event.preventDefault()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const previous = horizontal ? 'ArrowLeft' : 'ArrowUp'
|
||||
const next = horizontal ? 'ArrowRight' : 'ArrowDown'
|
||||
|
||||
if (![previous, next, 'Home', 'End'].includes(event.key)) return
|
||||
|
||||
const items = Array.from(
|
||||
menu.querySelectorAll<HTMLElement>('[role="menuitem"][tabindex="0"]'),
|
||||
).filter(
|
||||
(node) => node.checkVisibility?.({ visibilityProperty: true }) !== false,
|
||||
)
|
||||
|
||||
if (!items.length) return
|
||||
|
||||
const index = items.indexOf(item)
|
||||
const target =
|
||||
event.key === 'Home'
|
||||
? 0
|
||||
: event.key === 'End'
|
||||
? items.length - 1
|
||||
: (index + (event.key === previous ? -1 : 1) + items.length) %
|
||||
items.length
|
||||
|
||||
event.preventDefault()
|
||||
items[target]?.focus()
|
||||
}
|
||||
|
||||
return { nodeProps, dropdownProps, onKeydown }
|
||||
}
|
||||
@ -1,3 +1,8 @@
|
||||
.r-shell-menu [role='menuitem'][tabindex]:focus-visible {
|
||||
outline: 2px solid var(--r-theme-primary-color);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.r-layout-full {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
|
||||
@ -4,4 +4,5 @@ export interface TransitionProps {
|
||||
transitionPropName?: string
|
||||
transitionMode?: BaseTransitionProps['mode']
|
||||
transitionAppear?: boolean
|
||||
refreshingPath?: string | null
|
||||
}
|
||||
|
||||
@ -125,12 +125,14 @@ export interface ApiResponse<T> {
|
||||
code: number
|
||||
msg: string
|
||||
data: T
|
||||
revision?: string
|
||||
error?: { key: string; fields?: Record<string, string> }
|
||||
}
|
||||
export const envelopeSchema = v.object({
|
||||
code: v.number(),
|
||||
msg: v.string(),
|
||||
data: v.unknown(),
|
||||
revision: v.optional(v.string()),
|
||||
error: v.optional(
|
||||
v.object({
|
||||
key: v.string(),
|
||||
@ -138,6 +140,21 @@ export const envelopeSchema = v.object({
|
||||
}),
|
||||
),
|
||||
})
|
||||
/**
|
||||
*
|
||||
* @param value 编辑接口返回的资源快照
|
||||
*
|
||||
* @returns 快照内容的 SHA-256 摘要,供条件写入核对版本。
|
||||
*/
|
||||
export async function editRevision(value: unknown): Promise<string> {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(value))
|
||||
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
||||
|
||||
return Array.from(new Uint8Array(digest), (byte) =>
|
||||
byte.toString(16).padStart(2, '0'),
|
||||
).join('')
|
||||
}
|
||||
|
||||
export const userListSchema = v.object({
|
||||
items: v.array(userSchema),
|
||||
total: v.pipe(v.number(), v.integer(), v.minValue(0)),
|
||||
|
||||
@ -98,6 +98,7 @@ export function getAdminOpenApi() {
|
||||
permission?: string,
|
||||
input?: string,
|
||||
publicEndpoint = false,
|
||||
editing?: 'read' | 'write',
|
||||
) => ({
|
||||
operationId: id,
|
||||
summary: id,
|
||||
@ -112,6 +113,20 @@ export function getAdminOpenApi() {
|
||||
...(input
|
||||
? { requestBody: { required: true, content: json(ref(input)) } }
|
||||
: {}),
|
||||
...(editing === 'write'
|
||||
? {
|
||||
parameters: [
|
||||
{
|
||||
name: 'If-Match',
|
||||
in: 'header',
|
||||
required: false,
|
||||
schema: { type: 'string' },
|
||||
description:
|
||||
'Quoted revision from the editor read. A changed resource returns 412 editConflict.',
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Success',
|
||||
@ -121,6 +136,15 @@ export function getAdminOpenApi() {
|
||||
properties: {
|
||||
code: { const: 200 },
|
||||
msg: { type: 'string' },
|
||||
...(editing === 'read'
|
||||
? {
|
||||
revision: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Opaque edit revision. Route configuration includes it only for view=editor.',
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
data: Array.isArray(result)
|
||||
? { anyOf: result.map(ref) }
|
||||
: result
|
||||
@ -130,7 +154,17 @@ export function getAdminOpenApi() {
|
||||
}),
|
||||
},
|
||||
...Object.fromEntries(
|
||||
[400, 401, 403, 404, 409, 413, 429, 503].map((status) => [
|
||||
[
|
||||
400,
|
||||
401,
|
||||
403,
|
||||
404,
|
||||
409,
|
||||
...(editing === 'write' ? [412] : []),
|
||||
413,
|
||||
429,
|
||||
503,
|
||||
].map((status) => [
|
||||
status,
|
||||
{
|
||||
description: 'See error.key for a stable machine-readable reason.',
|
||||
@ -285,7 +319,14 @@ export function getAdminOpenApi() {
|
||||
},
|
||||
'/admin/route-config': {
|
||||
get: {
|
||||
...operation('getRouteConfig', 'RouteConfig'),
|
||||
...operation(
|
||||
'getRouteConfig',
|
||||
'RouteConfig',
|
||||
void 0,
|
||||
void 0,
|
||||
false,
|
||||
'read',
|
||||
),
|
||||
description:
|
||||
'Authorized navigation snapshot for the current session; returns an empty routes array without routes:read. Request view=editor with routes:write to read the complete saved configuration.',
|
||||
parameters: [
|
||||
@ -302,6 +343,8 @@ export function getAdminOpenApi() {
|
||||
'RouteConfig',
|
||||
'routes:write',
|
||||
'RouteConfig',
|
||||
false,
|
||||
'write',
|
||||
),
|
||||
},
|
||||
'/admin/users/options': {
|
||||
@ -325,8 +368,15 @@ export function getAdminOpenApi() {
|
||||
},
|
||||
'/admin/users/{id}': {
|
||||
parameters: [pathId],
|
||||
get: operation('getUser', 'User', 'users:read'),
|
||||
put: operation('updateUser', 'User', 'users:update', 'UserInput'),
|
||||
get: operation('getUser', 'User', 'users:read', void 0, false, 'read'),
|
||||
put: operation(
|
||||
'updateUser',
|
||||
'User',
|
||||
'users:update',
|
||||
'UserInput',
|
||||
false,
|
||||
'write',
|
||||
),
|
||||
},
|
||||
'/admin/users/batch-delete': {
|
||||
post: operation('deleteUsers', 'Changed', 'users:delete', 'Ids'),
|
||||
|
||||
@ -3,7 +3,7 @@ import * as v from 'valibot'
|
||||
const text = v.pipe(v.string(), v.minLength(1), v.maxLength(256))
|
||||
const finiteNumber = v.pipe(v.number(), v.finite())
|
||||
const title = v.union([text, finiteNumber])
|
||||
const icon = v.pipe(text, v.regex(/^[\w-]+\/[\w-]+$/))
|
||||
const icon = v.pipe(text, v.regex(/^[a-z][a-z0-9_-]*(\/[a-z][a-z0-9_-]*)+$/))
|
||||
const segment = '(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)'
|
||||
const absolutePath = v.pipe(
|
||||
text,
|
||||
|
||||
@ -7,6 +7,8 @@ import type { CSSProperties } from 'vue'
|
||||
import type { BasicTarget } from './types'
|
||||
import { unrefElement } from './vue/unref-element'
|
||||
|
||||
export { navigateHorizontalChoice } from './keyboard-choice'
|
||||
|
||||
const classTokens = (names: string | string[]) =>
|
||||
(typeof names === 'string' ? [names] : names)
|
||||
.flatMap((name) => name.split(/[\t\n\f\r ]+/))
|
||||
|
||||
63
packages/composables/src/keyboard-choice.ts
Normal file
63
packages/composables/src/keyboard-choice.ts
Normal file
@ -0,0 +1,63 @@
|
||||
/**
|
||||
*
|
||||
* @param event 横向标签或单选项上的键盘事件
|
||||
* @param trigger 组件用于选中选项的原生事件
|
||||
*
|
||||
* @description
|
||||
* 在同组选项间循环移动焦点,复用鼠标选择路径以保留禁用状态及切换前校验。
|
||||
*/
|
||||
export function navigateHorizontalChoice(
|
||||
event: KeyboardEvent,
|
||||
trigger = 'click',
|
||||
) {
|
||||
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey)
|
||||
return
|
||||
|
||||
const current = event.currentTarget as HTMLElement
|
||||
const group = current.closest('[role="tablist"], [role="radiogroup"]')
|
||||
const role = current.getAttribute('role')
|
||||
|
||||
if (!group || (role !== 'tab' && role !== 'radio')) return
|
||||
|
||||
const choices = Array.from(
|
||||
group.querySelectorAll<HTMLElement>(
|
||||
`[role="${role}"]:not([aria-disabled="true"])`,
|
||||
),
|
||||
)
|
||||
const index = choices.indexOf(current)
|
||||
|
||||
if (index < 0) return
|
||||
|
||||
let target: HTMLElement
|
||||
|
||||
switch (event.key) {
|
||||
case 'Home':
|
||||
target = choices[0]
|
||||
break
|
||||
case 'End':
|
||||
target = choices[choices.length - 1]
|
||||
break
|
||||
case 'ArrowLeft':
|
||||
case 'ArrowRight': {
|
||||
const forward =
|
||||
(event.key === 'ArrowRight') !==
|
||||
(getComputedStyle(current).direction === 'rtl')
|
||||
|
||||
target =
|
||||
choices[(index + (forward ? 1 : choices.length - 1)) % choices.length]
|
||||
break
|
||||
}
|
||||
case ' ':
|
||||
case 'Enter':
|
||||
target = current
|
||||
break
|
||||
default:
|
||||
return
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
target.focus()
|
||||
|
||||
if (trigger === 'hover') target.dispatchEvent(new MouseEvent('mouseenter'))
|
||||
else target.click()
|
||||
}
|
||||
@ -354,14 +354,14 @@
|
||||
"path": "router-demo-home",
|
||||
"component": "demo/router-demo/router-demo-home",
|
||||
"meta": {
|
||||
"noLocalTitle": "人员信息(平级模式)"
|
||||
"i18nKey": "menu.RouterPeople"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "router-demo-detail",
|
||||
"component": "demo/router-demo/router-demo-detail",
|
||||
"meta": {
|
||||
"noLocalTitle": "信息详情",
|
||||
"i18nKey": "menu.RouterPersonDetail",
|
||||
"sameLevel": true
|
||||
}
|
||||
}
|
||||
@ -383,7 +383,7 @@
|
||||
"name": "MultiMenuOne",
|
||||
"component": "demo/multi/views/multi-menu-one",
|
||||
"meta": {
|
||||
"noLocalTitle": "多级菜单-1",
|
||||
"i18nKey": "menu.NestedOne",
|
||||
"keepAlive": true
|
||||
}
|
||||
},
|
||||
@ -392,7 +392,7 @@
|
||||
"name": "MultiMenuTwo",
|
||||
"component": "layout",
|
||||
"meta": {
|
||||
"noLocalTitle": "多级菜单-2"
|
||||
"i18nKey": "menu.NestedTwo"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@ -400,7 +400,7 @@
|
||||
"name": "SubMenuOther",
|
||||
"component": "demo/multi/views/multi-menu-two/views/sub-menu-other",
|
||||
"meta": {
|
||||
"noLocalTitle": "多级菜单-2-1",
|
||||
"i18nKey": "menu.NestedTwoOne",
|
||||
"keepAlive": true
|
||||
}
|
||||
},
|
||||
@ -409,7 +409,7 @@
|
||||
"name": "SubMenu",
|
||||
"component": "layout",
|
||||
"meta": {
|
||||
"noLocalTitle": "多级菜单-2-2",
|
||||
"i18nKey": "menu.NestedTwoTwo",
|
||||
"keepAlive": true
|
||||
},
|
||||
"children": [
|
||||
@ -418,7 +418,7 @@
|
||||
"name": "MultiMenuTwoOne",
|
||||
"component": "demo/multi/views/multi-menu-two/views/sub-menu/views/multi-menu-two-one",
|
||||
"meta": {
|
||||
"noLocalTitle": "多级菜单-2-2-1",
|
||||
"i18nKey": "menu.NestedTwoTwoOne",
|
||||
"keepAlive": true
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,22 +1,12 @@
|
||||
import { removeClass, setClass } from '@ray-template/composables/element'
|
||||
import type { CustomDirectiveFC } from '../../types'
|
||||
|
||||
const updateElementDisabledType = (el: HTMLElement, value: boolean) => {
|
||||
if (el) {
|
||||
const classes = 'r-template__directive--disabled'
|
||||
const nativeControl = el.matches(
|
||||
'button, input, select, textarea, fieldset, optgroup, option',
|
||||
)
|
||||
|
||||
if (value) {
|
||||
el.setAttribute('disabled', 'disabled')
|
||||
|
||||
setClass(el, classes)
|
||||
} else {
|
||||
el.removeAttribute('disabled')
|
||||
|
||||
removeClass(el, classes)
|
||||
}
|
||||
|
||||
el?.setAttribute('disabled', value ? 'disabled' : '')
|
||||
}
|
||||
el.toggleAttribute(nativeControl ? 'disabled' : 'inert', value)
|
||||
el.classList.toggle('r-template__directive--disabled', value)
|
||||
}
|
||||
|
||||
const disabledDirective: CustomDirectiveFC<HTMLElement, boolean> = () => {
|
||||
|
||||
@ -27,6 +27,36 @@ import type { AppRawRequestConfig, CancelerParams } from './types'
|
||||
export default class RequestCanceler {
|
||||
/** 待处理请求的 Map,key 为请求标识,value 为 AbortController */
|
||||
private readonly pendingRequest = new Map<string, AbortController>()
|
||||
private readonly fileIds = new WeakMap<File, number>()
|
||||
private nextFileId = 0
|
||||
|
||||
private serializePart(value: unknown) {
|
||||
if (
|
||||
typeof URLSearchParams !== 'undefined' &&
|
||||
value instanceof URLSearchParams
|
||||
)
|
||||
return ['query', value.toString()]
|
||||
|
||||
if (typeof FormData !== 'undefined' && value instanceof FormData) {
|
||||
const entries = Array.from(value, ([key, entry]) => {
|
||||
if (typeof entry === 'string') return [key, entry]
|
||||
|
||||
// 文件同名且尺寸相同也可能有不同内容,只将同一文件实例视为相同。
|
||||
let id = this.fileIds.get(entry)
|
||||
|
||||
if (id === void 0) {
|
||||
id = ++this.nextFileId
|
||||
this.fileIds.set(entry, id)
|
||||
}
|
||||
|
||||
return [key, id]
|
||||
})
|
||||
|
||||
return ['form', entries]
|
||||
}
|
||||
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
@ -57,7 +87,12 @@ export default class RequestCanceler {
|
||||
): string {
|
||||
const { method = '', url = '', params, data } = config
|
||||
|
||||
return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&')
|
||||
return JSON.stringify([
|
||||
url,
|
||||
method,
|
||||
this.serializePart(params),
|
||||
this.serializePart(data),
|
||||
])
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -12,8 +12,16 @@ export function getIconAsset(name: IconName) {
|
||||
|
||||
if (!svg) return
|
||||
|
||||
const paint = Object.fromEntries(
|
||||
Array.from(
|
||||
svg[1].matchAll(/\s((?:fill|stroke)(?:-[\w-]+)?|opacity|color|style|preserveAspectRatio)\s*=\s*(["'])([\s\S]*?)\2/g),
|
||||
([, name, , value]) => [name, value],
|
||||
),
|
||||
)
|
||||
|
||||
return {
|
||||
viewBox: svg[1].match(/viewBox=["']([^"']+)["']/i)?.[1],
|
||||
body: svg[2],
|
||||
paint,
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,20 +18,16 @@ export default defineComponent({
|
||||
const containerSize = ref({ width: 0, height: 0 })
|
||||
|
||||
const cssVars = computed(() => {
|
||||
let width = completeSize(props.width)
|
||||
let height = completeSize(props.height)
|
||||
|
||||
if (props.width === 'responsive' && containerSize.value.width > 0) {
|
||||
width = `${containerSize.value.width}px`
|
||||
}
|
||||
|
||||
if (props.height === 'responsive' && containerSize.value.height > 0) {
|
||||
height = `${containerSize.value.height}px`
|
||||
}
|
||||
|
||||
const relativeSize = props.responsive ? '100%' : 'auto'
|
||||
const cssVar = {
|
||||
'--r-barcode-width': width,
|
||||
'--r-barcode-height': height,
|
||||
'--r-barcode-width':
|
||||
props.width === 'responsive'
|
||||
? relativeSize
|
||||
: completeSize(props.width),
|
||||
'--r-barcode-height':
|
||||
props.height === 'responsive'
|
||||
? relativeSize
|
||||
: completeSize(props.height),
|
||||
}
|
||||
|
||||
return cssVar
|
||||
|
||||
@ -15,11 +15,6 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
.r-barcode {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.r-barcode-spin,
|
||||
|
||||
@ -303,7 +303,7 @@ export default defineComponent({
|
||||
.draggable({
|
||||
inertia: true,
|
||||
autoScroll: true,
|
||||
allowFrom: cardHeader ? '.n-card-header' : '.n-card__content',
|
||||
allowFrom: cardHeader ? '.n-card-header' : '.n-card-content',
|
||||
modifiers: [interact.modifiers.restrictRect(restrictRectOptions)],
|
||||
listeners: {
|
||||
move: (event) => {
|
||||
|
||||
@ -50,25 +50,27 @@ export default defineComponent({
|
||||
}
|
||||
},
|
||||
render() {
|
||||
const svgAttrs = { RIconAttribute: 'r-icon', 'aria-hidden': true }
|
||||
|
||||
return (
|
||||
<span
|
||||
class={['r-icon', this.customClassName]}
|
||||
style={[this.cssVars]}
|
||||
onClick={this.iconClick}
|
||||
>
|
||||
<svg
|
||||
viewBox={this.asset?.viewBox}
|
||||
innerHTML={this.asset?.body}
|
||||
fill={this.color}
|
||||
{...({
|
||||
RIconAttribute: 'r-icon',
|
||||
'aria-hidden': true,
|
||||
} as object)}
|
||||
>
|
||||
{this.symbolId ? (
|
||||
<use href={this.symbolId} fill={this.color} />
|
||||
) : null}
|
||||
</svg>
|
||||
{this.asset ? (
|
||||
<svg
|
||||
{...svgAttrs}
|
||||
viewBox={this.asset.viewBox}
|
||||
fill={this.color}
|
||||
{...this.asset.paint}
|
||||
innerHTML={this.asset.body}
|
||||
/>
|
||||
) : (
|
||||
<svg {...svgAttrs} fill={this.color}>
|
||||
{this.symbolId && <use href={this.symbolId} fill={this.color} />}
|
||||
</svg>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
|
||||
@ -13,11 +13,10 @@
|
||||
opacity: var(--r-icon-depth);
|
||||
cursor: var(--r-icon-cursor);
|
||||
|
||||
& svg[RIconAttribute='r-icon'] {
|
||||
> svg {
|
||||
display: block;
|
||||
width: var(--r-icon-width);
|
||||
height: var(--r-icon-height);
|
||||
fill: currentColor;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
import { computed, defineComponent } from 'vue'
|
||||
import { computed, defineComponent, ref } from 'vue'
|
||||
import './index.scss'
|
||||
import { completeSize } from '@ray-template/composables/element'
|
||||
import {
|
||||
completeSize,
|
||||
navigateHorizontalChoice,
|
||||
} from '@ray-template/composables/element'
|
||||
import { isValueType } from '@ray-template/utils'
|
||||
import { NFlex, NPopover, NTab, NTabs } from 'naive-ui'
|
||||
import type { TabsProps } from 'naive-ui'
|
||||
@ -55,6 +58,22 @@ export default defineComponent({
|
||||
name: 'RSegment',
|
||||
props,
|
||||
setup(props, { expose }) {
|
||||
const uncontrolled = ref(
|
||||
props.value ?? props.activeName ?? props.defaultValue,
|
||||
)
|
||||
const selected = computed(
|
||||
() =>
|
||||
props.value ??
|
||||
props.activeName ??
|
||||
uncontrolled.value ??
|
||||
props.options[0]?.key,
|
||||
)
|
||||
const tabStop = computed(
|
||||
() =>
|
||||
props.options.find(
|
||||
(option) => option.key === selected.value && !option.disabled,
|
||||
)?.key ?? props.options.find((option) => !option.disabled)?.key,
|
||||
)
|
||||
const cssVars = computed(() => {
|
||||
const { width: propsWidth } = props
|
||||
let segmentWidthVar: string
|
||||
@ -86,14 +105,23 @@ export default defineComponent({
|
||||
|
||||
return {
|
||||
cssVars,
|
||||
selected,
|
||||
tabStop,
|
||||
rememberSelection: (key: string | number) => {
|
||||
uncontrolled.value = key
|
||||
},
|
||||
}
|
||||
},
|
||||
render() {
|
||||
const { $props, options, cssVars, themeOverrides: _themeOverrides } = this
|
||||
const { onUpdateValue, ...tabsProps } = $props
|
||||
|
||||
return (
|
||||
<NTabs
|
||||
{...($props as TabsProps)}
|
||||
{...(tabsProps as TabsProps)}
|
||||
value={this.selected}
|
||||
{...{ role: 'radiogroup' }}
|
||||
onUpdateValue={[onUpdateValue ?? [], this.rememberSelection].flat()}
|
||||
style={[cssVars]}
|
||||
class={[
|
||||
'r-segment',
|
||||
@ -108,6 +136,14 @@ export default defineComponent({
|
||||
<NTab
|
||||
key={curr.key}
|
||||
name={curr.key}
|
||||
{...{
|
||||
role: 'radio',
|
||||
onKeydown: (event: KeyboardEvent) =>
|
||||
navigateHorizontalChoice(event, $props.trigger),
|
||||
tabindex: curr.key === this.tabStop ? 0 : -1,
|
||||
}}
|
||||
aria-checked={curr.key === this.selected}
|
||||
aria-disabled={curr.disabled || void 0}
|
||||
tab={() =>
|
||||
!curr.popover ? iconSegmentTab(curr) : popoverSegmentTab(curr)
|
||||
}
|
||||
|
||||
@ -1,6 +1,11 @@
|
||||
.r-segment {
|
||||
width: var(--r-segment-width);
|
||||
max-inline-size: 100%;
|
||||
|
||||
[role='radio']:focus-visible {
|
||||
outline: 2px solid currentColor;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
}
|
||||
|
||||
.r-segment--intrinsic {
|
||||
|
||||
@ -507,7 +507,7 @@ export default defineComponent({
|
||||
icon="action/reload"
|
||||
label={t('reload')}
|
||||
disabled={props.loading}
|
||||
onClick={props.reload}
|
||||
onClick={() => props.reload?.()}
|
||||
/>
|
||||
) : null}
|
||||
{props.columns.length ? (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user