diff --git a/__test__/app/user-management.spec.ts b/__test__/app/user-management.spec.ts index fd7d095b..952fc7da 100644 --- a/__test__/app/user-management.spec.ts +++ b/__test__/app/user-management.spec.ts @@ -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() + } +}) diff --git a/__test__/components/barcode.spec.tsx b/__test__/components/barcode.spec.tsx index 997d80d3..a945f279 100644 --- a/__test__/components/barcode.spec.tsx +++ b/__test__/components/barcode.spec.tsx @@ -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 } }) diff --git a/__test__/components/disabled-directive.spec.ts b/__test__/components/disabled-directive.spec.ts new file mode 100644 index 00000000..573e78e4 --- /dev/null +++ b/__test__/components/disabled-directive.spec.ts @@ -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() + } +}) diff --git a/__test__/components/draggable-card.spec.tsx b/__test__/components/draggable-card.spec.tsx index 7e679e66..75e8b40e 100644 --- a/__test__/components/draggable-card.spec.tsx +++ b/__test__/components/draggable-card.spec.tsx @@ -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' } }) diff --git a/__test__/components/table-pro-search.spec.ts b/__test__/components/table-pro-search.spec.ts index 83fa738b..728564bb 100644 --- a/__test__/components/table-pro-search.spec.ts +++ b/__test__/components/table-pro-search.spec.ts @@ -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 = [ diff --git a/__test__/components/table-pro-toolbar.spec.tsx b/__test__/components/table-pro-toolbar.spec.tsx index 47c72c7b..ae7f7632 100644 --- a/__test__/components/table-pro-toolbar.spec.tsx +++ b/__test__/components/table-pro-toolbar.spec.tsx @@ -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(async () => ({ data, total: 1 })) + const [register, actions] = useTablePro() + const request = vi.fn(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', ) diff --git a/__test__/components/wrapper-contracts.spec.tsx b/__test__/components/wrapper-contracts.spec.tsx index 166b99ad..292166c0 100644 --- a/__test__/components/wrapper-contracts.spec.tsx +++ b/__test__/components/wrapper-contracts.spec.tsx @@ -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' } }) diff --git a/__test__/hooks/useAppNavigation.spec.ts b/__test__/hooks/useAppNavigation.spec.ts index 6ed493b2..33d532b9 100644 --- a/__test__/hooks/useAppNavigation.spec.ts +++ b/__test__/hooks/useAppNavigation.spec.ts @@ -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 () => { diff --git a/__test__/layout/menu-keyboard.spec.ts b/__test__/layout/menu-keyboard.spec.ts new file mode 100644 index 00000000..ad7ad69f --- /dev/null +++ b/__test__/layout/menu-keyboard.spec.ts @@ -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() + } + }, +) diff --git a/__test__/layout/preferences.spec.ts b/__test__/layout/preferences.spec.ts index cc57de43..78ef21c8 100644 --- a/__test__/layout/preferences.spec.ts +++ b/__test__/layout/preferences.spec.ts @@ -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() diff --git a/__test__/layout/route-transition.spec.tsx b/__test__/layout/route-transition.spec.tsx index d8aad761..4aec0026 100644 --- a/__test__/layout/route-transition.spec.tsx +++ b/__test__/layout/route-transition.spec.tsx @@ -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', + ) + }, +) diff --git a/__test__/mock/admin-api.spec.ts b/__test__/mock/admin-api.spec.ts index e7db31cd..ad5429b7 100644 --- a/__test__/mock/admin-api.spec.ts +++ b/__test__/mock/admin-api.spec.ts @@ -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 () => { diff --git a/__test__/router/config.spec.ts b/__test__/router/config.spec.ts index 8a857ded..ecc2af26 100644 --- a/__test__/router/config.spec.ts +++ b/__test__/router/config.spec.ts @@ -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() + } +}) diff --git a/__test__/router/source.spec.ts b/__test__/router/source.spec.ts index 4f1a12bd..167b11aa 100644 --- a/__test__/router/source.spec.ts +++ b/__test__/router/source.spec.ts @@ -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() + } +}) diff --git a/__test__/workspace/http-client.spec.ts b/__test__/workspace/http-client.spec.ts index e88297cd..1bf404eb 100644 --- a/__test__/workspace/http-client.spec.ts +++ b/__test__/workspace/http-client.spec.ts @@ -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) => diff --git a/apps/admin/public/contracts/admin-api.json b/apps/admin/public/contracts/admin-api.json index ff28391e..8d283b73 100644 --- a/apps/admin/public/contracts/admin-api.json +++ b/apps/admin/public/contracts/admin-api.json @@ -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": { diff --git a/apps/admin/src/api/admin/client.ts b/apps/admin/src/api/admin/client.ts index 4ba26a4c..13dbaf14 100644 --- a/apps/admin/src/api/admin/client.ts +++ b/apps/admin/src/api/admin/client.ts @@ -53,6 +53,7 @@ export async function adminRequest( path: string, schema: Schema, options: AppRawRequestConfig = {}, + onRevision?: (revision: string | undefined) => void, ): Promise> { let body: unknown const version = sessionVersion @@ -121,5 +122,9 @@ export async function adminRequest( ), ) - return v.parse(schema, envelope.data) + const result = v.parse(schema, envelope.data) + + onRevision?.(envelope.revision) + + return result } diff --git a/apps/admin/src/api/admin/index.ts b/apps/admin/src/api/admin/index.ts index eb67a01e..c8db2b93 100644 --- a/apps/admin/src/api/admin/index.ts +++ b/apps/admin/src/api/admin/index.ts @@ -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[]) => diff --git a/apps/admin/src/axios/README.md b/apps/admin/src/axios/README.md index 56b3ee09..9e4eb072 100644 --- a/apps/admin/src/axios/README.md +++ b/apps/admin/src/axios/README.md @@ -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. diff --git a/apps/admin/src/directives/README.DIR.md b/apps/admin/src/directives/README.DIR.md index c98ae122..3c36a027 100644 --- a/apps/admin/src/directives/README.DIR.md +++ b/apps/admin/src/directives/README.DIR.md @@ -143,7 +143,7 @@ const Demo = defineComponent({ #### Tip -> 该指令基于 css 层面进行禁用操作,如果元素含有 `disabled` 属性方法,会尝试使用原生 `disabled` 属性。对于组件库而言,本身就提供了丰富的 `disabled props`,所以应该是优先使用组件自带属性。 +> 原生表单控件使用 `disabled` 属性。表单和其他容器使用 `inert` 暂停整棵子树的键盘和指针交互。组件提供 `disabled` prop 时优先使用组件自身的接口。 #### 示例 diff --git a/apps/admin/src/hooks/template/useAppNavigation.ts b/apps/admin/src/hooks/template/useAppNavigation.ts index 1c07def5..8be533ab 100644 --- a/apps/admin/src/hooks/template/useAppNavigation.ts +++ b/apps/admin/src/hooks/template/useAppNavigation.ts @@ -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 } diff --git a/apps/admin/src/hooks/template/useSpinning.ts b/apps/admin/src/hooks/template/useSpinning.ts index e710e73b..f9168210 100644 --- a/apps/admin/src/hooks/template/useSpinning.ts +++ b/apps/admin/src/hooks/template/useSpinning.ts @@ -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 diff --git a/apps/admin/src/layout/components/Menu/index.tsx b/apps/admin/src/layout/components/Menu/index.tsx index 6fa123e4..bf903742 100644 --- a/apps/admin/src/layout/components/Menu/index.tsx +++ b/apps/admin/src/layout/components/Menu/index.tsx @@ -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} > - { - changeMenuModelValue(key, option as unknown as AppMenuOption) + ) diff --git a/apps/admin/src/layout/components/MenuTag/index.tsx b/apps/admin/src/layout/components/MenuTag/index.tsx index 086c3f80..cd368c2a 100644 --- a/apps/admin/src/layout/components/MenuTag/index.tsx +++ b/apps/admin/src/layout/components/MenuTag/index.tsx @@ -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: () => { diff --git a/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSegment.tsx b/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSegment.tsx index a12805b7..fc659d0c 100644 --- a/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSegment.tsx +++ b/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/components/ThemeSegment.tsx @@ -36,6 +36,7 @@ export default defineComponent({ }) return { + t, options, modelAppTheme, } @@ -45,6 +46,7 @@ export default defineComponent({ return ( { - return checked - ? { - backgroundColor: '#000000', - } - : { - color: '#000000', - } - } - - return { - darkTheme, - lightTheme, - getAppTheme, - railStyle, - modelAppThemeRef, - } - }, - render() { - const { $t, darkTheme, lightTheme, railStyle } = this - - return ( - - - {{ - trigger: () => ( - - bool ? darkTheme() : lightTheme() - } - > - {{ - 'checked-icon': () => , - 'unchecked-icon': () => ( - - ), - checked: () => '亮', - unchecked: () => '暗', - }} - - ), - default: () => - this.getAppTheme - ? $t('headerSettingOptions.ThemeOptions.Dark') - : $t('headerSettingOptions.ThemeOptions.Light'), - }} - - + return () => ( + + {{ + trigger: () => ( + (dark ? darkTheme() : lightTheme())} + > + {{ + 'checked-icon': () => , + 'unchecked-icon': () => , + checked: () => t('theme.dark'), + unchecked: () => t('theme.light'), + }} + + ), + default: () => t(getAppTheme.value ? 'theme.dark' : 'theme.light'), + }} + ) }, }) diff --git a/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.scss b/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.scss index dd37b9ee..7978801d 100644 --- a/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.scss +++ b/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.scss @@ -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, diff --git a/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.tsx b/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.tsx index 98e70f56..08d7c109 100644 --- a/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.tsx +++ b/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.tsx @@ -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('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({ ), default: () => ( - - {categories.map(({ key, icon, view: View }) => ( - ( - - + {categories.map(({ key, view: View }) => ( + ))} - + ), footer: () => (
diff --git a/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/segment-views/Common.tsx b/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/segment-views/Common.tsx index ffef3f71..1394808d 100644 --- a/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/segment-views/Common.tsx +++ b/apps/admin/src/layout/components/SiderBar/components/SettingDrawer/segment-views/Common.tsx @@ -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({
reload()} + onClick={() => reloadWorkspace()} > {t('general.refresh')} diff --git a/apps/admin/src/layout/default/ContentWrapper/index.tsx b/apps/admin/src/layout/default/ContentWrapper/index.tsx index 1f9fc593..dccc2d50 100644 --- a/apps/admin/src/layout/default/ContentWrapper/index.tsx +++ b/apps/admin/src/layout/default/ContentWrapper/index.tsx @@ -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 () => ( <> - {globalMainLayoutLoad.value ? ( + {globalMainLayoutLoad.value || refreshingPath.value !== null ? ( ) : null} diff --git a/apps/admin/src/locales/lang/en-US/menu.json b/apps/admin/src/locales/lang/en-US/menu.json index abc265fd..c9f6c59a 100644 --- a/apps/admin/src/locales/lang/en-US/menu.json +++ b/apps/admin/src/locales/lang/en-US/menu.json @@ -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" } diff --git a/apps/admin/src/locales/lang/en-US/preferences.json b/apps/admin/src/locales/lang/en-US/preferences.json index a5ef0348..b80fd8a5 100644 --- a/apps/admin/src/locales/lang/en-US/preferences.json +++ b/apps/admin/src/locales/lang/en-US/preferences.json @@ -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", diff --git a/apps/admin/src/locales/lang/en-US/routeManagement.json b/apps/admin/src/locales/lang/en-US/routeManagement.json index 8e7d39e8..19a9c22f 100644 --- a/apps/admin/src/locales/lang/en-US/routeManagement.json +++ b/apps/admin/src/locales/lang/en-US/routeManagement.json @@ -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" } diff --git a/apps/admin/src/locales/lang/en-US/userManagement.json b/apps/admin/src/locales/lang/en-US/userManagement.json index a6263420..115d5bf7 100644 --- a/apps/admin/src/locales/lang/en-US/userManagement.json +++ b/apps/admin/src/locales/lang/en-US/userManagement.json @@ -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" diff --git a/apps/admin/src/locales/lang/zh-CN/menu.json b/apps/admin/src/locales/lang/zh-CN/menu.json index 00870dcc..09102ff6 100644 --- a/apps/admin/src/locales/lang/zh-CN/menu.json +++ b/apps/admin/src/locales/lang/zh-CN/menu.json @@ -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" } diff --git a/apps/admin/src/locales/lang/zh-CN/preferences.json b/apps/admin/src/locales/lang/zh-CN/preferences.json index c0ed6ed1..dd456bf5 100644 --- a/apps/admin/src/locales/lang/zh-CN/preferences.json +++ b/apps/admin/src/locales/lang/zh-CN/preferences.json @@ -20,6 +20,7 @@ "general": "通用" }, "theme": { + "darkMode": "深色模式", "light": "浅色", "dark": "深色", "auto": "跟随系统" @@ -131,7 +132,7 @@ "language": "界面语言", "workspaceActions": "工作区操作", "refresh": "刷新工作区", - "refreshHint": "重新加载当前页面并释放工作区中的页面实例;未保存的表单内容会丢失。", + "refreshHint": "重新加载工作区并清空所有页面缓存。各标签页未保存的表单内容都会丢失。", "scrollTop": "回到内容顶部", "cacheLimitHint": "按最近访问顺序管理缓存。设为 0 将停止加入新页面;如需立即停用,请关闭页面缓存。", "clearCache": "清理页面缓存", diff --git a/apps/admin/src/locales/lang/zh-CN/routeManagement.json b/apps/admin/src/locales/lang/zh-CN/routeManagement.json index 53a515fa..26f39c1a 100644 --- a/apps/admin/src/locales/lang/zh-CN/routeManagement.json +++ b/apps/admin/src/locales/lang/zh-CN/routeManagement.json @@ -66,5 +66,8 @@ "group": "菜单分组", "redirect": "重定向", "external": "外部链接" - } + }, + "editConflict": "其他管理员已保存新配置。请先导出需要保留的草稿,再重新读取配置并合并修改。", + "readOnlyHint": "远程地址只支持读取。启用后将重新加载工作区,编辑器的改动仅供导出或另存为本地配置。", + "activateRemote": "启用远程配置" } diff --git a/apps/admin/src/locales/lang/zh-CN/userManagement.json b/apps/admin/src/locales/lang/zh-CN/userManagement.json index 301f6516..f06e2f12 100644 --- a/apps/admin/src/locales/lang/zh-CN/userManagement.json +++ b/apps/admin/src/locales/lang/zh-CN/userManagement.json @@ -78,7 +78,11 @@ "invalidCredentials": "账号或密码错误。", "forbidden": "当前账号没有执行此操作的权限。", "invalidRoutes": "路由配置未通过校验。", - "requestFailed": "请求失败,请稍后重试。" + "requestFailed": "请求失败,请稍后重试。", + "editConflict": "此账号已被其他人修改。请重新打开编辑框,核对最新内容后再保存。", + "serverStorage": "服务器暂时无法访问数据库,请稍后重试。", + "serviceUnavailable": "服务暂时不可用,请稍后重试。", + "tooManyRequests": "请求过于频繁,请稍后再试。" }, "allUsers": "全部用户", "apiContract": "API 接入契约" diff --git a/apps/admin/src/mocks/database.ts b/apps/admin/src/mocks/database.ts index 7a1956f7..b90a5a81 100644 --- a/apps/admin/src/mocks/database.ts +++ b/apps/admin/src/mocks/database.ts @@ -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[] = [] let credentials: v.InferOutput['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 +type Snapshot = ReturnType + +export type AdminDatabase = ( + action: (snapshot: Snapshot) => T | Promise, +) => Promise + +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 + } +} diff --git a/apps/admin/src/mocks/handlers.ts b/apps/admin/src/mocks/handlers.ts index fc5b93c4..9152a082 100644 --- a/apps/admin/src/mocks/handlers.ts +++ b/apps/admin/src/mocks/handlers.ts @@ -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) => { + const respond = async ( + action: () => unknown | Promise, + 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[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(), diff --git a/apps/admin/src/router/app-route-modules.ts b/apps/admin/src/router/app-route-modules.ts index 9c2043d0..5abca667 100644 --- a/apps/admin/src/router/app-route-modules.ts +++ b/apps/admin/src/router/app-route-modules.ts @@ -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() 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) diff --git a/apps/admin/src/router/config/contract.ts b/apps/admin/src/router/config/contract.ts index 5dc17ce7..3aba6765 100644 --- a/apps/admin/src/router/config/contract.ts +++ b/apps/admin/src/router/config/contract.ts @@ -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([ + [ + '/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 +} diff --git a/apps/admin/src/router/config/source.ts b/apps/admin/src/router/config/source.ts index a3d9ea4c..bdaf0fe5 100644 --- a/apps/admin/src/router/config/source.ts +++ b/apps/admin/src/router/config/source.ts @@ -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 { 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') } diff --git a/apps/admin/src/store/hooks/useRuntimeStore.ts b/apps/admin/src/store/hooks/useRuntimeStore.ts index 442cf42b..5c0d5bc7 100644 --- a/apps/admin/src/store/hooks/useRuntimeStore.ts +++ b/apps/admin/src/store/hooks/useRuntimeStore.ts @@ -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), diff --git a/apps/admin/src/store/modules/menu/index.ts b/apps/admin/src/store/modules/menu/index.ts index bc6021ef..48862bfd 100644 --- a/apps/admin/src/store/modules/menu/index.ts +++ b/apps/admin/src/store/modules/menu/index.ts @@ -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]) { diff --git a/apps/admin/src/store/modules/runtime/index.ts b/apps/admin/src/store/modules/runtime/index.ts index 3dbab3f5..cbe44f50 100644 --- a/apps/admin/src/store/modules/runtime/index.ts +++ b/apps/admin/src/store/modules/runtime/index.ts @@ -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({ 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) } diff --git a/apps/admin/src/store/modules/setting/index.ts b/apps/admin/src/store/modules/setting/index.ts index 8fcd09c6..2f892e06 100644 --- a/apps/admin/src/store/modules/setting/index.ts +++ b/apps/admin/src/store/modules/setting/index.ts @@ -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, }, } }) diff --git a/apps/admin/src/store/modules/setting/primary-button-colors.ts b/apps/admin/src/store/modules/setting/primary-button-colors.ts new file mode 100644 index 00000000..c75c90f2 --- /dev/null +++ b/apps/admin/src/store/modules/setting/primary-button-colors.ts @@ -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, + } +} diff --git a/apps/admin/src/views/login/components/Signing/index.tsx b/apps/admin/src/views/login/components/Signing/index.tsx index 607923db..9c9ef63a 100644 --- a/apps/admin/src/views/login/components/Signing/index.tsx +++ b/apps/admin/src/views/login/components/Signing/index.tsx @@ -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() }} diff --git a/apps/admin/src/views/route-management/index.tsx b/apps/admin/src/views/route-management/index.tsx index cb3d85d8..00e00c9e 100644 --- a/apps/admin/src/views/route-management/index.tsx +++ b/apps/admin/src/views/route-management/index.tsx @@ -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(routeSourceStatus.requested) const draft = ref('') const checked = shallowRef() @@ -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', + )} -

{t(`${source.value}Hint`)}

+

+ {t( + source.value === 'remote' && remoteRoutesReadOnly + ? 'readOnlyHint' + : `${source.value}Hint`, + )} +

{remoteRouteUrl && ( {remoteRouteUrl} )} @@ -252,7 +298,11 @@ export default defineComponent({ {t('loadStatic')} {remoteRouteUrl && ( - + void loadRemote()} + > {t('loadRemote')} )} @@ -335,6 +385,7 @@ export default defineComponent({ }} onUpdateValue={(value) => { draft.value = value + selectDraftSource() checked.value = void 0 error.value = '' }} diff --git a/apps/admin/src/views/route-management/visual.tsx b/apps/admin/src/views/route-management/visual.tsx index 533da6d0..bbab82ce 100644 --- a/apps/admin/src/views/route-management/visual.tsx +++ b/apps/admin/src/views/route-management/visual.tsx @@ -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(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({ )} -

{text('visualHint')}

+

+ {text(remoteRoutesReadOnly ? 'readOnlyHint' : 'visualHint')} +

{text('apply')} diff --git a/apps/admin/src/views/user-management/UserEditor.tsx b/apps/admin/src/views/user-management/UserEditor.tsx index 9c1b54a1..a34c8115 100644 --- a/apps/admin/src/views/user-management/UserEditor.tsx +++ b/apps/admin/src/views/user-management/UserEditor.tsx @@ -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, default: void 0 }, options: { type: Object as PropType, 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 } diff --git a/apps/admin/src/views/user-management/error-message.ts b/apps/admin/src/views/user-management/error-message.ts new file mode 100644 index 00000000..f24412b0 --- /dev/null +++ b/apps/admin/src/views/user-management/error-message.ts @@ -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', + ) + } +} diff --git a/apps/admin/src/views/user-management/index.tsx b/apps/admin/src/views/user-management/index.tsx index 08fb958a..5cc6ba69 100644 --- a/apps/admin/src/views/user-management/index.tsx +++ b/apps/admin/src/views/user-management/index.tsx @@ -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() + const editingRevision = ref() const details = shallowRef() const credentialTarget = shallowRef() 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 && ( @@ -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: '请输入姓名', diff --git a/apps/docs/guide/appearance.md b/apps/docs/guide/appearance.md index 8b177a94..e1c565fe 100644 --- a/apps/docs/guide/appearance.md +++ b/apps/docs/guide/appearance.md @@ -11,7 +11,7 @@ | Material | 紫色调、较大的圆角、胶囊按钮和分层表面 | | 朴素 | 中性灰、小圆角和无阴影表面 | -手动选择的主题色优先于预设,并随风格保留;点击「使用风格默认色」可恢复当前风格的配色。新用户、恢复默认设置,以及缺少风格的历史配置都使用现代化。已有的显式风格选择会在刷新和导入时保留。 +手动选择的主题色优先于预设,并随风格保留;点击「使用风格默认色」可恢复当前风格的配色。自定义主色的实心按钮会按各交互状态的实际填充色选择黑字或白字,半透明主色按当前主题卡片底色合成。新用户、恢复默认设置,以及缺少风格的历史配置都使用现代化。已有的显式风格选择会在刷新和导入时保留。 ### 样式放在哪里 diff --git a/apps/docs/guide/backend.md b/apps/docs/guide/backend.md index 3e1c8dd3..91c79c97 100644 --- a/apps/docs/guide/backend.md +++ b/apps/docs/guide/backend.md @@ -77,6 +77,8 @@ Redis 为 API、登录和改密提供跨进程限流,并缓存可重建的演 } ``` +用户详情与完整路由配置(`view=editor`)的成功包络会携带不透明的 `revision`。编辑后保存到同一资源时,发送 `If-Match: ""`。如果读取后已有其他修改,API 返回 412 和 `editConflict`,编辑器保留草稿。请重新读取并核对差异,再提交。已有客户端仍可省略请求头执行完整替换。自有后端要返回修订值并在写入事务中核对它,才能提供同样的并发保护。 + 400 表示输入不合法,401 表示会话失效,403 表示权限不足,404 表示对象不存在,409 表示账号/邮箱冲突或当前账号保护,413 表示请求体过大,429 表示请求受到限流,503 表示存储或依赖暂时不可用(Mock 中包括演示数据库写入失败)。`error.key` 是稳定的业务错误标识;可选的 `error.fields` 为字段到错误键的映射。API 层把错误转换为 `AdminApiError`,用户页将已约定的错误键翻译为中英文提示。读取响应也会经过 Schema 校验。 ## 登录、会话与权限 diff --git a/apps/docs/guide/layout.md b/apps/docs/guide/layout.md index eb5b94cc..508362b0 100644 --- a/apps/docs/guide/layout.md +++ b/apps/docs/guide/layout.md @@ -16,6 +16,8 @@ import { withBase } from 'vitepress' <<< @/examples/ShellDemo.vue ::: +菜单支持键盘操作。Tab 可聚焦菜单项,Enter 或空格展开分组或打开页面。侧栏用上下方向键移动焦点,顶部菜单用左右方向键。折叠侧栏和顶部菜单的子菜单可用方向键选择、Enter 打开、Esc 关闭。 + ## 配置工作区 ```ts diff --git a/apps/docs/guide/requests.md b/apps/docs/guide/requests.md index 721728c6..eb8476cd 100644 --- a/apps/docs/guide/requests.md +++ b/apps/docs/guide/requests.md @@ -38,7 +38,7 @@ export function loadOrders( } ``` -默认取消器按 URL、方法、参数和请求体识别重复请求,默认布局在路由更新前取消受管理的请求。示例将信号交给 TablePro 管理,所以关闭模板的默认注入;否则默认取消器会替换调用方传入的 signal。后台任务禁用默认取消后,需要自行管理生命周期。 +默认取消器按 URL、方法、参数和请求体识别重复请求。`URLSearchParams` 比较编码后的参数序列,`FormData` 比较有序字段、文本值和文件实例。默认布局在路由更新前取消受管理的请求。调用方提供 `signal` 或设置 `cancelConfig.cancel: false` 时自行管理取消;示例中的信号由 TablePro 管理。 ## 配置与拦截器 diff --git a/apps/docs/guide/routing.md b/apps/docs/guide/routing.md index e39cc06e..7528d5a9 100644 --- a/apps/docs/guide/routing.md +++ b/apps/docs/guide/routing.md @@ -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)。 diff --git a/apps/docs/public/contracts/admin-api.json b/apps/docs/public/contracts/admin-api.json index ff28391e..8d283b73 100644 --- a/apps/docs/public/contracts/admin-api.json +++ b/apps/docs/public/contracts/admin-api.json @@ -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": { diff --git a/apps/docs/reference/components/barcode.md b/apps/docs/reference/components/barcode.md index 09361109..b80cb52a 100644 --- a/apps/docs/reference/components/barcode.md +++ b/apps/docs/reference/components/barcode.md @@ -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 前验证输入长度和校验位。打印后是否可扫取决于设备和成品尺寸。 diff --git a/apps/docs/reference/components/segment.md b/apps/docs/reference/components/segment.md index 2cd79be9..6eb594cc 100644 --- a/apps/docs/reference/components/segment.md +++ b/apps/docs/reference/components/segment.md @@ -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` 需唯一。 | diff --git a/apps/docs/reference/directives.md b/apps/docs/reference/directives.md index 24874874..21a20fb0 100644 --- a/apps/docs/reference/directives.md +++ b/apps/docs/reference/directives.md @@ -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) diff --git a/apps/docs/reference/hooks/layout.md b/apps/docs/reference/hooks/layout.md index 624aa630..5f277557 100644 --- a/apps/docs/reference/hooks/layout.md +++ b/apps/docs/reference/hooks/layout.md @@ -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 只保留最后一次恢复计时。 diff --git a/apps/docs/reference/hooks/navigation.md b/apps/docs/reference/hooks/navigation.md index 6dab0d64..9f6cc732 100644 --- a/apps/docs/reference/hooks/navigation.md +++ b/apps/docs/reference/hooks/navigation.md @@ -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(兼容接口) + + +## useAppRoot(兼容接口) {#useapproot} 此接口已废弃,仅为旧调用方保留历史偏好的读写。`getRootRoute`、`getRootPath`、`getRootName` 是计算引用,`setRootRoute({ name?, path? })` 合并更新该字段;它不再控制登录落点、标签保护或关闭全部后的导航,也没有启动时首页校验。空工作区固定使用 `/welcome`。新代码直接通过 Router 显式导航。 diff --git a/apps/docs/reference/store/runtime.md b/apps/docs/reference/store/runtime.md index a60a24b4..84b66df4 100644 --- a/apps/docs/reference/store/runtime.md +++ b/apps/docs/reference/store/runtime.md @@ -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' diff --git a/apps/docs/reference/store/signing.md b/apps/docs/reference/store/signing.md index dd661aa9..bfb49613 100644 --- a/apps/docs/reference/store/signing.md +++ b/apps/docs/reference/store/signing.md @@ -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`。调用方通过 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) diff --git a/apps/docs/reference/table-pro.md b/apps/docs/reference/table-pro.md index 48b1a3a6..2928dc79 100644 --- a/apps/docs/reference/table-pro.md +++ b/apps/docs/reference/table-pro.md @@ -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`,表示是否成功应用条件。设 `submitMode: 'change'` 可在编辑时防抖提交,`debounce` 默认 300 ms。 ### 远程选项、联动和布局 diff --git a/apps/server/README.md b/apps/server/README.md index f0f0d4ac..1ec23c38 100644 --- a/apps/server/README.md +++ b/apps/server/README.md @@ -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. diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 14a8b63f..de06ef05 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -70,11 +70,18 @@ export class EnvelopeInterceptor implements NestInterceptor { response.status(200) return next.handle().pipe( - map((data: unknown): ApiResponse => ({ - code: 200, - msg: 'OK', - data: data ?? null, - })), + map((data: unknown): ApiResponse => { + const revision: string | undefined = response.locals.editRevision + + if (revision) response.setHeader('ETag', `"${revision}"`) + + return { + code: 200, + msg: 'OK', + data: data ?? null, + ...(revision ? { revision } : {}), + } + }), ) } } diff --git a/apps/server/src/modules/routes/routes.controller.ts b/apps/server/src/modules/routes/routes.controller.ts index d86f187f..16113a63 100644 --- a/apps/server/src/modules/routes/routes.controller.ts +++ b/apps/server/src/modules/routes/routes.controller.ts @@ -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 }, diff --git a/apps/server/src/modules/users/users.controller.ts b/apps/server/src/modules/users/users.controller.ts index fa40c4d4..798aa4db 100644 --- a/apps/server/src/modules/users/users.controller.ts +++ b/apps/server/src/modules/users/users.controller.ts @@ -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'), ) } diff --git a/apps/server/src/modules/users/users.service.ts b/apps/server/src/modules/users/users.service.ts index 7e590fab..a889ad12 100644 --- a/apps/server/src/modules/users/users.service.ts +++ b/apps/server/src/modules/users/users.service.ts @@ -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 ( diff --git a/apps/server/src/platform/runtime.ts b/apps/server/src/platform/runtime.ts index dfe4ad8d..f3c3f9fc 100644 --- a/apps/server/src/platform/runtime.ts +++ b/apps/server/src/platform/runtime.ts @@ -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() diff --git a/apps/server/test/integration.test.ts b/apps/server/test/integration.test.ts index c116f4dc..e2a3ded4 100644 --- a/apps/server/test/integration.test.ts +++ b/apps/server/test/integration.test.ts @@ -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(`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('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, + }) + } +}) diff --git a/packages/admin-shell/src/RouteTransition.vue b/packages/admin-shell/src/RouteTransition.vue index 0d7678b2..9f9a61b0 100644 --- a/packages/admin-shell/src/RouteTransition.vue +++ b/packages/admin-shell/src/RouteTransition.vue @@ -15,11 +15,20 @@ :exclude="getKeepAliveConfig.keepAliveExclude" > - + + + - + @@ -27,6 +36,8 @@